モデルのデプロイ

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

Dr. Chris Anagnostopoulos

Honorary Associate Professor

特徴選択・モデル選定・チューニング・学習を含むパイプラインを本番に投入し、予測に利用する流れ。

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

モデルのシリアライズ

分類器をファイルに保存:

import pickle
clf = RandomForestClassifier().fit(X_train, y_train)
with open('model.pkl', 'wb') as file:
    pickle.dump(clf, file=file)

ファイルから再読み込み:

with open('model.pkl', 'rb') as file:
    clf2 = pickle.load(file)
Python で設計する Machine Learning ワークフロー

パイプラインのシリアライズ

開発環境:

vt = SelectKBest(f_classif).fit(
    X_train, y_train)
clf = RandomForestClassifier().fit(
    vt.transform(X_train), y_train)
with open('vt.pkl', 'wb') as file: 
     pickle.dump(vt)
with open('clf.pkl', 'wb') as file: 
     pickle.dump(clf)

特徴選択器と学習済みモデルを別々に本番へ渡す必要があるワークフロー。

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

パイプラインのシリアライズ

本番環境:

with open('vt.pkl', 'rb') as file: 
    vt = pickle.load(vt)
with open('clf.pkl', 'rb') as file: 
    clf = pickle.load(clf)
clf.predict(vt.transform(X_new))

特徴選択器と学習済みモデルを別々に本番へ渡す必要があるワークフロー。

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

パイプラインのシリアライズ

開発環境:

pipe = Pipeline([
    ('fs', SelectKBest(f_classif)), 
    ('clf', RandomForestClassifier())
])
params = dict(fs__k=[2, 3, 4],
    clf__max_depth=[5, 10, 20])
gs = GridSearchCV(pipe, params)
gs = gs.fit(X_train, y_train)

with open('pipe.pkl', 'wb') as file: pickle.dump(gs, file)

特徴選択とモデル学習を1つのパイプラインにまとめた最適化ワークフロー。

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

パイプラインのシリアライズ

本番環境:

with open('pipe.pkl', 'rb') as file:
   gs = pickle.dump(gs, file)
gs.predict(X_test)

特徴選択とモデル学習を1つのパイプラインにまとめた最適化ワークフロー。

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

カスタム特徴量変換

   checking_status  duration       ...        own_telephone  foreign_worker
0                1         6       ...                    1               1
1                0        48       ...                    0               1
def negate_second_column(X):
    Z = X.copy()
    Z[:,1] = -Z[:,1]
    return Z
pipe = Pipeline([('ft', FunctionTransformer(negate_second_column)), 
    ('clf', RandomForestClassifier())])
Python で設計する Machine Learning ワークフロー

本番準備完了!

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

Preparing Video For Download...