比方说我想找到一个等式的 alpha (a) 值,它有类似的内容
y=a+ax1+ax2+...+axi
使用 OLS 假设我们从 i=2 的基本情况的 10 个值开始
#y=a+ax1+ax2
y = np.arange(1, 10)
x = np.array([[ 5, 10], [10, 5], [ 5, 15],
[15, 20], [20, 25], [25, 30],[30, 35],
[35, 5], [ 5, 10], [10, 15]])
使用 statsmodel 我通常会使用以下代码来获取 nx1 x 和 y 数组的根:
import numpy as np
import statsmodels.api as sm
X = sm.add_constant(x)
# least squares fit
model = sm.OLS(y, X)
fit = model.fit()
alpha=fit.params
但是当 x 不等于 y 时,这不起作用。等式是here如果您不知道什么是 OLS,请在第一页。
最佳答案
回溯告诉你哪里出了问题
raise ValueError("endog and exog matrices are different sizes")
ValueError: endog and exog matrices are different sizes
您的 x 有 10 个值,您的 y 有 9 个值。回归仅在两者具有相同数量的观察值时才有效。
endog 是 y,exog 是 x,这些是 statsmodels 中用于自变量和解释变量的名称。
如果您将 y
替换为
y = np.arange(1, 11)
然后一切都按预期工作。
关于python - 多元回归参数的 Statsmodels OLS 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21234539/