You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
fromsklearn.neighborsimportKNeighborsRegressorX, y=mglearn.datasets.make_wave(n_samples=40)
# split the wave dataset into a training and a test setX_train, X_test, y_train, y_test=train_test_split(X, y, random_state=0)
# instantiate the model and set the number of neighbors to consider to 3reg=KNeighborsRegressor(n_neighbors=3)
# fit the model using the training data and training targetsreg.fit(X_train, y_train)
print("Test set predictions:\n{}".format(reg.predict(X_test)))
print("Test set R^2: {:.2f}".format(reg.score(X_test, y_test)))
线性回归
fromsklearn.linear_modelimportLinearRegressionX, y=mglearn.datasets.make_wave(n_samples=60)
X_train, X_test, y_train, y_test=train_test_split(X, y, random_state=42)
lr=LinearRegression().fit(X_train, y_train)
# 打印系数print("lr.coef_: {}".format(lr.coef_))
# 打印截距print("lr.intercept_: {}".format(lr.intercept_))
# 训练集分数print("Training set score: {:.2f}".format(lr.score(X_train, y_train)))
# 测试集分数print("Test set score: {:.2f}".format(lr.score(X_test, y_test)))
Ridge 回归
# %%fromsklearn.linear_modelimportRidgeridge=Ridge().fit(X_train,y_train)
# %%ridge.score(X_train,y_train)
# %%ridge.score(X_test,y_test)
# 调参ridge10=Ridge(alpha=.1).fit(X_train, y_train)
print("Training set score: {:.2f}".format(ridge10.score(X_train, y_train)))
print("Test set score: {:.2f}".format(ridge10.score(X_test, y_test)))
Lasso 回归
fromsklearn.linear_modelimportLassolasso=Lasso()..fit(X_train, y_train)
lasso001=Lasso(alpha=0.01, max_iter=100000).fit(X_train, y_train)
print("Training set score: {:.2f}".format(lasso001.score(X_train, y_train)))
print("Test set score: {:.2f}".format(lasso001.score(X_test, y_test)))
print("Number of features used: {}".format(np.sum(lasso001.coef_!=0)))