私の評価のために、this link(https://drive.google.com/drive/folders/0B2Iv8dfU4fTUMVFyYTEtWXlzYkk)にあるデータセットに対して、ローリングを3つのウィンドウOLS regression estimation
として実行したいとします。私のデータセットの3番目の列(Y)は私の本当の価値です - それが私が予測したい(推定する)ものです。PythonでのOLSローリング回帰 - IndexError:インデックスの範囲外
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
を使用してIndexError: index out of bounds
のattachedデータセットの上位サブセット(たとえば、1000行以上のデータセット)をreturingして、次のスクリプトを動作させようとしました。
# /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)
最後に、私はどのように我々はpd.stats.ols.MovingOLS
ためstatsmodels
またはscikit-learn
のいずれかを使用してこれを行うことができます。Y
の予測をしたい(すなわちX
の前の3ローリング値に応じてY
の現在の値を予測を除去しましたPandas
バージョン0.20.0と私はすべての参照を見つけることができませんので、
エラーの完全なトレースを報告できますか? – FLab
ここでは、エラーの完全なトレースです。 'File'は改行用です:' Traceback(直近の最後の呼び出し): ファイル "../Desktop/rolling_regression/rolling_regression2.py"、行26、 df.iloc [i、df.columns.get_loc 'b2')] = RollOLS.params [2] ファイル "../anaconda/lib/python3.5/site-packages/pandas/indexes/base.py"、1986行目、get_value 戻り値tslib.get_value_box s、key) pandas.tslib.get_value_box(pandas/tslib.c:17017)のファイル "pandas/tslib.pyx" 777行 pandas.tslibのファイル "pandas/tslib.pyx"(793行目)。 get_value_box(pandas/tslib.c:16774) IndexError:インデックスが範囲外です。 –
sm.OLSの呼び出しが成功したようです。 RollOls.paramsをチェックして実際に3つのエントリがあることを確認してください。 – FLab