如何计算多标签分类的 F1-score?

How To Calculate F1-Score For Multilabel Classification?

我尝试计算 f1_score 但在某些情况下,当我使用 sklearn f1_score 方法时会收到一些警告。

我有一个多标签 5 类 预测问题。

import numpy as np
from sklearn.metrics import f1_score

y_true = np.zeros((1,5))
y_true[0,0] = 1 # => label = [[1, 0, 0, 0, 0]]

y_pred = np.zeros((1,5))
y_pred[:] = 1 # => prediction = [[1, 1, 1, 1, 1]]

result_1 = f1_score(y_true=y_true, y_pred=y_pred, labels=None, average="weighted")

print(result_1) # prints 1.0

result_2 = f1_score(y_true=y_ture, y_pred=y_pred, labels=None, average="weighted")

print(result_2) # prints: (1.0, 1.0, 1.0, None) for precision/recall/fbeta_score/support

当我使用 average="samples" 而不是 "weighted" 时,我得到 (0.1, 1.0, 0.1818..., None)。 "weighted" 选项对多标签问题没有用还是我如何正确使用 f1_score 方法?

我在使用 average="weighted" 时也收到警告:

"UndefinedMetricWarning: Recall and F-score are ill-defined and being set to 0.0 in labels with no true samples."

稍微加点数据就可以了:

y_true = np.array([[1,0,0,0], [1,1,0,0], [1,1,1,1]])
y_pred = np.array([[1,0,0,0], [1,1,1,0], [1,1,1,1]])

recall_score(y_true=y_true, y_pred=y_pred, average='weighted')
>>> 1.0
precision_score(y_true=y_true, y_pred=y_pred, average='weighted')
>>> 0.9285714285714286

f1_score(y_true=y_true, y_pred=y_pred, average='weighted')
>>> 0.95238095238095244

数据表明我们没有错过任何真阳性,也没有预测到任何假阴性(recall_score 等于 1)。然而,我们在第二次观察中预测了一个误报,导致 precision_score 等于 ~0.93.

由于 precision_scorerecall_score 都不是零且带有 weighted 参数,因此 f1_score 存在。由于示例中缺少信息,我认为您的案例无效。