告诉 LabelEnocder 忽略新标签?

Tell LabelEnocder to ignore new labels?

我正在处理文本数据,其中必须考虑很多用户错误,例如。在很多情况下,在预测新数据时,由于拼写错误等原因,编码器以前没有看到过新标签。我只想忽略这些(所以当我 运行 labelencoder.transform(df_newdata['GL_Description']),我只是想让它忽略以前没有见过的任何东西)。我怎样才能做到这一点?我没有在文档中找到这个参数,但是真正逐个检查每个单词 "by hand" 并删除它们的唯一方法是什么?有什么方法可以告诉编码器忽略任何不在其字典中的新标签吗?

为此,您可以使用自定义编码器覆盖原始的 LabelEncoder。 像这样:

import numpy as np
class TolerantLabelEncoder(LabelEncoder):
    def __init__(self, ignore_unknown=False,
                       unknown_original_value='unknown', 
                       unknown_encoded_value=-1):
        self.ignore_unknown = ignore_unknown
        self.unknown_original_value = unknown_original_value
        self.unknown_encoded_value = unknown_encoded_value

    def transform(self, y):
        check_is_fitted(self, 'classes_')
        y = column_or_1d(y, warn=True)

        indices = np.isin(y, self.classes_)
        if not self.ignore_unknown and not np.all(indices):
            raise ValueError("y contains new labels: %s" 
                                         % str(np.setdiff1d(y, self.classes_)))

        y_transformed = np.searchsorted(self.classes_, y)
        y_transformed[~indices]=self.unknown_encoded_value
        return y_transformed

    def inverse_transform(self, y):
        check_is_fitted(self, 'classes_')

        labels = np.arange(len(self.classes_))
        indices = np.isin(y, labels)
        if not self.ignore_unknown and not np.all(indices):
            raise ValueError("y contains new labels: %s" 
                                         % str(np.setdiff1d(y, self.classes_)))

        y_transformed = np.asarray(self.classes_[y], dtype=object)
        y_transformed[~indices]=self.unknown_original_value
        return y_transformed

用法示例:

en = TolerantLabelEncoder(ignore_unknown=True)
en.fit(['a','b'])

print(en.transform(['a', 'c', 'b']))
# Output: [ 0 -1  1]

print(en.inverse_transform([-1, 0, 1]))
# Output: ['unknown' 'a' 'b']

为每个字符串columns

准备一个未知的class('UNK')
from sklearn import preprocessing
from collections import defaultdict
d = defaultdict(preprocessing.LabelEncoder)
df.select_dtypes(include='object').append({}.fromkeys(df.select_dtypes(include='object').columns, '_UNK_'), ignore_index=True).apply(lambda x: d[x.name].fit_transform(x))

看不见的列值可以class化为未知class

dftc = dfTest.select_dtypes(include='object').apply(lambda x: d[x.name].transform(list(map(lambda xx: xx if xx in d[x.name].classes_ else '_UNK_', x))))