代码演示

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
from sklearn.dataseats import load_boston # 使用库自带的数据演示

# 导入波士顿房价数据
data = load_boston()

# 提取x和y
x = data['data']
y = data['target']

# 使用sklearn线性回归库
from sklearn.linear_model import LinearRegression

# 实例化一个线性回归
clf = LineaRegression()

# 根据已知的xy进行训练
clf.fit(x,y)

# 查看每个x对应的系数
clf.coef_
# 查看常数项(截距项)
clf.intercept_

# 测试,选101行
clf.predict([x[101]])
# 将所有x进行预测,可以用来对比
y_pred = clf.predict(x)

# 调用函数,计算均方和
import sklearn.metrics import mean_squared_error
mean_squared_error(y,y_pred)

# 画图展示一下
import matplotlib.pyplot as plt
x = list(range(len(y)))
plt.plot(x,y,label = 'true') # 真实值曲线
plt.plot(x,y_pred,label = 'pred') # 预测值曲线
plt.legend()
plt.show()