Sub topic 18
More data and data augmentation
This chapter assumes you know how to train a Keras or scikit-learn model, can read a learning curve, and understand the difference between training and validation error. Earlier chapters showed how to diagnose overfitting and how to penalise complexity. Here the remedy is different. You leave the model alone and change what it learns from.
Why more data reduces overfitting
Overfitting happens when a flexible model fits noise that is specific to its training sample. Each new example gives the model another chance to see that a pattern is not general. With more examples, noise averages out and real structure stays. The gap between training error and validation error shrinks, and the model needs less penalty to stay stable.
More data fixes high variance. It does not fix high bias. A model that is too simple for the problem makes about the same errors with a thousand rows or a million. Check this before you spend money on collection.
Use the learning curve to decide
A learning curve plots training and validation error against training set size. Read it like this:
| What you see | Meaning | Is more data worth it? |
|---|---|---|
| Large gap between curves, validation error still falling as size grows | High variance | Yes |
| Curves have converged at a high error | High bias | No. Increase capacity or improve features |
| Curves have converged at a low error | Model is working | Little to gain |
| Large gap, but validation error is flat at the largest sizes | Variance that data alone will not fix soon | Probably not by a small amount. Combine with regularisation |
The code below produces a learning curve with scikit-learn. It uses the degree-15 ridge pipeline from earlier in the tutorial, so the effect of sample size is easy to see.
import numpy as np
from sklearn.model_selection import learning_curve
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn.linear_model import Ridge
rng = np.random.default_rng(0)
X = rng.uniform(-3, 3, size=(400, 1))
y = np.sin(X).ravel() + rng.normal(0, 0.2, size=400)
model = make_pipeline(PolynomialFeatures(15), StandardScaler(), Ridge(alpha=1e-4))
sizes, train_scores, val_scores = learning_curve(
model, X, y,
train_sizes=[20, 40, 80, 160, 320],
cv=5,
scoring="neg_mean_squared_error",
shuffle=True,
random_state=0,
)
for n, tr, va in zip(sizes, -train_scores.mean(axis=1), -val_scores.mean(axis=1)):
print(n, round(tr, 3), round(va, 3))With 20 training points the validation error is much larger than the training error. As the size grows, the two values move toward each other and approach the noise floor of about 0.04, which is the variance of the noise we added (0.2 squared). That floor matters. No amount of data pushes error below irreducible noise.
Practical ways to get more data
Collecting more labelled examples is the most reliable fix, but it is slow and costly. Consider these options in roughly this order:
- Collect or label more of the same kind of data. This gives the biggest gain when the new data matches the distribution you will see in production.
- Use unlabelled data. Pretraining, self-supervised learning, or pseudo-labelling can use examples that have no labels.
- Use a pretrained model. Fine-tuning a model trained on a large dataset transfers its learned features, which acts like having more data.
- Generate synthetic data. Simulation or generative models can help, but they carry the risk of teaching the model the simulator's flaws.
- Augment the data you have. This is the cheapest option and the subject of the rest of the chapter.
Data augmentation
Data augmentation creates new training examples by applying transformations that change the input but keep the label correct. A photo of a cat flipped left to right is still a cat. The model sees more variety and learns that the flip does not matter. In effect, augmentation builds a known invariance into the model.
The key rule is that each transformation must preserve the label. That depends on the task, not on the transformation alone.
| Domain | Typical label-preserving transformations | Transformations that can break the label |
|---|---|---|
| Photos of objects | Flips, small crops, small rotations, brightness and contrast changes | Heavy crops that remove the object |
| Handwritten digits | Small shifts, small rotations, slight scaling | Vertical flips (6 and 9 swap), large rotations |
| Text | Synonym replacement, back-translation | Random word deletion that removes the negation in "not good" |
| Audio | Added background noise, small time shifts, pitch changes within a range | Speed changes large enough to alter the words |
| Tabular data | Small noise on continuous features, SMOTE-style oversampling for rare classes | Noise on features that are identifiers or categories |
Augmentation in Keras
Keras provides preprocessing layers that apply random transformations. These layers are active only during training. At inference time they pass inputs through unchanged, so you do not need to switch anything off.
from tensorflow import keras
augment = keras.Sequential([
keras.layers.RandomFlip("horizontal"),
keras.layers.RandomRotation(0.05),
keras.layers.RandomZoom(0.1),
keras.layers.RandomContrast(0.1),
])
model = keras.Sequential([
keras.layers.Input(shape=(64, 64, 3)),
augment,
keras.layers.Rescaling(1.0 / 255),
keras.layers.Conv2D(16, 3, activation="relu"),
keras.layers.MaxPooling2D(),
keras.layers.Conv2D(32, 3, activation="relu"),
keras.layers.GlobalAveragePooling2D(),
keras.layers.Dropout(0.3),
keras.layers.Dense(10, activation="softmax"),
])
model.compile(
optimizer="adam",
loss="sparse_categorical_crossentropy",
metrics=["accuracy"],
)
model.summary()Because the transformations are random, the model sees a slightly different version of each image every epoch. One epoch over 10,000 images therefore acts like many more distinct examples. This is why models with augmentation often train for more epochs before validation loss turns upward, and why early stopping patience may need to be larger.
Augmentation in the data flow
Augment only the training data. The validation and test sets must stay as they would appear in real use, or the error estimates become unreliable. Also split the data before augmenting. If you create augmented copies first and then split at random, copies of the same original can land in both training and validation. That is data leakage, and it makes validation error look better than it is.
Edge cases and failure modes
- Augmenting beyond the real distribution. Extreme transformations create images the model will never see in use. It then spends capacity on cases that do not matter, and accuracy on real data can drop.
- Label-breaking transformations. A flipped "b" becomes a "d". Check each transformation against the labels, not only against how the output looks.
- Class imbalance. Augmenting every class equally keeps the imbalance. If you augment mostly the rare class, you improve balance but risk overfitting to a few originals. Many copies of ten examples are still ten examples.
- Duplicates across splits. Near-duplicate data, such as several frames from one video or several scans from one patient, must stay together in one split. Use grouped splitting, for example
GroupKFold, so one source never appears on both sides. - Lower training accuracy. Augmentation makes the training task harder, so training accuracy is often lower than without it. That is expected. Judge the result by validation error.
- Slower training. Random transforms cost compute. For heavy pipelines, run them in the input pipeline with
tf.dataand prefetching so the accelerator is not left waiting.
How this fits with other remedies
More data and augmentation address the same problem as L2, dropout, and early stopping, but from the input side. They combine well. A common stack for an image classifier is augmentation, a small weight penalty, moderate dropout, and early stopping on validation loss. Change one thing at a time and compare validation scores, so you know which change helped. In the diagnosis workflow that closes this tutorial, you reach for more data when the learning curve shows high variance and validation error is still falling.
Exercise
A model has training error 0.02 and validation error 0.30. The learning curve shows validation error still dropping as the training set grows from 1,000 to 8,000 rows. A teammate suggests flipping each image upside down as augmentation for a street-sign classifier. What do you recommend for the data, and what is wrong with the teammate's idea?
Show answer
The large gap with validation error still falling signals high variance, so more data (or label-preserving augmentation) should help. Collect more real examples if possible. Vertical flips are a bad choice for street signs: signs appear upright in real use, so flipped images do not match the real distribution, and they can change meaning for some signs. Use small rotations, crops, brightness changes, and blur instead, and apply them only to the training set after splitting.
Exercise
You generate five augmented copies of every image, then call traintestsplit on the enlarged set. Validation accuracy is 99%, but accuracy in production is 82%. What went wrong, and how do you fix it?
Show answer
Copies of the same original image ended up in both the training and validation sets, so the model was tested on near-duplicates of what it trained on. This is data leakage. Split the original images first, then augment only the training portion (or use random augmentation layers during training). Keep the validation set unaugmented.