标签: label-encoding

为什么 sklearn 的 LabelEncoder 只能用于目标变量?

我试图使用 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,还有其他转换器有这样的条件吗?

python machine-learning scikit-learn label-encoding

7
推荐指数
1
解决办法
6067
查看次数

对训练和测试数据帧使用相同的标签编码器

我有 2 个不同的 csv,其中包含训练数据和测试数据。我从这些 train_features_df 和 test_features_df 创建了两个不同的数据帧。请注意,测试和训练数据有多个分类列,因此我需要对它们应用 labelEncoder,因为它适合我的数据集。所以我在训练和测试数据上分别应用了标签编码器。当我打印训练和测试数据集的新编码值时,我发现对于相同特征的相同分类值,新编码数据的输出是不同的。这是否意味着我必须合并训练数据和测试数据。然后应用标签编码,然后再次将它们分开?

 from sklearn.preprocessing import LabelEncoder
 target=train_features_df['y']
 train_features_df=train_features_df.drop(['y'], axis=1)
 train_features_df.head()
 y = target.values
 print("printing feature column of train datasets: \n")
 print(train_features_df.values)
 le=LabelEncoder()
 X_train_label_encoded=train_features_df.apply(le.fit_transform)
 print("\n printing feature column of train datasets after label encoder: \n")
 print(X_train_label_encoded.head())

 print("printing test feature datasets: \n")
 print(test_features_df)
 X_test_label_encoded=test_features_df.apply(le.fit_transform)
 print("printing test feature encoded  datasets: \n")
 print(X_test_label_encoded)
Run Code Online (Sandbox Code Playgroud)

上述输出如下:-

printing feature column of train datasets: 

[['k' 'v' 'at' ... 0 0 0]
 ['k' 't' 'av' ... 0 0 0]
 ['az' 'w' 'n' …
Run Code Online (Sandbox Code Playgroud)

python machine-learning scikit-learn label-encoding

5
推荐指数
1
解决办法
1万
查看次数