You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Pipeline中对目标变量做Label Encoding并实现预测解码

在Pipeline中同时处理特征与目标变量的编码及解码

问题背景

已有针对特征的预处理Pipeline,需要对目标变量target执行Label Encoding(将yes转1、no转0),同时要能对模型预测结果进行解码还原。

示例数据集:

v1  v2  target
0  1   a   yes
1  5   c   no
2  3   f   yes

原特征处理Pipeline(已修正语法错误):

import pandas as pd
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import MinMaxScaler, LabelEncoder
from sklearn.compose import ColumnTransformer
from sklearn.tree import DecisionTreeClassifier

# 定义列和模型
num_cols = ['v1']
cat_cols = ['v2']
clf = DecisionTreeClassifier()

# 数值特征预处理流程
num_transformer = Pipeline(steps=[
    ('impute', SimpleImputer(strategy='mean')),
    ('scale', MinMaxScaler())
])

# 类别特征预处理流程
cat_transformer = Pipeline(steps=[('impute', SimpleImputer(strategy='most_frequent'))])

# 列转换器(修正原代码括号闭合问题)
col_trans = ColumnTransformer(transformers=[
    ('num_pipeline', num_transformer, num_cols),
    ('cat_pipeline', cat_transformer, cat_cols)
])

# 完整特征+模型Pipeline
clf_pipeline = Pipeline(steps=[
    ('col_trans', col_trans),
    ('model', clf)
])

解决方案

目标变量的编码/解码需单独使用LabelEncoder处理,它不属于特征预处理流程,需独立拟合和转换:

1. 准备数据并编码目标变量

# 构造示例数据
data = pd.DataFrame({
    'v1': [1,5,3],
    'v2': ['a','c','f'],
    'target': ['yes','no','yes']
})

X = data[num_cols + cat_cols]
y = data['target']

# 初始化并拟合LabelEncoder
le = LabelEncoder()
y_encoded = le.fit_transform(y)

2. 训练模型

# 使用编码后的目标变量训练Pipeline
clf_pipeline.fit(X, y_encoded)

3. 预测并解码结果

# 预测(得到编码后的结果:1/0)
y_pred_encoded = clf_pipeline.predict(X)

# 解码还原为原始标签:yes/no
y_pred_decoded = le.inverse_transform(y_pred_encoded)

print("编码后的预测结果:", y_pred_encoded)
print("解码后的预测结果:", y_pred_decoded)

运行后输出:

编码后的预测结果: [1 0 1]
解码后的预测结果: ['yes' 'no' 'yes']

关键说明

  • LabelEncoder需单独保存(示例中为le),用于后续解码操作,不能直接整合到特征Pipeline中(特征Pipeline仅处理输入特征X)。
  • 原代码中ColumnTransformer存在括号未闭合的语法错误,已修正。

内容的提问来源于stack exchange,提问作者Fernando Quintino

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 01:26:04