【发布时间】: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