[英]How to make sklearn.metrics.confusion_matrix() to always return TP, TN, FP, FN?
I am using sklearn.metrics.confusion_matrix(y_actual, y_predict)
to extract tn, fp, fn, tp and most of the time it works perfectly. 我正在使用
sklearn.metrics.confusion_matrix(y_actual, y_predict)
来提取tn,fp,fn,tp,并且大部分时间它都能完美地运行。
from sklearn.metrics import confusion_matrix
y_actual, y_predict = [1,1,1,1], [0,0,0,0]
tn, fp, fn, tp = confusion_matrix(y_actual, y_predict).ravel()
>>> [0 0 4 0] # ok
y_actual, y_predict = [1,1,1,1],[0,1,0,1]
tn, fp, fn, tp = confusion_matrix(y_actual, y_predict).ravel()
>>> [0 0 2 2] # ok
However, in some cases the confusion_matrix() doesn't always return those info and I would get ValueError as shown below. 但是,在某些情况下,confusion_matrix()并不总是返回这些信息,我会得到ValueError,如下所示。
from sklearn.metrics import confusion_matrix
y_actual, y_predict = [0,0,0,0],[0,0,0,0]
tn, fp, fn, tp = confusion_matrix(y_actual, y_predict).ravel()
>>> [4] # ValueError: not enough values to unpack (expected 4, got 1)
y_actual, y_predict = [1,1,1,1],[1,1,1,1]
tn, fp, fn, tp = confusion_matrix(y_actual, y_predict).ravel()
>>> [4] # ValueError: not enough values to unpack (expected 4, got 1)
My temporary solution is to write my own function to extract those info. 我的临时解决方案是编写自己的函数来提取这些信息。 Is there any way I can force the
confusion_matrix()
to always return the tn, fp, fn, tp output? 有什么方法可以强制
confusion_matrix()
总是返回tn,fp,fn,tp输出?
Thanks 谢谢
This issue has to do with the number of unique labels that are included in your input matrices. 此问题与输入矩阵中包含的唯一标签数有关。 In your second block of examples, it is (correctly) building a confusion matrix with just one class, either 0 or 1, respectively.
在你的第二个例子中,它(正确地)构建一个只有一个类的混淆矩阵,分别为0或1。
To force it to output both classes even when one of them is not predicted, use the label
attribute. 要强制它输出两个类,即使没有预测其中一个类,也要使用
label
属性。
y_actual, y_predict = [0,0,0,0],[0,0,0,0]
tn, fp, fn, tp = confusion_matrix(y_actual, y_predict, labels=[0,1]).ravel()
>> array([[4, 0],
[0, 0]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.