Error analysis for machine learning models
Run an error-analysis loop that compares slices, bootstraps uncertainty, flags label mistakes and records data limitations.
By Invicly Tech, , in AI and Machine Learning with Python. About 12 minutes to read.
In short
One overall score hides where a model fails. Error analysis breaks the score down by meaningful slices such as region, device or age band, measures how uncertain each number is, looks at the worst mistakes by hand and writes down what the data cannot tell you. It turns evaluation into a repeatable loop that tells you what to fix next and what to warn users about.
Think of it like this: An overall score is a school's average grade; error analysis is reading the results class by class and finding the one class where half the pupils failed.
Explained simply
Your model scores 0.85 overall. That number is an average, and averages hide things. The model might score 0.95 for city customers and 0.55 for rural ones. Error analysis is the habit of breaking the score into pieces to find out where the model struggles and why.
A piece of the data is called a slice: one country, one device type, one age band, one product line. You compute the same metric for each slice and look for big gaps. You also count how many rows each slice has, because a slice with ten rows can look terrible or perfect by pure luck.
To know whether a gap is real, you measure uncertainty. The bootstrap is a simple trick: draw rows at random with replacement to make many pretend test sets, compute the metric on each, and see how much it moves. The middle 95 percent of those values is a confidence interval.
Finally, read some mistakes yourself. Sometimes the model is wrong. Sometimes the label is wrong, and the model was right. Sometimes the data simply does not cover a case. Write down what you find, including what the data cannot tell you, so the next person does not have to rediscover it.
Press Play on a diagram to walk through it one step at a time.
- 1Score
Out-of-fold or validation predictions
- 2Slice
Metrics by group, with row counts
- 3Quantify
Bootstrap intervals per slice
- 4Inspect
Read the worst errors and suspect labels
- 5Act and record
Fix data or model, log limitations
- Back to step 1
- Label is wrong
- Fix with review and a reason
- Check the labelling guide
- Case is ambiguous
- Clarify the label definition
- Consider an abstain or review route
- Data missing or unusual
- Record as a limitation
- Collect more of this slice
- Model limitation
- New feature or model type
- Re-check the slice after changes
In depth
Choosing slices that matter
Good slices come from how the model will be used and who it affects. Start with groups the business cares about (region, product, channel), groups where data quality may differ (device, data source, collection period), and groups where unfair outcomes would cause harm (age band or other sensitive attributes, where you are allowed and able to hold them). Add slices from the model itself, such as rows with missing values or very low confidence.
For each slice report row count, positive count, the main metric and the error types. Compare false negative and false positive rates across groups, not only accuracy, because a model can have equal accuracy while one group gets most of the false alarms. Keep the slice list in code so every new model version is checked the same way.
- Business groups: region, product, channel
- Data quality groups: device, source, period
- Groups at risk of unfair outcomes
- Model-driven: missing values, low confidence
Bootstrapping metric uncertainty
The bootstrap estimates how much a metric would change with a different sample of evaluation data. Take the n evaluation rows, draw n rows with replacement, compute the metric, and repeat 1,000 or more times. The 2.5th and 97.5th percentiles of the results form a 95 percent percentile interval.
Do it per slice: small slices give wide intervals, which stops you from over-reacting to noise. To compare two models, resample the same rows for both in each round and look at the interval of the difference; if it excludes zero, the gap is probably real. Keep rows from the same group together by resampling groups instead of rows when your data has repeated customers. Fix the random seed so the report is reproducible.
- 1Slice rows
n predictions with true labels
- 2Resample
Draw n rows with replacement
- 3Compute metric
Recall, MAE or any score
- 4Repeat 1,000 times
Collect the distribution
- 5Take percentiles
2.5th and 97.5th give the interval
Finding likely label mistakes
Labels come from people and processes, and both make errors. A practical way to find suspects is to get out-of-fold probabilities with cross_val_predict(method="predict_proba"), so each row is scored by a model that did not train on it. Then list rows where the model is very confident and disagrees with the label, such as a score above 0.95 for a row labelled negative.
Review a sample of these by hand with a clear guide, and record for each one whether the label was wrong, the case was ambiguous, or the model was wrong. If label errors are common, fixing them may help more than any model change. Libraries such as cleanlab automate this idea, known as confident learning. Never silently relabel the test set to raise your score; document every change and why.
- Use out-of-fold scores, not training scores
- Sort by confident disagreement
- Review by hand with a written guide
- Log each relabel with a reason
An evaluation rubric and a limitations log
A rubric turns evaluation into a checklist that every model version must pass. It names the primary metric and its minimum, the baseline to beat, the slices to report and the worst acceptable slice score, the confidence interval method, the threshold and how it was chosen, and the manual review steps such as reading 50 errors.
The limitations log records what the data cannot support: regions with too few rows, label definitions that changed in a given month, features that are missing for one source, populations not represented at all. Each entry should say how it affects the model and what users should do about it. Both documents feed the model card, which is covered later in the path.
Learn it in 5 short steps
About 35m each. Track them with a timer in your plan.
- 1Compare metrics by slice~35m
- 2Bootstrap metric uncertainty~35m
- 3Inspect likely label errors~35m
- 4Write an evaluation rubric~35m
- 5Record data limitations~35m
Key points
- Report each slice with its row count; a slice of 30 rows can swing wildly by chance.
- Bootstrap resampling of the evaluation set gives a confidence interval for any metric.
- Some errors are label mistakes, not model mistakes; confident disagreements between model and label are good places to look.
- A written rubric with metrics, minimum slice performance and review steps makes evaluation repeatable across model versions.
- Record data limitations, such as missing regions or old labels, so they reach the model card and the people who use the model.
Key terms
Tap a card to flip it. 0/6 known
Examples
import pandas as pd
from sklearn.metrics import recall_score, precision_score
# df has columns: y_true, y_pred, region (from a validation set)
def summarise(g):
return pd.Series({
"rows": len(g),
"positives": int(g.y_true.sum()),
"recall": recall_score(g.y_true, g.y_pred, zero_division=0),
"precision": precision_score(g.y_true, g.y_pred, zero_division=0),
})
report = df.groupby("region")[["y_true", "y_pred"]].apply(summarise)
print(report.sort_values("recall"))Sort by the weakest metric so the worst slices appear first.
A slice report with bootstrap intervals
You have validation predictions for a churn model with a region column. Step 1: group by region and compute recall with its row and positive counts. Step 2: for each region, bootstrap recall 1,000 times with a fixed seed. Step 3: print the interval next to each value. Expect large regions to have narrow intervals and the smallest region a very wide one. Step 4: only flag a region as weak if its interval sits clearly below the others, and write the small regions into the limitations log as under-tested.
import numpy as np
from sklearn.metrics import recall_score
rng = np.random.default_rng(42)
def boot_recall(y, p, n=1000):
idx = rng.integers(0, len(y), size=(n, len(y)))
vals = [recall_score(y[i], p[i], zero_division=0) for i in idx]
return np.percentile(vals, [2.5, 97.5])
for region, g in df.groupby("region"):
y, p = g.y_true.to_numpy(), g.y_pred.to_numpy()
lo, hi = boot_recall(y, p)
print(f"{region:8s} n={len(g):5d} pos={y.sum():4d} "
f"recall={recall_score(y, p, zero_division=0):.2f} [{lo:.2f}, {hi:.2f}]")Hunting for label errors with out-of-fold scores
Step 1: on the training data, get out-of-fold probabilities with 5-fold cross_val_predict. Step 2: compute how strongly each row disagrees with its label: the score for rows labelled 0, one minus the score for rows labelled 1. Step 3: list the 30 strongest disagreements. Step 4: review them with the labelling guide and tag each as label error, ambiguous or model error. Step 5: report the share of each tag. If, say, a third are label errors, fixing labels is a better next step than tuning the model. The numbers here are illustrative; your share will differ.
import numpy as np
import pandas as pd
from sklearn.model_selection import cross_val_predict
p = cross_val_predict(model, X_tr, y_tr, cv=5, method="predict_proba")[:, 1]
y = np.asarray(y_tr)
disagree = np.where(y == 1, 1 - p, p)
suspects = (pd.DataFrame({"label": y, "score": p, "disagree": disagree})
.sort_values("disagree", ascending=False).head(30))
print(suspects)
# Review these rows by hand and record a tag for each one.Quick reference
- Report every slice with row count and positive count
- Bootstrap: resample n rows with replacement 1,000+ times; take 2.5th and 97.5th percentiles
- Compare models on the same resampled rows and check the interval of the difference
- Use cross_val_predict(method="predict_proba") to get out-of-fold scores
- Confident disagreement with the label = candidate label error
- Compare false positive and false negative rates across groups, not just accuracy
- Keep the rubric and slice list in code so every version is checked the same way
Common mistakes
- Chasing a slice that looks bad but has so few rows that its score is mostly noise.
- Slicing the test set over and over until something looks interesting, then treating it as a finding without checking on fresh data.
- Assuming every high-confidence error is the model's fault when the label itself may be wrong.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Build a small DataFrame of synthetic predictions with a device column (mobile, desktop, tablet) and print accuracy and row count per device.
- Exercise 2medium
Write a function that returns a 95 percent bootstrap interval for any metric function and apply it to accuracy per device from the easy exercise.
- Exercise 3hard
Flip 5 percent of labels in the breast cancer training set on purpose, then use out-of-fold probabilities to rank suspects. Report how many of the top 30 suspects are rows you flipped.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- How many errors should I read by hand?
- Start with 50 to 100, sampled from the largest error types and the weakest slices. Stop when new rows stop revealing new kinds of mistake.
- Is error analysis only for classification?
- No. For regression, slice MAE or RMSE and read the rows with the largest absolute residuals. The same loop applies.
- What if I do not have sensitive attributes to check fairness?
- Say so in the limitations log. Check related slices you do have, such as region, and plan how to evaluate properly with appropriate data and permission.
- Can I slice the test set as much as I want?
- Slicing for reporting is fine, but if you search many slices for something odd, some will look bad by chance. Confirm surprising findings on validation data or new data before acting.