机器学习之线程回归

线性回归公式:
这里写图片描述

import pandas as pd
import matplotlib.pyplot as plt

columns = ["mpg","cylinders","displacement","horsepower","weight","acceleration","model year","origin","car name"]
#由于原使数据只有数据,因此columns是为他们增加列的分类,delim_whitespace代表以空格作为分隔符
cars = pd.read_table("D:\\test\machineLearning\\auto-mpg.data",delim_whitespace=True,names=columns)
cars.head(2)
mpgcylindersdisplacementhorsepowerweightaccelerationmodel yearorigincar name
018.08307.0130.03504.012.0701chevrolet chevelle malibu
115.08350.0165.03693.011.5701buick skylark 320
fig = plt.figure()
ax1=fig.add_subplot(2,1,1)
cars.plot("weight","mpg",kind="scatter",ax=ax1)
plt.show()

这里写图片描述

import sklearn 
from sklearn.linear_model import LinearRegression

lr =LinearRegression();#获取线性回归模型
lr.fit(cars[["weight"]], cars["mpg"]) #输入是重量,输出是每加仑能跑的距离,对它进行训练
prediction = lr.predict(cars[["weight"]])#训练完后,就可以用测试数据进行测试,观察预测的输出值是多少,此处为方便仍然使用训练的数据
print (prediction[0:5])
print (cars["mpg"][0:5])
[ 19.41852276  17.96764345  19.94053224  19.96356207  19.84073631]
0    18.0
1    15.0
2    18.0
3    16.0
4    17.0
Name: mpg, dtype: float64
plt.scatter(cars["weight"],cars["mpg"],c='red')
plt.scatter(cars["weight"],prediction,c='blue')
plt.show()

这里写图片描述

from sklearn.metrics import mean_squared_error
mse = mean_squared_error(cars["mpg"],prediction)#求真实值与预测值之间的均方差
print (mse)
18.7809397346
mse**0.5 #再开根号
4.3336981591509574
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值