gpt4 book ai didi

python - 用户警告 : Label not :NUMBER: is present in all training examples

转载 作者:太空狗 更新时间:2023-10-29 20:19:44 24 4
gpt4 key购买 nike

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

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?

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

How can I avoid those empty predictions?

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

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)

关于python - 用户警告 : Label not :NUMBER: is present in all training examples,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42821315/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com