【问题标题】:Getting error: Shapes not aligned, with statsmodels and simple 2 dimensional linear regression出现错误:形状未对齐,带有 statsmodels 和简单的二维线性回归
【发布时间】:2020-12-12 22:03:35
【问题描述】:
import numpy as np
import statsmodels.api as sm


list21 = [-0.77, -0.625, -0.264, 0.888, 1.8, 2.411, 2.263, 2.23, 1.981, 2.708]
list23 = [-1.203, -1.264, -1.003, -0.388, -0.154, -0.129, -0.282, -0.017, -0.06, 0.275]

X1 = np.asarray(list21)
Y1 = np.asarray(list23)
    
x = X1.reshape(-1, 1)
y = Y1.reshape(-1, 1)

   
model = sm.OLS(x, y)
fit = model.fit()

y_pred = model.predict(x)

错误读作:

--> 161     y_pred = model.predict(x)

ValueError: shapes (10,1) and (10,1) not aligned: 1 (dim 1) != 499 (dim 0)

过去半小时我的头一直在撞墙,请帮忙。

【问题讨论】:

  • 除此之外:statsmodels 要求将因变量或结果变量放在首位,即OLS(y, x)

标签: python numpy statsmodels


【解决方案1】:

您将预测分配给错误的变量。使用:

model = sm.OLS(x, y)
fit = model.fit()
y_pred = fit.predict(x)

或者使用

model = sm.OLS(x, y).fit()
y_pred = model.predict(x)

在任何一种情况下:将 predict 分配给与 fit() 一起使用的变量

编辑

回答你的问题为什么这条线会通过零:你没有定义一个截距,你可以用 sm.add_constant 来做。请参考此文档:https://www.statsmodels.org/dev/examples/notebooks/generated/ols.html

应用到你得到的代码:

import numpy as np
import statsmodels.api as sm
import matplotlib.pyplot as plt

list21 = [-0.77, -0.625, -0.264, 0.888, 1.8, 2.411, 2.263, 2.23, 1.981, 2.708]
list23 = [-1.203, -1.264, -1.003, -0.388, -0.154, -0.129, -0.282, -0.017, -0.06, 0.275]

x = np.asarray(list21)
y = np.asarray(list23)
X = sm.add_constant(x)
model = sm.OLS(y,X)
results = model.fit()
y_pred = results.predict(X)
plt.scatter(list21,list23)
plt.plot(x,y_pred)

【讨论】:

  • 是的,谢谢。你知道为什么我的线在 y 轴上只通过 0 吗?即使我更改列表,它也总是通过零。那真的不是应该发生的事情。我的其他回归线没有这样做。
  • 请检查我的编辑。我修改了您的示例,以便您可以了解如何使用 ols 获得正确的回归线。 :)
猜你喜欢
  • 2022-08-03
  • 2019-05-11
  • 2017-05-07
  • 1970-01-01
  • 2018-02-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-13
相关资源
最近更新 更多