回帰の R 二乗を確認する
R 二乗は、データが回帰直線にどれだけよく当てはまっているかを表します。したがって、単回帰の R 二乗は 2 つの変数間の相関と関係があります。特に、相関の大きさは R 二乗の平方根に等しく、相関の符号は回帰係数の符号と一致します。
この演習では、統計パッケージの statsmodels を使い始めます。これは、R や SAS、MATLAB のようなソフトウェアにある多くの統計モデリングや検定を実行できます。
2 つの系列 x と y の相関を計算し、続いて statsmodels.api ライブラリの関数 OLS(y,x) を使って y を x に対して回帰します(従属変数、すなわち右辺の変数である y が最初の引数である点に注意してください)。多くの線形回帰には切片(回帰 \(\small y_t=\alpha + \beta x_t + \epsilon_t\) における \(\small \alpha\))である定数項が含まれます。OLS() で定数項を含めるには、回帰の右辺に 1 の列を追加する必要があります。
statsmodels.api モジュールは sm としてインポート済みです。
この演習はコースの一部です
Pythonで学ぶ時系列解析
演習の手順
.corr()メソッドを使ってxとyの相関を計算します。- 回帰を実行します:
- まず Series の
xを DataFrame のdfxに変換します。 sm.add_constant()を使って定数項を追加し、dfx1に代入します。sm.OLS().fit()でyをdfx1に対して回帰します。
- まず Series の
- 回帰結果を出力し、R 二乗と相関を比較します。
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
# Import the statsmodels module
import statsmodels.api as sm
# Compute correlation of x and y
correlation = ___
print("The correlation between x and y is %4.2f" %(correlation))
# Convert the Series x to a DataFrame and name the column x
dfx = pd.DataFrame(x, columns=['x'])
# Add a constant to the DataFrame dfx
dfx1 = sm.add_constant(___)
# Regress y on dfx1
result = sm.OLS(___, ___).fit()
# Print out the results and look at the relationship between R-squared and the correlation above
print(result.summary())