python - Scikit-learn f1_score 用于字符串列表

标签 python machine-learning scikit-learn jupyter

有没有办法计算字符串标签列表的 f1_score 而不管它们的顺序?

f1_score(['a','b','c'],['a','c','b'],average='macro')

我希望返回 1 而不是 0.33333333333

我知道我可以对标签进行矢量化,但就我而言,这种语法会容易得多,因为我正在处理许多标签

最佳答案

您需要的是多标签分类任务的 f1_score,为此您需要一个形状为 [n_samples,的 y_truey_pred 的二维矩阵, n_labels]

您当前仅提供一维数组。因此,它将被视为多类问题,而不是多标签问题。

official documentation提供必要的详细信息。

为了正确评分,您需要y_truey_pred 转换为标签指示符矩阵 documented here :

y_true : 1d array-like, or label indicator array / sparse matrix

y_pred : 1d array-like, or label indicator array / sparse matrix

所以你需要像这样更改代码:

from sklearn.preprocessing import MultiLabelBinarizer
from sklearn.metrics import f1_score

y_true = [['a','b','c']]
y_pred = [['a','c','b']]

binarizer = MultiLabelBinarizer()

# This should be your original approach
#binarizer.fit(your actual true output consisting of all labels)

# In this case, I am considering only the given labels.
binarizer.fit(y_true)

f1_score(binarizer.transform(y_true), 
         binarizer.transform(y_pred), 
         average='macro')

Output:  1.0

您可以在此处查看 MultilabelBinarizer 的示例:

关于python - Scikit-learn f1_score 用于字符串列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43198613/

相关文章:

python - 如何使用 Python 通过 HTTP 发送文件?

python - 格式化字符串

Python 字符串 "Modifiers"

python - 如何重新训练现有的 K-Means 聚类模型

python - 区分过拟合与良好预测

python - 如何将这些数据转换为逻辑回归?

python - 当要求打印 dirpaths 时,os.walk() 永远不会返回

r - 绘制套索 beta 系数

machine-learning - 使用 Tensorflow 和 inception V3 预训练模型训练高清图像

python - Tensorflow 错误 : "Label IDs must < n_classes", 但我的标签 ID 似乎已经满足此要求