【发布时间】:2020-11-03 14:34:06
【问题描述】:
我试图创建一个带有 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 这样的转换器不应该与特征一起使用,而应该只用于预测目标。
sklearn.preprocessing.LabelEncoder 类
使用 0 到 n_classes-1 之间的值对目标标签进行编码。
这个转换器应该用于编码目标值,即 y,而不是输入 X。
我的问题是,为什么我们不能在特征变量上使用 LabelEncoder,还有其他具有这种情况的转换器吗?
【问题讨论】:
-
序数编码对于一个特性来说不是一个好的选择,因为你给它一个人为的隐含排序。你的分类的基数是什么?如果它不是太高,一种热编码是最常见的选择,尽管它对于基于树的模型不是很好,尤其是在基数很高的时候。这是一整套替代方案:contrib.scikit-learn.org/category_encoders
标签: python machine-learning scikit-learn label-encoding