如何解释 sklearn confusion_matrix 函数中的标签参数?
How do I interpret the labels argument in the sklearn confusion_matrix function?
假设我有以下两组类别和一个包含目标名称的变量:
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
提供我只想要来自 'blue' 的指标的信息时,我得到了这个结果:
confusion_matrix(spam, flagged, labels=["blue"])
array([[1]])
只有一个数字,我无法计算准确性、精确度、召回率等。
我在这里做错了什么?填写黄色、白色或蓝色将得到 0、1 和 1。
However, when i give the parameter labels
the information that i only want the metrics from 'blue'
不是这样的。
在像您这样的多 class 设置中,根据整个混淆矩阵 class 计算精度和召回率。
我已经在中详细解释了原理和计算;这是它如何适用于您自己的混淆矩阵 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. ])
即对于您的 'blue' class,您获得了 50% 的准确率和召回率。
这里的准确率和召回率恰好相同纯属巧合,因为 FP 和 FN 数组恰好相同;尝试不同的预测以获得感觉...
假设我有以下两组类别和一个包含目标名称的变量:
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
提供我只想要来自 'blue' 的指标的信息时,我得到了这个结果:
confusion_matrix(spam, flagged, labels=["blue"])
array([[1]])
只有一个数字,我无法计算准确性、精确度、召回率等。 我在这里做错了什么?填写黄色、白色或蓝色将得到 0、1 和 1。
However, when i give the parameter
labels
the information that i only want the metrics from 'blue'
不是这样的。
在像您这样的多 class 设置中,根据整个混淆矩阵 class 计算精度和召回率。
我已经在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. ])
即对于您的 'blue' class,您获得了 50% 的准确率和召回率。
这里的准确率和召回率恰好相同纯属巧合,因为 FP 和 FN 数组恰好相同;尝试不同的预测以获得感觉...