UserWarning: Label not :NUMBER: 存在于所有训练示例中

UserWarning: Label not :NUMBER: is present in all training examples

我正在进行多标签分类,我尝试为每个文档预测正确的标签,这是我的代码:

mlb = MultiLabelBinarizer()
X = dataframe['body'].values 
y = mlb.fit_transform(dataframe['tag'].values)

classifier = Pipeline([
    ('vectorizer', CountVectorizer(lowercase=True, 
                                   stop_words='english', 
                                   max_df = 0.8, 
                                   min_df = 10)),
    ('tfidf', TfidfTransformer()),
    ('clf', OneVsRestClassifier(LinearSVC()))])

predicted = cross_val_predict(classifier, X, y)

当 运行 我的代码收到多个警告时:

UserWarning: Label not :NUMBER: is present in all training examples.

当我打印出预测标签和真实标签时,大约有一半文档的标签预测为空。

为什么会这样,是否与训练时打印出的警告有关运行?我怎样才能避免那些空洞的预测?


EDIT01: 使用 LinearSVC().

以外的其他估算器时也会发生这种情况

我试过 RandomForestClassifier(),它也给出了空的预测。奇怪的是,当我使用 cross_val_predict(classifier, X, y, method='predict_proba') 来预测每个标签的概率,而不是二元决策 0/1 时,对于给定文档,每个预测集总是至少有一个概率 > 0 的标签。所以我不知道为什么这个标签没有选择二元决策?或者二元决策的评估方式与概率不同?

EDIT02: 我发现了一个旧的 post,OP 正在处理类似的问题。这是同一个案例吗?

Why is this happening, is it related to warnings it prints out while training is running?

问题很可能是某些标签只出现在少数文档中(查看 了解详细信息)。当您将数据集拆分为训练和测试以验证您的模型时,训练数据中可能会丢失某些标签。设 train_indices 为包含训练样本索引的数组。如果特定标签(索引 k)未出现在训练样本中,则指示矩阵 y[train_indices] 的第 k 列中的所有元素均为零。

How can I avoid those empty predictions?

在上述场景中,分类器将无法可靠地预测测试文档中的第 k 个标签(下一段将详细介绍)。因此,您不能相信 clf.predict 做出的预测,您需要自己实现预测功能,例如,按照 中的建议,使用 clf.decision_function 返回的决策值。

So I don't know why is this label not chosen with binary decisioning? Or is binary decisioning evaluated in different way than probabilities?

在包含许多标签的数据集中,大多数标签的出现频率都非常低。如果将这些低值馈送到二进制分类器(即进行 0-1 预测的分类器),则分类器很可能会为所有文档的所有标签选择 0。

I have found an old post where OP was dealing with similar problem. Is this the same case?

是的,绝对是。那个人面临着和你完全一样的问题,他的代码和你的非常相似。


演示

为了进一步解释这个问题,我使用模拟数据详细说明了一个简单的玩具示例。

Q = {'What does the "yield" keyword do in Python?': ['python'],
     'What is a metaclass in Python?': ['oop'],
     'How do I check whether a file exists using Python?': ['python'],
     'How to make a chain of function decorators?': ['python', 'decorator'],
     'Using i and j as variables in Matlab': ['matlab', 'naming-conventions'],
     'MATLAB: get variable type': ['matlab'],
     'Why is MATLAB so fast in matrix multiplication?': ['performance'],
     'Is MATLAB OOP slow or am I doing something wrong?': ['matlab-oop'],
    }
dataframe = pd.DataFrame({'body': Q.keys(), 'tag': Q.values()})    

mlb = MultiLabelBinarizer()
X = dataframe['body'].values 
y = mlb.fit_transform(dataframe['tag'].values)

classifier = Pipeline([
    ('vectorizer', CountVectorizer(lowercase=True, 
                                   stop_words='english', 
                                   max_df=0.8, 
                                   min_df=1)),
    ('tfidf', TfidfTransformer()),
    ('clf', OneVsRestClassifier(LinearSVC()))])

请注意我设置了 min_df=1 因为我的数据集比你的小得多。当我运行下面这句话时:

predicted = cross_val_predict(classifier, X, y)

我收到一堆警告

C:\...\multiclass.py:76: UserWarning: Label not 4 is present in all training examples.
  str(classes[c]))
C:\multiclass.py:76: UserWarning: Label not 0 is present in all training examples.
  str(classes[c]))
C:\...\multiclass.py:76: UserWarning: Label not 3 is present in all training examples.
  str(classes[c]))
C:\...\multiclass.py:76: UserWarning: Label not 5 is present in all training examples.
  str(classes[c]))
C:\...\multiclass.py:76: UserWarning: Label not 2 is present in all training examples.
  str(classes[c]))

和以下预测:

In [5]: np.set_printoptions(precision=2, threshold=1000)    

In [6]: predicted
Out[6]: 
array([[0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 1],
       [0, 0, 0, 0, 0, 0, 1],
       [0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0],
       [0, 1, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0]])

那些条目都是0的行表示没有为相应的文档预测标签。


解决方法

为了便于分析,让我们手动验证模型而不是通过 cross_val_predict

import warnings
from sklearn.model_selection import ShuffleSplit

rs = ShuffleSplit(n_splits=1, test_size=.5, random_state=0)
train_indices, test_indices = rs.split(X).next()

with warnings.catch_warnings(record=True) as received_warnings:
    warnings.simplefilter("always")
    X_train, y_train = X[train_indices], y[train_indices]
    X_test, y_test = X[test_indices], y[test_indices]
    classifier.fit(X_train, y_train)
    predicted_test = classifier.predict(X_test)
    for w in received_warnings:
        print w.message

执行上面的代码片段时会发出两个警告(我使用上下文管理器来确保捕捉到警告):

Label not 2 is present in all training examples.
Label not 4 is present in all training examples.

这与训练样本中缺少索引24的标签是一致的:

In [40]: y_train
Out[40]: 
array([[0, 0, 0, 0, 0, 1, 0],
       [0, 1, 0, 0, 0, 0, 0],
       [0, 1, 0, 1, 0, 0, 0],
       [1, 0, 0, 0, 0, 0, 1]])

对于某些文档,预测为空(那些文档对应于 predicted_test 中全为零的行):

In [42]: predicted_test
Out[42]: 
array([[0, 1, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0],
       [0, 1, 0, 1, 0, 0, 0]])

要解决这个问题,您可以像这样实现自己的预测函数:

def get_best_tags(clf, X, lb, n_tags=3):
    decfun = clf.decision_function(X)
    best_tags = np.argsort(decfun)[:, :-(n_tags+1): -1]
    return lb.classes_[best_tags]

通过这样做,每个文档总是分配有最高置信度得分的 n_tag 标签:

In [59]: mlb.inverse_transform(predicted_test)
Out[59]: [('matlab',), (), (), ('matlab', 'naming-conventions')]

In [60]: get_best_tags(classifier, X_test, mlb)
Out[60]: 
array([['matlab', 'oop', 'matlab-oop'],
       ['oop', 'matlab-oop', 'matlab'],
       ['oop', 'matlab-oop', 'matlab'],
       ['matlab', 'naming-conventions', 'oop']], dtype=object)

我也遇到了同样的错误。然后我使用 LabelEncoder() 而不是 Mu​​ltiLabelBinarizer() 对标签进行编码。

from sklearn import preprocessing
le = preprocessing.LabelEncoder()
y = le.fit_transform(Labels)

我不会再收到那个错误了。