我试图做多元线性回归。但我发现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]
为了找到初始系数,在构造线性回归时需要使用关键字
fit_intercept=False
。使用
fit_intercept=False
可防止LinearRegression
对象与x - x.mean(axis=0)
一起工作,否则它将使用y = xb + c
(并使用常量偏移量捕获平均值)或通过向x
添加1
列来等效地使用x
。顺便说一下,在1D数组上调用
transpose
没有任何效果(它会反转轴的顺序,而您只有一个)。相关问题 更多 >
编程相关推荐