模型部署

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

Dr. Chris Anagnostopoulos

Honorary Associate Professor

一個模型管線物件包含特徵選擇、模型選擇、模型調參與模型擬合,接著推送到正式環境,使用已擬合的管線進行預測。

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

序列化你的模型

將分類器存成檔案:

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

序列化你的管線

開發環境:

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

序列化你的管線

正式環境:

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

序列化你的管線

開發環境:

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)

最佳化流程:特徵選擇與模型擬合皆封裝在單一管線物件中。

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

序列化你的管線

正式環境:

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

最佳化流程:特徵選擇與模型擬合皆封裝在單一管線物件中。

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

自訂特徵轉換

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

準備上線!

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

Preparing Video For Download...