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.

71 lines
2.0 KiB

  1. from sklearn.base import clone
  2. from sklearn.pipeline import Pipeline
  3. from sklearn import preprocessing
  4. from sklearn.preprocessing import PolynomialFeatures
  5. import numpy as np
  6. import matplotlib.pyplot as plt
  7. from sklearn.linear_model import SGDRegressor
  8. from sklearn.metrics import mean_squared_error
  9. from sklearn.preprocessing import StandardScaler
  10. from sklearn.model_selection import train_test_split
  11. np.random.seed(42)
  12. m = 100
  13. X = 6 * np.random.rand(m, 1) - 3
  14. y = 2 + X + 0.5 * X**2 + np.random.randn(m, 1)
  15. plt.plot(X,y,".", label = "Datos originales")
  16. X_train, X_val, y_train, y_val = train_test_split(X[:50], y[:50].ravel(), test_size=0.5, random_state=10)
  17. poly_scaler = Pipeline([
  18. ("poly_features", PolynomialFeatures(degree=90, include_bias=False)),
  19. ("std_scaler", StandardScaler()),
  20. ])
  21. X_train_poly_scaled = poly_scaler.fit_transform(X_train)
  22. X_val_poly_scaled = poly_scaler.transform(X_val)
  23. sgd_reg = SGDRegressor(max_iter=1, tol=-np.infty, warm_start=True, penalty=None,
  24. learning_rate="constant", eta0=0.0005, random_state=42)
  25. print(sgd_reg)
  26. minimum_val_error = float("inf")
  27. best_epoch = None
  28. best_model = None
  29. for epoch in range(1000):
  30. sgd_reg.fit(X_train_poly_scaled, y_train) # continues where it left off
  31. y_val_predict = sgd_reg.predict(X_val_poly_scaled)
  32. val_error = mean_squared_error(y_val, y_val_predict)
  33. if val_error < minimum_val_error:
  34. minimum_val_error = val_error
  35. best_epoch = epoch
  36. best_model = clone(sgd_reg)
  37. print(best_epoch)
  38. sgd_reg = SGDRegressor(max_iter=best_epoch, tol=-np.infty, warm_start=True, penalty=None,
  39. learning_rate="constant", eta0=0.0005, random_state=42)
  40. poly_features = PolynomialFeatures(degree=2, include_bias=False)
  41. X_pol = poly_features.fit_transform(X)
  42. sgd_reg.fit(X_pol,y.ravel())
  43. yout=sgd_reg.predict(X_pol)
  44. plt.plot(X,yout,"*", label = "Predicciones")
  45. # naming the x axis
  46. plt.xlabel('Eje X')
  47. # naming the y axis
  48. plt.ylabel('Eje Y')
  49. # giving a title to my graph
  50. plt.legend()
  51. plt.show()