线性回归:波士顿房价(利用现成函数)

机器学习 线性回归:波士顿房价
利用python库函数

python代码:

from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn import metrics
import matplotlib.pyplot as plt
import numpy as np
 
# (1)导入数据
boston = load_boston()
 
# (2)分割数据
X_train, X_test, y_train, y_test = train_test_split(boston.data, boston.target, test_size=0.3, random_state=0)
 
# (3)导入线性回归模型并训练模型
model = LinearRegression()
model.fit(X_train, y_train)
LinearRegression(copy_X=True, fit_intercept=True, n_jobs=None, normalize=False)
 
# (4)在测试集上预测
y_pred = model.predict(X_test)
# (5)评估模型
mse = metrics.mean_squared_error(y_test, y_pred)
print("MSE = ", mse)  # 性能评估:模型的均方差
MSE =  27.195965766883408
 
# (6)绘制预测结果 散装图,X轴表示真实值,Y轴表示预测值
plt.scatter(y_test, y_pred)
plt.xlabel("True Price: $Y_i$")
plt.ylabel("Predicted prices: $\hat{Y}_i$")
plt.title("True Prices vs Predicted prices: $Y_i$ vs $\hat{Y}_i$")
#绘制一条预测与真实结果一致的曲线,y=x,
# 如果预测房价和实际房价一致的话,那么所有的数据点都应该汇集在 y=x 这条线上,但这并不是现实,于是可以看到,除了少数点,大部分点散落在 y=x 附近,大趋势说明预测的结果还不错。
#请补充y=x代码
x=np.arange(0,50,1)
y=x
plt.plot(x,y,linewidth = '5',color='#FF0000')
plt.show()

 

 

 
posted @   月月今天做题了吗  阅读(332)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
点击右上角即可分享
微信分享提示