sklearn线性回归算法实现
作者:互联网
导入库
import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets,linear_model
from sklearn.metrics import mean_squared_error,r2_score
加载数据
diabetes=datasets.load_diabetes()
## 查看数据集
>>>diabetes['data']
array([[ 0.03807591, 0.05068012, 0.06169621, ..., -0.00259226,
0.01990842, -0.01764613],
[-0.00188202, -0.04464164, -0.05147406, ..., -0.03949338,
-0.06832974, -0.09220405],
[ 0.08529891, 0.05068012, 0.04445121, ..., -0.00259226,
0.00286377, -0.02593034],
...,
[ 0.04170844, 0.05068012, -0.01590626, ..., -0.01107952,
-0.04687948, 0.01549073],
[-0.04547248, -0.04464164, 0.03906215, ..., 0.02655962,
0.04452837, -0.02593034],
[-0.04547248, -0.04464164, -0.0730303 , ..., -0.03949338,
-0.00421986, 0.00306441]]
>>>diabetes['target']
array([151., 75., 141., 206., 135., 97., 138., 63., 110., 310., 101.,
69., 179., 185., 118., 171., 166., 144., 97., 168., 68., 49.,
......,
220., 57.])
划分数据集
diabetes_x=diabetes.data[:,np.newaxis,2]
diabetes_x_train=diabetes_x[:-20]
diabetes_x_test=diabetes_x[-20:]
diabetes_y_train=diabetes.target[:-20]
diabetes_y_test=diabetes.target[-20:]
模型的训练
reg=linear_model.LinearRegression()
reg.fit(diabetes_x_train,diabetes_y_train)
diabetes_y_pred=reg.predict(diabetes_x_test)
reg.score(diabetes_x_test,diabetes_y_test)
plt.scatter(diabetes_x_test,diabetes_y_test,color='black')
plt.plot(diabetes_x_test,diabetes_y_pred,color='blue')
模型的结果
>>>reg.score(diabetes_x_test,diabetes_y_test)
0.4725754479822712
>>>r2_score(diabetes_y_test,diabetes_y_pred)
0.4725754479822712
>>>plt.scatter(diabetes_x_test,diabetes_y_test,color='black')
>>>plt.plot(diabetes_x_test,diabetes_y_pred,color='blue')
标签:...,plt,20,test,算法,线性,sklearn,reg,diabetes 来源: https://blog.csdn.net/qq_38290604/article/details/94594066