Compute macro and micro F1 for a multi-class classifier
With imbalanced classes, one F1 number can hide a lot. Micro F1 pools every decision, so big classes dominate. Macro F1 averages the per-class scores, so a rare class you always miss drags it down. Reporting both is standard for intent classifiers and safety filters.
Write f1_scores(y_true, y_pred, num_classes). Labels are ints in [0, num_classes). For each class c compute TP, FP, FN. Per class: precision = TP / (TP + FP), recall = TP / (TP + FN), F1 = 2 * P * R / (P + R). Any division by zero gives 0 (so a class that never appears and is never predicted has F1 = 0).
- macro = mean of the per-class F1 over all num_classes classes.
- micro = F1 computed from the summed TP, FP and FN across classes.
Return (macro, micro) as floats.
def f1_scores(y_true, y_pred, num_classes)Example
y_true = [0, 0, 1, 2], y_pred = [0, 1, 1, 2], num_classes = 3. Per-class F1 = [0.6667, 0.6667, 1.0], macro = 0.7778, micro = 0.75.
Understand the idea
F1 balances two questions: of the items I called class c, how many were right (precision), and of the real class c items, how many did I catch (recall). With several classes you can average in two ways. Macro F1 scores each class on its own and takes the plain mean, so a rare class counts as much as a big one. Micro F1 first adds up TP, FP and FN over all classes and computes one F1 from the totals. Worked example: y_true = [0, 1, 1, 1], y_pred = [0, 0, 1, 1]. Class 0: TP 1, FP 1, FN 0, so P = 0.5, R = 1, F1 = 0.667. Class 1: TP 2, FP 0, FN 1, so P = 1, R = 0.667, F1 = 0.8. Macro = (0.667 + 0.8) / 2 = 0.733. Micro: TP 3, FP 1, FN 1, so F1 = 0.75. Rule: F1 = 2PR / (P + R), and any 0 / 0 is treated as 0. Used for intent classifiers, toxicity filters and any imbalanced label set.