Level 3 · BeginnerLesson 3.2 34 min read 10 question quiz 13 marks of written practice

Datasets, Splits and Bias: Good Data In, Good AI Out

Where data comes from

"Garbage in, garbage out" is older than AI, and nowhere truer. A model can only learn what its data contains.

SourceExamplesWatch out for
CollectedSensor readings, app logs, sales recordsMissing values, faulty sensors, consent
Public datasetsMNIST (70,000 handwritten digits), ImageNet, Common Crawl (billions of web pages)Licences, errors, what and who is missing
Labelled by peopleCrowd workers tagging images, doctors marking scansCost, disagreement, labellers' assumptions
SyntheticSimulated driving scenes, text generated by another modelWhether it matches the real world

Personal data is protected by law. In the UK, the UK GDPR and the Data Protection Act 2018 require a lawful basis for using it, data minimisation and security, and give people rights over data about them.

Training, validation and test sets

A model must be judged on data it has never seen, or you only learn how well it memorised. So the data is split before training starts.

Training, validation and test setsA row of twenty coloured squares, every example in a random order, is split into three parts: training, the first 70 percent; validation, the next 15 percent; and test, the last 15 percent, marked with a padlock. Training data is used to learn the parameters, seen thousands of times, like practice questions. Validation data is used to tune and choose settings, the model and when to stop, like mock exams. Test data gives the final score, once, and is never used to make choices, like the real exam.Shuffle once, then split before any training happensevery example, in a random orderTRAINING 70%VALIDATION15%TEST15%Learn the parametersthe model sees these thousands of timeslike practice questionsTune and choosesettings, model,when to stoplike mock examsFinal score, oncenever used tomake choiceslike the real exam
The test set is locked away until the very end.
SetTypical shareUsed forExam analogy
Training70 to 80%Learning the parametersPractice questions
Validation10 to 15%Choosing settings, comparing models, deciding when to stopMock exams
Test10 to 15%One final, honest estimate of performanceThe real exam, sat once

If you keep tweaking the model until the test score looks good, the test set has quietly become a second validation set, and the final score is too optimistic. It should be used once, at the end.

Data leakage

Leakage is when information that would not be available in real use sneaks into training. Common causes:

  • The same item, or a near copy, in both training and test sets
  • Several photos of the same patient split across sets, so the model recognises the patient rather than the illness
  • Features from the future, such as using "was refunded" to predict "will complain"
  • Scaling or cleaning using statistics from the whole dataset

Shuffle before splitting, but never shuffle time series: train on the past and test on the future, as the model will be used.

Cleaning data

Real data is messy. Data scientists often say cleaning takes most of their time.

ProblemExampleTypical fix
Missing valuesNo age recordedDrop the row, fill with the median, or add a "was missing" feature
DuplicatesThe same customer entered twiceRemove them, before splitting
OutliersAge 160Correct an obvious typo; keep genuine extremes
Inconsistent formatsHeights in cm and m; "UK", "U.K." and "Britain"Convert to one standard
Label noiseA dog labelled "cat"Review suspicious labels, get several labellers to agree
An outlier is not always an error

A transaction a hundred times larger than usual might be a typo, or it might be the fraud you are trying to catch. Deleting outliers without thinking can delete the most important examples.

Class imbalance and the accuracy trap

Suppose 1 card payment in 100 is fraud. A "model" that always answers not fraud is right 99% of the time and catches no fraud at all.

The accuracy trapA grid of 100 squares, 99 teal for genuine payments and 1 pink for fraud, which is circled and marked missed. A lazy model that always says OK is right about 99 of the 100, so its accuracy is 99 percent, but it catches 0 percent of the fraud: its recall is zero. The lesson: measure the rare class directly with recall, how much fraud is caught, and precision, how many alerts are real.100 payments, 1 fraud. The lazy model: always say “OK”.99 genuine, 1 fraudmissed99%accuracyright about 99 of 1000%of fraud caughtrecall: misses every oneMeasure the rare class directly:recall: how much fraud is caughtprecision: how many alerts are real
On imbalanced data, accuracy mostly measures the imbalance.

