我正在努力提高我对线性回归/多元线性回归的掌握。我在YouTube上看到了这个视频,他在excel中使用了回归工具对一组数据进行线性回归。
https://www.youtube.com/watch?v=HgfHefwK7VQ&list=PLo8L7S3J29iOX0pvRqAgLDDdwobNWqG9C&index=21&t=0s
他使用预测 A、B 和 C 作为因变量的最终答案是 45149.21
。成本是自变量
这是我用来尝试复制他的结果的方法
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
# create linear regression object
lm = LinearRegression()
# develop a model using these variables as predictor variables
X = df[['A Made', 'B Made', 'C Made']]
Y = df['Cost']
# Fit the linear model using the three above-mentioned variables.
lm.fit(X , Y)
# value of the intercept
intercept = lm.intercept_
# values of the coefficients
coef = lm.coef_.tolist()
# final estimated linear model
Z = intercept + (coef[0] * 1200) + (coef[1] * 800) + (coef[2] * 1000)
吐出的预测值为
Z = 10606.098714826765
intercept = 35108.59711204488
coefficient (list) = [2.072061216849437, 4.153422708041111, 4.796887088174573]
实际数据
data = {
'Month':[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19],
'Cost':[44439,43936,44464,41533,46343,44922,43203,43000,40967,48582,45003,44303,42070,44353,45968,47781,43202,44074,44610],
'A Made':[515,929,800,979,1165,651,847,942,630,1113,1086,843,500,813,1190,1200,731,1089,786],
'B Made':[541,692,710,685,1147,939,755,908,738,1175,1075,640,752,989,823,1108,590,607,513],
'C Made':[928,711,824,758,635,901,580,589,682,1050,984,828,708,804,904,1120,1065,1132,839]
}
df = pd.DataFrame(data)
我预计预测值接近该 44000 值。我做错了什么?
编辑:松了一口气,发现过程是正确的。再次检查后,截距打印出-2值。然后我做了一些调整,我分配了一个截距值,它又回到了它应该在的位置。
感谢所有回答的人。非常感谢!
我刚刚尝试了您的代码并在刺 Z 时得到了这个:45714.69582687167
我唯一更改的是导入:from sklearn.linear_model import LinearRegression()
from sklearn.linear_model import LinearRegression
再做一次,你的过程是正确的。您无需手动提取系数和拦截。
x_test = [[1200, 800, 1000]]
y_predict = lm.predict(x_test)
输出
array([[45714.69582687]])
顺便说一句,修复from sklearn.linear_model import LinearRegression
Z = 45714.69582687167
这就是我通过运行您的代码得到的,它接近 44000
并将导入更改为
from sklearn.linear_model import LinearRegression