使用opencv python绘制混淆矩阵错误

时间:2019-04-18 14:50:13

标签: python opencv precision confusion-matrix precision-recall

我使用confusion_matrix中的opencv-python的sklearn.metrics来为我的任务绘制混淆矩阵。当我绘制召回率矩阵(在我的代码中设置axis=1)时,它可以工作。但是,当我要绘制Precision矩阵(在我的代码中设置axis=0)时,矩阵的数量不正确。这是我的矩阵:

enter image description here

例如,在中等精度混淆矩阵中,0.8(第一行,第一列)加0.02(第二行,第一列)应为1.0,但不是。你能告诉我哪里错了吗?

这是我有关函数定义的代码

def plot_confusion_matrix(cm, classes,
                          normalize=False,
                          title='Confusion matrix',
                          cmap=plt.cm.Blues,
                          axis=1): 

    if normalize:
        cm = cm.astype('float') / cm.sum(axis=axis)[:, np.newaxis]
        print("Normalized confusion matrix")
    else:
        print('Confusion matrix, without normalization')

    print(cm)

    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(classes))
    plt.xticks(tick_marks, classes, rotation=45)
    plt.yticks(tick_marks, classes)

    fmt = '.2f' if normalize else 'd'
    thresh = cm.max() / 2.
    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        plt.text(j, i, format(cm[i, j], fmt),
                 horizontalalignment="center",
                 color="white" if cm[i, j] > thresh else "black")

    plt.ylabel('True label')
    plt.xlabel('Predicted label')
    plt.tight_layout()

这是有关绘制图形的代码:

# Compute confusion matrix
cnf_matrix = confusion_matrix(y_true, y_pred)
np.set_printoptions(precision=2)

# Plot non-normalized confusion matrix
plt.figure()
plot_confusion_matrix(cnf_matrix, classes=class_name,
                      title='Confusion matrix, without normalization')

# Plot normalized Precision confusion matrix
plt.figure()
plot_confusion_matrix(cnf_matrix, classes=class_name, normalize=True,
                      title='Normalized Precision confusion matrix',
                      axis=0)

# Plot normalized Recall confusion matrix
plt.figure()
plot_confusion_matrix(cnf_matrix, classes=class_name, normalize=True,
                      title='Normalized Recall confusion matrix',
                      axis=1)

plt.show()

非常感谢您的帮助!

0 个答案:

没有答案