Python中的多元线性回归

Zac*_*ach 119 python statistics numpy scipy linear-regression

我似乎找不到任何进行多重回归的python库.我发现的唯一的东西只做简单的回归.我需要对几个自变量(x1,x2,x3等)回归我的因变量(y).

例如,使用此数据:

print 'y        x1      x2       x3       x4      x5     x6       x7'
for t in texts:
    print "{:>7.1f}{:>10.2f}{:>9.2f}{:>9.2f}{:>10.2f}{:>7.2f}{:>7.2f}{:>9.2f}" /
   .format(t.y,t.x1,t.x2,t.x3,t.x4,t.x5,t.x6,t.x7)
Run Code Online (Sandbox Code Playgroud)

(以上输出:)

      y        x1       x2       x3        x4     x5     x6       x7
   -6.0     -4.95    -5.87    -0.76     14.73   4.02   0.20     0.45
   -5.0     -4.55    -4.52    -0.71     13.74   4.47   0.16     0.50
  -10.0    -10.96   -11.64    -0.98     15.49   4.18   0.19     0.53
   -5.0     -1.08    -3.36     0.75     24.72   4.96   0.16     0.60
   -8.0     -6.52    -7.45    -0.86     16.59   4.29   0.10     0.48
   -3.0     -0.81    -2.36    -0.50     22.44   4.81   0.15     0.53
   -6.0     -7.01    -7.33    -0.33     13.93   4.32   0.21     0.50
   -8.0     -4.46    -7.65    -0.94     11.40   4.43   0.16     0.49
   -8.0    -11.54   -10.03    -1.03     18.18   4.28   0.21     0.55
Run Code Online (Sandbox Code Playgroud)

我如何在python中回归这些,以获得线性回归公式:

Y = a1x1 + a2x2 + a3x3 + a4x4 + a5x5 + a6x6 + + a7x7 + c

Dou*_*gal 95

sklearn.linear_model.LinearRegression 会做的:

from sklearn import linear_model
clf = linear_model.LinearRegression()
clf.fit([[getattr(t, 'x%d' % i) for i in range(1, 8)] for t in texts],
        [t.y for t in texts])
Run Code Online (Sandbox Code Playgroud)

然后clf.coef_将有回归系数.

