使用Pandas OLS,我可以按照如下方式拟合和使用模型:
ols_test = pd.ols(y=merged2[:-1].Units, x=merged2[:-1].lastqu) #to exclude current year, then do forecast method
yrahead=(ols_test.beta['x'] * merged2.lastqu[-1:]) + ols_test.beta['intercept']
我需要切换到statsmodels来获得一些额外的功能(主要是剩余图请参见(question here)
所以现在我有:
def fit_line2(x, y):
X = sm.add_constant(x, prepend=True) #Add a column of ones to allow the calculation of the intercept
model = sm.OLS(y, X,missing='drop').fit()
"""Return slope, intercept of best fit line."""
X = sm.add_constant(x)
return model
以及:
model=fit_line2(merged2[:-1].lastqu,merged2[:-1].Units)
print fit.summary()
但我得不到
yrahead2=model.predict(merged2.lastqu[-1:])
或者有什么变体可以给我一个预测?请注意,pd.ols使用相同的merged2.lastqu[-1:]从中获取我想要“预测”的数据,无论我在()中输入什么进行预测,我都没有任何乐趣。看起来statsmodels想要的是除了熊猫DF细胞之外的特殊的东西,我甚至试着在那里放了一个数字,例如2696,但是仍然没有。。。 我现在的错误是
----> 3 yrahead2=model.predict(merged2.lastqu[-1:])
/usr/lib/pymodules/python2.7/statsmodels/base/model.pyc in predict(self, exog, transform, *args, **kwargs)
1004 exog = np.atleast_2d(exog) # needed in count model shape[1]
1005
-> 1006 return self.model.predict(self.params, exog, *args, **kwargs)
1007
1008
/usr/lib/pymodules/python2.7/statsmodels/regression/linear_model.pyc in predict(self, params, exog)
253 if exog is None:
254 exog = self.exog
--> 255 return np.dot(exog, params)
256
257 class GLS(RegressionModel):
ValueError: objects are not aligned
> /usr/lib/pymodules/python2.7/statsmodels/regression/linear_model.py(255)predict()
254 exog = self.exog
--> 255 return np.dot(exog, params)
256
我更喜欢statsmodels的公式api。至少在这方面,
model.fit().predict
需要一个数据帧,其中的列与预测值具有相同的名称。下面是一个例子:您的
merged2.lastqu[-1:]
不包含常量yrahead2=model.predict(sm.add_constant(merged2.lastqu[-1:], prepend=True))
应该有用。
另一种方法是以与模型中的X相同的方式将常数添加到数据帧中,并使用数据帧
df[['const', my_other_X]]
的适当列相关问题 更多 >
编程相关推荐