When one class is rare, accuracy mostly measures the imbalance. Better measures, explained fully in Level 4:

  • Recall: of all the real fraud, how much did we catch?
  • Precision: of everything we flagged, how much was really fraud?

Fixes for imbalance

  • Measure with precision and recall, not accuracy alone
  • Oversample the rare class or undersample the common one
  • Give mistakes on the rare class a bigger weight during training
  • Collect more examples of the rare class

Bias: how unfairness gets into data

A model learns the patterns in its data, including the unfair ones. Bias can enter at every stage.

Where bias enters an AI systemSix stages in a row, joined by arrows: the world, who is affected; collection, what gets recorded; labelling, what counts as right; features, what is measured; training, what is optimised; and decisions, what happens next. Under each a warning sign names the bias that can enter there: historical bias, past unfairness faithfully recorded; sampling bias, some people missing or rare; labelling bias, labellers' assumptions; measurement bias, a poor stand-in such as spending for need; evaluation bias, one average hiding groups; and feedback loops, decisions shaping new data. A dashed arrow runs from decisions back to the world, because the system's decisions change what happens, which becomes tomorrow's data.Bias can enter at every stage, and decisions feed back into the worldThe worldwho is affected!historical biaspast unfairness,faithfully recordedCollectionwhat gets recorded!sampling biassome people missingor rareLabellingwhat counts as right!labelling biaslabellers'assumptionsFeatureswhat is measured!measurement biasa poor stand-in,e.g. spend for needTrainingwhat is optimised!evaluation biasone average hidesgroupsDecisionswhat happens next!feedback loopsdecisions shape newdatathe system's decisions change what happens, which becomes tomorrow's data
Fixing bias means checking every stage, not only the model.
TypeWhat happensReal example
Sampling biasThe data does not represent the people the system will serveThe 2018 Gender Shades study found commercial face analysis systems misclassified the gender of darker-skinned women up to 34.7% of the time, against 0.8% for lighter-skinned men
Historical biasThe data accurately records an unfair pastAn experimental recruiting tool, reported in 2018, learned from ten years of mostly male CVs to mark down CVs containing the word "women's". It was scrapped
Measurement biasThe feature measured is a poor stand-in for what mattersA 2019 study in Science found a widely used US health algorithm used past healthcare spending to stand in for health need, so it underestimated the needs of Black patients who had less spent on them
Labelling biasLabellers' assumptions become the "truth"Different groups of labellers rate the same text as offensive at very different rates
Feedback loopsThe model's decisions shape the next dataSending more patrols where a model predicts crime records more crime there, which "confirms" the prediction

What engineers do about it

  • Check who and what is missing from the data before training
  • Audit by subgroup: a good overall accuracy can hide a much worse result for one group
  • Document datasets with a datasheet (what was collected, how, by whom, and its gaps), an idea proposed by Timnit Gebru and colleagues in 2018
  • Keep people involved in high-stakes decisions, and let those affected challenge them

Hands-on: splitting, auditing and the accuracy trap

A reproducible split

Python
import random

random.seed(7)                   # the same "random" shuffle every run
data = [f"photo_{i:02}" for i in range(20)]
random.shuffle(data)

n = len(data)
train = data[:int(0.7 * n)]
valid = data[int(0.7 * n):int(0.85 * n)]
test = data[int(0.85 * n):]
print(len(train), "training:", train[:4], "...")
print(len(valid), "validation:", valid)
print(len(test), "test:", test)
print("Any overlap?", bool(set(train) & set(test)))

The accuracy trap

Python
labels = ["ok"] * 990 + ["fraud"] * 10
predictions = ["ok"] * len(labels)          # a lazy model: never says fraud

