AI Logic

Evaluation Metrics

F1 Score

Updated:

Computation of the F1 score. The left shows the confusion matrix for 100 examples (TP 40, FN 20, FP 10, TN 30) and the column and row that form the denominators of precision and recall. The right shows the values computed from it: precision 0.80, recall 0.67, F1 score 0.73, and accuracy 0.70

Background and Overview

The F1 score is an evaluation metric that condenses classification results into a single number, the harmonic mean of precision and recall. It takes values from 0 to 1, and values closer to 1 mean the classifier "misses nothing it should catch, and catches nothing it should not".

F1=2⋅P⋅RP+RF_1 = \frac{2 \cdot P \cdot R}{P + R}

Here, PP is precision (the fraction of items predicted positive that are actually positive), and RR is recall (the fraction of actually positive items that were predicted positive).

Consider spam filtering as an example. High precision means "almost everything flagged as spam really is spam", and high recall means "almost no spam slips through". Either one alone is easy to raise: flagging everything as spam gives a recall of 1, but precision drops. The F1 score combines the two so that it is high only when both are high.

It originates from the effectiveness measure EE that the information retrieval researcher van Rijsbergen presented in his 1979 book. Today's F-measure corresponds to F=1−EF = 1 - E, and the version that weights precision and recall equally is called the F1 score.

Computing It from the Confusion Matrix

The F1 score is computed from the confusion matrix, a table that counts the number of items for each combination of actual label and prediction. In binary classification, it has four cells.

Predicted: positivePredicted: negative
Actual: positiveTP (correctly positive)FN (missed)
Actual: negativeFP (false detection)TN (correctly negative)

TP stands for True Positive, FP for False Positive, FN for False Negative, and TN for True Negative. The computation proceeds as follows.

  1. Count the items in the four cells of the confusion matrix.
    • Example: out of 100 items, TP = 40, FN = 20, FP = 10, TN = 30
  2. Compute precision from the predicted-positive column: P=TPTP+FPP = \dfrac{TP}{TP + FP}
    • Example: 40÷(40+10)=0.8040 \div (40 + 10) = 0.80
  3. Compute recall from the actual-positive row: R=TPTP+FNR = \dfrac{TP}{TP + FN}
    • Example: 40÷(40+20)≈0.6740 \div (40 + 20) \approx 0.67
  4. Take their harmonic mean: F1=2PRP+RF_1 = \dfrac{2PR}{P + R}
    • Example: 2×0.80×0.667÷(0.80+0.667)≈0.732 \times 0.80 \times 0.667 \div (0.80 + 0.667) \approx 0.73

Rearranging the formula, it can also be computed directly from the counts in the confusion matrix.

F1=2 TP2 TP+FP+FNF_1 = \frac{2\,TP}{2\,TP + FP + FN}

In the example above, 80÷(80+10+20)=80÷110≈0.7380 \div (80 + 10 + 20) = 80 \div 110 \approx 0.73, the same value. As this formula shows, the F1 score does not use TN (the number of items correctly judged negative).

The harmonic mean is used instead of the arithmetic mean so that the score is pulled strongly toward the lower value. For a model with precision 1.0 and recall 0.02 (a model that labels almost nothing as positive), the arithmetic mean is 0.51, but the harmonic mean (F1) is about 0.04. This keeps models that sacrifice one of the two from scoring well.

Difference from Accuracy

Accuracy (the fraction of all items classified correctly) is easy to understand, but it is useless on data where class counts are heavily imbalanced.

For example, consider a test for a disease where only 10 of 1,000 cases are positive, and a model that predicts "negative" for everything.

MetricComputationValue
Accuracy(0+990)÷1000(0 + 990) \div 10000.99
Recall0÷(0+10)0 \div (0 + 10)0
F1 score2×0÷(0+0+10)2 \times 0 \div (0 + 0 + 10)0

Accuracy looks high at 0.99, but the model has not found a single positive. The F1 score does not use TN and looks only at how well positives are caught, so it rates such a model at 0. On data with few positives (anomaly detection, disease screening, information retrieval, and so on), the F1 score reflects reality better than accuracy.

When TP and FP are both 0 (the model never predicts positive), the denominator of precision is 0 and the value is undefined. Libraries handle this differently: scikit-learn's f1_score returns 0 with a warning by default (this can be changed with zero_division). When comparing values across papers or experiments, match this handling and which class is treated as positive.

Fβ Score: Changing the Weights of Precision and Recall

The FβF_\beta score generalizes the F1 score so that you can choose whether to emphasize precision or recall.

Fβ=(1+β2)⋅P⋅Rβ2⋅P+RF_\beta = \frac{(1 + \beta^2) \cdot P \cdot R}{\beta^2 \cdot P + R}

