Skip to main content

Build a confusion matrix for a classifier with k classes, given integer true labels and predicted labels. For example, true labels 0, 0, 1, 2, 2, 2 and predictions 0, 1, 1, 2, 2, 0 give the rows (1, 1, 0), (0, 1, 0) and (1, 0, 2), with true classes as rows.

Coding rounds · Intermediate 2

Short answer

Make a k by k grid of zeros and add 1 at cell (true, predicted) for every example. State the convention: rows are true classes, columns are predicted. In NumPy use np.add.at(cm, (y, pred), 1), because plain indexed addition drops repeated pairs. Cost is O(n + k squared).

Deeper answer

Clarify first: are the labels integers from 0 to k - 1, or strings that need a mapping? Fix k from the full label set, not from this batch, or a class that is missing today removes a row. State the convention out loud: rows are the true class and columns are the predicted class.

Start with cm = np.zeros((k, k), dtype=int) and loop over the pairs, adding 1 at cm[t, p]. The vectorised version is np.add.at(cm, (y, pred), 1), or np.bincount(y * k + pred, minlength=k * k).reshape(k, k). The diagonal holds the correct predictions. Recall for each class is the diagonal divided by the row sums, and precision is the diagonal divided by the column sums.

Test that the matrix sums to n, that a perfect prediction gives a diagonal matrix, and that a repeated pair is counted twice. Interviewers watch for cm[y, pred] += 1, which counts each repeated pair only once, and for mixing up rows and columns.

What a strong answer covers

Answer it out loud in the mock interview about 2.5 min

Follow-ups to expect

Common mistakes

Learn it

Classification

Practice Coding rounds questions

More on this topic

Today's AI turns are used

Lessons, roadmaps, videos, practice cards and the code playground stay free with your account, with no limit.