Lesson 17 of 187 min
Loading pictures and augmentation
Change each training photo at random every time it is read, in ways that keep its label, and give the network every photo at one size, prepared exactly as it was trained.
After this lesson you can turn a folder of pictures into batches a network takes, prepare a photo the way a pretrained network expects, and make a few pictures go further with augmentation.
Loading the video…
Refreshers
An idea from an earlier lesson shows up here when the video leans on it.
In real code
What the video left out, as you will meet it in your own code.
Read the folder's labels
Unzip the Beans training archive into a beans folder to get beans/train. ImageFolder numbers the class folders alphabetically. Keep the same class-to-number mapping when you open the validation folder.
from torchvision.datasets import ImageFolder
from torchvision.transforms import v2
train = ImageFolder("beans/train")
print(len(train), train.class_to_idx)1034 {'angular_leaf_spot': 0, 'bean_rust': 1, 'healthy': 2}Open one photo
decode_image gives you a tensor with channels first. Ask for RGB so each photo has three channels. Hugging Face's ImageFolder builder also reads the classes from local directories and can open a folder with load_dataset("imagefolder", data_dir="beans").
from torchvision.io import ImageReadMode, decode_image
path, label = train.samples[0]
photo = decode_image(path, mode=ImageReadMode.RGB)
print(tuple(photo.shape), photo.dtype, train.classes[label])(3, 500, 500) torch.uint8 angular_leaf_spot
Load ahead while the GPU trains
A positive num_workers lets other processes prepare upcoming batches. Start with zero in a notebook. In a Python script, try four workers and keep the loader and training loop inside an if __name__ == "__main__": guard on macOS and Windows. Measure a full pass before keeping the change.
import torch
from torch.utils.data import DataLoader
train.transform = v2.Compose([
v2.Resize(256), v2.CenterCrop(224), v2.ToImage(),
v2.ToDtype(torch.float32, scale=True),
])
loader = DataLoader(train, batch_size=32, shuffle=True, num_workers=0)
x, y = next(iter(loader))
print(x.shape, y.shape)torch.Size([32, 3, 224, 224]) torch.Size([32])
Compare at more than one data size
The changes helped at 20 photos of each kind. At 50, one five-epoch run scored lower with them. Keep the same photos set aside and repeat the comparison across several picks before deciding to keep a recipe. These are the recorded validation scores for DINOv2 small.
for count, without, with_changes in [(20, 93.0, 96.7), (50, 97.7, 94.7)]:
print(f"{count} per kind: {with_changes - without:+.1f} percentage points")20 per kind: +3.7 percentage points 50 per kind: -3.0 percentage points
Compare with a frozen network
At 10 photos per kind, augmentation moved the frozen network from 82.2% to 81.2%. With fine-tuning and augmentation, every pick beat its matching frozen baseline. Swapping red and blue scored 83.5% in this frozen experiment. Keep RGB for the model and check color order if you read photos with OpenCV.
frozen = [82.0, 83.5, 81.2]
tuned_with_changes = [84.2, 93.2, 82.0]
print([round(tuned - base, 1) for base, tuned in zip(frozen, tuned_with_changes)])[2.2, 9.7, 0.8]
Try a stronger recipe
RandAugment draws a fixed number of operations at one chosen strength. TrivialAugmentWide draws one operation and its strength. Both work on individual photos. MixUp blends two images and their labels. CutMix pastes a patch from one image into another and mixes the labels by area. Apply those last two to training batches.
pictures = (x * 255).round().to(torch.uint8)
for change in (v2.RandAugment(), v2.TrivialAugmentWide()):
print(change(pictures[0]).shape)
for change in (v2.MixUp(num_classes=3), v2.CutMix(num_classes=3)):
_, soft_labels = change(x, y)
print(soft_labels.shape)torch.Size([3, 224, 224]) torch.Size([3, 224, 224]) torch.Size([32, 3]) torch.Size([32, 3])
Run on Python 3.13.3, PyTorch 2.15.0, torchvision 0.29.2, Transformers 5.24.0. Checked on .
Quiz
Two questions on this lesson, and one from earlier. Answer as often as you like.
1 of 3
From earlier: Stochastic gradient descent
Your data holds 1,000 examples, and your code has DataLoader(data, batch_size=64, shuffle=True). How many times does opt.step() run in one epoch?
2 of 3
You have a few pictures of handwritten digits to train a network on, and you want more from the same pictures. Which plan is right?
3 of 3
One square of a photo has a red number of 204. The processor's red average is 0.485, and its spread is 0.229. After the scale and the shift, what is the red number? Give two decimals.
The ideas in this lesson
- Augmentation
- Change each training photo at random every time it is read, keeping its label: new examples from the same photos.
- From a folder to batches
- A dataset reads each photo with its folder's label and makes it one size; a loader stacks them into batches.
- Prepared as it was trained
- Prepare photos exactly as a pretrained network's were: its size, divided by 255, each color shifted by its own numbers.
It leans on
- A PyTorch class
Transcript
What the video says, part by part. Press a time to watch from there.
More from the same photos
Here's a bet. You have only a few photos of each kind of leaf.
Taking more means going back to the field. Can you get more training examples from the photos you have?
The bet
Here are thirty photos of bean leaves, ten of each kind. A pretrained network, fine-tuned on them, gets seventy-six percent right. That's on other photos, set aside, that it never learns from.
Now try this. Every time a photo is read for training, change it at random. Flip it, zoom in on a part, and change its light. It's the same thirty photos, and not a single new one. Will it score better, the same, or worse?
It learned the photos
First, why only seventy-six?
Take a pretrained network, fine-tuned on thirty photos of leaves. On its own thirty photos: every single one right.
On the photos set aside: seventy-six percent. We picked the ten photos of each kind at random, three times, and that's the average. It learned these thirty photos... not what a sick leaf looks like.
A new version every time
So how can the same photos teach it more? Don't let them stay the same.
Every time a photo is read for training, change it at random. Flip it. Zoom in on a random part. Make it lighter, or darker. Think of a leaf in your hand. Turn it over, look closer, or step into the shade. It's still the same sick leaf, so its label stays. Each pass through the photos brings new versions of the same thirty. This is called augmentation.
The bet's answer
So, your bet. The same thirty photos, with their changes... eighty-six and a half percent. Not seventy-six.
And it's higher in each of the three picks. To get every version right, it has to find what they all share. The spots on the leaf, not where they sit, or the light.
A change must keep the answer
So can you change a photo any way you like?
Spot the problem. These handwritten digits are turned upside down at random.
A six, turned upside down... is a nine.
And its label still says six.
Trained like that, the network starts to mix them up.
Of the seventy-two sixes and nines set aside, it now reads about four as the other digit. Without the turn, it got none of them wrong that way.
So only use changes that keep the answer.
Only the training photos
And only the training photos change. The photos set aside stay as they are. That way, the score measures real photos, and it's the same every time.
DINOv2 learned this way
Big networks learn this way too. DINOv2, the pretrained network here, was trained on random crops of its photos, flipped, with their colors changed. Two crops of the same photo had to get close numbers.
A photo is numbers
A network reads photos in batches. But what does it get from one photo?
A grid of small squares, with three numbers for each square: red, green and blue. Each number is between zero and two hundred fifty-five. This photo is five hundred squares by five hundred. That's seven hundred and fifty thousand numbers.
One size
A batch is one block of numbers. So can a tall photo go in with a square one?
No. PyTorch stops with this error. Every photo in a batch has to be the same size.
So each photo is shrunk, and its middle is cut out.
Now every photo is two hundred twenty-four squares by two hundred twenty-four.
A dataset and a loader
Now the whole folder: over a thousand photos to learn from. It holds one folder for each kind of leaf, and the folder's name is the label. A dataset reads one photo when it's asked. It opens the photo, changes it at random, makes it one size, and hands it over with its label. A loader asks for thirty-two photos at a time, in a shuffled order, and stacks them. So what's the shape of one batch?
Thirty-two photos, three colors, two hundred twenty-four by two hundred twenty-four.
And each photo is opened only when its batch comes. So the folder can be far bigger than the computer's memory.
Prepared as it was trained
Can those numbers stay between zero and two hundred fifty-five? A pretrained network, like DINOv2, learned from photos prepared one way. So yours need the same size, and the same numbers.
First, the scale. Each number is divided by two hundred fifty-five, so it runs from zero to one.
Then the shift. For each color, take away the processor's average and divide by its spread. It's the same kind of math as normalization in a network's layers. Here it's done once, on the photo. You don't type these numbers. The processor that comes with the network holds them.
Skip the scale
So what if you skip the scale? Here's the network kept frozen, with only its new last layer learning, on the same thirty photos. The shift is there. Only the scale is missing.
Fifty-two percent, where it got eighty-two. And no error warns you. Skip only the shift, or squash the photo instead of cutting it, and you get about eighty.
So prepare the photos exactly the way the network was trained.
In code
In code, the training photos get a list of steps. A random cut, made one size. Two flips. A change of light. Then the scale, and the shift with the processor's numbers. The photos set aside get the same list, without the random changes: shrunk, and cut from the middle. ImageFolder reads the folder, one folder for each kind. DataLoader makes the batches. So what does one batch print?
Thirty-two, three, two hundred twenty-four, two hundred twenty-four. And look at scale equals true. Leave it out, and the numbers stay as big as two hundred fifty-five. Nothing warns you.
Keep the answer
So change each training photo at random, and keep its answer. Make every photo one size, and stack them in batches. And prepare them exactly the way the network was trained.
Keep its answer
Change each photo at random, but keep its answer. That's how a few photos teach more. Now try it on this lesson's page, and take the quiz. Find out when the changes stop helping.
Facts last checked on .
