Python:Sklearn.linear_model.LinearRegression工作很奇怪

Mac*_*nhe 4 python scikit-learn

我正在尝试做多变量线性回归.但我发现sklearn.linear_model的工作非常奇怪.这是我的代码:

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]
Run Code Online (Sandbox Code Playgroud)

eic*_*erg 11

为了找回你的初始系数,你需要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_)
Run Code Online (Sandbox Code Playgroud)

使用fit_intercept=False可以防止LinearRegression对象使用x - x.mean(axis=0),否则它将执行(并使用常量偏移捕获均值y = xb + c) - 或等效地添加一列1to x.

作为旁注,调用transpose一维数组没有任何影响(它会反转轴的顺序,而你只有一个).