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

问题描述 投票:1回答:1

请原谅我的无知。我要做的就是在我的回归中添加平方项,而不用麻烦在数据框中定义新列。我使用的是statsmodels.formula.api(作为统计信息),因为格式类似于R,我对此更为熟悉。

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

以上工作正常。

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

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

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

任何帮助将不胜感激。

python linear-regression statsmodels
1个回答
1
投票

您可以像在R中一样尝试使用I()

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  ]])
© www.soinside.com 2019 - 2024. All rights reserved.