【问题标题】:Sklearn pipeline keep in ID column untouchedSklearn 管道保持在 ID 列不变
【发布时间】:2020-03-18 07:59:30
【问题描述】:

我正在尝试通过功能联合将我的不同管道全部部署到一起,除了一个问题外,一切正常。

在我的 DataFrame 中,我有一个列 ID,我希望在所有管道中保持不变。 我必须把它交给管道,因为我应用了一些热编码和其他东西,我不能在最后把它合并回来。

from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.impute import SimpleImputer

scaler_pipeline = Pipeline([
    ('selector', DataFrameSelector(col_scalar)),
    ('imputer', SimpleImputer(strategy="median")),
    ('std_scaler', StandardScaler())
])
one_hot_pipeline = Pipeline([
    ('selector', DataFrameSelector(col_one_hot)),
    ('imputer', SimpleImputer(strategy="most_frequent")),
    ('one_hot', OneHotEncoder())
])

  full_pipeline = FeatureUnion(transformer_list=[
    ("DataFrameSelector", DataFrameSelector(immutable_col)),
    ("scaler_pipeline", scaler_pipeline),
    ("one_hot_pipeline", one_hot_pipeline),
])

我的 DataFrameSelector 是这样的:

class DataFrameSelector(BaseEstimator, TransformerMixin):
    def __init__(self, attribute_names):
        self.attribute_names = attribute_names

    def fit(self, X, y=None):
        return self

    def transform(self, X):
        return X[self.attribute_names]

在“full_pipeline”的开头,我想选择一些列(此处为 ID)并保持不变。

现在我得到这个错误

TypeError: 不支持类型转换:(dtype('O'), dtype('float64'), dtype('float64'))

【问题讨论】:

    标签: python scikit-learn pipeline


    【解决方案1】:

    您可以使用ColumnTransformerremainder='passthrough' 将转换器安装到选定的列,而其他列保持不变。

    scaler_pipeline = Pipeline([
        ('imputer', SimpleImputer(strategy="median")),
        ('std_scaler', StandardScaler())
    ])
    
    one_hot_pipeline = Pipeline([
        ('imputer', SimpleImputer(strategy="most_frequent")),
        ('one_hot', OneHotEncoder())
    ])
    
    selector = ColumnTransformer([
        ('scalar', scaler_pipeline, col_scalar),
        ('one_hot', one_hot_pipeline, col_one_hot)
    ], remainder='passthrough')
    

    请注意,如果您有除ID 之外的任何列,但不在immutable_colcol_scalar 中,则需要在适合之前删除它们。

    或者,您可以为 ID 列创建一个直通转换器并删除其他列:

    selector = ColumnTransformer([
        ('scalar', scaler_pipeline, col_scalar),
        ('one_hot', one_hot_pipeline, col_one_hot), 
        ('passthough', FunctionTransformer(lambda x: x, lambda x: x), ['ID'])
    ], remainder='drop')
    

    【讨论】:

    • 谢谢,我想你是想写 ('one_hot', one_hot_pipeline, *col_one_hot) 对吧?它似乎有效,但现在我有了这个:ValueError: For a sparse output, all columns should be a numeric or convertible to a numeric. 实际上我什至不想要稀疏输出,是否有可能避免它到目前为止我所做的只是返回带有 .toarray() 的稀疏输出以进行转换它到numpy数组。我想我可以用 to 数组做一个自定义类。我会试试这个。
    • 是的,我确实弄错了。您需要使用sparse_threshold=0 作为ColumnTransformer 的参数。
    猜你喜欢
    • 2018-01-09
    • 2018-01-01
    • 2015-11-01
    • 2020-10-01
    • 2021-09-21
    • 1970-01-01
    • 2017-03-10
    • 2014-01-29
    相关资源
    最近更新 更多