再次构建您的第一个管道!
回到心律失常创业公司,月度评审临近,将有一位资深 Python 程序员审阅您的代码。您决定按照最佳实践进行整理,用管道替换之前用于特征选择和随机森林分类的脚本。您将使用训练数据集 X_train 和 y_train,以及若干模块:用于特征选择的 RandomForestClassifier、SelectKBest() 和 f_classif(),以及 GridSearchCV 和 Pipeline。
本练习是课程的一部分
用 Python 设计机器学习工作流
练习说明
- 使用示例代码给出的特征选择器和随机森林分类器创建一个管道。将第一步命名为
feature_selection。 - 在
params中添加两个键值对:一个是选择器中特征数量k的备选值 10 和 20,另一个是随机森林中n_estimators的备选值 2 和 5。 - 使用给定的管道和参数网格初始化一个
GridSearchCV对象。 - 将该对象拟合到数据上,并打印性能最佳的参数组合。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Create pipeline with feature selector and classifier
pipe = ___([
(___, SelectKBest(f_classif)),
('clf', ___(random_state=2))])
# Create a parameter grid
params = {
'feature_selection__k':___,
___:[2, 5]}
# Initialize the grid search object
grid_search = ___(___, ___=params)
# Fit it to the data and print the best value combination
print(grid_search.fit(___, ___).___)