python - 渲染混淆矩阵

标签 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

最佳答案

matplotlib 版本 3.1.1 和 scikit-plot 之间似乎存在冲突。引用这个 GitHub issue , 这显示了类似的问题。

将 matplotlib 降级到版本 3.1.0 可以立即修复。

关于python - 渲染混淆矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57329189/

相关文章:

python - Pyramid:如何在运行时获取view.py中当前渲染器名称

python - 在单元测试中使用 django.template 上下文时遇到问题

python - 无法调用openfile函数

python - Sklearn 指标值与 Keras 值有很大不同

python-3.x - 如何解释线性判别分析的结果?

python - 将 Pandas 'categorical' dtype 与 sklearn 一起使用

python - 来自几张图片的动画 Sprite

python - python中的LFU缓存实现

highcharts - 如何在 Highcharts 中的 Yaxis 上渲染图像

Android 和 OpenGL 启动时出现黑框