Python 使用statsmodels.formula.api的多项式回归
请原谅我的无知。我所要做的就是在我的回归中添加一个平方项,而不必在我的数据框架中定义一个新的列。我使用statsmodels.formula.api(作为stats),因为其格式类似于我更熟悉的RPython 使用statsmodels.formula.api的多项式回归,python,linear-regression,statsmodels,Python,Linear Regression,Statsmodels,请原谅我的无知。我所要做的就是在我的回归中添加一个平方项,而不必在我的数据框架中定义一个新的列。我使用statsmodels.formula.api(作为stats),因为其格式类似于我更熟悉的R hours_model = stats.ols(formula='act_hours ~ h_hours + C(month) + trend', data = df).fit() 以上工作如预期 hours_model = stats.ols(formula='act_hours ~ h_hour
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_小时**2,并返回与上一行相同的输出
我也试过:h_hours^2,math.pow(h_hours,2),和poly(h_hours,2)
都会抛出错误
任何帮助都将不胜感激。您可以尝试使用I()
如R:
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 ]])
h_小时数
值的数据类型是什么?如果它被视为分类的,那么您需要转换为浮点型或其他被patsy视为数字的类型。请查看sklearn.preprocessing.PolynomialFeatures,它会有所帮助。@Josef,谢谢您的回答。df['h_hours']的数据类型是float64。@GIRISHkuniyal,谢谢。我调查过了,但我认为这不适合我正在尝试的。我只是在找一个没有任何交互作用的平方项。谢谢!这就成功了。我已将您的答案标记为正确,但由于我的代表原因,无法投票。对不起!