カテゴリカル変数を機械学習にかけるために必要な処理方法に関するメモ
参考サイト:
▶ All about Categorical Variable Encoding
▶︎ Handling Categorical Data in Python
▶︎ Understanding Feature Engineering (Part 2) Categorical Data
▶︎ Feature Transformation for Machine Learning, a Beginners Guide
▶︎ Smarter Ways to Encode Categorical Data for Machine Learning
参考コード掲載サイト
▶ Tutorial: Categorical Encoding
▶ Preprocessing: Encode and KNN Impute All Categorical Features Fast
カテゴリカル変数の主な欠損値処理方法
- 欠損値データを捨てる
- 最頻値で埋める
- KNNやMICEで埋める
- 予測モデルを作成して埋める
カテゴリカル変数の欠損値穴埋め時の注意点
KNNやMICEでカテゴリカル変数を埋めると、2.56や1.78などfloat型の値が埋まり、カテゴリにはない値が入ってしまう。なので、埋める時は、値をnp.round()などで丸めた値を入れる。
コード例)
imputer = KNN()
# impute data and convert
encode_data = pd.DataFrame(np.round(imputer.fit_transform(impute_data)),columns = impute_data.columns)
one-hotエンコーディング使用時の注意点
- 線形回帰モデルに利用する時は、自由度を揃えるため、変数の数を「カテゴリ数−1」の数に修正する。単純に、one-hotで出来た各カテゴリの変数から一つを削除すればよい。(1カテゴリを示す変数を一つ削除しても、その他のカテゴリを示す変数たちが0ならば、そのレコードは削除した変数を示すので、一つ削除しても問題ない。)
- 一方で、判別モデル(特に分類木モデル)では、one-hotでできた全ての変数をそのまま使う。
Label Encoding使用時の注意点
- 単純にカテゴリに0,1,2...と番号を振るだけなので、名義変数に使うと各カテゴリに不要な順位付け(重み付け)がされてしまう。
- sklearnのLabelEncoderだと、数値は小さい順に0,1,2...と文字列はアルファベット順に0,1,2...と番号が振られる。
Ordinal Encoding使用時の注意点
- 順序変数の各カテゴリに順位付けを正しく行う時は、Pandasの辞書を使って各カテゴリごとに順位をつけ、mapメソッドで変換したほうが確実。sklearnのLabelEncoderを使うと勝手に番号が振られるので、順位を指定できない。(※ sklearnのLabelEncoderだと、文字列型の場合は、アルファベット順に、0,1,2...と順番が振られる。)
Label Encoderを欠損値有り変数に適用する時のコード例
# 対象データ
users = pd.read_csv('userprofile.csv')
users.head()
# -- 欠損値のある'ambience'変数をOrdinal Encodingする
from sklearn.preprocessing import OrdinalEncoder
# Create Ordinal Encoder
ambience_ord_enc = OrdinalEncoder()
# Select non-null values in ambience
ambience = users['ambience']
ambience_not_null = ambience[ambience.notnull()]
reshaped_vals = ambience_not_null.values.reshape(-1, 1)
# Encode the non-null values of ambience
encoded_vals = ambience_ord_enc.fit_transform(reshaped_vals)
# Replace the ambience column with ordinal values
users.loc[ambience.notnull(), 'ambience'] = np.squeeze(encoded_vals)
カテゴリ数がとても多いときに使うといい方法
- Binary Encoding:カテゴリの数を2進数に置き換えて、その桁数内で2進数で各カテゴリを表現する。例えばカテゴリ数が4つあれば、2進数では3桁の0,1で表現でき、各桁に変数を割り当てるので、変数の数は3になる。カテゴリ数が100ある時は、2進数では7桁で表現できるので、変数の数は7つで済む。
・コード例
0コメント