在statsmodels OLS类中使用分类变量

时间:2019-04-18 01:45:05

标签: python pandas statsmodels

我想使用statsmodels OLS类创建一个多元回归模型。考虑以下数据集:

import statsmodels.api as sm
import pandas as pd
import numpy as np

dict = {'industry': ['mining', 'transportation', 'hospitality', 'finance', 'entertainment'],
  'debt_ratio':np.random.randn(5), 'cash_flow':np.random.randn(5) + 90} 

df = pd.DataFrame.from_dict(dict)

x = data[['debt_ratio', 'industry']]
y = data['cash_flow']

def reg_sm(x, y):
    x = np.array(x).T
    x = sm.add_constant(x)
    results = sm.OLS(endog = y, exog = x).fit()
    return results

当我运行以下代码时:

reg_sm(x, y)

我收到以下错误:

TypeError: '>=' not supported between instances of 'float' and 'str'

我尝试将industry变量转换为分类变量,但是仍然出现错误。我没办法了。

2 个答案:

答案 0 :(得分:2)

我也遇到了这个问题,需要将许多列视为类别,这使得处理dummify变得很烦人。而且转换为string对我不起作用。

对于任何寻求解决方案而又不对数据进行热编码的人, R接口提供了一种很好的方法:

import statsmodels.formula.api as smf
import pandas as pd
import numpy as np

dict = {'industry': ['mining', 'transportation', 'hospitality', 'finance', 'entertainment'],
  'debt_ratio':np.random.randn(5), 'cash_flow':np.random.randn(5) + 90} 

df = pd.DataFrame.from_dict(dict)

x = df[['debt_ratio', 'industry']]
y = df['cash_flow']

# NB. unlike sm.OLS, there is "intercept" term is included here
smf.ols(formula="cash_flow ~ debt_ratio + C(industry)", data=df).fit()

参考(仍然是dev版本): https://www.statsmodels.org/dev/example_formulas.html#categorical-variables

答案 1 :(得分:0)

您在转换为分类dtype的正确道路上。但是,将DataFrame转换为NumPy数组后,您将获得object dtype(NumPy数组总体上是一种统一的类型)。这意味着各个值仍然是str的基础,而回归肯定不会像这样。

您可能想做的就是dummify此功能。您想要维持某种分类的外观,而不是factorizing来有效地将变量视为连续的,

>>> import statsmodels.api as sm
>>> import pandas as pd
>>> import numpy as np
>>> np.random.seed(444)
>>> data = {
...     'industry': ['mining', 'transportation', 'hospitality', 'finance', 'entertainment'],
...    'debt_ratio':np.random.randn(5),
...    'cash_flow':np.random.randn(5) + 90
... }
>>> data = pd.DataFrame.from_dict(data)
>>> data = pd.concat((
...     data,
...     pd.get_dummies(data['industry'], drop_first=True)), axis=1)
>>> # You could also use data.drop('industry', axis=1)
>>> # in the call to pd.concat()
>>> data
         industry  debt_ratio  cash_flow  finance  hospitality  mining  transportation
0          mining    0.357440  88.856850        0            0       1               0
1  transportation    0.377538  89.457560        0            0       0               1
2     hospitality    1.382338  89.451292        0            1       0               0
3         finance    1.175549  90.208520        1            0       0               0
4   entertainment   -0.939276  90.212690        0            0       0               0

现在,您可以使用statsmodels可以更好地使用的dtypes。 drop_first的目的是避免使用dummy trap

>>> y = data['cash_flow']
>>> x = data.drop(['cash_flow', 'industry'], axis=1)
>>> sm.OLS(y, x).fit()
<statsmodels.regression.linear_model.RegressionResultsWrapper object at 0x115b87cf8>

最后,只有一个小指针:它有助于避免使用带有内置对象类型的名称来命名引用,例如dict