python 统计模型 - 回归中的二次项 [英] python stats models - quadratic term in regression

查看:45
本文介绍了python 统计模型 - 回归中的二次项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下线性回归:

import statsmodels.formula.api as sm

model = sm.ols(formula = 'a ~ b + c', data = data).fit()

我想在这个模型中为 b 添加一个二次项.

I want to add a quadratic term for b in this model.

是否有一种简单的方法可以使用 statsmodels.ols 做到这一点?
我应该使用更好的软件包来实现这一目标吗?

Is there a simple way to do this with statsmodels.ols?
Is there a better package I should be using to achieve this?

推荐答案

虽然 Alexander 的解决方案有效,但在某些情况下并不是很方便.例如,每次要预测新值的模型结果时,您都需要记住同时传递 b**2 和 b 值,这很麻烦,应该没有必要.尽管 patsy 不能识别符号b**2",但它可以识别 numpy 函数.因此,您可以使用

Although the solution by Alexander is working, in some situations it is not very convenient. For example, each time you want to predict the outcome of the model for new values, you need to remember to pass both b**2 and b values which is cumbersome and should not be necessary. Although patsy does not recognize the notation "b**2", it does recognize numpy functions. Thus, you can use

import statsmodels.formula.api as sm
import numpy as np

data = {"a":[2, 3, 5], "b":[2, 3, 5], "c":[2, 3, 5]}
model = sm.ols(formula = 'a ~ np.power(b, 2) + b + c', data = data).fit()

这样,后者就可以重用这个模型,而无需为 b**2 指定值

In this way, latter, you can reuse this model without the need to specify a value for b**2

model.predict({"a":[1, 2], "b":[5, 2], "c":[2, 4]})

这篇关于python 统计模型 - 回归中的二次项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