Micro-F1: Pool the Counts, Then Score

Metrics & EvaluationEasy+10 XP+10

Micro-F1: Pool the Counts, Then Score

With more than two classes there's no single "positive" class, so precision and recall need pooling. Micro-averaging pools the counts themselves: total up true positives, false positives and false negatives across every class, then compute one precision, one recall, one F1.

For each class c, counting over all samples:

  • TP — predicted c, actually c
  • FP — predicted c, actually something else
  • FN — predicted something else, actually c

Then precision = TP / (TP + FP), recall = TP / (TP + FN), and F1 = 2·P·R / (P + R).

Task: write micro_f1(y_true, y_pred) returning the micro-averaged F1, rounded to 4 decimal places.

  • Consider every class appearing in either list.
  • Return 0.0 if there are no true positives at all.

Micro-averaging is dominated by whichever classes have the most samples — a rare class barely moves it. That's the opposite of macro-averaging, which gives every class an equal vote regardless of size. Neither is more correct; they answer different questions.

Examples

y_true = [0, 1, 2, 0, 1]
y_pred = [0, 2, 2, 0, 1]
returns 0.8
y_true = [1, 1, 0]
y_pred = [1, 1, 0]
returns 1.0

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run