【问题标题】:How to set intercept to 0 with statsmodel - for multiple linear regression如何使用 statsmodel 将截距设置为 0 - 用于多元线性回归
【发布时间】:2019-01-18 15:43:34
【问题描述】:

几年前有一篇关于此的帖子,但只包括了一个快速修复。 Specifying a Constant in Statsmodels Linear Regression?

快速解决方法是先运行并减去截距方程,然后再次运行。如果你一遍又一遍地跑,那就很乏味了。

我认为您可以传递一个参数,告诉它将截距设置为零。除了 statsmodels 之外,还可以使用其他统计包。

【问题讨论】:

  • 请注意,所引用的问题是针对一个固定的非零常量,这比完全忽略截距更难做到。

标签: python pandas statsmodels


【解决方案1】:

这取决于您使用的 api。如果您使用的是statsmodels.api,那么您需要通过将1s 列添加到exog 来显式地将常量添加到您的模型中。如果你不这样做,那么就没有拦截。

import pandas as pd
import statsmodels.formula.api as smf
import statsmodels.api as sm

df = pd.DataFrame({'x': range(0,10)}).assign(y=lambda x: x+8)

# Fit y = B*x, no intercept
res1 = sm.OLS(endog=df.y, exog=df.x).fit()
==============================================================================
                 coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------
x              2.2632      0.269      8.421      0.000       1.655       2.871
==============================================================================


# fit y = B*x + C, by adding a column of ones
res2 = sm.OLS(endog=df.y, exog=df[['x']].assign(intercept=1)).fit()
==============================================================================
                 coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------
x              1.0000   8.64e-16   1.16e+15      0.000       1.000       1.000
intercept      8.0000   4.61e-15   1.73e+15      0.000       8.000       8.000
==============================================================================

如果您使用的是smf api,则可以将-1 添加到 Patsy 公式中,这将告诉它删除常量,否则包含 Intercept。

res3 = smf.ols('y ~ x -1', data=df).fit()
==============================================================================
                 coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------
x              2.2632      0.269      8.421      0.000       1.655       2.871
==============================================================================

# Default includes the constant
res4 = smf.ols('y ~ x', data=df).fit()
==============================================================================
                 coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------
Intercept      8.0000   2.72e-15   2.94e+15      0.000       8.000       8.000
x              1.0000   5.09e-16   1.96e+15      0.000       1.000       1.000
==============================================================================

【讨论】:

    猜你喜欢
    • 2016-10-23
    • 2012-05-27
    • 2018-08-01
    • 1970-01-01
    • 2016-04-16
    • 1970-01-01
    • 1970-01-01
    • 2018-01-08
    • 2022-01-09
    相关资源
    最近更新 更多