決定係數($R^2$)

R 中的監督式學習:回歸

Nina Zumel and John Mount

Win-Vector LLC

什麼是 $R^2$?

衡量模型擬合與解釋資料的程度。

  • 介於 0–1 之間
    • 接近 1:擬合良好
    • 接近 0:不比猜平均值好
R 中的監督式學習:回歸

計算 $R^2$

$R^2$ 是「模型解釋的變異」。

$$ R^2 = 1 - \frac{RSS}{SS_{Tot}} $$

其中:

  • $RSS = \sum{(y - prediction)^2}$
    • 殘差平方和(來自模型的變異)
  • $SS_{Tot} = \sum{(y - \overline{y})^2}$
    • 總平方和(資料本身的變異)
R 中的監督式學習:回歸

計算房價模型的 $R^2$:RSS

  • 計算誤差
err <- houseprices$prediction - houseprices$price
  • 平方後加總
rss <- sum(err^2)
  • price:實際成交價欄(單位:千)
  • pred:預測成交價欄(單位:千)
  • $RSS \approx$ 136138
R 中的監督式學習:回歸

計算房價模型的 $R^2$:$SS_{Tot}$

  • 價格減去平均價格
toterr <- houseprices$price - mean(houseprices$price)
  • 平方後加總
sstot <- sum(toterr^2)
  • $RSS \approx$ 136138
  • $SS_{Tot} \approx$ 713615
R 中的監督式學習:回歸

計算房價模型的 $R^2$

(r_squared <- 1 - (rss/sstot) )
0.8092278
  • $RSS \approx$ 136138
  • $SS_{Tot} \approx$ 713615
  • $R^2 \approx$ 0.809
R 中的監督式學習:回歸

從 lm() 模型讀取 $R^2$

# From summary()
summary(hmodel)
...
Residual standard error: 60.66 on 37 degrees of freedom
Multiple R-squared:  0.8092, Adjusted R-squared:  0.7989 
F-statistic: 78.47 on 2 and 37 DF,  p-value: 4.893e-14
summary(hmodel)$r.squared
0.8092278
# From glance()
glance(hmodel)$r.squared
0.8092278
R 中的監督式學習:回歸

相關係數與 $R^2$

rho <- cor(houseprices$prediction, houseprices$price)
0.8995709
rho^2
0.8092278
  • $\rho$ = cor(prediction, price) = 0.8995709
  • $\rho^2$ = 0.8092278 = $R^2$
R 中的監督式學習:回歸

相關係數與 $R^2$

  • 適用於最小化平方誤差的模型:
    • 線性迴歸
    • GAM 迴歸
    • 以平方誤差為目標的樹模型
  • 對訓練資料成立;對未來應用資料不一定成立
R 中的監督式學習:回歸

一起來練習吧!

R 中的監督式學習:回歸

Preparing Video For Download...