Sub topic 2
Invariance and Label-Preserving Transforms
This chapter assumes you know how an image is stored as an array of pixel values, how a supervised classifier is trained with a train/validation/test split, and what overfitting looks like in a PyTorch training loop. You do not need any augmentation code yet. The goal is to learn how to decide whether a transform is safe for your task, before you apply it.
The core idea: augmentation encodes a claim about the world
Every augmentation makes a claim: "if I change the image this way, the correct answer stays the same." A horizontal flip of a cat photo claims that a mirrored cat is still a cat. A brightness change claims that a darker cat is still a cat.
When the claim is true, the transform adds useful variety. The model sees a new pixel pattern with a correct label, and it learns to ignore the change. When the claim is false, you create wrong training examples. The model is then rewarded for the wrong behavior, and the damage can be hard to notice because training loss still goes down.
Two terms describe this precisely.
- A model is invariant to a transform when its prediction does not change under that transform. For a classifier,
f(T(x)) = f(x). - A model is equivariant to a transform when its output changes in the same way as the input. For a segmentation model, flipping the image should flip the predicted mask. Formally,
f(T(x)) = T(f(x)).
A transform is label-preserving when the true label of T(x) is the same as the true label of x. This is a property of the task and the data, not of the transform alone. The same flip is label-preserving for "cat versus dog" and label-changing for "is this text mirrored?".
Deciding whether a transform preserves the label
Ask three questions for each candidate transform.
- What information does the label depend on? For "cat versus dog", the label depends on shape and texture of the animal. For "ripe versus unripe tomato", it depends strongly on color.
- Does the transform destroy or alter that information? A strong hue shift alters the color information a ripeness classifier needs. A small crop usually does not alter animal identity.
- Could the change happen in real deployment? Even if a transform keeps the label, it helps only if it resembles real variation. Training on upside-down street scenes costs capacity if the camera is always mounted upright.
The third question separates two goals. Label preservation keeps the data correct. Realism keeps the data useful. A good augmentation passes both tests.
The same transform in different tasks
The table shows how the answer changes with the task.
| Transform | Task | Label-preserving? | Reason |
|---|---|---|---|
| Horizontal flip | Animal species classification | Yes | Species does not depend on left or right orientation. |
| Horizontal flip | Handwritten digit recognition | Mostly no | A mirrored 2 or 5 looks like something else, and some digits become invalid shapes. |
| Horizontal flip | Traffic sign reading | No for text and arrows | A "turn left" arrow becomes "turn right". |
| Vertical flip | Natural photo classification | Usually no | Real photos are rarely upside down, so it adds unrealistic data. |
| Vertical flip | Satellite or microscope images | Yes | There is no fixed up direction. |
| Rotation by 180 degrees | Digit recognition | No | A 6 becomes a 9. |
| Hue shift | Ripeness or skin-lesion color grading | No, or only very small | Color carries the label. |
| Brightness change | Object classification | Yes, within limits | Lighting varies in real use. |
| Strong crop | Object classification | Risky | The crop may remove the object the label names. |
| Random erasing | Fine-grained classification | Risky | The erased patch may hide the only distinguishing part. |
Notice that "yes" and "no" often come with a qualifier such as "within limits". Most transforms have a range of strengths. A rotation of 10 degrees keeps almost any label. A rotation of 90 degrees keeps many labels but breaks others. Strength is a second axis you have to reason about, and later chapters return to it when we tune augmentation.
Symmetries in your data
The most reliable guide is the set of symmetries of the problem. A symmetry is a change that leaves the correct answer alone.
- Reflection symmetry. Many object categories are mirror-symmetric in meaning. Left-right flips are standard for ImageNet-style classification and rarely hurt.
- Rotation symmetry. Aerial, satellite, and microscopy images have no preferred orientation, so rotations by any angle are valid. Street scenes have a strong "up" direction and do not.
- Translation and scale. Objects can appear anywhere in the frame and at different distances. This is why random crops and rescaling are almost universally used. Convolutional networks are partly translation-equivariant by construction, but augmentation still helps because pooling, padding, and strides make the match imperfect.
- Photometric symmetry. Exposure, white balance, and sensor noise change between cameras and times of day, usually without changing what is in the scene.
When you are unsure, look at how the data will be collected in production. If the production camera, lighting, and framing are fixed, you need less augmentation of those factors, and aggressive augmentation can even hurt by spending model capacity on variation that never occurs.
Three kinds of risk
Unsafe augmentation falls into three groups. Naming them helps when you debug.
1. The label changes
The transform turns the image into an example of a different class. Flipping a "b" into a "d", rotating a "6" into a "9", or mirroring a left-turn sign are examples. The training label is now wrong. This is the hardest case to detect from metrics alone, because the model can still fit the noisy labels.
2. The label becomes uncertain
The transform removes the evidence for the label, but the label stays. A tight random crop that cuts out a small bird from a landscape photo still carries the label "bird", yet the bird is no longer visible. A heavy blur on a task that depends on fine texture does the same. The model is forced to guess, and it may learn to rely on background context instead of the object.
3. The distribution shifts away from reality
The label is still correct, but the images no longer look like anything the model will meet. Extreme color jitter turns skin tones green. Vertical flips of road scenes put the sky below the road. The model wastes capacity, and on small datasets this can lower accuracy on real test images.
A quick check you can run
You can test a transform's safety empirically before trusting your reasoning. Apply it to a sample of images, save them in a grid, and read the labels yourself. If a human would sometimes disagree with the label, the transform is unsafe at that strength.
The following script applies a candidate transform to a few images and saves a contact sheet. It uses a generated test image so it runs without any dataset.
import numpy as np
from PIL import Image
from torchvision import transforms
# Build a simple test image with an arrow-like asymmetric shape.
canvas = np.zeros((128, 128, 3), dtype=np.uint8)
canvas[:, :] = (30, 30, 30)
canvas[54:74, 20:90] = (240, 240, 240) # shaft
for i in range(30): # head, pointing right
canvas[64 - i:64 + i + 1, 90 + i] = (240, 60, 60)
image = Image.fromarray(canvas)
candidates = {
"original": transforms.Lambda(lambda im: im),
"hflip": transforms.RandomHorizontalFlip(p=1.0),
"vflip": transforms.RandomVerticalFlip(p=1.0),
"rotate10": transforms.RandomRotation((10, 10)),
"hue_shift": transforms.ColorJitter(hue=(0.4, 0.4)),
}
sheet = Image.new("RGB", (128 * len(candidates), 128))
for i, (name, tf) in enumerate(candidates.items()):
sheet.paste(tf(image), (128 * i, 0))
sheet.save("transform_check.png")
print("Saved transform_check.png with:", ", ".join(candidates))Open transform_check.png. If the task were "does the arrow point left or right?", the hflip panel would show a wrong label. If the task were "is there an arrow?", every panel would be fine. The contact sheet makes the dependence on the task visible.
Deciding in practice
Follow the flow in order. It rejects transforms that break labels first, and then it filters out transforms that are harmless but unrealistic.
Edge cases
- Labels that encode orientation or chirality. Text, digits, clocks, arrows, medical images with left and right organs, and driving-side-specific scenes. Flips can silently swap classes. In medical imaging, a flipped chest X-ray can show the heart on the wrong side, which never occurs in a normal patient.
- Labels that encode position. Object detection and segmentation labels are tied to coordinates. These transforms are still valid, but the annotations must be transformed with the image. A later chapter covers this.
- Multi-label images. A crop can remove one of several labels while keeping others. Check that every label is still visible, or accept the noise knowingly.
- Small objects. Crops and scaling can push small objects out of the frame. The label remains in the file, but the object is gone.
- Texture-driven classes. Blur, resize with heavy downscaling, and strong noise can erase the cue that separates the classes.
- Class-dependent safety. A transform can be safe for some classes and unsafe for others within one dataset. In a dataset that includes both "stop sign" and "one-way arrow", flips affect the classes differently. When this happens, either drop the transform or apply it per class.
Common mistakes
- Copying an augmentation recipe from an ImageNet tutorial onto a task with different symmetries.
- Judging a transform by validation accuracy alone, without looking at the transformed images.
- Using a high strength because "more augmentation is more regularization". Regularization only helps when the labels stay right.
- Treating realism as optional. A label-preserving but unrealistic transform can still lower test accuracy.
Summary
Augmentation is a claim that a change leaves the answer the same. That claim depends on the task, the transform, and its strength. Check what information the label depends on, check whether the change occurs in deployment, and confirm by viewing samples. The next chapters build on this by describing specific families of transforms and how to compose them.
Exercise
You are building a classifier that reads analog clock faces and outputs the time shown (for example, "3:15"). A colleague proposes adding RandomHorizontalFlip(p=0.5) and RandomRotation(degrees=30) to the training pipeline. Which of the two is more dangerous, and why? Name the type of risk from this chapter.
Show answer
Horizontal flip is more dangerous. Mirroring a clock face swaps the positions of the hands around the vertical axis, so 3:15 becomes roughly 8:45, and the stored label is now wrong. This is the "label changes" risk. A rotation of 30 degrees is also risky, because the orientation of the dial defines which direction is 12, and rotating the whole image can make hand positions read as a different time. If you keep rotation at all, use a small range such as 5 degrees to model camera tilt. The flip should be dropped.
Exercise
A satellite-image classifier distinguishes "farmland" from "forest". Is a random vertical flip label-preserving? Is it also realistic? Explain how these two properties differ.
Show answer
Yes to both. A vertically flipped aerial image is still farmland or forest, so the label is preserved. Satellite imagery has no fixed up direction, so flipped views also look like real images the model could meet, which makes the transform realistic. Label preservation means the stored label stays correct. Realism means the transformed images resemble deployment data. A transform such as a vertical flip on street photos keeps the "car" label but fails the realism test.
Exercise
Write the formal condition for a model that is invariant to a transform T, and for one that is equivariant. Give one task where you want each.
Show answer
Invariant: f(T(x)) = f(x). Example: image classification with horizontal flip, where "cat" should stay "cat". Equivariant: f(T(x)) = T(f(x)). Example: semantic segmentation with horizontal flip, where the predicted mask should be flipped in the same way as the image.