线性回归

使用线性回归预测波士顿房价

载入数据集

import numpy as np
from sklearn import datasets
from sklearn import metrics
from sklearn import model_selection as modsel
from sklearn import linear_model
import matplotlib.pyplot as plt
plt.style.use('ggplot')

boston = datasets.load_boston()
dir(boston)  #  "dir"显示文本列表

训练模型

linreg = linear_model.LinearRegression()  
x_train, x_test, y_train, y_test = modsel.train_test_split(
    boston.data, boston.target, test_size=0.1, random_state=42)
linreg.fit(x_train, y_train)
metrics.mean_squared_error(y_train, linreg.predict(x_train))
#  linreg对象的score方法返回的是确定系数(R方值)
linreg.score(x_train, y_train)

测试模型
在测试数据上计算均方误差

y_pred = linreg.predict(x_test)   #  预测值
metrics.mean_squared_error(y_test, y_pred)

画出数据

plt.figure(figsize=(10, 6)) #  对应figsize的宽和高
plt.plot(y_test, linewidth=1, label='ground truth')
plt.plot(y_pred, linewidth=1, label='predicted')
plt.legend(loc='best')
plt.xlabel('test data points')
plt.ylabel('target value')
plt.show()

在这里插入图片描述

plt.plot(y_test, y_pred, '^') #'^'表示正三角形, "o"代表圆点
plt.plot([-10, 60], [-10, 60], 'k--')  
plt.axis([-10, 60, -10, 60])
plt.xlabel('ground truth')
plt.ylabel('predicted')
scorestr = r'R$^2$ = %.3f' % linreg.score(x_test, y_test)  # R**2值
errstr = 'MSE = %.3f' % metrics.mean_squared_error(y_test, y_pred)
#  用一个文本框显示R**2值和均方误差值
plt.text(-5, 50, scorestr, fontsize=10)
plt.text(-5, 45, errstr, fontsize=10)
plt.show()

在这里插入图片描述
从图中可以得到:R**2表明我们可以解释数据76%的离散度, 均方误差为15.011。

在下"人工智能"小白一枚,如果有什么不足的地方请在评论区留言指出

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值