Ejemplos de Machine Learning para el uso y aplicación de regresiones
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

78 lines
2.4 KiB

  1. from sklearn import datasets
  2. from sklearn.linear_model import LogisticRegression
  3. import numpy as np
  4. import matplotlib.pyplot as plt
  5. iris = datasets.load_iris()
  6. list(iris.keys())
  7. print(iris.DESCR)
  8. X = iris["data"][:, 3:] # petal width
  9. y = (iris["target"] == 2).astype(np.int) # 1 if Iris-Virginica, else 0
  10. log_reg = LogisticRegression(solver="liblinear", random_state=42)
  11. log_reg.fit(X, y)
  12. X_new = np.linspace(0, 3, 1000).reshape(-1, 1)
  13. y_proba = log_reg.predict_proba(X_new)
  14. decision_boundary = X_new[y_proba[:, 1] >= 0.5][0]
  15. plt.figure(figsize=(8, 3))
  16. plt.plot(X[y==0], y[y==0], "bs")
  17. plt.plot(X[y==1], y[y==1], "g^")
  18. plt.plot([decision_boundary, decision_boundary], [-1, 2], "k:", linewidth=2)
  19. plt.plot(X_new, y_proba[:, 1], "g-", linewidth=2, label="Iris-Virginica")
  20. plt.plot(X_new, y_proba[:, 0], "b--", linewidth=2, label="Not Iris-Virginica")
  21. plt.text(decision_boundary+0.02, 0.15, "Decision boundary", fontsize=14, color="k", ha="center")
  22. plt.arrow(decision_boundary, 0.08, -0.3, 0, head_width=0.05, head_length=0.1, fc='b', ec='b')
  23. plt.arrow(decision_boundary, 0.92, 0.3, 0, head_width=0.05, head_length=0.1, fc='g', ec='g')
  24. plt.xlabel("Ancho de petalo (cm)", fontsize=14)
  25. plt.ylabel("Probabilidad", fontsize=14)
  26. plt.legend(loc="center left", fontsize=14)
  27. plt.axis([0, 3, -0.02, 1.02])
  28. X = iris["data"][:, (2, 3)] # petal length, petal width
  29. y = iris["target"]
  30. softmax_reg = LogisticRegression(multi_class="multinomial",solver="lbfgs", C=10, random_state=42)
  31. softmax_reg.fit(X, y)
  32. x0, x1 = np.meshgrid(
  33. np.linspace(0, 8, 500).reshape(-1, 1),
  34. np.linspace(0, 3.5, 200).reshape(-1, 1),
  35. )
  36. X_new = np.c_[x0.ravel(), x1.ravel()]
  37. y_proba = softmax_reg.predict_proba(X_new)
  38. y_predict = softmax_reg.predict(X_new)
  39. zz1 = y_proba[:, 1].reshape(x0.shape)
  40. zz = y_predict.reshape(x0.shape)
  41. plt.figure(figsize=(10, 4))
  42. plt.plot(X[y==2, 0], X[y==2, 1], "g^", label="Iris-Virginica")
  43. plt.plot(X[y==1, 0], X[y==1, 1], "bs", label="Iris-Versicolor")
  44. plt.plot(X[y==0, 0], X[y==0, 1], "yo", label="Iris-Setosa")
  45. from matplotlib.colors import ListedColormap
  46. custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])
  47. plt.contourf(x0, x1, zz, cmap=custom_cmap)
  48. contour = plt.contour(x0, x1, zz1, cmap=plt.cm.brg)
  49. plt.clabel(contour, inline=1, fontsize=12)
  50. plt.xlabel("Largo de petalo", fontsize=14)
  51. plt.ylabel("ancho de petalo", fontsize=14)
  52. plt.legend(loc="center left", fontsize=14)
  53. plt.axis([0, 7, 0, 3.5])
  54. plt.show()