【问题标题】:Scikit-learn f1_score for list of strings用于字符串列表的 Scikit-learn f1_score
【发布时间】:2017-08-29 03:28:54
【问题描述】:

有没有什么方法可以将标签列表的 f1_score 计算为字符串,无论它们的顺序如何?

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

我希望它返回 1 而不是 0.33333333333

我知道我可以对标签进行矢量化,但在我的情况下,这种语法会容易得多,因为我要处理很多标签

【问题讨论】:

    标签: python machine-learning scikit-learn jupyter


    【解决方案1】:

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

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

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

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

    y_true:一维数组,或标签指示数组/稀疏矩阵

    y_pred:一维数组,或标签指示数组/稀疏矩阵

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

    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 的示例:

    【讨论】:

      猜你喜欢
      • 2016-01-19
      • 2012-06-12
      • 1970-01-01
      • 2016-01-24
      • 2014-12-11
      • 1970-01-01
      • 1970-01-01
      • 2015-09-01
      • 2018-12-13
      相关资源
      最近更新 更多