python - 为什么 sklearn 的 LabelEncoder 应该只用于目标变量?

标签 python machine-learning scikit-learn label-encoding

我试图创建一个带有 LabelEncoder 的管道来转换分类值。

cat_variable = Pipeline(steps = [
    ('imputer',SimpleImputer(strategy = 'most_frequent')),
    ('lencoder',LabelEncoder())
])
                        
num_variable = SimpleImputer(strategy = 'mean')

preprocess = ColumnTransformer (transformers = [
    ('categorical',cat_variable,cat_columns),
    ('numerical',num_variable,num_columns)
])

odel = RandomForestRegressor(n_estimators = 100, random_state = 0)

final_pipe = Pipeline(steps = [
    ('preprocessor',preprocess),
    ('model',model)
])

scores = -1 * cross_val_score(final_pipe,X_train,y,cv = 5,scoring = 'neg_mean_absolute_error')

但这会引发 TypeError:

TypeError: fit_transform() takes 2 positional arguments but 3 were given

在进一步的引用中,我发现像 LabelEncoders 这样的转换器不应该与特征一起使用,而应该只用于预测目标。
From Documentation:

class sklearn.preprocessing.LabelEncoder

Encode target labels with value between 0 and n_classes-1.

This transformer should be used to encode target values, i.e. y, and not the input X.


我的问题是,为什么我们不能在特征变量上使用 LabelEncoder,还有其他变压器有这样的条件吗?

最佳答案

LabelEncoder可用于标准化标签或转换非数字标签。对于输入分类,您应该使用 OneHotEncoder .
区别:

le = preprocessing.LabelEncoder()
le.fit_transform([1, 2, 2, 6])
array([0, 0, 1, 2])

enc = OneHotEncoder(handle_unknown='ignore')
enc.fit_transform([[1], [2], [2], [6]]).toarray()
array([[1., 0., 0.],
       [0., 1., 0.],
       [0., 1., 0.],
       [0., 0., 1.]])

关于python - 为什么 sklearn 的 LabelEncoder 应该只用于目标变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62892086/

相关文章:

带有 Bloomberg API 的 Python 2.7 导入 blpapi 失败

python - 如何在Python中实现/使用人工免疫系统(AIS)?

python - ValueError : Error when checking input: expected dense_151_input to have 3 dimensions, 但得到形状为 (2, 2100) 的数组

python - 在 MLPClassification Python 中实现 K 折交叉验证

python - Sklearn StandardScaler + ElasticNet 具有可解释系数

python 在加载模块时捕获 NameError

python - Numpy:索引 i < j 的一维数组的总和

python - 用于解析完整 Iptables 日志 Python 的正则表达式代码

python - 使用 scikit learn DictVectorizer 对特定列进行矢量化时出现问题?

python - 如何为机器学习预处理数据?