VitalyD

Untitled

Dec 5th, 2017
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.61 KB | None | 0 0
  1. print(__doc__)
  2.  
  3. import numpy as np
  4. import matplotlib.pyplot as plt
  5. from sklearn.pipeline import Pipeline
  6. from sklearn.preprocessing import PolynomialFeatures
  7. from sklearn.linear_model import LinearRegression
  8. from sklearn.model_selection import cross_val_score
  9.  
  10.  
  11. def true_fun(X):
  12.     return np.cos(1.5 * np.pi * X)
  13.  
  14. np.random.seed(0)
  15.  
  16. n_samples = 30
  17. degrees = [1, 4, 15]
  18.  
  19. X = np.sort(np.random.rand(n_samples))
  20. y = true_fun(X) + np.random.randn(n_samples) * 0.1
  21.  
  22. plt.figure(figsize=(14, 5))
  23. for i in range(len(degrees)):
  24.     ax = plt.subplot(1, len(degrees), i + 1)
  25.     plt.setp(ax, xticks=(), yticks=())
  26.  
  27.     polynomial_features = PolynomialFeatures(degree=degrees[i],
  28.                                              include_bias=False)
  29.     linear_regression = LinearRegression()
  30.     pipeline = Pipeline([("polynomial_features", polynomial_features),
  31.                          ("linear_regression", linear_regression)])
  32.     pipeline.fit(X[:, np.newaxis], y)
  33.  
  34.     # Evaluate the models using crossvalidation
  35.     scores = cross_val_score(pipeline, X[:, np.newaxis], y,
  36.                              scoring="neg_mean_squared_error", cv=10)
  37.  
  38.     X_test = np.linspace(0, 1, 100)
  39.     plt.plot(X_test, pipeline.predict(X_test[:, np.newaxis]), label="Model")
  40.     plt.plot(X_test, true_fun(X_test), label="True function")
  41.     plt.scatter(X, y, edgecolor='b', s=20, label="Samples")
  42.     plt.xlabel("x")
  43.     plt.ylabel("y")
  44.     plt.xlim((0, 1))
  45.     plt.ylim((-2, 2))
  46.     plt.legend(loc="best")
  47.     plt.title("Degree {}\nMSE = {:.2e}(+/- {:.2e})".format(
  48.         degrees[i], -scores.mean(), scores.std()))
  49. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment