在statsmodels OLS类中使用分类变量

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

我想使用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变量转换为分类变量,但我仍然遇到错误。我没有选择。

python pandas statsmodels
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

现在你有dtypes,statsmodels可以更好地使用。 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

© www.soinside.com 2019 - 2024. All rights reserved.