Before you start
Build the confusion matrix for a multiclass problem.
C[i, j] counts the samples whose true label is i and whose predicted label is
j. The diagonal holds the correct predictions and everything off it is a
specific kind of mistake, which is why the matrix tells you far more than a
single accuracy number: it says which classes the model confuses.
Labels are integers in [0, num_classes). Return an integer array of shape
(num_classes, num_classes).
Watch the orientation. Rows are truth and columns are predictions, so C[2, 5]
means "actually a 2, called a 5".
def confusion_matrix(y_true, y_pred, num_classes):
Input
y_true = np.array([0, 1, 1, 2])
y_pred = np.array([0, 1, 2, 2])
confusion_matrix(y_true, y_pred, 3)
Output
array([[1, 0, 0],
[0, 1, 1],
[0, 0, 1]])
Reasoning
Three samples are correct, so they land on the diagonal. The one mistake is a true 1 predicted as 2, which adds one to C[1, 2].
(num_classes, num_classes).Check runs the visible cases against a fresh kernel. Submit runs the hidden ones too.
⇧↵run cell