觀察迴歸的 R-squared
R-squared 衡量資料與迴歸線的貼合程度,因此在簡單迴歸中,R-squared 與兩個變數之間的相關係數有關。特別是,相關係數的大小等於 R-squared 的平方根,而相關係數的正負號與迴歸係數的正負相同。
在這個練習中,你會開始使用統計套件 statsmodels。它能執行許多在 R 與 SAS、MATLAB 等軟體中常見的統計建模與檢定。
你將取兩個序列 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轉為 DataFramedfx。 - 使用
sm.add_constant()加入常數項,指定為dfx1。 - 使用
sm.OLS().fit()將y對dfx1做迴歸。
- 先將 Series
- 列印迴歸結果,並比較 R-squared 與相關係數。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# 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())