Skip to content

← Metrics & Evaluation step 3 of 7

Medium Primitives

Precision, Recall & F1

Precision and recall answer different questions for each class:

  • Precision: of the examples predicted as this class, how many were correct?
  • Recall: of the examples truly in this class, how many were found?

For a chosen class, a true positive (TP) is a correct prediction of that class. A false positive (FP) is a prediction of that class with another true label. A false negative (FN) is a true example of that class predicted as something else.

precision = TP / (TP + FP)

recall = TP / (TP + FN)

F1 = 2 * precision * recall / (precision + recall)

F1 is the harmonic mean of precision and recall. It is zero if either is zero. It summarizes the two rates, but does not replace choosing how much false positives and false negatives matter for a particular task.

For labels [0, 0, 1, 1] and predictions [0, 1, 1, 1], class 0 has precision 1, recall 0.5, and F1 about 0.666667. Class 1 has precision about 0.666667, recall 1, and F1 0.8. Their macro-F1 is the mean of those two F1 values, approximately 0.733333.

Your task

Implement precision_recall_f1(predictions, labels, num_classes):

  • predictions and labels are class IDs with matching shape (N,), not score vectors. Whole-number IDs lie in [0, C - 1] and may be stored as floating-point values by the test input.
  • num_classes is a positive integer C. Compute results for all C classes.
  • Whenever a metric's denominator is zero, return 0 for that metric. Thus a class absent from both predictions and labels has P=R=F1=0.

Compute each metric separately per class, then take its unweighted mean over all C classes, including absent ones. These are macro-averages. Macro-F1 is the mean of the per-class F1 values, not the harmonic mean of macro-precision and macro-recall. Do not weight by class frequency. For empty inputs, every entry of the result is zero.

Return a floating-point tensor of shape (3, C + 1):

Row First C columns, in class-ID order Last column
0 Per-class precision Macro-precision
1 Per-class recall Macro-recall
2 Per-class F1 Macro-F1

A confusion matrix can help: with true labels in rows and predictions in columns, TP is the diagonal, TP+FP is a column sum, and TP+FN is a row sum. You may also count those quantities directly.