Python:Sklearn.linear_model.LinearRegression工作异常

2024-05-16 01:37:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图做多元线性回归。但我发现sklearn.linear_模型工作得很奇怪。这是我的代码:

import numpy as np
from sklearn import linear_model

b = np.array([3,5,7]).transpose() ## the right answer I am expecting
x = np.array([[1,6,9],   ## 1*3 + 6*5 + 7*9 = 96
              [2,7,7],   ## 2*3 + 7*5 + 7*7 = 90
              [3,4,5]])  ## 3*3 + 4*5 + 5*7 = 64
y = np.array([96,90,64]).transpose()

clf = linear_model.LinearRegression()
clf.fit([[1,6,9],
         [2,7,7],
         [3,4,5]], [96,90,64])
print clf.coef_ ## <== it gives me [-2.2  5  4.4] NOT [3, 5, 7]
print np.dot(x, clf.coef_) ## <== it gives me [ 67.4  61.4  35.4]

Tags: 模型importmodelnpit线性sklearnarray
1条回答
网友
1楼 · 发布于 2024-05-16 01:37:34

为了找到初始系数,在构造线性回归时需要使用关键字fit_intercept=False

import numpy as np
from sklearn import linear_model

b = np.array([3,5,7])
x = np.array([[1,6,9],  
              [2,7,7],   
              [3,4,5]])  
y = np.array([96,90,64])

clf = linear_model.LinearRegression(fit_intercept=False)
clf.fit(x, y)
print clf.coef_
print np.dot(x, clf.coef_)

使用fit_intercept=False可防止LinearRegression对象与x - x.mean(axis=0)一起工作,否则它将使用y = xb + c(并使用常量偏移量捕获平均值)或通过向x添加1列来等效地使用x

顺便说一下,在1D数组上调用transpose没有任何效果(它会反转轴的顺序,而您只有一个)。

相关问题 更多 >