我试图创建一个带有 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/