前言
线性回归是机器学习中最简单的有监督学习算法之一,由于它非常简单,有时甚至不被认为是机器学习的一部分。当目标向量是数值时(如房价),线性回归及其扩展一直是常见且有效的预测方法。回归分析是一种基于因果分析原理的预测方法,通过分析各因素对需求结果的影响,利用历史数据,建立回归方程,再利用所得方程进行预测。本例为单因素回归。
使用的数据
数据来源于赵晓波编著的库存管理课本P28的汽车销售数据:
价格 (万元) | 销量(千辆) |
---|---|
9 | 12.23 |
9.23 | 11.7 |
9.41 | 10.21 |
9.41 | 10.21 |
9.68 | 9.60 |
9.98 | 8.72 |
10.20 | 7.70 |
10.58 | 7.10 |
10.68 | 6.61 |
10.88 | 6.10 |
10.98 | 5.82 |
11.28 | 5.50 |
11.38 | 5.23 |
11.56 | 4.65 |
11.88 | 4.20 |
12.00 | 3.50 |
Python代码
import pandas as pd
import matplotlib.pyplot as plt
import pylab
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import mean_squared_error,r2_score
from sklearn.metrics import mean_absolute_percentage_error
#数据分布的散点图
car=pd.read_csv("file.csv")
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.scatter(car.iloc[:,0],car.iloc[:,1]) #iloc基于行索引和列索引从 0 开始(index,columns)
plt.xlabel("价格")
plt.ylabel("汽车销量")
pylab.show()
car.iloc[:,0:2].corr()#计算相关系数 -1为负相关,1为正相关
#拟合一条直线
model = LinearRegression() #创建线性回归对象
feature_cols = ["price"]
x=car[feature_cols]
y=car.sales
model.fit(x,y) #拟合线性回归模型
#画图
plt.scatter(car.price,car.sales)
plt.plot(car.price,model.predict(x),color='blue')
plt.xlabel("价格")
plt.ylabel("汽车销量")
plt.savefig('线性回归-销量预测.jpg')
pylab.show()
print("截距与斜率:",model.intercept_,model.coef_) #查看截距和斜率
#截距与斜率为: 36.56335380116659 [-2.76953318]
#回归方程为Y=-2.77X+36.57
#预测
model.predict([[9.5]])
#预测结果:array([10.25278855])
#预测效果评价
y_pre = model.predict(x)
print("model score: ", model.score(x, y))
print("MAE: ", mean_absolute_error(y, y_pre))
print("MSE: ", mean_squared_error(y, y_pre))
print("RMSE: ", np.sqrt(mean_squared_error(y, y_pre)))
print("MAPE: ", (abs(y_pre-y)/ y).mean()) #或者直接使用下边一行
print("MAPE: ", mean_absolute_percentage_error(truth, prediction))
#MAPE = np.mean(np.abs((truths - predictions) / truths)) * 100 ,这个公式算出来的是%的结果
print("R^2: ", r2_score(y, y_pre))
结果
#指标评价结果:
model score: 0.978982802405129
MAE: 0.32866551360682056
MSE: 0.14336088290418628
RMSE: 0.378630272038814
MAPE: 0.04757063612534798
R^2: 0.978982802405129
参考文献
[1] https://www.yisu.com/zixun/587864.html.
[2] 赵晓波, 黄四民. 库存管理 : Inventory management[M]. 清华大学出版社, 2008.
[3] (美)Chris Albon. Python机器学习手册 : 从数据预处理到深度学习[M]. 中国工信出版集团, 2019.