カテゴリ変数のエンコーディング
同僚が LabelEncoder() を使って、信用情報データセットの各列を数値に変換しました。1 列だけ未処理のものがあり、それが申請者の信用履歴を表す credit_history です。データセットの 2 つのバージョンを用意し、比較したいと考えています。1 つは LabelEncoder() を使い、もう 1 つはワンホットエンコーディングを使います。特徴量行列は credit として用意されています。LabelEncoder() は事前に読み込まれており、pandas は pd として利用できます。
この演習はコースの一部です
Python で設計する Machine Learning ワークフロー
演習の手順
LabelEncoder()を使ってcredit_historyをエンコードします。- 結果を元のデータフレームに連結します。
- ワンホットエンコーディングのダミー変数を元のフレームに連結して、新しいデータフレームを作成します。
- ワンホットエンコーディングの方が、ラベルエンコーディングより列数が多くなることを確認します。
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
# Create numeric encoding for credit_history
credit_history_num = ____.____(
credit[____])
# Create a new feature matrix including the numeric encoding
X_num = pd.concat([X, pd.Series(____)], ____)
# Create new feature matrix with dummies for credit_history
X_hot = pd.concat(
[X, ____.____(credit[____])], ____)
# Compare the number of features of the resulting DataFrames
print(X_hot.shape[____] > X_num.shape[____])