【问题标题】:How to include label encoding in scikit learn pipeline?如何在 scikit 学习管道中包含标签编码?
【发布时间】:2021-10-11 07:20:40
【问题描述】:

我想创建一个包含所有必要(预处理)步骤的管道。在我的情况下,这是估算、Xy 的编码、缩放、特征选择和估计器。

我编写了以下代码,但它给了我一个错误ValueError: too many values to unpack (expected 2)

# Creating a scikit learn pipeline for preprocessing

## Selecting categorical and numeric features
numerical_ix = X.select_dtypes(include=np.number).columns
categorical_ix = X.select_dtypes(exclude=np.number).columns

## Create preprocessing pipelines for each datatype 
numerical_transformer = Pipeline(steps=[
    ('imputer', SimpleImputer(strategy='median')),
    ('scaler', StandardScaler())])

categorical_transformer = Pipeline(steps=[
    ('encoder', OrdinalEncoder()),
    ('scaler', StandardScaler())])

## Putting the preprocessing steps together
preprocessor = ColumnTransformer([
        ('numerical', numerical_transformer, numerical_ix),
        ('categorical', categorical_transformer, categorical_ix)],
         remainder='passthrough')


## Create example pipeline with kNN as estimator
example_pipe = Pipeline(steps=[
    ('preprocessor', preprocessor),
    ('label', LabelEncoder(), y),
    ('selector', SelectKBest(k=len(X.columns))), # keep the same amount of columns for now
    ('classifier', KNeighborsClassifier())
])

## Test pipeline
example_pipe.fit_transform(X_train, y_train)
example_pipe.score(X_test, y_test)

我读过一些关于这个话题的文章,似乎LabelEncoder() 只收到 1 个参数。这就是为什么我试图指定它应该只在创建y 时处理example_pipe

有没有办法在管道中包含标签编码,还是必须事先完成(例如使用 pandas)?如果可能,我如何在管道中包含标签编码?

【问题讨论】:

    标签: python scikit-learn pipeline


    【解决方案1】:

    您不需要标签编码; sklearn 分类器(您的 KNeighborsClassifier)会在内部为您执行此操作。

    您无法将y 转换为Pipeline(除非您将其添加为X 的列,在这种情况下,您需要在拟合实际模型之前手动将其分离)。您也不能在Pipeline 中指定要应用转换器的列;为此,请参阅 ColumnTransformer(它仍然无法转换 y)。


    这与您的问题无关,但未来的搜索者在尝试对其自变量进行有序编码时可能会偶然发现这一点。为此,不要使用LabelEncoder,使用OrdinalEncoder

    【讨论】:

    • 谢谢!是的,我偶然发现了OrdinalEncoderLabelEncoder 的问题。也感谢您提到ColumnTransformer 部分。那么LabelEncoder 是如何以及在什么情况下使用的?只能在管道外部使用吗?
    • 在大多数情况下,不要使用它(“sklearn 分类器会在内部为你做这件事”)。对于某些兼容 sklearn 的第三方模型,您可以使用它(手动,而不是在管道中)为模型准备数据。
    猜你喜欢
    • 2019-12-03
    • 2016-12-11
    • 2020-01-01
    • 2021-10-12
    • 1970-01-01
    • 2018-10-23
    • 2017-09-01
    • 2016-10-01
    • 2018-10-18
    相关资源
    最近更新 更多