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)
在过去的半小时里,我的头一直撞在墙上,请帮忙。
您正在将预测分配给错误的变量。采用:
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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句