2017-07-03 9 views
0

私の評価のために、this linkhttps://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 boundsattachedデータセットの上位サブセット(たとえば、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と私はすべての参照を見つけることができませんので、

+0

エラーの完全なトレースを報告できますか? – FLab

+0

ここでは、エラーの完全なトレースです。 '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:インデックスが範囲外です。 –

+0

sm.OLSの呼び出しが成功したようです。 RollOls.paramsをチェックして実際に3つのエントリがあることを確認してください。 – FLab

答えて

1

私は私はあなたの問題を見つけたと思う:?sm.add_constantdocumentationから 、あなたがに設定する必要がhas_constantと呼ばれる引数があります(デフォルトはskip)。ループの反復のための基本的

has_constant : str {'raise', 'add', 'skip'} Behavior if ``data'' already has a constant. The default will return data without adding another constant. If 'raise', will raise an error if a constant is present. Using 'add' will duplicate the constant, if one is present. Has no effect for structured or recarrays. There is no checking for a constant in this case.

timeあなたの変数は、それゆえ関数が定数を追加していないと、結果としてRollOLS.paramsはわずか2エントリを持っていた、サブセットで一定でした。

temp 
Out[12]: 
     time X  Y  a   b1   b2 
541 0.16182 13 20.0 19.49  3.15289 -1.26116e-05 
542 0.16182 14 20.0  20   0 7.10543e-15 
543 0.16182 15 20.0  20 -7.45058e-09   0 

sm.add_constant(temp.loc[:,['time','X']]) 
Out[13]: 
     time X 
541 0.16182 13 
542 0.16182 14 
543 0.16182 15 

sm.add_constant(temp.loc[:,['time','X']], has_constant = 'add') 
Out[14]: 
    const  time X 
541  1 0.16182 13 
542  1 0.16182 14 
543  1 0.16182 15 

ですから、sm.add_constant機能でhas_constant = 'add'を持っていた場合は、エラーが離れて行くされていますが、回帰は意味がありませんので、行列が可逆でない可能おり、説明変数に2つの直線依存の列を持っているでしょう。

+0

ありがとうFLab。私はまだ、それがエラーなしで、例えば100行のデータセットだけを扱っていた理由を理解できません。あなたは何を意味するのですか?説明変数に2つの線形従属列があると、行列は可逆ではなくなり、回帰は意味をなさないでしょう。私は 'df ['a']'がスクリプト内で定数であると思った。 –

+1

私は、指標が541-543で初めて、時間が3回以上の観測であると思います。 2番目の点で、スニペットコードの最後の出力を見てください。基本的にはtime = 0.16182 * constなので、マトリックスのランクは2(3ではなく)です。この問題は、マルチ共線性(この場合は完璧)と呼ばれています。https://en.wikipedia.org/wiki/Multicollinearity – FLab

+0

aha、perfect and thank you。 'print(temp)'を実行すると、最後の3つの予測だけが出力され、すべての予測を出力したいのですが? –

関連する問題