Sub topic 2
Organizing and Splitting Your Images
This chapter assumes you know basic Python, PyTorch tensors and modules, and the purpose of loss, gradients, and epochs. You will prepare the labeled files that a transfer-learning classifier needs.
Use one folder per class
A supervised image classifier learns from an image and its label. A label is the correct category for that image, such as cat or dog.
torchvision.datasets.ImageFolder reads labels from directory names. Every class needs its own folder:
data/
├── train/
│ ├── cats/
│ │ ├── cat_001.jpg
│ │ └── cat_002.jpg
│ ├── dogs/
│ │ ├── dog_001.jpg
│ │ └── dog_002.jpg
├── val/
│ ├── cats/
│ └── dogs/
└── test/
├── cats/
└── dogs/The class names must be consistent across all three splits. A split is a separate part of the dataset used for a different purpose.
| Split | Purpose | Used to update weights? |
|---|---|---|
| Train | Fit the model | Yes |
| Validation | Choose settings and detect overfitting | No |
| Test | Report final performance once | No |
Keep the test set untouched until model decisions are complete.
Create the splits without leakage
Data leakage occurs when information from validation or test images influences training. For example, putting nearly identical frames from one video into both train and test makes the score look better than real-world performance.
Split related images as a group. If one person, object, patient, or video appears in many files, keep that source in only one split. Otherwise, the model may recognize the source rather than the class.
For independent images, a common starting point is 70% train, 15% validation, and 15% test. Preserve the proportion of each class in every split. This is called a stratified split.
The following script creates a reproducible, per-class split. It copies files rather than moving them, so the source directory remains available. It assumes each immediate subdirectory of images/ is a class.
from pathlib import Path
import random
import shutil
source = Path("images")
destination = Path("data")
ratios = (0.70, 0.15, 0.15)
seed = 7
extensions = {".jpg", ".jpeg", ".png", ".bmp", ".webp"}
random.seed(seed)
for class_dir in sorted(path for path in source.iterdir() if path.is_dir()):
files = sorted(
path for path in class_dir.iterdir()
if path.is_file() and path.suffix.lower() in extensions
)
random.shuffle(files)
n = len(files)
train_end = int(n * ratios[0])
val_end = train_end + int(n * ratios[1])
groups = {
"train": files[:train_end],
"val": files[train_end:val_end],
"test": files[val_end:],
}
for split, split_files in groups.items():
target_dir = destination / split / class_dir.name
target_dir.mkdir(parents=True, exist_ok=True)
for file in split_files:
shutil.copy2(file, target_dir / file.name)
print(f"Created splits under {destination}/")Small classes can produce uneven counts because the script rounds down. Check the resulting counts and consider collecting more examples instead of accepting a misleading test score.
Verify the layout with ImageFolder
After splitting, load each directory and compare its class mapping. ImageFolder sorts class names and assigns each name an integer index. The same class must receive the same index in every split.
from torchvision.datasets import ImageFolder
train_ds = ImageFolder("data/train")
val_ds = ImageFolder("data/val")
test_ds = ImageFolder("data/test")
if train_ds.class_to_idx != val_ds.class_to_idx:
raise ValueError("Training and validation classes do not match")
if train_ds.class_to_idx != test_ds.class_to_idx:
raise ValueError("Training and test classes do not match")
print(train_ds.class_to_idx)
print(len(train_ds), len(val_ds), len(test_ds))The loader will fail or produce unreliable results if a class folder is empty, files are corrupt, or class names differ by capitalization. Inspect samples from every class before training.
Exercise
Why should frames from the same video usually stay in one split?
Show answer
They are highly similar, so placing frames in different splits can leak visual information and produce an overly optimistic evaluation.