Sub topic 2
Choosing metrics and setting a baseline
Error analysis starts before you look at a single mistake. You need a metric that reflects what the model is for, and a baseline that tells you whether the score is good. This chapter covers both. It assumes you can train and evaluate a text classifier or tagger, that you know accuracy, precision, recall and F1, and that you use separate train, validation and test splits.
Why the metric choice comes first
Every later step in error analysis depends on the metric. Slicing, ranking error categories and judging whether a fix worked all compare numbers. If the metric rewards the wrong behavior, you will optimize the wrong thing and your error analysis will point you at the wrong errors.
Choose the metric from the decision the model supports, not from habit. Ask three questions:
- Which mistake costs more: a false positive or a false negative?
- Are the classes balanced, or does one class dominate?
- Is the output a single label per text, several labels per text, or spans inside the text?
Common metrics and when they mislead
| Metric | What it measures | Typical failure |
|---|---|---|
| Accuracy | Share of examples predicted correctly | Looks high when one class dominates |
| Micro F1 | F1 from pooled counts over all examples | Dominated by frequent classes. For single-label tasks it equals accuracy |
| Macro F1 | Unweighted mean of per-class F1 | Noisy when a class has very few examples |
| Weighted F1 | Mean of per-class F1 weighted by class size | Hides rare-class failures like micro F1 does |
| Precision / recall | Cost of false positives / false negatives | Each alone can be gamed by predicting too much or too little |
| Entity-level F1 | F1 over whole spans, with exact match | Counts a one-token boundary slip as a full miss plus a spurious span |
Two points deserve attention.
First, micro and macro averaging answer different questions. Micro F1 asks how often the model is right across all predictions. Macro F1 asks how well the model does on the average class, so a rare class counts as much as a common one. If a rare class matters to your users, report macro F1 or the per-class scores, and do not rely on a pooled number.
Second, a metric is only meaningful with its support, the number of examples behind it. A per-class F1 computed from five examples can swing widely from one run to the next. Always print the class counts next to the scores.
Pick one primary metric and a few diagnostics
Select one primary metric to decide whether a change helped. Keep a short list of diagnostic metrics, such as per-class recall or slice scores, to understand why. Without a single primary metric, every comparison becomes an argument, and you can find some number that improved after any change.
Write the choice down with the reason. For example: "Primary: macro F1 on the held-out test set, because the neg class is rare but is the one the support team acts on. Diagnostics: per-class precision and recall, confusion matrix." This record keeps later experiments comparable.
A baseline tells you what a score means
A score of 0.80 means nothing alone. On a balanced task it may be strong. On a dataset where 70% of examples share one label it may barely beat a model that ignores the text.
Build baselines from simple to complex, and keep every one in your results table:
- Majority-class baseline. Always predict the most frequent training label. It sets the floor for accuracy.
- Simple model baseline. A bag-of-words or TF-IDF model with logistic regression. It is fast and shows how much a large model adds.
- Rule or lexicon baseline. Keyword rules, if the task has obvious cues. It also reveals which errors need real language understanding.
- Human or annotator agreement. When two people disagree on 10% of examples, a model cannot be expected to exceed roughly 90% agreement with either of them.
The majority baseline takes a few lines. This example shows how accuracy hides what macro F1 reveals:
import numpy as np
from sklearn.dummy import DummyClassifier
from sklearn.metrics import accuracy_score, f1_score
y_train = ["pos"] * 70 + ["neu"] * 20 + ["neg"] * 10
y_test = ["pos"] * 14 + ["neu"] * 4 + ["neg"] * 2
# Model predictions: 13/14 pos right, 2/4 neu right, 1/2 neg right.
y_model = (
["pos"] * 13 + ["neu"] # true pos
+ ["neu", "neu", "pos", "neg"] # true neu
+ ["neg", "pos"] # true neg
)
# The majority baseline ignores its features, so zeros are enough.
baseline = DummyClassifier(strategy="most_frequent")
baseline.fit(np.zeros((len(y_train), 1)), y_train)
y_base = baseline.predict(np.zeros((len(y_test), 1)))
for name, pred in [("majority", y_base), ("model", y_model)]:
acc = accuracy_score(y_test, pred)
macro = f1_score(y_test, pred, average="macro", zero_division=0)
print(f"{name:9s} accuracy={acc:.2f} macro-F1={macro:.2f}")The majority baseline reaches accuracy 0.70 with a macro F1 of about 0.27. The model reaches 0.80 and about 0.66. The accuracy gap looks small, while the macro F1 gap shows that the baseline never predicts two of the three classes.
Evaluate on the right split
Metrics are only trustworthy on data the model did not learn from or tune against. Keep these rules:
- Tune hyperparameters and choose thresholds on the validation set.
- Read errors from the validation set during development. Reserve the test set for a small number of final checks.
- If you read test errors and then change the model to fix them, the test set has become part of development. Keep a fresh held-out set if you plan many rounds.
- Make sure no near-duplicate texts appear across splits. Duplicates inflate scores and hide errors you would otherwise see.
Run-to-run variance
Neural models vary between runs because of random initialization, data order and dropout. A difference of 0.5 points between two models can be a different seed rather than a real improvement. Train the baseline and the model with several seeds and compare the spread:
import numpy as np
# Macro F1 from five seeds for each system (illustrative values).
baseline_scores = np.array([0.61, 0.64, 0.60, 0.63, 0.62])
model_scores = np.array([0.66, 0.69, 0.65, 0.70, 0.67])
for name, s in [("baseline", baseline_scores), ("model", model_scores)]:
print(f"{name:9s} mean={s.mean():.3f} std={s.std(ddof=1):.3f}")
gap = model_scores.mean() - baseline_scores.mean()
print(f"gap={gap:.3f}")Here the gap of about 0.05 is several times the standard deviation of each system, so it is unlikely to be seed noise. If the gap were smaller than the standard deviation, you could not claim an improvement from this evidence. Chapter-level details on uncertainty for slices come later in this tutorial.
Metrics for sequence labeling
For taggers such as named entity recognition, token-level accuracy is misleading. Most tokens carry the outside tag, so a model that tags nothing scores high. Use entity-level precision, recall and F1, where a predicted span counts as correct only if its boundaries and type both match a gold span.
Exact match is strict. A prediction of "New York City" against a gold "New York" counts as one missed span and one spurious span. Report the strict score as your primary metric, and keep in mind that later error analysis will separate boundary errors from type errors, since they need different fixes.
Common mistakes
- Reporting only accuracy on an imbalanced dataset.
- Comparing a model against a baseline scored with a different metric or split.
- Using weighted F1 and assuming it protects rare classes. It does the opposite.
- Changing the primary metric after seeing results.
- Treating a single run as the final number.
- Computing macro F1 over a class with only a handful of test examples and reading the result as precise.
Record the starting point
Before you inspect any errors, save a short results table: metric definitions, split sizes, class counts, baseline scores, model scores with seed spread, and the date and code version. Every later chapter's findings compare against this record. It also shows when an apparent improvement is smaller than the noise.
Exercise
A test set has 95% negative and 5% positive examples. A model predicts "negative" for every text. What are its accuracy and macro F1, and what should you conclude about reporting accuracy for this task?
Show answer
Accuracy is 0.95. For the negative class, precision is 0.95 and recall is 1.0, so F1 is about 0.974. For the positive class, F1 is 0. Macro F1 is the mean, about 0.49. A model that never finds a positive example scores 95% accuracy, so accuracy cannot tell a useful model from a useless one here. Report macro F1 or per-class precision and recall for the positive class, and show the majority baseline next to every score.
Exercise
Two systems have mean macro F1 of 0.672 and 0.668 across five seeds, and each has a standard deviation of 0.015. Can you say the first is better?
Show answer
No. The gap of 0.004 is far smaller than the seed-to-seed standard deviation of 0.015, so the difference is within run-to-run noise. You would need more seeds, a larger test set, or a bigger gap before claiming an improvement.