如何在 scikit 学习管道中包含标签编码?

How to include label encoding in scikit learn pipeline?

我想创建一个包含所有必要(预处理)步骤的管道。在我的例子中,这是插补、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 个参数。这就是为什么我试图指定它应该只在创建 example_pipe.

时处理 y

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

你不需要标签编码; sklearn 分类器(您的 KNeighborsClassifier)会在内部为您完成。

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


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