渲染混乱矩阵

时间:2019-08-02 15:09:06

标签: python scikit-learn renderer confusion-matrix

我正在与jupyterlab合作,专门绘制了一个混淆矩阵。但是,渲染矩阵时,似乎出现了问题,因为图形没有完全渲染。

我已经安装了sklearn软件包,但是仍然是同样的问题。我尝试了其他替代方法,但仍然呈现了一个模糊的混淆矩阵。

下面是一个我知道会呈现适当混淆矩阵的代码示例。

from sklearn.metrics import classification_report, confusion_matrix
import itertools
import matplotlib.pyplot as plt
def plot_confusion_matrix(cm, classes,
                          normalize=False,
                          title='Confusion matrix',
                          cmap=plt.cm.Blues):
    """
    This function prints and plots the confusion matrix.
    Normalization can be applied by setting `normalize=True`.
    """
    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, 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.tight_layout()
    plt.ylabel('True label')
    plt.xlabel('Predicted label')
# Compute confusion matrix
cnf_matrix = confusion_matrix(y_test, yhat, labels=[2,4])
np.set_printoptions(precision=2)

print (classification_report(y_test, yhat))

# Plot non-normalized confusion matrix
plt.figure()
plot_confusion_matrix(cnf_matrix, classes=['Benign(2)','Malignant(4)'],normalize= False,  title='Confusion matrix')

从上面的代码中,我得到了这个混淆矩阵:

enter image description here

但是,我希望有一个不可分割的混淆矩阵,例如:

enter image description here

积分:@Calvin Duy Canh Tran

更新2019-08-05:

为了对上面使用的代码没有疑问,我使用了其他参考:相反,我尝试使用代码scikit-learn作为混淆矩阵文档的示例之一。链接就是这个https://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html

在运行上述代码之前,我安装了相应的模块:

pip install -q scikit-plot

不幸的是,输出继续渲染已剪切的矩阵(参见图片):

enter image description here

正确的输出应该是这个(忽略方向):

enter image description here

2 个答案:

答案 0 :(得分:1)

matplotlib版本3.1.1与scikit-plot之间似乎存在冲突。请参阅此GitHub issue,它显示了类似的问题。

将matplotlib降级到3.1.0版可能是立即修复。

答案 1 :(得分:0)

请勿将混淆矩阵作为输入参数传递给绘图函数。您需要传递y_test, y_pred,混淆矩阵将在内部进行计算。

要对此进行绘图,请使用此

def plot_confusion_matrix(y_true, y_pred, classes,
                          normalize=False,
                          title=None,
                          cmap=plt.cm.Blues):
    """
    This function prints and plots the confusion matrix.
    Normalization can be applied by setting `normalize=True`.
    """
    if not title:
        if normalize:
            title = 'Normalized confusion matrix'
        else:
            title = 'Confusion matrix, without normalization'

    # Compute confusion matrix
    cm = confusion_matrix(y_true, y_pred)
    # Only use the labels that appear in the data
    classes = classes[unique_labels(y_true, y_pred)]
    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
        print("Normalized confusion matrix")
    else:
        print('Confusion matrix, without normalization')

    print(cm)

    fig, ax = plt.subplots()
    im = ax.imshow(cm, interpolation='nearest', cmap=cmap)
    ax.figure.colorbar(im, ax=ax)
    # We want to show all ticks...
    ax.set(xticks=np.arange(cm.shape[1]),
           yticks=np.arange(cm.shape[0]),
           # ... and label them with the respective list entries
           xticklabels=classes, yticklabels=classes,
           title=title,
           ylabel='True label',
           xlabel='Predicted label')

    # Rotate the tick labels and set their alignment.
    plt.setp(ax.get_xticklabels(), rotation=45, ha="right",
             rotation_mode="anchor")

    # Loop over data dimensions and create text annotations.
    fmt = '.2f' if normalize else 'd'
    thresh = cm.max() / 2.
    for i in range(cm.shape[0]):
        for j in range(cm.shape[1]):
            ax.text(j, i, format(cm[i, j], fmt),
                    ha="center", va="center",
                    color="white" if cm[i, j] > thresh else "black")
    fig.tight_layout()
    return ax


# Plot non-normalized confusion matrix
plot_confusion_matrix(y_test, y_pred, classes=['Benign(2)','Malignant(4)'],normalize= False,  title='Confusion matrix')

代替

plot_confusion_matrix(cnf_matrix, classes=['Benign(2)','Malignant(4)'],normalize= False,  title='Confusion matrix')

参考:https://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html