【问题标题】:creating a pipeline for onehotencoded variables not working为 onehotencoded 变量创建管道不起作用
【发布时间】:2021-02-21 14:58:08
【问题描述】:

我有一个问题,我试图将转换应用于我的分类特征“国家”和我的其余数字列。我该怎么做,因为我在下面尝试:

preprocess = make_column_transformer(
    (numeric_cols, make_pipeline(MinMaxScaler())),
    (categorical_cols, OneHotEncoder()))

model = make_pipeline(preprocess,XGBClassifier())

model.fit(X_train, y_train)

注意 numeric_cols 作为列表传递,categorical_cols 也是如此。

但是i get this error: TypeError: All estimators should implement fit and transform, or can be 'drop' or 'passthrough' specifiers. 以及我所有数字列的列表(type <class 'list'>) doesn't.

我做错了什么,我该如何处理列国家/地区中看不见的类别?

【问题讨论】:

    标签: python pandas scikit-learn pipeline one-hot-encoding


    【解决方案1】:

    您需要先放置转换函数,然后将列作为后续参数,如果您查看帮助页面,它会写道:

    sklearn.compose.make_column_transformer(*transformers, **kwargs)

    下面的一些会起作用:

    from sklearn.preprocessing import StandardScaler, OneHotEncoder,MinMaxScaler
    from sklearn.compose import make_column_transformer
    from sklearn.pipeline import make_pipeline
    
    from xgboost import XGBClassifier
    
    import numpy as np
    import pandas as pd
    
    X = pd.DataFrame({'x1':np.random.uniform(0,1,5),
                       'x2':np.random.choice(['A','B'],5)})
    
    y = pd.Series(np.random.choice(['0','1'],5))
     
    numeric_cols = X.select_dtypes('number').columns.to_list()
    categorical_cols = X.select_dtypes('object').columns.to_list()
        
    preprocess = make_column_transformer(
        (MinMaxScaler(),numeric_cols),
        (OneHotEncoder(),categorical_cols)
        )
    
    model = make_pipeline(preprocess,XGBClassifier())
    model.fit(X,y)
    
    Pipeline(steps=[('columntransformer',
                     ColumnTransformer(transformers=[('minmaxscaler',
                                                      MinMaxScaler(), ['x1']),
                                                     ('onehotencoder',
                                                      OneHotEncoder(), ['x2'])])),
                    ('xgbclassifier', XGBClassifier())])
    

    【讨论】:

    • 谢谢你这有效,当我这样做时:model.predict(x_test) 我认为它将训练中的预处理步骤应用到这个测试集是对的吗?
    • 是的,应该。您可以随时尝试使用您的训练数据进行预测以确保
    猜你喜欢
    • 2019-10-04
    • 1970-01-01
    • 2016-05-26
    • 1970-01-01
    • 2020-06-08
    • 2022-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多