Home > Software engineering >  Why we flip coordinates when we plot confusion matrix
Why we flip coordinates when we plot confusion matrix

Time:08-12

I am trying to plot the confusion matrix, but I have a question, why the indices are flipped in the for loop below where we start with plt.text(j, i) instead of `plt.text(i, j)? I assume that 2D confusion matrix has values as follows:

  1. (0,0): true zeros.
  2. (0,1): false ones.
  3. (1,0): false zeros.
  4. (1,1): true ones.

Code:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import pandas as pd
from sklearn.metrics import confusion_matrix
import itertools
true = np.array([0, 1, 0])
pred = np.array([0., 0., 0.])


def plot_confusion_matrix(y_true, y_pred, title='', labels=[0, 1]):
    cm = confusion_matrix(y_true, y_pred)
    fig = plt.figure()
    ax = fig.add_subplot(111)
    cax = ax.matshow(cm)
    plt.title(title)
    fig.colorbar(cax)
    ax.set_xticklabels(['']   labels)
    ax.set_yticklabels(['']   labels)
    plt.xlabel('Predicted')
    plt.ylabel('True')
    fmt = '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="black" if cm[i, j] > thresh else "white")
    plt.show()


plot_confusion_matrix(true, pred, title='Confusion Matrix')

CodePudding user response:

The first coordinate of the plot usually is drawn horizontally, while the first coordinate of the matrix usually is represented vertically.

For example, the upper right square of the plot has coordinates x=1, y=0 This is false-positive values, which are presented in the cell (0, 1) of the confusion matrix.

To bring them into line with each other, it is necessary to flip the matrix along the main diagonal, i.e. transpose it. This is why you see coordinate transposition when displaying the confusion matrix in the coordinate system of the plot layout.

plot

  • Related