R 方差解释率($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 中的监督学习:回归

Passons à la pratique !

R 中的监督学习:回归

Preparing Video For Download...