Pickle 持久化
现在,您将首次把模型推送到生产环境。这个模型是一个随机森林分类器,您会将其作为基线模型,同时继续开发更优的替代方案。您可以使用按常规命名拆分好的训练/测试数据:X_train、X_test、y_train 和 y_test。同时已提供模块 RandomForestClassifier() 和 pickle,本练习中您需要用到其 .load() 和 .dump() 方法。
本练习是课程的一部分
用 Python 设计机器学习工作流
练习说明
- 训练一个随机森林分类器。将随机种子固定为 42,以确保结果可复现。
- 使用 pickle 将模型写入文件。使用
with open(____) as ____语法打开目标文件。 - 现在从文件中加载模型到另一个变量名
clf_from_file。 - 将加载的模型产生的预测结果保存到变量
preds中。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Fit a random forest to the training set
clf = ____(____=42).____(
X_train, y_train)
# Save it to a file, to be pushed to production
with ____('model.pkl', ____) as ____:
pickle.____(clf, file=file)
# Now load the model from file in the production environment
with ____ as file:
clf_from_file = pickle.____(file)
# Predict the labels of the test dataset
preds = clf_from_file.____