【问题标题】:roc_auc_score mismatch between y_test and y_scoreroc_auc_score y_test 和 y_score 不匹配
【发布时间】:2020-11-18 05:54:52
【问题描述】:

我正在尝试计算以下内容:

auc = roc_auc_score(gt, pr, multi_class="ovr")

其中gt 是一个大小为3470208 的列表,包含0 到41 之间的值(全部为int),pr 是一个大小为3470208(相同大小)的列表列出每个大小为 42,每个位置的概率总和为 1。

但是,我收到以下错误:

ValueError: Number of classes in y_true not equal to the number of columns in 'y_score'

所以我有点迷茫,因为y_true (gt) 中的类数是 42,因为我有一个从 0 到 41 的整数列表。

因为pr 是一个大小为 42 的列表,所以我认为它应该可以工作。

我们将不胜感激!

【问题讨论】:

    标签: python keras auc


    【解决方案1】:

    确保 gt 中存在 所有 0 到 41(含)之间的整数。

    一个简单的例子:

    import numpy as np
    from sklearn.metrics import roc_auc_score
    
    # results in error:
    gt1 = np.array([0,1,3])
    pr1 = np.array(
        [[0.1, 0.7, 0.1, 0.1], 
         [0.3, 0.3, 0.2, 0.2], 
         [0.5, 0.1, 0.1, 0.3]]
    )
    #roc_auc_score(gt1, pr1, multi_class='ovr')
    
    
    # does not result in error:
    gt2 = np.array([0,2,1,3])
    pr2 = np.array(
        [[0.1, 0.7, 0.1, 0.1], 
         [0.3, 0.3, 0.2, 0.2], 
         [0.5, 0.1, 0.1, 0.3],
         [0.3, 0.3, 0.2, 0.2]] 
    )
    #roc_auc_score(gt2, pr2, multi_class='ovr')
    

    因为整数/标签 2 在 gt1 中不存在,所以会引发错误。换言之,gt1 中的类数 (3) 不等于 pr1 中的列数 (4)。

    【讨论】:

    • 如果测试集中没有一个训练标签怎么办?
    • 好问题。我不确定这里哪种方法最好。希望其他人可以提出一个好的建议。 :) 我在想,因为无法评估该标签(该标签未定义 roc_auc_score),它可以被丢弃吗?即,可以删除 y_pred ("pr") 中的该列。请注意,如果在生成预测后删除一列,则剩余概率加起来不会为 1,因此需要重新缩放。
    【解决方案2】:

    roc_auc_score 方法有一个 labels 参数,可用于指定缺失的标签。

    不幸的是,这仅适用于 multi_class="ovo" 模式,而不适用于 "ovr" 模式。

    # without labels
    gt1 = np.array([0,1,3])
    pr1 = np.array(
        [[0.1, 0.7, 0.1, 0.1], 
         [0.3, 0.3, 0.2, 0.2], 
         [0.5, 0.1, 0.1, 0.3]]
    )
    roc_auc_score(gt1, pr1, multi_class='ovo')
    > ValueError: Number of classes in y_true not equal to the number of columns in 'y_score'
    
    # with labels and multi-class="ovo":
    gt1 = np.array([0,1,3])
    pr1 = np.array(
        [[0.1, 0.7, 0.1, 0.1], 
         [0.3, 0.3, 0.2, 0.2], 
         [0.5, 0.1, 0.1, 0.3]]
    )
    roc_auc_score(gt1, pr1, multi_class='ovo', labels=[0, 1, 2, 3])
    > 0.5
    
    # with labels and multi-class="ovr":
    gt1 = np.array([0,1,3])
    pr1 = np.array(
        [[0.1, 0.7, 0.1, 0.1], 
         [0.3, 0.3, 0.2, 0.2], 
         [0.5, 0.1, 0.1, 0.3]]
    )
    roc_auc_score(gt1, pr1, multi_class='ovr', labels=[0, 1, 2, 3])
    > ValueError: Only one class present in y_true. ROC AUC score is not defined in that case.
    

    在这种情况下,y_true 中只有一个类,因为 roc_auc_score 函数会遍历每个类(标识为 A 类)并将它们与其他类进行比较(标识为 B 类)。对于class 2,y_true数组等于[B, B, B],所以只有一个class,无法计算ROC AUC分数。

    【讨论】:

      猜你喜欢
      • 2020-06-22
      • 2015-09-18
      • 2021-12-22
      • 2022-09-23
      • 2013-01-14
      • 2019-01-25
      • 1970-01-01
      • 1970-01-01
      • 2011-12-21
      相关资源
      最近更新 更多