Как я могу улучшить свой график матрицы путаницы? - PullRequest
0 голосов
/ 03 ноября 2019

Я работаю над проблемой классификации с 20 классами. Я пытаюсь визуализировать результаты с помощью матрицы путаницы, используя matplotlib .

После вычисления моей матрицы путаницы я использовал plot_confusion_matrix, описанный здесь .

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 Похоже, что проблема возникает из-за слишком большого количества классов, поэтому естественным решением было бы растянуть сюжет. Но это искажает это. Кроме того, как выбрать правильный масштаб / размер?

Как мне сделать так, чтобы он выглядел лучше?

PS Матрицу конфуций можно найти в виде файла CSV здесь .

1 Ответ

0 голосов
/ 03 ноября 2019

Так как вы не указали строгое использование 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)

и это результат. будьте осторожны с ограничениями heatM.set_ylim ([10,0]) и для x, это должно быть количество переменных, которые у вас есть.

надеюсь, это было полезно.

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...