且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

python制表混淆矩阵

更新时间:2023-12-03 23:36:22

Have you considered creating a figure rather than a table? Adapting some code from a scikit-learn example you can get a decent looking figure which shows what you want.

import numpy as np
from matplotlib import pyplot as plt

def plot_confusion_matrix(cm, target_names, title='Confusion matrix', cmap=plt.cm.Blues):
    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(target_names))
    plt.xticks(tick_marks, target_names, rotation=45)
    plt.yticks(tick_marks, target_names)
    plt.tight_layout()

    width, height = cm.shape

    for x in xrange(width):
        for y in xrange(height):
            plt.annotate(str(cm[x][y]), xy=(y, x), 
                        horizontalalignment='center',
                        verticalalignment='center')
    plt.ylabel('True label')
    plt.xlabel('Predicted label')

cm = np.array([[13,  0,  0],[ 0, 10,  6],[ 0,  0,  9]])
plot_confusion_matrix(cm, ['A', 'B', 'C'])