我试图使用 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')
Run Code Online (Sandbox Code Playgroud)
但这会引发类型错误:
TypeError: fit_transform() takes 2 positional arguments but 3 were given
Run Code Online (Sandbox Code Playgroud)
经过进一步参考,我发现像 LabelEncoders 这样的转换器不应该与特征一起使用,而应该只用于预测目标。
sklearn.preprocessing.LabelEncoder 类
使用 0 到 n_classes-1 之间的值对目标标签进行编码。
该转换器应用于对目标值(即 y)进行编码,而不是对输入 X 进行编码。
我的问题是,为什么我们不能在特征变量上使用 LabelEncoder,还有其他转换器有这样的条件吗?