为啥在 scikit-learn 中使用 make_pipeline 时出现“管道的最后一步”错误?

Posted

技术标签:

【中文标题】为啥在 scikit-learn 中使用 make_pipeline 时出现“管道的最后一步”错误?【英文标题】:Why am I getting 'last step of pipeline' error when using make_pipeline in scikit-learn?为什么在 scikit-learn 中使用 make_pipeline 时出现“管道的最后一步”错误? 【发布时间】:2021-01-12 12:44:56 【问题描述】:

所以我试图在scikit-learn 中使用make_pipeline 来清理我的数据(替换缺失值,然后清理异常值,将编码函数应用于分类变量,然后最后通过RandomForestRegressor 添加随机森林回归器. 输入是DataFrame。最终我想通过GridSearchCV 搜索回归器的最佳超参数。

为了做到这一点,我按照here 的建议构建了一些继承TransformerMixin 类的自定义类。这是我到目前为止所拥有的

from sklearn.pipeline import make_pipeline
from sklearn.base import TransformerMixin
import pandas as pd

class Cleaning(TransformerMixin):
    def __init__(self, column_labels):
        self.column_labels = column_labels
    def fit(self, X, y=None):
        return self
    def transform(self, X):
        """Given a dataframe X with predictors, clean it."""
        X_imputed, medians_X = median_imputer(X) # impute all missing numeric data with median
        
        quantiles_X = get_quantiles(X_imputed, self.column_labels)
        X_nooutliers, _ = replace_outliers(X_imputed, self.column_labels, medians_X, quantiles_X)
        return X_nooutliers

class Encoding(TransformerMixin):
    def __init__(self, encoder_list):
        self.encoder_list = encoder_list
    def fit(self, X, y=None):
        return self
    def transform(self, X):
        """Takes in dataframe X and applies encoding transformation to them"""
        return encode_data(self.encoder_list, X)

但是,当我运行以下代码行时出现错误:

import category_encoders as ce

pipeline_cleaning = Cleaning(column_labels = train_labels)

OneHot_binary = ce.OneHotEncoder(cols = ['new_store']) 
OneHot = ce.OneHotEncoder(cols= ['transport_availability']) 
Count = ce.CountEncoder(cols = ['county'])
pipeline_encoding = Encoding([OneHot_binary, OneHot, Count])

baseline = RandomForestRegressor(n_estimators=500, random_state=12)
make_pipeline([pipeline_cleaning, pipeline_encoding,baseline])

错误是Last step of Pipeline should implement fit or be the string 'passthrough'。我不明白为什么?

编辑:最后一行有轻微错字,正确。传递给make_pipeline 的列表中的第三个元素是回归量

【问题讨论】:

【参考方案1】:

换行:

make_pipeline([pipeline_cleaning, pipeline_encoding,baseline])

到(无列表):

make_pipeline(pipeline_cleaning, pipeline_encoding,baseline)
Pipeline(steps=[('cleaning', <__main__.Cleaning object at 0x7f617260c1d0>),
                ('encoding', <__main__.Encoding object at 0x7f617260c278>),
                ('randomforestregressor',
                 RandomForestRegressor(n_estimators=500, random_state=12))])

你可以走了

【讨论】:

啊,就是这样!这很奇怪,因为我认为出于某种奇怪的原因它接受了估算者列表。我现在已经接受了你的回答。谢谢!

以上是关于为啥在 scikit-learn 中使用 make_pipeline 时出现“管道的最后一步”错误?的主要内容,如果未能解决你的问题,请参考以下文章

软件IDEA web项目里包含node_modules 一直处于make状态

IDEA JetBrains IntelliJ - 'make' 上的编译错误,但使用 Maven 编译时很好,并且 IntelliJ 在类文件中没有报告错误

为啥使用 Make 3.8.1 构建与 Make 4.1 不同?

为啥在使用静态 constexpr 成员构造时 std::make_shared 与 new 不同? [复制]

libevent:为啥 evutil_make_socket_nonblocking 在他们的示例中调用了两次

为啥 php artisan make:factory 不使用模型生成