木ベースの特徴選択

Pythonで学ぶ次元削減

Jeroen Boeye

Head of Machine Learning, Faktion

ランダムフォレスト分類器

ランダムフォレストの模式図

Pythonで学ぶ次元削減

ランダムフォレスト分類器

from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score

rf = RandomForestClassifier()

rf.fit(X_train, y_train)

print(accuracy_score(y_test, rf.predict(X_test)))
0.99
Pythonで学ぶ次元削減

ランダムフォレスト分類器

注釈付きランダムフォレスト模式図

Pythonで学ぶ次元削減

特徴量重要度

rf = RandomForestClassifier()

rf.fit(X_train, y_train)

print(rf.feature_importances_)
array([0.  , 0.  , 0.  , 0.  , 0.  , 0.  , 0.  , 0.04, 0.  , 0.01, 0.01,
       0.  , 0.  , 0.  , 0.  , 0.01, 0.01, 0.  , 0.  , 0.  , 0.  , 0.05,
       ...
       0.  , 0.14, 0.  , 0.  , 0.  , 0.06, 0.  , 0.  , 0.  , 0.  , 0.  ,
       0.  , 0.07, 0.  , 0.  , 0.01, 0.  ])
print(sum(rf.feature_importances_))
1.0
Pythonで学ぶ次元削減

重要度による特徴選択

mask = rf.feature_importances_ > 0.1

print(mask)
array([False, False, ..., True, False])
X_reduced = X.loc[:, mask]

print(X_reduced.columns)
Index(['chestheight', 'neckcircumference', 'neckcircumferencebase',
       'shouldercircumference'], dtype='object')
Pythonで学ぶ次元削減

ランダムフォレストでのRFE

from sklearn.feature_selection import RFE

rfe = RFE(estimator=RandomForestClassifier(), 
          n_features_to_select=6, verbose=1)

rfe.fit(X_train,y_train)
94 個の特徴で推定器を学習中。
93 個の特徴で推定器を学習中
...
8 個の特徴で推定器を学習中。
7 個の特徴で推定器を学習中。
print(accuracy_score(y_test, rfe.predict(X_test))
0.99
Pythonで学ぶ次元削減

ランダムフォレストでのRFE

from sklearn.feature_selection import RFE

rfe = RFE(estimator=RandomForestClassifier(), 
          n_features_to_select=6, step=10, verbose=1)

rfe.fit(X_train,y_train)
94 個の特徴で推定器を学習中。
84 個の特徴で推定器を学習中。
...
24 個の特徴で推定器を学習中。
14 個の特徴で推定器を学習中。
print(X.columns[rfe.support_])
Index(['biacromialbreadth', 'handbreadth', 'handcircumference', 
       'neckcircumference', 'neckcircumferencebase', 'shouldercircumference'], dtype='object')
Pythonで学ぶ次元削減

練習してみましょう!

Pythonで学ぶ次元削減

Preparing Video For Download...