1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| from sklearn.datasets import load_boston data = load_boston() x = data['data'] y = data['target']
from sklearn.model_selection import train_test_split X_train,X_test,y_train,y_test = train_test_split(x,y,test_size = 0.2,random = ...)
from sklearn.linear_model import Lasso clf1 = Lasso(alpha = 0.1) clf1.fit(X_train,y_train)
y_train_pred = clf1.predict(X_train) y_test_pred = clf1.predict(X_test)
from sklearn.metrics import mean_squared_error mean_squared_error(y_train,y_train_pred) mean_squared_error(y_test,y_test_pred)
alphas = [0.001,0.005,0.1,0.2,0.3,0.4,0.5,1,1.5] mse_trains = [] mse_tests = [] for alpha in alphas: clf = Lasso(alpha = alpha) clf.fit(X_train,y_train) y_train_pred = clf.predict(X_train) y_test_pred = clf.predict(X_test) mse_trains.append(mean_squared_error(y_train,y_train_pred)) mse_tests.append(mean_squared_error(y_test,y_test_pred))
import matplotlib.pyplot as plt plt.plot(alphas,mse_trains,label = 'train') plt.plot(alphas,mse_tests,label = 'test') plt.legend() plt.show()
|