模型部署

用 Python 设计机器学习工作流

Dr. Chris Anagnostopoulos

Honorary Associate Professor

一个模型 Pipeline 对象包含特征选择、模型选择、调参和拟合,被推送到生产流水线以进行预测。

用 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 设计机器学习工作流

序列化你的 Pipeline

开发环境:

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 设计机器学习工作流

序列化你的 Pipeline

生产环境:

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 设计机器学习工作流

序列化你的 Pipeline

开发环境:

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)

一个优化的工作流:特征选择与模型拟合都在同一 Pipeline 对象中。

用 Python 设计机器学习工作流

序列化你的 Pipeline

生产环境:

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

一个优化的工作流:特征选择与模型拟合都在同一 Pipeline 对象中。

用 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...