我怎样才能使我的混乱矩阵图更好?

2024-03-29 06:32:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我在研究一个有20个班的分类问题。我试图通过使用matplotlib的混淆矩阵来可视化结果。你知道吗

在计算了混淆矩阵之后,我使用了plot_confusion_matrix描述的here。你知道吗

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

下面是它的样子: enter image description here 看起来问题来自处理太多的类,所以自然的解决方案是按比例放大绘图。但这样做会扭曲它。另外,如何选择正确的比例/大小?你知道吗

我怎样才能让它看起来更好呢?你知道吗

另外,你可以在csv文件here中找到混淆矩阵。你知道吗


Tags: andthetrueiftitlecm矩阵ax
2条回答

既然你没有指定matplotlib的限制用法,我建议你使用seaborn库,因为它非常简单,如果你想改变一些奇怪的东西,如果我没有错的话,它是用matplolib构建的。使用seaborn是:

import seaborn as sns 

plt.figure(figsize = (10,10))  #This is the size of the image
heatM = sns.heatmap(cov_vals, vmin = -1, vmax = 1,center = 0, cmap = sns.diverging_palette(20, 220, n = 200),  square = True, annot = True) #this are the caracteristics of the heatmap
heatM.set_ylim([10,0]) # This is the limit in y axis (number of features)

这就是结果。小心极限加热装置([10,0])对于x,这需要是您拥有的变量数。你知道吗

希望这有用。你知道吗

enter image description here

我最终使用了seaborn,但我遇到了一个问题。混淆矩阵看起来像this。它实际上是seaborn的最新版本(3.1.1)中的一个bug(参见这个issue)。解决方案是使用以前的版本(在我的例子中是3.1.0)。你知道吗

相关问题 更多 >