微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

python – Pandas Statsmodels使用DF预测器进行回归预测?

使用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 

解决方法:

你的merged2.lastqu [-1:]不包含常量

yrahead2 = model.predict(sm.add_constant(merged2.lastqu [-1:],prepend = True))

应该管用.

另一种方法是以与模型中X相同的方式将常量添加到数据框中,并使用数据框的相应列df [[‘const’,my_other_X]]

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