Python 呈现混淆矩阵

Python 呈现混淆矩阵,python,scikit-learn,renderer,confusion-matrix,Python,Scikit Learn,Renderer,Confusion Matrix,我正在使用jupyterlab,特别是渲染混淆矩阵。但是,在渲染矩阵时,似乎出现了一些错误,因为图形没有完全渲染 我已经安装了sklearn软件包,但仍然存在相同的问题。我尝试了不同的选择,但仍然呈现了一个被剪断的混乱矩阵 from sklearn.metrics import classification_report, confusion_matrix import itertools import matplotlib.pyplot as plt 下面是一个代码示例,我知道它将呈现一个正

我正在使用jupyterlab,特别是渲染混淆矩阵。但是,在渲染矩阵时,似乎出现了一些错误,因为图形没有完全渲染

我已经安装了sklearn软件包,但仍然存在相同的问题。我尝试了不同的选择,但仍然呈现了一个被剪断的混乱矩阵

from sklearn.metrics import classification_report, confusion_matrix
import itertools
import matplotlib.pyplot as plt
下面是一个代码示例,我知道它将呈现一个正确的混淆矩阵

from sklearn.metrics import classification_report, confusion_matrix
import itertools
import matplotlib.pyplot as plt
从上述代码中,我获得了这个混淆矩阵:

但是,我希望有一个非截取的混淆矩阵,例如:

信用证:@Calvin Duy Canh Tran

更新2019-08-05:

为了不怀疑上面使用的代码,我使用了附加参考:相反,我尝试了混淆矩阵文档示例之一的代码是
scikit learn
。链接就是这个

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

pip install -q scikit-plot
不幸的是,输出将继续渲染截断的矩阵(请参见图片):

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


不要将混淆矩阵作为输入参数传递给plotting函数。您需要通过
y_测试,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')

参考资料:

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


将matplotlib降级到3.1.0版可能是一个立即解决方案

查看中的
plot\u composition\u matrix
。您正在传递2个类
classes=[“良性(2)”,“恶性(4)”
,为什么您希望输出中包含3个类?查看YellowBrick模块。它为sklearn提供了很好的可视化效果,并提供了很好的引导文档@谢谢你!使用YellowBrick,渲染工作应该是这样的。嗨!我试过你的建议,但混乱矩阵仍然以错误的方式呈现。不知道,发生了什么事!你能在你的问题中添加一些可复制的例子吗?我添加了它。在udpate中,我使用了
Scikit学习
文档中的一个代码作为示例。链接是这样的:我认为您的问题看起来与谢谢类似,执行
sudopip3卸载matplotlib&&sudopip3安装matplotlib==3.1.0
对我来说很有效!你好谢谢我试过你的上述建议,但问题仍然存在。请参阅我今天所做问题的更新。
plot_confusion_matrix(cnf_matrix, classes=['Benign(2)','Malignant(4)'],normalize= False,  title='Confusion matrix')