accuracy = sum(p == y for p, y in zip(predictions, labels)) / len(labels)
caught = sum(p == y == "fraud" for p, y in zip(predictions, labels))
print(f"Accuracy: {accuracy:.1%}")
print(f"Fraud caught: {caught} of {labels.count('fraud')}  (recall {caught / labels.count('fraud'):.0%})")

Cleaning a messy table

Python
rows = [
    {"name": "Ava", "age": 15, "score": 72},
    {"name": "Ben", "age": None, "score": 65},
    {"name": "Ava", "age": 15, "score": 72},
    {"name": "Cai", "age": 16, "score": None},
    {"name": "Dee", "age": 160, "score": 81},
]

seen, clean = set(), []
for r in rows:
    key = tuple(r.values())
    if key in seen:
        print("Duplicate removed:", r["name"])
        continue
    seen.add(key)
    clean.append(r)

for r in clean:
    if r["age"] is not None and not 10 <= r["age"] <= 19:
        print("Suspicious age for", r["name"], "->", r["age"])

scores = sorted(r["score"] for r in clean if r["score"] is not None)
median = scores[len(scores) // 2]
for r in clean:
    if r["score"] is None:
        r["score"] = median
        print("Filled missing score for", r["name"], "with the median", median)

An audit by subgroup

Python
# How often a face unlock model was right, for two groups of users
results = {"group A": (950, 1000), "group B": (42, 50)}

total_right = sum(r for r, n in results.values())
total = sum(n for r, n in results.values())
print(f"Overall accuracy: {total_right / total:.1%}")
for group, (right, n) in results.items():
    print(f"  {group}: {right / n:.1%} from {n} people")

An overall score of 94.5% looks excellent, until the audit shows one group gets 84%: about one failure in six. The smaller group barely moves the average, which is exactly why averages hide unfairness.

Activity: who is missing?

A company trains a voice assistant on 10,000 hours of speech recorded by its own staff in one city. In groups, list who is likely to be under-represented, what would go wrong for them, and what data you would collect to fix it.

Level check

  • Describe four sources of training data and a risk of each
  • Explain the purpose of the training, validation and test sets
  • Explain data leakage and give two ways it happens
  • Describe how to deal with missing values, duplicates and outliers
  • Explain why accuracy misleads on imbalanced data
  • Describe three types of bias with a real example of each, and how engineers reduce them

Key terms you must be able to define

Training set
The data a model learns its parameters from.
Validation set
Data held back to choose settings and compare models during development.
Test set
Data kept unseen until the end, used once for an honest estimate of performance.
Data leakage
Information that would not be available in real use getting into training, making results look better than they are.
Class imbalance
When one class is far rarer than another, such as fraud among payments.
Outlier
A value far from the rest, which may be an error or a genuine and important extreme.
Label noise
Training examples whose labels are wrong.
Sampling bias
Data that does not represent the population the system will be used on.
Historical bias
Data that accurately records an unfair past, which a model then learns to repeat.
Measurement bias
Using a feature that is a poor stand-in for the thing that really matters.
Datasheet for a dataset
A document describing how a dataset was made, what it contains, and its gaps and intended uses.

Flashcards

DefineTraining set
AnswerThe data a model learns its parameters from.
DefineValidation set
AnswerData held back to choose settings and compare models during development.
DefineTest set
AnswerData kept unseen until the end, used once for an honest estimate of performance.
DefineData leakage
AnswerInformation that would not be available in real use getting into training, making results look better than they are.
DefineClass imbalance
AnswerWhen one class is far rarer than another, such as fraud among payments.
DefineOutlier
AnswerA value far from the rest, which may be an error or a genuine and important extreme.
DefineLabel noise
AnswerTraining examples whose labels are wrong.
DefineSampling bias
AnswerData that does not represent the population the system will be used on.

Go further: notes for future AI engineers

Data-centric AI

For years research competed on better models for fixed datasets. Andrew Ng and others have argued for data-centric AI: hold the model fixed and systematically improve the data. In practice, cleaning labels, adding examples of the cases the model gets wrong and making the data consistent often helps more than a cleverer architecture.

Professional teams also version their data the way they version code, so every model can be traced back to exactly which data trained it. When a model misbehaves months later, that record is the first thing anyone asks for.

Misconceptions to avoid

Avoid these
  • Tuning a model on the test set. Once you have used it to make choices, it no longer gives an honest score.
  • Shuffling time series before splitting, which lets the model peek at the future.
  • Trusting accuracy on imbalanced data. Always check precision and recall for the rare class.
  • Deleting every outlier. Some are errors, but some are exactly the cases you need to catch.
  • Thinking bias only comes from biased people. Accurate data about an unfair world produces a biased model too.
  • Reporting one overall score without checking how the model does for each group of people it affects.
Fun fact

A 2021 study by researchers at MIT found that about 6% of the labels in the ImageNet validation set are wrong. Some of the benchmark results the whole field competed on were partly measuring how well models agreed with mistakes.

Knowledge check

0 of 10 answered
1What is the test set for?
2What is the validation set used for?
3Which is an example of data leakage?
4Why should time series data not be shuffled before splitting?
51 in 200 emails is a phishing attack. A model never flags anything. What is its accuracy?
6A dataset has a missing age for one student. Which is a sensible fix?
7A face recognition system was trained mostly on photos of lighter-skinned men. Which bias is this?
8A recruiting model learns from ten years of past hiring decisions that favoured men. Which bias is this?
9Why should accuracy be checked for each subgroup of users?
10What does random.seed(7) do before random.shuffle?
Score 0 / 10

Check you could explain this

13 marks
1Explain why data is split into training, validation and test sets.4 marks
Explain

Mark scheme0 / 4
  • LThe model must be judged on data it has not seen
  • LTraining set: learns the parameters
  • LValidation set: tune settings or compare models
  • LTest set: used once for an honest final estimate
Model answer

A model has to be judged on data it has never seen, otherwise we only measure how well it memorised. The training set is used to learn the parameters. The validation set is used during development to choose settings and compare models. The test set is kept unseen until the end and used once, so it gives an honest estimate of how the model will perform on new data.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.

Think this answer or mark scheme is wrong? Report it

2A bank trains a fraud detector on data where 0.5% of transactions are fraud. It reports 99.5% accuracy. Evaluate this claim.5 marks
Evaluate

Mark scheme0 / 5
  • LA model that never predicts fraud also scores 99.5%
  • LSo accuracy mostly measures the imbalance
  • LRecall: how much real fraud is caught
  • LPrecision: how many flagged transactions really are fraud
  • LA fix: resampling, class weights or more fraud examples
Model answer

The claim is meaningless on its own. Because only 0.5% of transactions are fraud, a model that never predicts fraud at all would also score 99.5% accuracy while catching nothing, so accuracy here mostly measures the imbalance. The bank should report recall, the share of real fraud that is caught, and precision, the share of flagged transactions that really are fraud. The model could also be improved by oversampling fraud cases or weighting mistakes on them more heavily.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.

Think this answer or mark scheme is wrong? Report it

3Describe two different ways bias can enter the data used to train an AI system. Give an example of each.4 marks
Describe

Mark scheme0 / 4
  • LA first type of bias named and described
  • LA valid example of it
  • LA second, different type named and described
  • LA valid example of the second
Model answer

Sampling bias happens when the data does not represent the people the system will be used on. For example, face analysis systems trained mostly on lighter-skinned faces were found in 2018 to misclassify darker-skinned women far more often. Historical bias happens when data accurately records an unfair past. For example, a recruiting tool trained on ten years of mostly male CVs learned to mark down CVs containing the word women's.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.

Think this answer or mark scheme is wrong? Report it

Machine mark 0 / 13