from sklearn import datasets # 数据集
from sklearn.model\_selection import train\_test\_split
from sklearn import linear\_model
import matplotlib.pyplot as plt
  • 1.
  • 2.
  • 3.
  • 4.
boston = datasets.load\_boston() # 波士顿房价数据
boston
  • 1.
  • 2.

【机器学习】线性回归-波士顿房价预测_ai

# 创建训练集 与 测试集
x\_train,x\_test,y\_train,y\_test = train\_test\_split(boston.data,boston.target,test\_size=0.1,random\_state=42)
print(x\_train.shape,x\_test.shape,y\_train.shape,y\_test.shape)
  • 1.
  • 2.
  • 3.

# 训练数据
linreg = linear_model.LinearRegression()
linreg.fit(x_train, y_train)

得出预测值

y\_pred = linreg.predict(x\_test)  
 y\_pred
  • 1.
  • 2.

【机器学习】线性回归-波士顿房价预测_ai_02

plt.figure(figsize=(10,6)) # 设置大小
plt.plot(y\_test,linewidth\=3,label='Actual') 
plt.plot(y\_pred,linewidth\=3,label='Prediction')

# 显示上面设置的名字与底部
plt.legend(loc='best')
plt.xlabel('test data point')
plt.ylabel('target value')
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.

【机器学习】线性回归-波士顿房价预测_线性回归_03

plt.plot(y\_test,y\_pred,'o')  
plt.plot(\[-10,60\],\[-10,60\],'k--')  
plt.axis(\[-10,60,-10,60\])

plt.xlabel('Actual')  
plt.ylabel('Prediction')
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.

【机器学习】线性回归-波士顿房价预测_语言模型_04