Data: Examples, Features & Splits
Feature vectors, labels, and why we hold data out.
Before any model is trained, someone has decided what counts as an example, which numbers describe it, what the right answer is, and which examples the model will never be allowed to see. Those decisions bound everything that follows. This lesson turns records into feature vectors, works out how large a test set must be and why it can be used only once, and shows how to split data that come in groups, in time order or with rare classes.
What you’ll learn
- Represent examples as rows of a design matrix, encoding numeric, categorical, text and image features.
- Explain the roles of training, validation and test sets, and why choosing among models by test score biases that score upward.
- Size a test set with the normal approximation or Hoeffding's inequality, and quantify the optimism of picking the best of many models on one test set.
- Choose stratified, grouped or time-based splits to match how a model will be used, and recognize data-quality problems and class imbalance.
From records to vectors
Learning algorithms consume numbers. Each example becomes a feature vector , and the examples stack into the design matrix , one row per example and one column per feature, with the labels collected in . Spreadsheet-like tabular data arrive almost in this form; everything else has to be encoded.
| Feature type | Example | Typical encoding |
|---|---|---|
| Numeric | floor area, blood pressure | as is, often standardized to mean 0 and variance 1 |
| Count | purchases last year | as is, or to tame long tails |
| Ordinal | "never" < "sometimes" < "often" | integers that respect the order |
| Categorical | city, product type | one-hot: one 0/1 column per category |
| Text | an email | bag of words: a count per vocabulary word, giving a long, mostly zero vector |
| Image | a grayscale digit | its 784 pixel intensities as a vector in , or features learned by a network |
| Date and time | a timestamp | parts such as hour and weekday, cyclical encodings, time since an event |
For example, three houses described by area (m²), bedrooms and neighborhood (North, South or East) become, with the neighborhood one-hot encoded,
Notice the scales: area is in the hundreds, the one-hot columns are 0 or 1. Methods based on distances or on gradient steps are sensitive to this, so features are usually standardized first; decision trees are not, because their splits do not care about monotone rescaling (topic Machine Learning in the Real World).
A feature "city" takes the values Paris, Lagos and Lima. Why encode it as three 0/1 columns instead of the single number 1, 2 or 3?
- Three columns take less memory than one
- A design matrix cannot hold integer codes
- One-hot encoding makes every model nonlinear
- Integer codes invent an order and distances (Lagos "between" Paris and Lima), which linear models and nearest neighbors would take seriously
Show the answer
D. Integer codes invent an order and distances (Lagos "between" Paris and Lima), which linear models and nearest neighbors would take seriously
A linear model would give Lima three times the effect of Paris, and -NN would find Paris closer to Lagos than to Lima, all artifacts of an arbitrary numbering. One-hot columns are equidistant: any two different cities differ in exactly two coordinates.
The label is a number for regression, a category for classification, and sometimes something richer: several tags at once, or a sequence. Labels come from people (annotators, clinicians), from measurements, or from later events (whether a loan was repaid), and each source has its own failure modes, which the Convergence lesson Label Noise & Weak Supervision studies.
Why hold data out
For a model chosen before the test set is looked at, test accuracy is an unbiased estimate of true accuracy, and its uncertainty can be computed. That turns "how big should the test set be?" into arithmetic.
Each of the test examples is an independent trial, correct with probability , the model's true accuracy. The test accuracy is their average:
By the central limit theorem, is an approximate 95% confidence interval. For a half-width , solve for ; the worst case is :
Hoeffding's inequality, , gives a guarantee with no approximation at all, at roughly twice the price:
A classifier scores 90% accuracy on 1,000 test examples. What is the half-width of an approximate 95% confidence interval for its true accuracy, in percentage points?
Show the answer
1.9 points
, and : the true accuracy is plausibly anywhere from about 88.1% to 91.9%. Two models whose test scores differ by one point on this test set are not reliably different.
The guarantee covers a model fixed in advance. Choose among models by their test scores and the winner's score is biased upward, because you selected it partly for its luck on these particular examples. Hence the three-way split: fit on the training set, make every choice (features, model family, hyperparameters) on a validation set, and touch the test set once, at the end. Proportions such as 60/20/20 are rules of thumb; by the calculation above, a few thousand test examples often suffice even when the dataset is huge.
Think first One hundred models all have true accuracy 80%. Each is scored on the same 1,000-example test set, and suppose, unrealistically, that their test-set errors are independent. What score will the best-looking model show?
About 83%. Each score has standard error points, and the largest of 100 independent standard normal draws averages about , so the winner shows roughly : three points of pure selection. Real models make correlated errors, which shrinks the effect without removing it. The Convergence lesson Benchmark Overfitting & Adaptive Data Analysis studies what repeated reuse does to a test set.
Splitting to match the future
A random split assumes that examples are independent draws from one distribution and that future data will look like another such draw. When either fails, a random split measures the wrong thing. The rule is simple to state: split the data the way the model will meet new data.
| Situation | What a random split gets wrong | Split instead |
|---|---|---|
| Rare classes | the test set may hold few or no positives, so its estimate swings wildly | stratified: the same class proportions in every split |
| Several examples per patient, user or document | the model can recognize the individual instead of learning the task, so test error is optimistic | grouped: all of a group's examples on one side |
| Time-ordered data: sales, sensors, prices | the model trains on the future to predict the past | temporal: train on earlier data, test on later data |
| Spatial data: maps, field plots | test points have near-copies at nearby training locations | spatial blocks: hold out whole regions |
In a large dataset, 1% of the examples are positive. A random test set of 100 examples is drawn. What is the probability that it contains no positive example at all, in percent?
Show the answer
37 %
Each draw misses the positives with probability , so all 100 do with probability . More than a third of the time the test set could not measure recall at all. Stratification guarantees exactly one positive here, and in practice you would also want a much larger test set.
from sklearn.model_selection import (train_test_split, GroupShuffleSplit,
TimeSeriesSplit)
# Stratified: the same class proportions in training and test sets
X_tr, X_te, y_tr, y_te = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=0)
# Grouped: every patient's records land on one side only
gss = GroupShuffleSplit(n_splits=1, test_size=0.2, random_state=0)
train_idx, test_idx = next(gss.split(X, y, groups=patient_id))
# Temporal: each fold trains on the past and tests on the next block
for train_idx, test_idx in TimeSeriesSplit(n_splits=5).split(X):
... # fit on X[train_idx], evaluate on X[test_idx]scikit-learn's splitters. TimeSeriesSplit assumes the rows are already sorted by time; patient_id holds one group label per row.
Quality, quantity and imbalance
No algorithm recovers information its data never contained. The usual suspects:
- Wrong labels: annotator mistakes, ambiguous cases, labels inferred from logs.
- Measurement problems: miscalibrated sensors, units mixed up, values missing for reasons related to the outcome.
- Duplicates: the same record copied into both training and test sets.
- Unrepresentative sampling: selection bias arises when the data were collected from a population different from the one the model will serve, such as only the patients who reached a specialist hospital.
More data reduces the variance part of the error, not the bias part: a straight line fitted to a curve stays wrong with a million points. And more data of the wrong kind does not help at all.
Key takeaways
- Examples become rows of a design matrix. Standardize numeric features, one-hot encode categories, use bag-of-words for text and pixels or learned features for images. Labels come from annotation, measurement or later events, each with its own errors.
- A test set gives an unbiased but noisy estimate of a fixed model's accuracy, with standard error : about 9,600 examples for point at 95% confidence (normal approximation), 18,445 by Hoeffding's inequality.
- Choosing among models by test score biases that score upward (the best of 100 equally good models looks about 3 points better on 1,000 examples). Choose on a validation set or by cross-validation, and use the test set once.
- Split the way the model will meet new data: stratify rare classes, keep groups together, respect time order and spatial structure.
- Data quality and representativeness bound what any model can learn; more data cures variance, not bias. With rare classes, always compare against the majority-class baseline.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
You evaluate 20 candidate models on the test set and report the best score as your final result. What is wrong with that?
- Nothing, as long as the test set is large
- The test set should have been used for training as well
- 20 candidates are too few to find a good model
- The reported score is biased upward: the best of 20 was selected partly for its luck on these test examples
Show the answer
D. The reported score is biased upward: the best of 20 was selected partly for its luck on these test examples
Selection turns an unbiased estimate into an optimistic one. Choose among the 20 on a validation set or by cross-validation, then score the chosen model once on the test set.
A dataset holds 10 chest X-rays from each of 500 patients. A random 80/20 split of the images gives 95% test accuracy. What is the main risk?
- Images of the same patient sit on both sides of the split, so the model can score by recognizing patients rather than disease
- The test set is too small to estimate accuracy
- X-rays should be split by pixel rather than by image
- 80/20 is the wrong ratio; it should be 50/50
Show the answer
A. Images of the same patient sit on both sides of the split, so the model can score by recognizing patients rather than disease
Patient-level features (anatomy, implants, the scanner used) are shared across a patient's images. A grouped split, with each patient's images all on one side, measures performance on new patients, which is what deployment needs.
You are building a model to forecast tomorrow's electricity demand from past data. Which evaluation is appropriate?
- Shuffle all days and run 10-fold cross-validation
- Evaluate on the training days, since demand patterns repeat
- Train on an earlier period and test on a later one, never letting the future into training
- Test on a random 20% of days chosen from the middle of the data
Show the answer
C. Train on an earlier period and test on a later one, never letting the future into training
Deployment always predicts the future from the past, so evaluation must do the same. Shuffling lets the model see days after the ones it is tested on, and neighboring days are strongly correlated.
Roughly how many test examples do you need to estimate a classifier's accuracy within ±1 percentage point with 95% confidence (normal approximation, worst case )?
- About 100
- About 9,600
- About 1,000
- About 1,000,000
Show the answer
B. About 9,600
. Hoeffding's inequality, which assumes nothing about normality, asks for about 18,445.
A classifier for a rare disease reaches 98.5% accuracy. 1.5% of patients have the disease. What should you check first?
- Whether the accuracy holds on the training set
- Whether a larger model reaches 99%
- Whether the test set was stratified by age
- Whether it beats the majority-class baseline, which also scores 98.5%, and how many diseased patients it actually catches
Show the answer
D. Whether it beats the majority-class baseline, which also scores 98.5%, and how many diseased patients it actually catches
Predicting "healthy" for everyone also scores 98.5%. Until you look at errors per class (recall on the diseased patients in particular) the accuracy says nothing.
Go deeper
- The i.i.d. Assumption & Its Failures · Exchangeability, dependence and what breaks when data is not i.i.d.
- Label Noise & Weak Supervision · Learning from labels that are wrong, partial or programmatic.
- Data Leakage & Contamination · How the test set sneaks into training, and how to stop it.
Further reading
- T. Hastie, R. Tibshirani & J. Friedman, The Elements of Statistical Learning, 2nd ed. (Springer, 2009), chapter 7.
- G. James, D. Witten, T. Hastie & R. Tibshirani, An Introduction to Statistical Learning, 2nd ed. (Springer, 2021), chapter 5.
- M. Hardt & B. Recht, Patterns, Predictions, and Actions: Foundations of Machine Learning (Princeton University Press, 2022).
- D. R. Roberts et al., "Cross-validation strategies for data with temporal, spatial, hierarchical, or phylogenetic structure," Ecography 40(8), 913–929 (2017).