Sub topic 15
Closing the Loop: Fix, Re-evaluate, Guard Against Regressions
This chapter covers the last step of error analysis: turning your ranked error categories into a change, checking whether the change worked, and making sure it stays working. It assumes you can already build an error table, slice results, and compute a bootstrap interval (earlier chapters), and that you know the roles of train, validation, and test splits.
Why one fix is not the end
Error analysis only pays off if the next model is better in the way you predicted. Three things commonly go wrong after a fix:
- The targeted category improves, but another category gets worse.
- The overall score rises by an amount that is within noise, so you cannot tell whether the fix did anything.
- You repeat the cycle many times on the same examples, and the model slowly overfits the data you analyze.
The remedy is a repeatable loop with a written hypothesis, a controlled change, a per-example comparison, and a permanent test suite.
Write the hypothesis first
Before changing anything, write one sentence that names the category, the fix, and the number you expect to move. For example: "Negation errors are 22% of errors. Adding 300 negated training examples should raise accuracy on the negation slice from 0.61 to at least 0.70 without lowering any other slice by more than 0.02."
This does two jobs. It tells you when to stop, and it prevents you from reading any improvement as a win after the fact.
Match the fix to the cause
The taxonomy you built should point toward the type of fix. The table lists common pairings.
| Error cause | Typical fix | Main risk |
|---|---|---|
| Label noise or inconsistent guidelines | Relabel or adjudicate the affected examples, then update the guidelines | Fixing the dev set but not the training set (or the reverse) makes scores incomparable |
| Missing coverage (rare phrasing, a domain, a dialect) | Collect or synthesize targeted examples | Synthetic data teaches the template, not the phenomenon |
| Systematic model weakness (negation, long inputs) | Data augmentation, a different architecture, or a longer context window | Gains on the slice with losses elsewhere |
| Preprocessing bug (tokenization, truncation, casing) | Fix the pipeline | Needs retraining, since the old model learned from the buggy inputs |
| Overconfident wrong predictions | Recalibrate (for example, temperature scaling) or add an abstain threshold | Calibration changes confidence, not accuracy |
| Spurious cues (a name or token the model leans on) | Counterfactual augmentation, as in your invariance tests | Fixing one cue and leaving others |
Pick the cheapest fix that plausibly addresses the largest category. A label correction or a pipeline bug fix often beats a model change.
Change one thing at a time
If you add data, switch the learning rate, and change the tokenizer in one run, you cannot attribute the result. Keep everything else fixed, including the random seed where possible.
Seeds still matter. Two runs of the same configuration with different seeds often differ by a few tenths of a point, and sometimes more on small data. For a decision that matters, train at least three seeds for both the baseline and the candidate. Compare the means and the spread, not a single pair of runs.
Re-evaluate on the right data
Use these rules to keep your measurements honest:
- Use the same dev set for before and after. If you relabeled dev examples, rescore the old model on the corrected labels too.
- Keep the test set out of the loop. Every time you look at test errors and act on them, the test set becomes another dev set. Do error analysis on dev, and spend the test set once per release decision.
- Do not train on the examples you inspected unless you split them first. If you add misclassified dev examples to the training set, your dev score will rise because of leakage, not because of the fix.
- Keep a fresh holdout if you iterate many times. After ten rounds of fixes guided by the same dev errors, the dev score is optimistic.
Compare before and after per example
An aggregate delta hides churn. A model that goes from 88% to 89% might have fixed 40 examples and broken 30 others. Those 30 "newly broken" examples are the ones users notice, because the old model got them right.
The code below joins the two runs, counts fixed and broken examples, and breaks the result down by slice.
import numpy as np
import pandas as pd
df = pd.DataFrame({
"id": range(8),
"slice": ["negation", "negation", "negation", "short",
"short", "long", "long", "long"],
"label": ["neg", "neg", "pos", "pos", "neg", "pos", "neg", "pos"],
"before": ["pos", "pos", "pos", "pos", "neg", "neg", "neg", "pos"],
"after": ["neg", "pos", "pos", "neg", "neg", "pos", "neg", "pos"],
})
df["ok_before"] = df["label"] == df["before"]
df["ok_after"] = df["label"] == df["after"]
df["fixed"] = ~df["ok_before"] & df["ok_after"]
df["broken"] = df["ok_before"] & ~df["ok_after"]
summary = df.groupby("slice").agg(
n=("id", "count"),
before=("ok_before", "mean"),
after=("ok_after", "mean"),
fixed=("fixed", "sum"),
broken=("broken", "sum"),
)
print(summary.round(2))
print("overall fixed:", int(df["fixed"].sum()), "broken:", int(df["broken"].sum()))
# Paired bootstrap on the per-example difference in correctness.
rng = np.random.default_rng(0)
diff = (df["ok_after"].astype(int) - df["ok_before"].astype(int)).to_numpy()
boot = [rng.choice(diff, size=len(diff), replace=True).mean() for _ in range(2000)]
low, high = np.percentile(boot, [2.5, 97.5])
print(f"mean gain={diff.mean():.3f}, 95% CI=({low:.3f}, {high:.3f})")In this toy data the negation slice improves, the short slice loses an example it used to get right, and overall the model gains one net example. With only eight rows the interval will include zero, which is the correct conclusion: the data cannot separate a real gain from noise.
Resampling the per-example differences (a paired bootstrap) is stronger than comparing two separate intervals. Both models are scored on the same examples, so their errors are correlated, and the paired interval uses that.
Guard against regressions
A regression is a case the model used to handle correctly and no longer does. Guarding against regressions means turning your findings into automated checks that run on every candidate model. Keep three kinds of cases in the suite:
- Fixed errors. Each category you repaired contributes a handful of representative examples. If a later change breaks them, you find out immediately.
- Behavioral tests. Keep the invariance and perturbation templates from earlier, with their failure rates tracked over time.
- Critical slices. Keep the slices that matter most to users, each with a minimum size so the metric is stable.
Then encode a release gate. The function below flags any slice that drops by more than a tolerance, and skips slices that are too small to judge, reporting them separately instead of silently passing them.
def check_regressions(before, after, max_slice_drop=0.02, min_n=30):
"""before/after map slice name -> (accuracy, n). Returns (problems, skipped)."""
problems, skipped = [], []
for name, (acc_before, n_before) in before.items():
acc_after, n_after = after[name]
n = min(n_before, n_after)
if n < min_n:
skipped.append(f"{name} (n={n})")
continue
if acc_before - acc_after > max_slice_drop:
problems.append(f"{name}: {acc_before:.2f} -> {acc_after:.2f} (n={n})")
return problems, skipped
before = {"overall": (0.88, 1000), "negation": (0.61, 120),
"short": (0.90, 200), "typos": (0.70, 20)}
after = {"overall": (0.89, 1000), "negation": (0.72, 120),
"short": (0.85, 200), "typos": (0.60, 20)}
problems, skipped = check_regressions(before, after)
print("problems:", problems)
print("skipped:", skipped)This prints one problem, the short slice falling from 0.90 to 0.85, and skips typos because 20 examples is too few. The overall score and the negation slice both improved, so a gate that only watched the overall score would have shipped the regression.
Wire a function like this into your test runner or CI job so that a failing gate blocks the merge. A tolerance of 0.02 is a starting point. Set it from the bootstrap interval width of each slice, so that noisy slices get wider tolerances.
Edge cases and failure modes
- Moving targets. If you relabel the dev set, rerun the baseline on the new labels. Never compare a new model on corrected labels with an old score on old labels.
- Overfitting to the suite. A regression suite that only grows becomes a training target if its examples leak into training data. Keep it out of the training set, and refresh it with new real examples periodically.
- Whack-a-mole. If every fix breaks something else, the categories likely share a cause, such as a capacity limit or conflicting labels. Revisit the taxonomy before making another fix.
- Diminishing returns. Stop when the remaining categories are small, hard to fix, or driven by ambiguous labels. Estimate the ceiling by checking how often annotators agree with each other.
- Production drift. Offline gates do not see new inputs. Sample production errors regularly, run them through the same taxonomy, and feed new categories back into the loop.
Exercise
A candidate model raises overall dev accuracy from 0.880 to 0.889, and the negation slice (n=120) from 0.61 to 0.72. The per-example comparison shows 45 examples fixed and 36 broken, and the "short text" slice drops from 0.90 to 0.85 (n=200). Should you ship? Name two checks you would run before deciding.
Show answer
Do not ship yet. The overall gain is small relative to churn (45 fixed, 36 broken), and the short-text slice dropped by 0.05, which is a regression on a slice that previously worked. First, compute a paired bootstrap interval on the per-example differences to see whether the overall gain is distinguishable from zero, and whether the short-text drop is. Second, read the broken short-text examples and tag them to see whether the fix caused a pattern (for example, the model now over-predicts negation on short inputs). Then adjust the fix, such as rebalancing the added data, and rerun the gate. Ship only if the target slice improves and no protected slice drops beyond its tolerance.