Multiclass Confusion Matrix & Macro-F1

easy
Checkpoint challenge
Solve this to show you know the material and jump straight to Unit 2. Everything before it counts as cleared.

For multiclass problems, accuracy hides which classes the model confuses. A confusion matrix shows it: row ii, column jj counts examples whose true label is labels[i] and predicted label is labels[j].

Implement:

  • confusion_matrix(y_true, y_pred, labels), returning a NumPy integer array of shape (len(labels), len(labels)). Ignore any example whose true or predicted label isn't in labels.
  • macro_f1(cm): compute F1 for each class from the matrix (precision = diagonal / column sum, recall = diagonal / row sum), then average over classes. A class with no predictions or no true examples has F1 of 0 for that class.

Example

confusion_matrix(["cat", "dog", "cat", "bird"], ["cat", "cat", "cat", "bird"], ["bird", "cat", "dog"])
# [[1, 0, 0],
#  [0, 2, 0],
#  [0, 1, 0]]
#evaluation#classification#numpy2 visible + 3 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
Multiclass Confusion Matrix & Macro-F1 · TechGradify