gpt4 book ai didi

python - 在statsmodels OLS类中使用分类变量

转载 作者:行者123 更新时间:2023-12-03 15:21:40 27 4
gpt4 key购买 nike

我想使用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变量转换为分类变量,但仍然出现错误。我没办法了。

最佳答案

转换为Categorical 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

关于python - 在statsmodels OLS类中使用分类变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55738056/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com