カテゴリ変数のOne-Hotエンコーディング

R による Supervised Learning:回帰

Nina Zumel and John Mount

Win-Vector, LLC

なぜ手動でカテゴリ変数を変換するのか?

  • ほとんどのR関数は自動的に変換を行う
    • model.matrix()
  • xgboost()は自動変換しない
    • カテゴリ変数を数値表現に変換する必要がある
  • インジケータへの変換:one-hotエンコーディング
R による Supervised Learning:回帰

`vtreat`によるOne-Hotエンコーディングとデータクリーニング

基本的な考え方:

  • 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

新しいlev変数とclean変数の名前を取得する

(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...