使用 statsmodels.formula.api 的多项式回归

Mat*_*row 4 python linear-regression statsmodels

请原谅我的无知。我想要做的就是在我的回归中添加一个平方项,而无需在我的数据框中定义新列。我正在使用 statsmodels.formula.api(作为 stats),因为格式类似于我更熟悉的 R。

hours_model = stats.ols(formula='act_hours ~ h_hours + C(month) + trend', data = df).fit()
Run Code Online (Sandbox Code Playgroud)

以上按预期工作。

hours_model = stats.ols(formula='act_hours ~ h_hours + h_hours**2 + C(month) + trend', data = df).fit()
Run Code Online (Sandbox Code Playgroud)

这省略了 h_hours**2 并返回与上一行相同的输出。

我也试过:h_hours^2、math.pow(h_hours,2) 和 poly(h_hours,2) 都抛出错误。

任何帮助,将不胜感激。

Stu*_*olf 9

您可以尝试I()在 R 中使用like:

import statsmodels.formula.api as smf

np.random.seed(0)

df = pd.DataFrame({'act_hours':np.random.uniform(1,4,100),'h_hours':np.random.uniform(1,4,100),
                  'month':np.random.randint(0,3,100),'trend':np.random.uniform(0,2,100)})

model = 'act_hours ~ h_hours + I(h_hours**2)'
hours_model = smf.ols(formula = model, data = df)

hours_model.exog[:5,]

array([[ 1.        ,  3.03344961,  9.20181654],
       [ 1.        ,  1.81002392,  3.27618659],
       [ 1.        ,  3.20558207, 10.27575638],
       [ 1.        ,  3.88656564, 15.10539244],
       [ 1.        ,  1.74625943,  3.049422  ]])
Run Code Online (Sandbox Code Playgroud)