R-제곱 ($R^2$)

R로 하는 Supervised Learning: 회귀

Nina Zumel and John Mount

Win-Vector LLC

$R^2$란 무엇인가?

모델이 데이터를 얼마나 잘 적합하거나 설명하는지 나타내는 지표

  • 0~1 사이의 값
    • 1에 가까울수록: 모델이 잘 적합됨
    • 0에 가까울수록: 평균값 추측과 다를 바 없음
R로 하는 Supervised Learning: 회귀

$R^2$ 계산

$R^2$는 모델이 설명하는 분산입니다.

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

여기서

  • $RSS = \sum{(y - prediction)^2}$
    • 잔차 제곱합 (모델의 분산)
  • $SS_{Tot} = \sum{(y - \overline{y})^2}$
    • 총 제곱합 (데이터의 분산)
R로 하는 Supervised Learning: 회귀

주택 가격 모델의 $R^2$ 계산: RSS

  • 오차 계산
err <- houseprices$prediction - houseprices$price
  • 제곱 후 합산
rss <- sum(err^2)
  • price: 실제 판매 가격 열 (단위: 천)
  • pred: 예측 판매 가격 열 (단위: 천)
  • $RSS \approx$ 136138
R로 하는 Supervised Learning: 회귀

주택 가격 모델의 $R^2$ 계산: $SS_{Tot}$

  • 가격과 평균 가격의 차이 계산
toterr <- houseprices$price - mean(houseprices$price)
  • 제곱 후 합산
sstot <- sum(toterr^2)
  • $RSS \approx$ 136138
  • $SS_{Tot} \approx$ 713615
R로 하는 Supervised Learning: 회귀

주택 가격 모델의 $R^2$ 계산

(r_squared <- 1 - (rss/sstot) )
0.8092278
  • $RSS \approx$ 136138
  • $SS_{Tot} \approx$ 713615
  • $R^2 \approx$ 0.809
R로 하는 Supervised Learning: 회귀

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로 하는 Supervised Learning: 회귀

상관관계와 $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로 하는 Supervised Learning: 회귀

상관관계와 $R^2$

  • 제곱 오차를 최소화하는 모델에서 성립:
    • 선형 회귀
    • GAM 회귀
    • 제곱 오차를 최소화하는 트리 기반 알고리즘
  • 훈련 데이터에서만 성립; 미래 적용 데이터에서는 성립하지 않음
R로 하는 Supervised Learning: 회귀

연습해 봅시다!

R로 하는 Supervised Learning: 회귀

Preparing Video For Download...