import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squred_error, r2_score
from sklearn import datasets
from sklearn.linear_model import LinearRegression, Ridge, Lasso, ElasticNet, ElasticNetCV, LassoCV
diabetes = datasets.load_diabetes()
X = diabetes['data']
y = diabetes['target']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.15)
lr = LinearRegression()
lr.fit(X_train, y_train)
# 回归问题的得分,不是准确率
lr.score(X_test, y_test)
# 0.5243489738860714
‘’‘
关于lr.score()的解释
The coefficient R^2 is defined as (1 - u/v), where u is the residual
sum of squares ((y_true - y_pred) ** 2).sum() and v is the total
sum of squares ((y_true - y_true.mean()) ** 2).sum().
The best possible score is 1.0 and it can be negative (because the
model can be arbitrarily worse). A constant model that always
predicts the expected value of y, disregarding the input features,
would get a R^2 score of 0.0.
’‘’
# 验证一下
y_ = lr.predict(y_test)
u = ((y_test - y_)**2).sum()
v = ((y_test - y_test.mean()) ** 2).sum()
r2 = 1-u/v
# 0.5243489738860714, 结果和上面lr.score()出来的结果一致
# 用r2_score()验证
r2_score(y_test, y_)
# 0.5243489738860714, 结果也是一样的
mean_squared_error(y_test, y_)
# 2363.0603637069144,mse值越小越好