【问题标题】:How do I interpret the labels argument in the sklearn confusion_matrix function?如何解释 sklearn 混淆矩阵函数中的标签参数?
【发布时间】:2019-06-05 09:22:00
【问题描述】:

假设我有以下两组类别和一个包含目标名称的变量:

spam = ["blue", "white", "blue", "yellow", "red"]
flagged = ["blue", "white", "yellow", "blue", "red"]
target_names = ["blue", "white", "yellow", "red"]

当我使用以下的confusion_matrix函数时,结果如下:

from sklearn.metrics import confusion_matrix
confusion_matrix(spam, flagged, labels=target_names)

[[1 0 1 0]
 [0 1 0 0]
 [1 0 0 0]
 [0 0 0 1]]

但是,当我向参数labels 提供我只想要来自“蓝色”的指标的信息时,我得到了这个结果:

confusion_matrix(spam, flagged, labels=["blue"])

array([[1]])

只有一个数字,我无法计算准确度、精确度、召回率等。 我在这里做错了什么?填充黄色、白色或蓝色将导致 0、1 和 1。

【问题讨论】:

    标签: python machine-learning scikit-learn metrics


    【解决方案1】:

    但是,当我给参数labels 提供我只想要来自“蓝色”的指标的信息时

    这样不行。

    在像您这样的多类设置中,每类从整个混淆矩阵中计算精度和召回率。

    我已经在another answer中详细解释了原理和计算;这是您自己的混淆矩阵cm

    import numpy as np
    
    # your comfusion matrix:
    cm =np.array([[1, 0, 1, 0],
                  [0, 1, 0, 0],
                  [1, 0, 0, 0],
                  [0, 0, 0, 1]])
    
    # true positives:
    TP = np.diag(cm)
    TP
    # array([1, 1, 0, 1])
    
    # false positives:
    FP = np.sum(cm, axis=0) - TP
    FP 
    # array([1, 0, 1, 0])
    
    # false negatives
    FN = np.sum(cm, axis=1) - TP
    FN
    # array([1, 0, 1, 0])
    

    现在,根据精确率和召回率的定义,我们有:

    precision = TP/(TP+FP)
    recall = TP/(TP+FN)
    

    以你的为例,给出:

    precision
    # array([ 0.5,  1. ,  0. ,  1. ])
    
    recall
    # array([ 0.5,  1. ,  0. ,  1. ])
    

    即对于您的“蓝色”课程,您可以获得 50% 的准确率和召回率。

    这里的精确率和召回率恰好相同的事实纯属巧合,因为 FP 和 FN 数组恰好相同;尝试不同的预测以获得感觉...

    【讨论】:

    • 哇,我现在明白了,很好的解释!还有一个问题,我怎样才能从矩阵中得到真底片?
    • @intStdu 我已经开始编写它,但我删除了它,因为它们对于计算精度和召回不是必需的;查看链接的答案(也欢迎投票;)
    猜你喜欢
    • 2018-09-18
    • 2013-10-14
    • 2017-11-03
    • 2020-07-06
    • 2021-08-17
    • 2019-05-22
    • 1970-01-01
    • 2020-01-22
    • 2019-10-15
    相关资源
    最近更新 更多