Sub topic 2
Organizing and splitting your images
This chapter assumes you know basic Python, can read a PyTorch Dataset and DataLoader, and understand what training and validation mean. By the end you will have a folder layout that torchvision.datasets.ImageFolder loads. The images will be split so that your evaluation numbers can be trusted.
Why the layout and the split matter
A pretrained model needs few images, but they must be labeled correctly and divided correctly. Two mistakes cause most bad results:
- Wrong labels or structure. The loader silently assigns the wrong class, or fails.
- Leakage. The same image, or a near copy, appears in both training and evaluation data. Accuracy then looks excellent and the model fails on real photos.
You fix both before writing any model code.
The ImageFolder layout
ImageFolder treats each sub-folder name as a class label. It sorts the folder names alphabetically and assigns indices 0, 1, 2, and so on. You need one root per split, with the same class folders under each.
data/
train/
cat/ 001.jpg 002.jpg ...
dog/ 003.jpg ...
fox/ ...
val/
cat/ ...
dog/ ...
fox/ ...
test/
cat/ ...
dog/ ...
fox/ ...Details that cause confusing errors:
- The class order comes from sorted folder names, not from the order you created them.
train_ds.classesandtrain_ds.class_to_idxshow the result. Saveclasseswith your model (a later chapter does this), because a predicted index means nothing without it. - A class folder missing from
valgives different class indices intrainandval. The labels then no longer match, and the loop still runs without an error. Keep the class folders identical in every split. - A class folder with no valid images raises a
FileNotFoundErrorwhen you construct the dataset. - The default loader accepts common image extensions such as
.jpg,.jpeg,.png, and.bmp. Other files are ignored. A folder of.heicphotos looks empty to it. - Images are opened with PIL. Grayscale and RGBA files load with different channel counts, which breaks batching. The preprocessing chapter handles this with
.convert("RGB"). For now, know that mixed modes are a data problem to look for.
What each split is for
| Split | Used for | Touched how often |
|---|---|---|
| train | Updating the weights | Every epoch |
| val | Choosing epochs, learning rates, augmentation, and model variants | Many times during development |
| test | One final, honest estimate of performance | Once, at the end |
Every time you adjust a setting after looking at the validation score, you fit your choices to the validation set. That is why the test set must stay untouched until the decisions are finished. A common ratio is 70/15/15. With a few hundred images per class, 80/10/10 gives training more data. Whatever the ratio, the validation and test sets need enough images per class to be meaningful. Ten images of a class make that class's accuracy move by 10 points per mistake. Try to have at least 20 to 30 per class in each held-out split. If you cannot, consider cross-validation, which is outside this chapter.
How many images per class
Transfer learning works with small data, but there are practical limits:
- Dozens per class can work for visually distinct classes. Hundreds per class are safer for similar-looking ones.
- Roughly balanced classes make evaluation simpler. Large imbalance is its own topic, covered in a later chapter. Splitting per class, as shown below, keeps each class's proportions the same in every split.
- Images should resemble what the model will see in use. If production photos are phone pictures taken indoors, a training set of studio photos will mislead you.
Splitting reproducibly
Do the split once, with a fixed random seed, and write the result to disk. Do not split inside the training script on every run. If the split changes between runs, an image that was in validation yesterday can be in training today, and you can no longer compare experiments.
The script below starts from a raw/<class>/ folder. It removes exact duplicate files, splits each class separately, and copies files into the layout above. It is complete and runnable.
import hashlib
import random
import shutil
from pathlib import Path
RAW = Path("raw")
OUT = Path("data")
FRACTIONS = {"train": 0.70, "val": 0.15} # the remainder goes to test
EXTENSIONS = {".jpg", ".jpeg", ".png"}
SEED = 42
def file_digest(path: Path) -> str:
return hashlib.sha256(path.read_bytes()).hexdigest()
def collect_unique(class_dir: Path, seen: dict) -> list:
"""Return (path, digest) pairs for files not seen before in any class."""
items = []
for path in sorted(class_dir.rglob("*")):
if path.suffix.lower() not in EXTENSIONS:
continue
digest = file_digest(path)
if digest in seen:
print(f"duplicate skipped: {path} (same as {seen[digest]})")
continue
seen[digest] = path
items.append((path, digest))
return items
def main() -> None:
rng = random.Random(SEED)
seen = {}
for class_dir in sorted(p for p in RAW.iterdir() if p.is_dir()):
items = collect_unique(class_dir, seen)
rng.shuffle(items)
n = len(items)
n_train = int(n * FRACTIONS["train"])
n_val = int(n * FRACTIONS["val"])
parts = {
"train": items[:n_train],
"val": items[n_train:n_train + n_val],
"test": items[n_train + n_val:],
}
for split, split_items in parts.items():
dest = OUT / split / class_dir.name
dest.mkdir(parents=True, exist_ok=True)
for src, digest in split_items:
# The digest prefix prevents name clashes between sub-folders.
shutil.copy2(src, dest / f"{digest[:8]}_{src.name}")
print(class_dir.name, {k: len(v) for k, v in parts.items()})
if __name__ == "__main__":
main()Points about this script:
- Sorting file names and class folders before shuffling, plus the seeded
random.Random, makes the result repeatable on the same files. - Splitting inside each class keeps class proportions equal across splits (a stratified split).
- The
seendictionary is shared across classes. This also catches the same file filed under two labels, which is a labeling error you want to hear about. - Copying instead of moving leaves
raw/intact, so you can redo the split with a different ratio.
Leakage that file hashing does not catch
Hashing finds byte-identical files. Leakage usually comes from files that differ but are not independent:
- Resized or re-encoded copies. The same photo saved at two sizes has two different hashes.
- Burst or video-frame images. Fifty frames from one clip are near duplicates. If some land in training and some in validation, validation accuracy measures memory, not generalization.
- Same subject, same session. Ten photos of one plant on one windowsill share background and lighting. The model can learn the windowsill.
- Augmented copies saved to disk before the split. If you generate flipped or cropped copies and then split, a copy of a training image can end up in validation. Augment during training only, and split first.
The fix is to split by group, not by file. If your files are named by source, for example clip17_frame004.jpg, assign whole groups to one split. Here is a minimal version for one class:
import random
from collections import defaultdict
from pathlib import Path
def group_key(path: Path) -> str:
# Assumes names like clip17_frame004.jpg; the part before "_" is the group.
return path.stem.split("_")[0]
def split_by_group(paths, train_frac=0.7, val_frac=0.15, seed=42):
groups = defaultdict(list)
for p in paths:
groups[group_key(p)].append(p)
keys = sorted(groups)
random.Random(seed).shuffle(keys)
n_train = int(len(keys) * train_frac)
n_val = int(len(keys) * val_frac)
chosen = {
"train": keys[:n_train],
"val": keys[n_train:n_train + n_val],
"test": keys[n_train + n_val:],
}
return {split: [p for k in ks for p in groups[k]] for split, ks in chosen.items()}Group sizes differ, so the split sizes will only approximately match your fractions. Check the counts afterward.
Verify before you train
Run a short check that loads all three splits and confirms they agree. This takes seconds and catches the silent problems above.
from pathlib import Path
from torchvision import datasets
splits = {name: datasets.ImageFolder(f"data/{name}") for name in ("train", "val", "test")}
reference = splits["train"].classes
for name, ds in splits.items():
assert ds.classes == reference, f"{name} classes differ from train"
counts = [0] * len(ds.classes)
for _, label in ds.samples:
counts[label] += 1
print(name, dict(zip(ds.classes, counts)))
# No file name may appear in two splits; names carry a content hash prefix.
names = {name: {Path(p).name for p, _ in ds.samples} for name, ds in splits.items()}
assert not (names["train"] & names["val"]), "train/val overlap"
assert not (names["train"] & names["test"]), "train/test overlap"
assert not (names["val"] & names["test"]), "val/test overlap"
print("layout OK")The overlap check relies on the hash prefix added by the split script. It would not work for files you copied in by hand under their original names.
Common errors
- Hidden folders. A
.ipynb_checkpointsfolder insidedata/traincan appear as an extra class in older torchvision versions. Delete it, and checkclassesafter loading. - Splitting after augmenting. See the leakage list above.
- Re-splitting between experiments. Commit the seed and the output folder, or record the file lists, so results stay comparable.
- Tiny validation sets. Differences of one or two points between runs are noise when each class has only a handful of validation images.
- Different cleaning in train and val. If you remove blurry images only from train, validation no longer represents the data you will meet later.
Exercise
Your dataset contains 40 photos each of 25 plants, taken with a phone in several shots per plant. A random per-file split gives 97% validation accuracy, but the model does poorly on photos of new plants. What is the most likely cause, and how would you change the split?
Show answer
Photos of the same plant appear in both training and validation, so the model recognizes individual plants and backgrounds instead of the class. Split by group, so that all photos of one plant go into the same split (for example by encoding the plant ID in the file name and using a group-based split like splitbygroup). Then validation measures performance on plants the model has not seen.
Exercise
After running the split script, ImageFolder reports 3 classes for train but 4 for val. Why is this a problem even if training runs without crashing, and what do you check?
Show answer
Class indices are assigned from the sorted folder names in each root, so the same index can mean different classes in train and val, and the validation labels no longer match the model's outputs. Compare trainds.classes with valds.classes, and create the missing class folder (with images) in the split that lacks it, or remove the extra class from the other. Also look for stray folders such as .ipynb_checkpoints.