Module 9 · Data: quality, splits, leakage, labels and distribution shift
Time: about 5 hours with readings · Lab: python course/labs/lab09_data.py (about a minute)
You need: Module 1 §3 and §7 (training, validation and test data, and why each exists) and Module 2 §6 (independence and the two probability rules) and §10 (sampling variability).
By the end you can:
- check a dataset's quality along six named dimensions, and say what each problem does to a result;
- describe exactly where TrayCheck's data came from and how it was split;
- explain what to split by, and name the common kinds of leakage;
- explain how wrong labels damage both training and measurement, and measure how much two people agree (Cohen's kappa);
- name the four kinds of distribution shift and say which ones a hospital pilot will face;
- prepare a test dataset for a proof of concept: representative, big enough, properly labelled, documented.
Why this matters for the internship
The position description asks you to "assist with identifying and preparing appropriate datasets for testing and validation" and to "support analysis of data quality, completeness and accuracy". An evaluation is only as honest as its data. An interviewer who knows ML will ask "how do you know that number is real?" The answer lives here: clean data, checked splits, choices made on validation data only, trustworthy labels, and a clear statement of what the data does not cover.
1. Data quality: six dimensions
Data quality is usually broken into a handful of named dimensions. The exact list varies between frameworks, but these six cover what you will meet in a food-service PoC:
| Dimension | Question | Food-service example | Typical check |
|---|---|---|---|
| Completeness | Is anything missing? | A tray with a served weight but no returned weight | Count missing values per field |
| Validity | Do values obey the rules? | Returned weight greater than served weight; a negative weight; a meal period called "brunch" | Range and rule checks |
| Accuracy | Do values match reality? | The photo is labelled bibimbap but the tray held ribs | Compare a sample against a trusted reference |
| Consistency | Do related values agree? | The menu says lunch had four dishes, the records show five | Cross-check between tables or systems |
| Uniqueness | Is anything recorded twice? | The same tray scanned twice | Look for duplicate IDs or identical photos |
| Timeliness | Is it recorded when it happened? | Weights typed in at the end of the shift, from memory | Compare event time with entry time |
What problems do to results. Missing returned weights silently drop trays from waste averages; if the trays most likely to go unweighed are the full ones (staff busy, trays cleared in a hurry), the reported waste is biased low, not just noisier. Invalid values such as "returned more than served" produce negative waste. Inaccurate labels move waste from one dish to another. Always ask whether the problem is random or systematic. Random problems add noise; systematic ones bias the answer.
TrayCheck's checks (records.py):
def data_problems(frame):
served, returned = frame["served_g"], frame["returned_g"]
return {
"served without returned weight": int((served.notna() & returned.isna()).sum()),
"returned without served weight": int((served.isna() & returned.notna()).sum()),
"returned more than served": int((returned > served).sum()),
}
In the simulated month (811 records) these find 21 trays with no returned weight and 5 where
the returned weight is larger than the served weight (simulated typing mistakes). The dashboard
shows these counts and leaves those trays out of waste figures (usable_weights), instead of
quietly averaging nonsense. Reporting how many records were excluded, and why, is part of an
honest result.
2. TrayCheck's data, precisely
- Source: Food-101 (Bossard, Guillaumin & Van Gool, ECCV 2014): 101 dishes, 101,000 photos from the Foodspotting website, 750 training and 250 test photos per dish. The authors deliberately did not clean the training photos, which contain some noise and some wrong labels. The test photos were checked by hand.
- Subset: the
food_mnistrepository (a small Food-101 sample: 10 dishes, 375 training and 125 test photos each). TrayCheck uses 4 dishes. - Splits (
vision_prepare.py, fixed random seed):
| Split | Per dish | Taken from | Used for |
|---|---|---|---|
| Training | 100 | Food-101 training photos | Fitting parameters |
| Validation | 20 | Food-101 training photos (different ones) | Early stopping; choosing the review threshold |
| Test | 40 | Food-101 test photos | The final measurement only |
- Provenance:
data/vision/manifest.csvrecords each photo's split, label, source URL and SHA-256 hash (a fingerprint of the file's contents), so anyone can verify the exact files used.
Lab 9 checks the hygiene from the manifest alone:
photos sharing identical file contents (SHA-256): 0
identical files in both train and val: 0
identical files in both train and test: 0
identical files in both val and test: 0
train+val photos all from the source's TRAIN split: True; test photos all from its TEST split: True
Hashes only catch identical files. A resized or re-saved copy has a different hash; finding those near-duplicates needs image similarity (Module 8's similarity matrix is the starting point).
3. Splits: why three, and split by what?
The validation set exists so the test set can stay untouched (Module 1). The less obvious question is what to split by.
Splitting photos at random is fine when photos are independent. In a hospital pilot they won't be: the same tray may be photographed at plating and at return, one kitchen shares its lighting and crockery, one day shares a menu. If photos of one tray land in both the training and the test set, the test partly measures memory, not recognition. The rule:
Split by the unit you want to generalise to. To know whether the model works on new trays, keep each tray's photos on one side. For a new kitchen, hold out whole kitchens. For next month, train on earlier dates and test on later ones.
The vendor's accuracy claim is only as strong as their split. "Tested on 2,000 held-out photos" means little if those photos came from the same days and trays as the training photos.
When data is scarce: cross-validation. With few examples, setting aside a validation set hurts. Cross-validation reuses the training data instead: split it into, say, 5 equal parts (folds); train on 4 and validate on the 5th; repeat so each fold takes a turn as the validation set; average the 5 scores. Every example is used for validation once, and the average is steadier than any single split. The test set still stays outside all of this, untouched until the end.
4. Leakage: the silent evaluation killer
Leakage is any way information about the evaluation data gets into training or into choices about the model, making results look better than they will be in real use. It is common even in published research: one review found leakage errors affecting hundreds of papers across many fields.
| Kind | Example | TrayCheck's guard |
|---|---|---|
| Duplicates across splits | The same photo (or tray) in training and test | Separate source splits; hash check |
| Preprocessing fitted on all data | Rescaling with the whole dataset's average, including test photos | preprocess_input uses fixed constants, not data statistics |
| Choosing on the test set | Picking the best model or threshold by test score | Threshold chosen on validation; test only measured |
| Target leakage | An input that secretly contains the answer (for example, the reviewer's label, or a field filled in after the outcome) | review_rules.decide() receives only the scores, the menu and a random number; it never sees the true dish |
| Temporal leakage | Training a forecast on data from after the dates it predicts | The old demand forecast splits by date (analyze.py) |
Lab 9 demonstrates two kinds of leakage. For speed it uses scikit-learn's handwritten-digits dataset (1,797 small images of the digits 0–9) rather than food photos; the lessons transfer directly.
Leakage by duplicates (half the test set copied into training):
logistic regression clean test acc 0.961 | after leak: whole test 0.983, leaked half 1.000, truly unseen half 0.967
Leakage by choosing on the test set (best of 200 models):
best of 200 models, judged on test half A: 0.689
the same model on fresh test half B: 0.626
The reported score rises while the model hasn't improved. Why does choosing on the test set inflate it? Think of each candidate's test score as true quality plus luck: a test set is a sample (Module 2 §10), so each score is off by a few points in a random direction. Picking the highest of 200 scores picks the candidate that is good and lucky on these particular examples. Score it on fresh examples and the luck doesn't come with it: 0.689 falls to 0.626, a 6-point inflation that was never real. The more candidates you compare, and the smaller the set, the bigger the effect. This is the statistical reason TrayCheck's threshold is chosen on validation photos, although choosing on test photos would have been easier.
5. Labels: the ground truth is made by people
Every supervised result rests on labels, and in a hospital PoC the labels come from staff: a cook confirming the dish, a dietitian estimating how much was eaten. Reviewer quality is label quality.
Wrong labels hurt training and measurement
From Lab 9 (digits dataset):
clean training labels: test acc 0.961
20% of TRAINING labels wrong: test acc 0.883
clean model, 20% of TEST labels wrong: measured acc 0.769 ← the model didn't change; the measurement did
Wrong training labels make a worse model. Wrong evaluation labels make a good model look worse, or a bad one look better. This isn't hypothetical: an audit of ten widely used benchmark datasets found label errors in the test sets of all ten, enough to change which models looked best.
TrayCheck connection: validation photos come from Food-101's uncleaned training split, test photos from its hand-checked test split. That is a plausible reason validation accuracy (85%) is below test accuracy (88.75%), the opposite of the usual pattern. It also explains Module 10's result that calibrating on the noisier validation set didn't help on the cleaner test set.
Measuring agreement between people: Cohen's kappa
Before trusting human labels as ground truth, have two people label the same sample independently and measure how often they agree. Raw agreement overstates it, because some agreement happens by chance. Cohen's kappa corrects for that:
where po is the observed agreement and pe the agreement expected by chance from each person's answer rates.
Worked example (illustrative numbers). Two dietitians judge 100 trays: "more than half returned?"
| B says yes | B says no | |
|---|---|---|
| A says yes | 20 | 10 |
| A says no | 10 | 60 |
- Observed agreement po = (20 + 60) / 100 = 0.80.
- Chance agreement: A says "yes" on 30 of 100 trays, and so does B. If they were labelling independently, with no real information, both would say "yes" on a share 0.3 × 0.3 = 0.09 of trays and both "no" on 0.7 × 0.7 = 0.49 (Rule 1, Module 2 §6). Those two can't happen together, so add them (Rule 2): pe = 0.58.
- κ = (0.80 − 0.58) / (1 − 0.58) = 0.52.
Read the formula as: of the agreement that wasn't guaranteed by chance, how much did they achieve? The top is agreement beyond chance (0.22); the bottom is the most that was possible beyond chance (0.42). 0 means no better than chance; 1 means perfect.
80% agreement sounds high, but κ = 0.52 is only "moderate" on the commonly used interpretation scale, where 0.61–0.80 is "substantial" and above 0.80 "almost perfect". Two consequences for a PoC:
- If two trained people agree only moderately, no model can be judged more precisely than that against either one of them. Tighten the labelling instructions first.
- Double-label a random sample (for example 10%) throughout the pilot, not just at the start, because labelling drifts as people get tired or busy.
6. Distribution shift
A model is tested on data like its training data. Deployment rarely cooperates. The kinds of distribution shift (a change in the data a model sees, compared with what it learned from):
| Type | What changes | Hospital example |
|---|---|---|
| Covariate shift | What the inputs look like; the input → label relationship stays the same | Hospital trays, steel crockery, kitchen lighting, photos from above instead of restaurant angles |
| Label shift | How often each class occurs | Menus rotate: bread pudding daily for a week, then not at all |
| Concept shift | What a label means | A recipe changes: "pasta bake" now has a different sauce and looks different |
| Open set | New classes appear | A dish the model has never seen; a closed-set model still picks one of its known dishes |
Lab 9 (digits again) shows that a shift can be harmless or catastrophic, and you only find out by testing:
same kind of data (test set) acc 0.961
faded ink (x 0.6) acc 0.963
inverted (white ink on black) acc 0.000
sensor noise (+/- 3) acc 0.917
moved one pixel right acc 0.463
Moving every image by a single pixel halved accuracy for this simple model. The reason is mechanical: a linear model on pixels has one weight per pixel position (its templates, Module 4 §3). Shift the image and every stroke lands on positions whose weights were learned for something else. Inverting the colours flips the sign of every input, so evidence for a digit becomes evidence against it. Shifts that look trivial to a person can matter a great deal to a model. (Convolutional networks, Module 7, are built to tolerate shifts; they still struggle with changes they never saw in training, such as new lighting.)
What TrayCheck does about it: the menu check catches some open-set and label-shift cases; the correction rate and the spot-check error on the dashboard act as monitoring signals. A rising correction rate after a menu change is the system telling you the model is out of its depth.
What this means for the PoC: TrayCheck's model learned from restaurant photos. A vendor's model may have learned from another hospital's trays. Either way, the honest first step is to test on this site's trays, with locally collected labels, before trusting any accuracy figure.
7. Preparing a test dataset for a PoC
Putting the module together, a test dataset for a proof of concept needs:
| Requirement | What to do | Why |
|---|---|---|
| Representative | Sample across dishes, wards, meal periods, days of the week, cameras and staff | The test should look like the deployment, including its awkward parts |
| Big enough | Use Module 10's table: about 140 checked trays per group for ±5 points | Small samples make differences meaningless |
| Split by the right unit | Keep each tray, and ideally each day or ward, on one side of the train/test line | Prevents near-duplicate leakage |
| Properly labelled | Written labelling instructions; double-label a random sample; report kappa | Ground truth quality caps how precisely the model can be judged |
| Frozen | Fix the test set before any results are seen; don't tune on it | Prevents choosing-on-test optimism |
| Clean, with exclusions reported | Run completeness and validity checks; report how many records were excluded and why | Silent exclusions can bias results |
| Privacy-safe | Make sure photos contain no patient faces, names or bed labels; follow ISS and SA Health privacy guidance | Hospital photos are health information |
| Documented | A datasheet (next section) | So others can judge what the result applies to |
8. Document your data
A datasheet is a short, standard document for a dataset, answering a fixed set of questions: why it was created, what's in it, how it was collected and labelled, what it shouldn't be used for. TrayCheck's README and manifest answer several: source and licence caveats (the Foodspotting photos' rights limit redistribution, which is why the repo ships only six photos), split method and known label noise. Module 13 pairs this with a model card.
Check your understanding
1. 8% of trays have no returned weight. Why does it matter whether those are random trays or mostly full ones?
If they are random, waste averages just get a bit noisier. If they are mostly full trays (say, cleared in a hurry), excluding them biases reported waste downward: the result is systematically wrong, not just uncertain. Check whether missingness is related to ward, meal period, staff or dish before trusting the averages.
2. A colleague tunes the review threshold on the 160 test photos "because there are more of them". What's wrong, and what would you say?
The test result becomes optimistic, because the threshold was chosen to look good on exactly those photos (Lab 9 shows a 6-point inflation from choosing on a set). Choose on validation, measure on test. If validation is too small, collect more or use cross-validation on the training data, but keep the test set untouched.
3. In a hospital pilot you photograph each tray at plating and at return. How should you split training and test data?
By tray at minimum, so both photos of a tray are on the same side, and preferably by date or kitchen, so the test measures performance on new days or sites rather than on near-copies of training photos.
4. Two cooks agree on the dish for 92% of 200 double-labelled trays. Is that good enough to use as ground truth?
Probably, but compute kappa: if most trays are one or two common dishes, chance agreement is high and kappa can be much lower than 92% suggests. Also look at which dishes they disagree on; those are the dishes where the model can't be judged precisely either.
5. Menus rotate weekly. Which kind of shift is that, and how could it affect the model?
Label shift: class frequencies change. A model trained when bread pudding was common may lean towards predicting it. The menu check helps directly by flagging predictions of dishes that aren't being served.
6. Why aren't SHA-256 hashes enough to prove there's no duplicate leakage?
They detect only byte-identical files. Re-saved, resized or cropped copies of the same photo hash differently. Near-duplicates need perceptual hashes (fingerprints computed from a tiny, blurred version of what the image looks like, so near-copies get near-identical fingerprints) or comparing images' feature vectors (Module 8).
Go deeper
Short on time? The study guide says which of these to read first.
Core (free)
- Google Machine Learning Crash Course, Datasets, generalization, and overfitting: the pages on data characteristics (completeness, reliability, labels) and dividing the original dataset.
- scikit-learn User Guide, Common pitfalls and recommended practices: data leakage and inconsistent preprocessing, with code. scikit-learn.org/stable/common_pitfalls.html
- Dive into Deep Learning, §4.7 Environment and Distribution Shift: covariate, label and concept shift with examples. d2l.ai
Optional
- Kapoor & Narayanan (2023), Leakage and the reproducibility crisis in machine-learning-based science, Patterns: a taxonomy of leakage with real cases. arxiv.org/abs/2207.07048
- Northcutt, Athalye & Mueller (2021), Pervasive Label Errors in Test Sets Destabilize Machine Learning Benchmarks. arxiv.org/abs/2103.14749
- Gebru et al. (2021), Datasheets for Datasets: read the question list in §3. arxiv.org/abs/1803.09010
- Landis & Koch (1977), The measurement of observer agreement for categorical data, Biometrics 33(1): the source of the kappa interpretation scale.
- Bossard et al. (2014), Food-101: Mining Discriminative Components with Random Forests, ECCV: the dataset paper, including the note on noisy training labels.
- Huyen, Designing Machine Learning Systems (2022), Chapter 4, Training Data and Chapter 8, Data Distribution Shifts and Monitoring. Paid.
- DeepLearning.AI Deep Learning Specialization, Course 3, Structuring Machine Learning Projects: train/dev/test distributions and error analysis. Free to audit on Coursera.
Interview angle
"Before trusting any accuracy number I look at the data. First quality: completeness, validity, duplicates, and whether problems are random or systematic. In TrayCheck's simulated month, 21 trays had no returned weight and 5 had returned more than served; the dashboard counts them and leaves them out of waste figures rather than hiding them.
Then the split: TrayCheck's training and validation photos come from Food-101's training split and test photos from its separate, hand-checked test split, with no shared files, and the threshold was chosen on validation only. In a hospital pilot I'd split by tray and ideally by day or ward, double-label a sample to check the labels with kappa, and remember these are restaurant photos: the first real test has to be on this site's trays."