類別變數的 One-Hot 編碼

R 中的監督式學習:回歸

Nina Zumel and John Mount

Win-Vector, LLC

為什麼要手動轉換類別?

  • 多數 R 函式會自動幫你轉換
    • model.matrix()
  • xgboost() 不會
    • 必須手動把類別變數轉成數值表示
  • 轉成指標變數:one-hot 編碼
R 中的監督式學習:回歸

用 `vtreat` 進行 one-hot 與資料清理

基本做法:

  • designTreatmentsZ() 從訓練資料設計「處理計畫」,然後
  • prepare() 產生「乾淨」資料
    • 全為數值
    • 無遺漏值
      • 對所有未來資料也用相同的處理計畫呼叫 prepare()
R 中的監督式學習:回歸

小型 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 中的監督式學習:回歸

建立處理計畫(Treatment Plan)

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

designTreatmentsZ() 的輸入:

  • dframe:訓練資料
  • varlist:輸入變數名稱清單
  • 將 verbose = FALSE 可關閉進度訊息
R 中的監督式學習:回歸

取得新變數名稱

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 中的監督式學習:回歸

為建模準備訓練資料

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

prepare() 的輸入:

  • treatmentplan:處理計畫
  • dframe:資料框
  • varRestriction:要處理的變數清單(選用)
    • 預設:處理所有變數
R 中的監督式學習:回歸

資料處理前後對照

訓練資料

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 中的監督式學習:回歸

在套用模型前準備測試資料

(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 中的監督式學習:回歸

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 中的監督式學習:回歸

一起來練習吧!

R 中的監督式學習:回歸

Preparing Video For Download...