【问题标题】:Python: Sklearn.linear_model.LinearRegression working weirdPython:Sklearn.linear_model.LinearRegression 工作很奇怪
【发布时间】:2014-08-15 02:55:50
【问题描述】:

我正在尝试进行多变量线性回归。但我发现 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]

【问题讨论】:

    标签: python scikit-learn


    【解决方案1】:

    为了找回你的初始系数,你需要在构建线性回归时使用关键字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 捕获平均值) - 或等效地通过将1 列添加到x.

    顺便说一句,对一维数组调用 transpose 没有任何效果(它会颠倒轴的顺序,而您只有一个)。

    【讨论】:

    • 非常感谢!你怎么会注意到这样的细节!
    猜你喜欢
    • 2011-05-07
    • 1970-01-01
    • 2016-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-26
    • 2020-08-06
    • 2017-06-30
    相关资源
    最近更新 更多