ワークフローからパイプラインへ

Python で設計する Machine Learning ワークフロー

Dr. Chris Anagnostopoulos

Honorary Associate Professor

ワークフローを再確認

from sklearn.ensemble import RandomForestClassifier as rf
X_train, X_test, y_train, y_test = train_test_split(X, y)
grid_search = GridSearchCV(rf(), param_grid={'max_depth': [2, 5, 10]})
grid_search.fit(X_train, y_train)
depth = grid_search.best_params_['max_depth']
vt = SelectKBest(f_classif, k=3).fit(X_train, y_train)
clf = rf(max_depth=best_value).fit(vt.transform(X_train), y_train)
accuracy_score(clf.predict(vt.transform(X_test), y_test))
Python で設計する Machine Learning ワークフロー

グリッドサーチの力

max_depth を最適化:

pg = {'max_depth': [2,5,10]}
gs = GridSearchCV(rf(),  
   param_grid=pg)
gs.fit(X_train, y_train)
depth = gs.best_params_['max_depth']

深さと推定器数の全組み合わせの表。3つの値を探索し、1つが最良と判定されたことを示す。

Python で設計する Machine Learning ワークフロー

グリッドサーチの力

次に n_estimators を最適化:

pg = {'n_estimators': [10,20,30]}
gs = GridSearchCV(
   rf(max_depth=depth),  
   param_grid=pg)
gs.fit(X_train, y_train)
n_est = gs.best_params_[
    'n_estimators']

深さと推定器数の全組み合わせの表。5つの値を探索し、別の最良値が見つかったことを示す。

Python で設計する Machine Learning ワークフロー

グリッドサーチの力

max_depth と n_estimators を同時に最適化:

pg = {
   'max_depth': [2,5,10],
   'n_estimators': [10,20,30]
}
gs = GridSearchCV(rf(),  
   param_grid=pg)
gs.fit(X_train, y_train)
print(gs.best_params_) 

{'max_depth': 10, 'n_estimators': 20}

深さと推定器数の全組み合わせの表。全てを探索し、同じ最良値が見つかったことを示す。

Python で設計する Machine Learning ワークフロー

パイプライン

この図では、2つのハイパーパラメータを持つランダムフォレストが、1つのハイパーパラメータを持つ特徴選択器と矢印で接続されています。

Python で設計する Machine Learning ワークフロー

パイプライン

両方のオブジェクトが1つの箱でまとめられています。

Python で設計する Machine Learning ワークフロー

パイプライン

from sklearn.pipeline import Pipeline
pipe = Pipeline([
    ('feature_selection', SelectKBest(f_classif)), 
    ('classifier', RandomForestClassifier())
])

params = dict( feature_selection__k=[2, 3, 4], classifier__max_depth=[5, 10, 20] )
grid_search = GridSearchCV(pipe, param_grid=params) gs = grid_search.fit(X_train, y_train).best_params_
{'classifier__max_depth': 20, 'feature_selection__k': 4}
Python で設計する Machine Learning ワークフロー

パイプラインをカスタマイズする

from sklearn.metrics import roc_auc_score, make_scorer
auc_scorer = make_scorer(roc_auc_score)

grid_search = GridSearchCV(pipe, param_grid=params, scoring=auc_scorer)
Python で設計する Machine Learning ワークフロー

やりすぎに注意

params = dict(
    feature_selection__k=[2, 3, 4], 
    clf__max_depth=[5, 10, 20], 
    clf__n_estimators=[10, 20, 30] 
)
grid_search = GridSearchCV(pipe, params, cv=10)

3 x 3 x 3 x 10 = 分類器の学習270回!

Python で設計する Machine Learning ワークフロー

強化されたワークフロー

Python で設計する Machine Learning ワークフロー

Preparing Video For Download...