從工作流程到管線

在 Python 設計機器學習工作流程

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 設計機器學習工作流程

Grid search 的威力

最佳化 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']

列出 depth 與 estimators 數量的所有組合表格;已探索 3 個值,並找到最佳者。

在 Python 設計機器學習工作流程

Grid search 的威力

接著最佳化 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']

列出 depth 與 estimators 數量的所有組合表格;已探索 5 個值,並找到另一個最佳者。

在 Python 設計機器學習工作流程

Grid search 的威力

同時調 max_depthn_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}

列出 depth 與 estimators 數量的所有組合表格;已探索所有值,且最佳結果相同。

在 Python 設計機器學習工作流程

管線(Pipelines)

此圖中,含兩個超參數的 random forest 透過箭頭連到含一個超參數的特徵選擇器。

在 Python 設計機器學習工作流程

管線(Pipelines)

兩個物件被同一個外框包起來。

在 Python 設計機器學習工作流程

管線(Pipelines)

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 設計機器學習工作流程

自訂你的管線

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 設計機器學習工作流程

別過度追求

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 設計機器學習工作流程

加速你的工作流程

在 Python 設計機器學習工作流程

Preparing Video For Download...