Data Augmentation
The Problem: Small Datasets
With only a few thousand pictures, a CNN quickly memorizes them. Data augmentation creates slightly changed copies of your images during training: flipped, rotated, zoomed. To the network each copy looks like a new picture, so it learns the real object and not the exact pixels.
Simple example: A cat is still a cat if the photo is flipped, a bit rotated or zoomed in. By showing these variations, we teach the model what really matters.
Augmentation Layers
python
import keras
from keras import layers
data_augmentation = keras.Sequential([
layers.RandomFlip("horizontal"),
layers.RandomRotation(0.1), # up to 10% of a full circle
layers.RandomZoom(0.1),
layers.RandomContrast(0.1),
], name="augmentation")
See What It Does
python
import matplotlib.pyplot as plt
for images, _ in train_ds.take(1):
plt.figure(figsize=(8, 8))
for i in range(9):
augmented = data_augmentation(images[:1], training=True)
plt.subplot(3, 3, i + 1)
plt.imshow(augmented[0].numpy().astype("uint8"))
plt.axis("off")
plt.show()
You will see 9 different versions of the same first image.
Add It to the Model
python
model = keras.Sequential([
keras.Input(shape=(180, 180, 3)),
data_augmentation, # only active during training
layers.Rescaling(1.0 / 255),
layers.Conv2D(32, 3, activation="relu"),
layers.MaxPooling2D(),
layers.Conv2D(64, 3, activation="relu"),
layers.MaxPooling2D(),
layers.Dropout(0.3),
layers.Flatten(),
layers.Dense(64, activation="relu"),
layers.Dense(1, activation="sigmoid"),
])
Good to know: Augmentation layers are automatically switched off during
evaluate() and predict(). Only training data is changed.
Choose Sensible Augmentations
| Data | Good augmentations | Avoid |
|---|---|---|
| Animals, objects | Horizontal flip, rotation, zoom | Extreme rotations |
| Handwritten digits | Small rotation, small shifts | Flipping (a 6 is not a 9) |
| Medical scans | Small rotation, brightness changes | Anything that changes meaning |
| Satellite images | Horizontal and vertical flips, rotation |
Result to expect: Training accuracy rises more slowly, but validation accuracy gets closer to it. The gap (overfitting) becomes smaller.
Conclusion
Data augmentation is a free way to get more data. Use realistic changes and keep them inside your model.
Quick Summary: Use RandomFlip, RandomRotation and RandomZoom layers at the start of the model to fight overfitting on image data.