β\beta expresses how many times more weight recall gets than precision (in van Rijsbergen's measure, it corresponds to "a user who attaches β\beta times as much importance to recall as to precision"). β=1\beta = 1 gives the F1 score.

MetricEmphasizesSuited for
F0.5F_{0.5}PrecisionWhen false detections are costly (e.g., in spam filtering, you do not want important mail marked as spam)
F1F_1Both, equallyWhen it is not decided which to emphasize
F2F_2RecallWhen misses are costly (e.g., disease screening, fraud detection)

Averaging in Multiclass Classification

In classification with three or more classes, the F1 score is computed for each class by treating "that class as positive and all others as negative", and the results are combined. There are three main ways to combine them.

AveragingHow it is computedCharacteristics
Macro averageSimple average of per-class F1Treats all classes equally. Performance on small classes has a strong effect
Micro averageSum TP, FP, and FN over all classes, then compute F1Performance on large classes has a strong effect
Weighted averageAverage per-class F1 weighted by each class's number of true instancesA macro average that accounts for class imbalance. The value may not lie between precision and recall

For example, with 3 classes, ground truth [0, 1, 2, 0, 1, 2] and predictions [0, 2, 1, 0, 0, 1], the per-class F1 scores are 0.8, 0, and 0, the macro average is about 0.27, and the micro average is about 0.33.

In multiclass classification where each item is assigned exactly one class, the micro-averaged F1 equals accuracy. This is because every error is an FP for one class and at the same time an FN for another. When you also want to see performance on small classes, use the macro average.

Caveats and Related Metrics

Keep the following in mind when using the F1 score.

  • It changes with the threshold: the F1 score depends on where the model's output probability is split into positive and negative. To evaluate model performance independently of the threshold, use ROC AUC or the precision–recall curve.
  • It ignores TN: for tasks where correctly identifying negatives also matters, the F1 score alone is not enough. Also check the confusion matrix itself and specificity (the fraction of negatives correctly judged negative).
  • The value depends on which class is positive: the same predictions give different values depending on which class is treated as positive.

The idea behind the F1 score underlies many task-specific metrics. mAP for object detection is computed from the precision–recall curve, and temporal action segmentation in video uses the segmental F1, which decides correctness by the overlap between segments. Also, because the F1 score is computed from classification results (0 or 1), it is not differentiable and cannot be used directly as a training loss. It is common to train with cross-entropy or similar and use the F1 score for evaluation. A loss that directly optimizes region overlap in a similar spirit is the Dice loss.

PyTorch example

Show code
python
import torch


def f1_per_class(pred, target, num_classes):
  '''Return per-class precision, recall, and F1 (0 when the denominator is 0)'''
  # Confusion matrix cm[i, j]: number of items whose actual class is i and predicted class is j
  cm = torch.zeros(num_classes, num_classes, dtype=torch.long)
  for t, p in zip(target.tolist(), pred.tolist()):
    cm[t, p] += 1
  tp = cm.diag().float()
  fp = cm.sum(dim=0).float() - tp  # items in the predicted-class column that were wrong
  fn = cm.sum(dim=1).float() - tp  # items in the actual-class row that were missed
  precision = torch.where(tp + fp > 0, tp / (tp + fp), torch.zeros_like(tp))
  recall = torch.where(tp + fn > 0, tp / (tp + fn), torch.zeros_like(tp))
  denom = 2 * tp + fp + fn
  f1 = torch.where(denom > 0, 2 * tp / denom, torch.zeros_like(tp))
  return precision, recall, f1, tp, fp, fn


# Binary example (positive = 1)
target = torch.tensor([1, 1, 1, 1, 0, 0, 0, 0, 0, 0])
pred   = torch.tensor([1, 1, 1, 0, 1, 0, 0, 0, 0, 0])
precision, recall, f1, *_ = f1_per_class(pred, target, num_classes=2)
print(f"precision {precision[1]:.3f}, recall {recall[1]:.3f}, F1 {f1[1]:.3f}")
# precision 0.750, recall 0.750, F1 0.750

# 3-class example: macro and micro averages
target = torch.tensor([0, 1, 2, 0, 1, 2])
pred   = torch.tensor([0, 2, 1, 0, 0, 1])
_, _, f1, tp, fp, fn = f1_per_class(pred, target, num_classes=3)
macro_f1 = f1.mean()                                          # average of per-class F1
micro_f1 = 2 * tp.sum() / (2 * tp.sum() + fp.sum() + fn.sum())  # sum the counts first, then compute
print(f"per-class F1 {[round(x, 3) for x in f1.tolist()]}, macro {macro_f1:.3f}, micro {micro_f1:.3f}")
# per-class F1 [0.8, 0.0, 0.0], macro 0.267, micro 0.333

FAQ

Q. What F1 score counts as good?
A.

There is no fixed threshold, because it varies greatly with the difficulty of the task and the proportion of positives. Judge it on the same data by comparing with predicting everything as positive, or with existing methods.

Q. Should I emphasize precision or recall?
A.

Decide by the cost of errors. If false detections are harmful, emphasize precision; if misses are harmful, emphasize recall, and use the F0.5 or F2 score. If you cannot decide, use the F1 score.

Q. Should I report the macro or the micro average?
A.

Use the macro average if performance on small classes matters just as much, and the micro average if you want to see how many items were classified correctly overall. It is important to use the same averaging as the papers you compare against.

References

  1. van Rijsbergen, C. J. (1979). Information Retrieval (2nd ed.), Chapter 7: Evaluation. Butterworths.
  2. Sokolova, M., & Lapalme, G. (2009). A systematic analysis of performance measures for classification tasks. Information Processing & Management, 45(4), 427–437.
  3. scikit-learn developers. sklearn.metrics.f1_score (API reference).