融会贯通
在心律失常检测初创项目中,您对自己的流水线有两个担忧:
- 应用在各年龄段患者的数据上训练,但主要由偏年轻的健身用户使用。您怀疑这是领域偏移(domain shift),因此想忽略所有年龄超过 50 岁的样本。
- 您仍担心过拟合,所以想看看让随机森林分类器更简单一些并选择部分特征,是否能有所帮助。
您将创建一个包含特征选择步骤 SelectKBest() 和 RandomForestClassifier 的流水线,两者都已导入。您也可以使用 GridSearchCV()、Pipeline、将 numpy 作为 np,以及 pickle。数据存为 arrh。
本练习是课程的一部分
用 Python 设计机器学习工作流
练习说明
- 创建一个流水线,使用
SelectKBest()作为步骤ft,RandomForestClassifier()作为步骤clf。 - 创建参数网格以同时调优
SelectKBest()的k和RandomForestClassifier()的max_depth。 - 使用
GridSearchCV()在仅包含年龄小于 50 岁样本的数据上优化您的流水线。 - 将优化后的流水线保存为用于生产的 pickle 文件。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Create a pipeline
pipe = Pipeline([
('ft', ____), ('clf', ____(random_state=2))])
# Create a parameter grid
grid = {'ft__k':[5, 10], '____':[10, 20]}
# Execute grid search CV on a dataset containing under 50s
grid_search = ____(pipe, param_grid=grid)
arrh = arrh.____[____(arrh['age'] < 50)]
____.____(arrh.drop('class', 1), arrh['class'])
# Push the fitted pipeline to production
with ____('pipe.pkl', ____) as file:
pickle.dump(____, file)