Skip to main content
 首页 » 编程设计

python之渲染混淆矩阵

2024年11月24日8zlslch

我正在使用 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') 

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

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

致谢:@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 

不幸的是,输出继续渲染截断的矩阵(见图片):

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

请您参考如下方法:

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

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