OLS②
引き続き、エコノメ最強の技OLSをPythonで。
今回はpandasのols関数を使って、前回と同じ下記の簡単な回帰式を推定する。
# -*- coding: utf-8 -*- import matplotlib.pyplot as plt import numpy as np import seaborn as sns import statsmodels.api as sm #サンプリング数 N=1000 #データ生成 np.random.seed(0) x=np.random.normal(1,1,N) eps=np.random.normal(0,1,N) y=2+1.5*x+eps #OLS(pandas) #x=pd.DataFrame(x) #y=pd.DataFrame(y) #pd.olsはDataFrameは受け付けてくれないようなのでSeriesに変換する x=pd.Series(x) y=pd.Series(y) model = pd.ols(y=y, x=x, intercept=True) model plt.plot(model.resid)
結果は、乱数の種をそろえているため当然ながら前回の結果と完全一致する。サマリーの情報は、statsmodelのほうが充実している模様。
In [141]: model Out[141]: -------------------------Summary of Regression Analysis------------------------- Formula: Y ~ <x> + <intercept> Number of Observations: 1000 Number of Degrees of Freedom: 2 R-squared: 0.6919 Adj R-squared: 0.6916 Rmse: 0.9686 F-stat (1, 998): 2240.9410, p-value: 0.0000 Degrees of Freedom: model 1, resid 998 -----------------------Summary of Estimated Coefficients------------------------ Variable Coef Std Err t-stat p-value CI 2.5% CI 97.5% -------------------------------------------------------------------------------- x 1.4691 0.0310 47.34 0.0000 1.4083 1.5299 intercept 2.0431 0.0426 47.94 0.0000 1.9596 2.1267 ---------------------------------End of Summary---------------------------------
推定結果が詰まったオブジェクトのメソッドを呼ぶことによって、他にも色々と情報が取れる。例えば、残差はよく見たくなるが、以下のようにすればその系列が取れる。この辺はRのlmと似たような感じか。
In [144]: plt.plot(model.resid) Out[144]: [<matplotlib.lines.Line2D at 0x19566b70>]