Python 告诉LabelenoCenter忽略新标签?
我处理的文本数据必须考虑很多用户错误,例如,在很多情况下,在预测新数据时,会出现编码器以前没有看到的新标签,这是由于打字错误等原因。我只想忽略这些(因此,当我运行Python 告诉LabelenoCenter忽略新标签?,python,scikit-learn,encoder,Python,Scikit Learn,Encoder,我处理的文本数据必须考虑很多用户错误,例如,在很多情况下,在预测新数据时,会出现编码器以前没有看到的新标签,这是由于打字错误等原因。我只想忽略这些(因此,当我运行labelencoder.transform(df_newdata['GL_Description']),我只想让它忽略以前没有见过的任何东西)。我该怎么做?我在文档中找不到这个参数,但唯一的方法是“手工”逐个检查每个单词并删除它们吗?是否有一种方法可以告诉编码器忽略字典中没有的任何新标签?因此,您可以使用自定义编码器覆盖原始Label
labelencoder.transform(df_newdata['GL_Description'])
,我只想让它忽略以前没有见过的任何东西)。我该怎么做?我在文档中找不到这个参数,但唯一的方法是“手工”逐个检查每个单词并删除它们吗?是否有一种方法可以告诉编码器忽略字典中没有的任何新标签?因此,您可以使用自定义编码器覆盖原始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']
为每个字符串列CLOUMNS准备一个未知类('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))
看不见的列值可以分类为未知类
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))))
它会自动做到这一点。什么都不用做。它将忽略词汇表中尚未出现的单词。但请确保不要再次调用
fit()
或fit\u transform()
。只调用transform()
,但它不会!我得到一个y包含新标签的错误。@VivekKumar哦,对了,我的坏。。。TF-IDF没有抛出错误,LabelEncoder抛出了错误。我已经更新了这个问题。你在目标或功能上使用它吗?你想怎么处理?我的意思是,你将如何填充忽略的值?一些随机值。请更详细地解释。我在功能上使用它。如果我能将这些分类标记为“未知”,只是为了让代码运行/预测,我会很高兴。然后,我可以将新数据添加回原始数据集,并时不时地再次进行训练。我只是想确保代码在遇到新输入时不会崩溃。应该检查什么?@MT467check\u is\u fitted
是内部scikit方法。看到这个:Upvote-你需要在你的代码中添加这个:来自sklearn.utils.validation import check\u是否合适,column\u或\u 1d
,对吗?顺便说一句,我也不确定这个措辞有多好ignore\u unknown=True
-在这种情况下,你实际上考虑到了未知,甚至对它们进行了编码,所以根本不忽略它们(!!).Ignore类似于跳过它们,既不会像原始的标签编码器那样对它们抛出错误,也不会对它们进行编码。