有没有办法确定scikit-learn的LabelEncoder中的标签顺序?

时间:2014-08-16 19:57:33

标签: python scikit-learn

让我们说我有一个分类任务,我想将文本分类为"垃圾邮件"或者" Ham"。 "精度"得分(计算" TP /(TP + FP)")将是一个有用的错误度量,用于确定有多少" Ham"邮件被错误地归类为"垃圾邮件"假设以下混淆矩阵:

enter image description here

据我所知,scikit计算了以下方案后的混淆矩阵:

enter image description here

现在,如果我使用标签编码器(参见下面的代码),它会给出“垃圾邮件”。班级标签1和'火腿'类标签0将反转混淆矩阵(FP将变为TN等),以便精确分数将得到不同的含义。所以,我的问题是,是否有一种方法可以告诉标签编码器将哪个标签分配给哪个类? (在这种情况下,它很简单,我可以用简单的列表理解来解决问题,但我想知道scikit中是否有某些内容。)

因此,我们的目标是使用LabelEncode来提供垃圾邮件'班级标签0和'火腿'类标签1。

from sklearn.preprocessing import LabelEncoder

X = df['text'].values 
y = df['class'].values

print('before: %s ...' %y[:5])

le = LabelEncoder()
y = le.fit_transform(y)

print('after: %s ...' %y[:5])


before: ['spam' 'ham' 'ham' 'ham' 'ham'] ...
after: [1 0 0 0 0] ...

2 个答案:

答案 0 :(得分:1)

当然,如果您使用precision_score(... pos_label=1, ...),您可以手动为该类分配正面标签,这对于计算“正确”分数很重要,因为精确等式取决于您的“正”类是什么(精度= tp /(tp + fp))

但标签可能导致问题的情况是我进行交叉验证时,例如,想要计算精度,因为cross_validation函数没有参数 “积极的标签”

cross_val_score(clf, X_train, y_train, cv=cv, scoring='precision')

但是,正如GitHub上所建议的,解决方法是创建一个“自定义记分器”,您可以在交叉验证中使用它来解决标签问题:

from functools import partial
from sklearn.metrics import precision_score, make_scorer
custom_scorer = make_scorer(partial(precision_score, pos_label="1"))

答案 1 :(得分:0)

LabelEncoder使用Python内置的排序,即没有sorted或比较函数从key获得的排序。但是不对称的评估指标。标签使用pos_label关键字参数明确地将一个类设为“正”类:

>>> a = np.random.randint(0, 2, 10)
>>> a
array([0, 0, 0, 0, 1, 0, 0, 0, 1, 0])
>>> precision_recall_fscore_support(a, np.ones(10), pos_label=1, average='micro')
(0.20000000000000001, 1.0, 0.33333333333333337, None)
>>> precision_recall_fscore_support(a, np.ones(10), pos_label=0, average='micro')
/home/larsmans/src/scikit-learn/sklearn/metrics/classification.py:920: UndefinedMetricWarning: Precision and F-score are ill-defined and being set to 0.0 due to no predicted samples.
(0.0, 0.0, 0.0, None)
相关问题