sklearn.linear_model 也有类似的接口,可以对回归进行各种规范化.

  • 这会在[某些输入]中返回错误(http://stackoverflow.com/questions/11549486/linearregression-returns-list-within-list-sklearn).还有其他解决方案吗? (2认同)
  • 跟进,你知道如何使用sklearn.linear_model.LinearRegression获得置信度吗?谢谢. (2认同)

Aka*_*all 58

这是我创建的一个小工作.我用R检查它,它的工作正常.

import numpy as np
import statsmodels.api as sm

y = [1,2,3,4,3,4,5,4,5,5,4,5,4,5,4,5,6,5,4,5,4,3,4]

x = [
     [4,2,3,4,5,4,5,6,7,4,8,9,8,8,6,6,5,5,5,5,5,5,5],
     [4,1,2,3,4,5,6,7,5,8,7,8,7,8,7,8,7,7,7,7,7,6,5],
     [4,1,2,5,6,7,8,9,7,8,7,8,7,7,7,7,7,7,6,6,4,4,4]
     ]

def reg_m(y, x):
    ones = np.ones(len(x[0]))
    X = sm.add_constant(np.column_stack((x[0], ones)))
    for ele in x[1:]:
        X = sm.add_constant(np.column_stack((ele, X)))
    results = sm.OLS(y, X).fit()
    return results
Run Code Online (Sandbox Code Playgroud)

结果:

print reg_m(y, x).summary()
Run Code Online (Sandbox Code Playgroud)

输出:

                            OLS Regression Results                            
==============================================================================
Dep. Variable:                      y   R-squared:                       0.535
Model:                            OLS   Adj. R-squared:                  0.461
Method:                 Least Squares   F-statistic:                     7.281
Date:                Tue, 19 Feb 2013   Prob (F-statistic):            0.00191
Time:                        21:51:28   Log-Likelihood:                -26.025
No. Observations:                  23   AIC:                             60.05
Df Residuals:                      19   BIC:                             64.59
Df Model:                           3                                         
==============================================================================
                 coef    std err          t      P>|t|      [95.0% Conf. Int.]
------------------------------------------------------------------------------
x1             0.2424      0.139      1.739      0.098        -0.049     0.534
x2             0.2360      0.149      1.587      0.129        -0.075     0.547
x3            -0.0618      0.145     -0.427      0.674        -0.365     0.241
const          1.5704      0.633      2.481      0.023         0.245     2.895

==============================================================================
Omnibus:                        6.904   Durbin-Watson:                   1.905
Prob(Omnibus):                  0.032   Jarque-Bera (JB):                4.708
Skew:                          -0.849   Prob(JB):                       0.0950
Kurtosis:                       4.426   Cond. No.                         38.6
Run Code Online (Sandbox Code Playgroud)

pandas 提供了一种方便的方式来运行OLS,如下面的答案所示:

使用Pandas Data Frame运行OLS回归

  • `reg_m`函数不必要地复杂化.`x = np.array(x).T`,`x = sm.add_constant(x)`和`results = sm.OLS(endog = y,exog = x).fit()`就足够了. (17认同)
  • 刚刚注意到你的x1,x2,x3在原始预测器列表中的顺序是相反的,即x = [x3,x2,x1]? (2认同)

Fra*_*urt 43

只是为了澄清,你给出的例子是多元线性回归,而不是多元线性回归参考.差异:

单个标量预测变量x和单个标量响应变量y的最简单情况称为简单线性回归.多个和/或向量值预测变量的扩展(用大写X表示)称为多元线性回归,也称为多变量线性回归.几乎所有现实世界的回归模型都涉及多个预测因子,线性回归的基本描述通常用多元回归模型来表达.但请注意,在这些情况下,响应变量y仍然是标量.另一个术语多元线性回归指的是y是矢量的情况,即与一般线性回归相同的情况.应强调多元线性回归与多变量线性回归之间的差异,因为它会在文献中引起很多混淆和误解.

简而言之:

  • 多元线性回归:响应y是标量.
  • 多元线性回归:响应y是向量.

(另一个来源.)

  • 这可能是有用的信息,但我不知道它是如何回答这个问题的. (5认同)
  • @Akavall使用正确的术语是找到答案的第一步. (5认同)

Imr*_*ran 26

你可以使用numpy.linalg.lstsq:

import numpy as np
y = np.array([-6,-5,-10,-5,-8,-3,-6,-8,-8])
X = np.array([[-4.95,-4.55,-10.96,-1.08,-6.52,-0.81,-7.01,-4.46,-11.54],[-5.87,-4.52,-11.64,-3.36,-7.45,-2.36,-7.33,-7.65,-10.03],[-0.76,-0.71,-0.98,0.75,-0.86,-0.50,-0.33,-0.94,-1.03],[14.73,13.74,15.49,24.72,16.59,22.44,13.93,11.40,18.18],[4.02,4.47,4.18,4.96,4.29,4.81,4.32,4.43,4.28],[0.20,0.16,0.19,0.16,0.10,0.15,0.21,0.16,0.21],[0.45,0.50,0.53,0.60,0.48,0.53,0.50,0.49,0.55]])
X = X.T # transpose so input vectors are along the rows
X = np.c_[X, np.ones(X.shape[0])] # add bias term
beta_hat = np.linalg.lstsq(X,y)[0]
print beta_hat
Run Code Online (Sandbox Code Playgroud)

结果:

[ -0.49104607   0.83271938   0.0860167    0.1326091    6.85681762  22.98163883 -41.08437805 -19.08085066]
Run Code Online (Sandbox Code Playgroud)

您可以通过以下方式查看估算输出:

print np.dot(X,beta_hat)
Run Code Online (Sandbox Code Playgroud)

结果:

[ -5.97751163,  -5.06465759, -10.16873217,  -4.96959788,  -7.96356915,  -3.06176313,  -6.01818435,  -7.90878145,  -7.86720264]
Run Code Online (Sandbox Code Playgroud)


Vol*_*pey 13

使用scipy.optimize.curve_fit.而且不仅仅是线性适合.

from scipy.optimize import curve_fit
import scipy

def fn(x, a, b, c):
    return a + b*x[0] + c*x[1]

# y(x0,x1) data:
#    x0=0 1 2
# ___________
# x1=0 |0 1 2
# x1=1 |1 2 3
# x1=2 |2 3 4

x = scipy.array([[0,1,2,0,1,2,0,1,2,],[0,0,0,1,1,1,2,2,2]])
y = scipy.array([0,1,2,1,2,3,2,3,4])
popt, pcov = curve_fit(fn, x, y)
print popt
Run Code Online (Sandbox Code Playgroud)


can*_*ine 8

将数据转换为pandas dataframe(df)后,

import statsmodels.formula.api as smf
lm = smf.ols(formula='y ~ x1 + x2 + x3 + x4 + x5 + x6 + x7', data=df).fit()
print(lm.params)
Run Code Online (Sandbox Code Playgroud)

截距项默认包含在内.

有关更多示例,请参阅此笔记本