범주형 변수의 원-핫 인코딩

R로 하는 Supervised Learning: 회귀

Nina Zumel and John Mount

Win-Vector, LLC

범주형 변수를 수동으로 변환하는 이유

  • 대부분의 R 함수는 변환을 자동으로 처리합니다
    • model.matrix()
  • xgboost()는 자동 처리하지 않습니다
    • 범주형 변수를 수치형으로 직접 변환해야 합니다
  • 지시자 변수로의 변환: 원-핫 인코딩
R로 하는 Supervised Learning: 회귀

`vtreat`를 이용한 원-핫 인코딩 및 데이터 정제

기본 개념:

  • designTreatmentsZ()로 훈련 데이터에서 처리 계획 설계 후
  • prepare()로 "정제된" 데이터 생성
    • 모두 수치형
    • 결측값 없음
      • 이후 모든 데이터에 처리 계획과 함께 prepare() 사용
R로 하는 Supervised Learning: 회귀

간단한 vtreat 예시

훈련 데이터

x u y
one 44 0.4855671
two 24 1.3683726
three 66 2.0352837
two 22 1.6396267

테스트 데이터

x u y
one 5 2.6488148
three 12 1.5012938
one 56 0.1993731
two 28 1.2778516
R로 하는 Supervised Learning: 회귀

처리 계획 생성

vars <- c("x", "u")
treatplan <- designTreatmentsZ(dframe, varslist, verbose = FALSE)

designTreatmentsZ() 입력값

  • dframe: 훈련 데이터
  • varlist: 입력 변수 이름 목록
  • verbose = FALSE로 설정하여 진행 메시지 표시 안 함
R로 하는 Supervised Learning: 회귀

새 변수 가져오기

scoreFrame은 변수 매핑과 유형을 나타냅니다

(scoreFrame <- treatplan$scoreFrame %>% 
     select(varName, origName, code))
        varName origName  code
1   x_lev_x.one        x   lev
2 x_lev_x.three        x   lev
3   x_lev_x.two        x   lev
4        x_catP        x  catP
5       u_clean        u clean

새로운 levclean 변수 이름 가져오기

(newvars <- scoreFrame %>% 
     filter(code %in% c("clean", "lev")) %>%
     use_series(varName))
"x_lev_x.one"   "x_lev_x.three" "x_lev_x.two"   "u_clean"
R로 하는 Supervised Learning: 회귀

모델링을 위한 훈련 데이터 준비

training.treat <- prepare(treatmentplan, dframe, varRestriction = newvars)

prepare() 입력값:

  • treatmentplan: 처리 계획
  • dframe: 데이터 프레임
  • varRestriction: 준비할 변수 목록 (선택 사항)
    • 기본값: 모든 변수 준비
R로 하는 Supervised Learning: 회귀

데이터 처리 전후 비교

훈련 데이터

x u y
one 44 0.4855671
two 24 1.3683726
three 66 2.0352837
two 22 1.6396267

처리된 훈련 데이터

x_lev _x. one x_lev _x. three x_lev _x. two u_clean
1 0 0 44
0 0 1 24
0 1 0 66
0 0 1 22
R로 하는 Supervised Learning: 회귀

모델 적용 전 테스트 데이터 준비

(test.treat <- prepare(treatplan, test, varRestriction = newvars))
  x_lev_x.one x_lev_x.three x_lev_x.two u_clean
1           1             0           0       5
2           0             1           0      12
3           1             0           0      56
4           0             0           1      28
R로 하는 Supervised Learning: 회귀

vtreat 처리의 견고성

이전에 없던 x 수준: four

x u y
one 4 0.2331301
two 14 1.9331760
three 66 3.1251029
four 25 4.0332491

four는 (0, 0, 0)으로 인코딩됩니다

prepare(treatplan, toomany, ...)
x_lev _x. one x_lev _x. three x_lev _x. two u_clean
1 0 0 4
0 0 1 14
0 1 0 66
0 0 0 25
R로 하는 Supervised Learning: 회귀

연습해 봅시다!

R로 하는 Supervised Learning: 회귀

Preparing Video For Download...