모델링 전 반응 변수 변환

R로 하는 Supervised Learning: 회귀

Nina Zumel and John Mount

Win-Vector, LLC

금전 데이터의 로그 변환

  • 금전적 가치: 로그 정규 분포
  • 긴 꼬리, 넓은 동적 범위 (6만~70만)
R로 하는 Supervised Learning: 회귀

로그 정규 분포

  • 평균 > 중앙값 (약 5만 vs 3.9만)
  • 평균 예측 시 일반적인 값을 과대 예측
R로 하는 Supervised Learning: 회귀

정규 분포로 돌아가기

정규 분포에서:

  • 평균 = 중앙값 (여기서: 4.53 vs 4.59)
  • 합리적인 동적 범위 (1.8 - 5.8)
R로 하는 Supervised Learning: 회귀

절차

  1. 결과 변수를 로그 변환하고 모델 적합
     model <- lm(log(y) ~ x, data = train)
    
R로 하는 Supervised Learning: 회귀

절차

  1. 결과 변수를 로그 변환하고 모델 적합
     model <- lm(log(y) ~ x, data = train)
    
  2. 로그 공간에서 예측값 계산
     logpred <- predict(model, data = test)
    
R로 하는 Supervised Learning: 회귀

절차

  1. 결과 변수를 로그 변환하고 모델 적합
     model <- lm(log(y) ~ x, data = train)
    
  2. 로그 공간에서 예측값 계산
     logpred <- predict(model, data = test)
    
  3. 예측값을 원래 공간으로 변환
     pred <- exp(logpred)
    
R로 하는 Supervised Learning: 회귀

로그 변환 결과 예측: 곱셈 오차

$log(a) + log(b) = log(ab)$

$log(a) - log(b) = log(a/b)$

  • 곱셈 오차: $pred/y$
  • 상대 오차: $(pred - y)/y = \frac{pred}{y} - 1$

곱셈 오차를 줄이면 상대 오차도 감소합니다.

R로 하는 Supervised Learning: 회귀

평균 제곱근 상대 오차

RMS 상대 오차 = $\sqrt{ \overline{ (\frac{pred-y}{y})^2 }}$

  • 로그 결과 예측 시 RMS 상대 오차 감소
  • 단, RMSE는 대체로 더 커짐
R로 하는 Supervised Learning: 회귀

예시: 소득 직접 모델링

modIncome <- lm(Income ~ AFQT + Educ, data = train)
  • AFQT: 설문 25년 전 시행된 능력 시험 점수
  • Educ: 설문 시점까지의 교육 연수
  • Income: 설문 시점의 소득
R로 하는 Supervised Learning: 회귀

모델 성능

test %>% 
+     mutate(pred = predict(modIncome, newdata = test),
+            err = pred - Income) %>%
+     summarize(rmse = sqrt(mean(err^2)),
+               rms.relerr = sqrt(mean((err/Income)^2))) 
RMSE RMS 상대 오차
36,819.39 3.295189
R로 하는 Supervised Learning: 회귀

log(Income) 모델링

modLogIncome <- lm(log(Income) ~ AFQT + Educ, data = train)
R로 하는 Supervised Learning: 회귀

모델 성능

test %>% 
+     mutate(predlog = predict(modLogIncome, newdata = test), 
+            pred = exp(predlog), 
+            err = pred - Income) %>%
+     summarize(rmse = sqrt(mean(err^2)),
+               rms.relerr = sqrt(mean((err/Income)^2)))
RMSE RMS 상대 오차
38,906.61 2.276865
R로 하는 Supervised Learning: 회귀

오차 비교

log(Income) 모델: RMS 상대 오차 작음, RMSE 큼

모델 RMSE RMS 상대 오차
Income 36,819.39 3.295189
log(Income) 38,906.61 2.276865
R로 하는 Supervised Learning: 회귀

연습해 봅시다!

R로 하는 Supervised Learning: 회귀

Preparing Video For Download...