【问题标题】:Statsmodels OLS terms undefinedStatsmodels OLS 术语未定义
【发布时间】:2021-09-20 13:22:03
【问题描述】:

我正在尝试做一个基本的线性回归示例,并且我有一个带有 sepal_length、sepal_width、petal_length、petal_width 的示例数据集。但是,在我的 R 论坛中,如果我尝试使用比 "sepal_length ~ petal_length" 更多的术语(例如 "sepal_length ~ petal_length + sepal_width + petal_width")我会收到错误 NameError: name 'sepal_width' is not defined 这发生在我使用 + 运算符从数据集中添加第三列的任何术语中。如果我独立添加它们,这些列就会起作用。我做错了什么?

代码如下:

irises = pd.read_csv("data/iris.csv")
model1 = sm.OLS.from_formula("sepal_length ~ petal_length", data=irises).fit()
print(model1.summary())
xs = pd.DataFrame({'petal_length': np.linspace(irises.petal_length.min(), irises.petal_length.max(), 100)})
ys = model1.predict(xs)
sns.scatterplot(x='petal_length', y='sepal_length', data=irises)
plt.plot(xs, ys, color='black', linewidth=4)
plt.show()

例如,

这行得通:

model1 = sm.OLS.from_formula("sepal_length ~ petal_length", data=irises).fit()

这不起作用:

model1 = sm.OLS.from_formula("sepal_length ~ petal_length + sepal_width", data=irises).fit()

我收到错误 sepal_width 未定义。对于我这样添加的任何术语,我都会遇到相同的错误。

但这确实有效:

model1 = sm.OLS.from_formula("sepal_length ~ sepal_width", data=irises).fit()

这也是如此:

model1 = sm.OLS.from_formula("sepal_length ~ petal_length + np.power(petal_length, 2)", data=irises).fit()

本质上,我试图在sm.OLS.from_formula 中使用两个以上的自变量。

【问题讨论】:

  • irises 数据框中的列名是什么?
  • 萼片长度、萼片宽度、花瓣长度、花瓣宽度和物种。

标签: python statsmodels


【解决方案1】:

尝试将 statsmodels.api 作为 sm 导入,我成功了。

【讨论】:

  • 我遇到的问题是在 OLS.from_formula 中使用的不仅仅是两个自变量
  • 我让它还在工作,检查 sm、numpy 和 pandas 的版本。尝试更新到最新版本。 pip install -U statsmodels pandas numpy
猜你喜欢
  • 2018-10-17
  • 2020-11-23
  • 2023-02-15
  • 2015-12-31
  • 2016-01-08
  • 2021-03-26
  • 2017-11-02
  • 2021-10-05
  • 1970-01-01
相关资源
最近更新 更多