如何仅执行 scikit-learn 管道的特定部分?

vas*_*111 1 python pipeline machine-learning python-3.x scikit-learn

以下是与问题相关的部分代码。如果需要完整代码,这里有一个完整的可重现代码,也可以下载数据: https: //github.com/ageron/handson-ml2/blob/master/02_end_to_end_machine_learning_project.ipynb

我有一个管道:

prepare_select_and_predict_pipeline = Pipeline([
    ('preparation', full_pipeline),
    ('feature_selection', TopFeatureSelector(feature_importances, k)),
    ('svm_reg', SVR(**rnd_search.best_params_))
])
Run Code Online (Sandbox Code Playgroud)

现在,我只想执行上面管道中的这一部分:

('preparation', full_pipeline),
('feature_selection', TopFeatureSelector(feature_importances, k)),
Run Code Online (Sandbox Code Playgroud)

我尝试过prepare_select_and_predict_pipeline.fit(housing, housing_labels),但它也执行 SVM 部分。

最后,我需要从上面的管道中获得与执行下面的代码相同的结果:

preparation_and_feature_selection_pipeline = Pipeline([
    ('preparation', full_pipeline),
    ('feature_selection', TopFeatureSelector(feature_importances, k))
])

housing_prepared_top_k_features = preparation_and_feature_selection_pipeline.fit_transform(housing)
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

Ben*_*ger 5

您可以像列表一样对管道进行切片(版本 >=0.21),因此

prepare_select_and_predict_pipeline[:-1].fit_transform(housing)
Run Code Online (Sandbox Code Playgroud)

应该管用。

(这里需要小心;您正在重新安装管道的变压器部分,因此在新数据集上执行此操作prepare_select_and_predict_pipeline.predict(X_new)将使用重新安装的变压器!clone如果需要,您可以使用新变量。)