【发布时间】:2017-07-03 13:23:48
【问题描述】:
对于我的评估,我想为this link (https://drive.google.com/drive/folders/0B2Iv8dfU4fTUMVFyYTEtWXlzYkk) 中找到的数据集运行 3 个窗口 OLS regression estimation 的滚动示例,格式如下。我数据集中的第三列 (Y) 是我的真实值 - 这就是我想要预测(估计)的值。
time X Y
0.000543 0 10
0.000575 0 10
0.041324 1 10
0.041331 2 10
0.041336 3 10
0.04134 4 10
...
9.987735 55 239
9.987739 56 239
9.987744 57 239
9.987749 58 239
9.987938 59 239
使用简单的OLS regression estimation,我用下面的脚本试了一下。
# /usr/bin/python -tt
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
df = pd.read_csv('estimated_pred.csv')
model = pd.stats.ols.MovingOLS(y=df.Y, x=df[['X']],
window_type='rolling', window=3, intercept=True)
df['Y_hat'] = model.y_predict
print(df['Y_hat'])
print (model.summary)
df.plot.scatter(x='X', y='Y', s=0.1)
但是,使用statsmodels 或scikit-learn 似乎是超越简单回归的不错选择。我尝试使用statsmodels 使以下脚本工作,但使用attached 数据集的更高子集返回IndexError: index out of bounds(例如,对于超过1000 行的数据集)。
# /usr/bin/python -tt
import pandas as pd
import numpy as np
import statsmodels.api as sm
df=pd.read_csv('estimated_pred.csv')
df=df.dropna() # to drop nans in case there are any
window = 3
#print(df.index) # to print index
df['a']=None #constant
df['b1']=None #beta1
df['b2']=None #beta2
for i in range(window,len(df)):
temp=df.iloc[i-window:i,:]
RollOLS=sm.OLS(temp.loc[:,'Y'],sm.add_constant(temp.loc[:,['time','X']])).fit()
df.iloc[i,df.columns.get_loc('a')]=RollOLS.params[0]
df.iloc[i,df.columns.get_loc('b1')]=RollOLS.params[1]
df.iloc[i,df.columns.get_loc('b2')]=RollOLS.params[2]
#The following line gives us predicted values in a row, given the PRIOR row's estimated parameters
df['predicted']=df['a'].shift(1)+df['b1'].shift(1)*df['time']+df['b2'].shift(1)*df['X']
print(df['predicted'])
#print(df['b2'])
#print(RollOLS.predict(sm.add_constant(predict_x)))
print(temp)
最后,我想做一个Y的预测(即根据X的前3个滚动值预测Y的当前值。我们如何使用statsmodels或@987654337来做到这一点@ for pd.stats.ols.MovingOLS 已在 Pandas 版本 0.20.0 中删除,因为我找不到任何参考?
【问题讨论】:
-
你能报告错误的完整跟踪吗?
-
当然。这是错误的完整跟踪。
File用于换行:Traceback (most recent call last): File "../Desktop/rolling_regression/rolling_regression2.py", line 26, in <module> df.iloc[i,df.columns.get_loc('b2')]=RollOLS.params[2] File "../anaconda/lib/python3.5/site-packages/pandas/indexes/base.py", line 1986, in get_value return tslib.get_value_box(s, key) File "pandas/tslib.pyx", line 777, in pandas.tslib.get_value_box (pandas/tslib.c:17017) File "pandas/tslib.pyx", line 793, in pandas.tslib.get_value_box (pandas/tslib.c:16774) IndexError: index out of bounds -
看起来对 sm.OLS 的调用成功了。请检查/显示 RollOls.params 以确保它实际上有 3 个条目。
-
是的。它实际上只适用于数据集的几行(例如:500 行)-
IndexError: index out of bounds错误发生在我尝试使用更高的数据集子集(比如说 1000)时。 -
我可以建议使用 %debug 和 "u" 去跟踪,这样你就可以看到错误是否发生在你这样做:RollOLS.params[2] 或当你做 df. iloc[i,df.columns.get_loc('b2')] 。无论如何,错误发生在循环的最后一行,这是与使用错误索引访问有关的错误,与 sm.OLS 无关
标签: python python-3.x numpy scikit-learn statsmodels