From Files to Batches
Training code wants batches: a tensor of shape (N, C, H, W) with a tensor
of N labels. Between the files on disk and those batches sit two PyTorch
pieces you already know: a Dataset, which returns one image and its
label for an index, and a DataLoader, which collects items into
batches. This lesson covers the three usual ways to get a Dataset of images:
a ready-made one from torchvision, ImageFolder over a folder per class,
and a Dataset you write yourself when labels live somewhere else.
EuroSAT
EuroSAT is a public collection of 27,000 satellite images of land in Europe, taken by the Sentinel-2 satellites and labelled with ten land-use classes such as Forest, Highway and River. Each tile is 64 by 64 pixels. It was published with a benchmark paper in 2017 and is released under the MIT licence, which allows use in a course. The course uses it for every lesson on classification with real images.
torchvision.datasets.EuroSAT(root, download=True) downloads the archive
EuroSAT.zip (94.3 MB) into root/eurosat and unpacks the tiles, one
folder per class. If the tiles are already there, it skips both, so the
course keeps them in ~/cv-practice/data and every lesson reuses one
download. The transform argument is applied to each image as it is read;
without one, items are Pillow images.
ImageFolder: One Folder per Class
EuroSAT is built on torchvision.datasets.ImageFolder, which you can use
for any images arranged like this:
shapes/
circle/ circle_00.png circle_01.png ...
square/ square_00.png ...
triangle/ triangle_00.png ...
The folder names become the classes. ImageFolder sorts them and numbers
them from 0 in that order, so circle is 0, square 1 and triangle 2.
The sort compares characters by code, which puts every capital letter
before every lowercase one: a folder called Hexagon would become 0 and
renumber all the others. Three attributes describe the result: classes
(the names in index order), class_to_idx (name to index) and targets
(the label of every image, in file order). Counting targets is far
faster than reading every image. A class folder with no images raises an
error unless you pass allow_empty=True.
A Dataset Written by Hand
When labels are not given by folders, for example a spreadsheet listing
each file and its label, write a Dataset with __len__ and
__getitem__. Reading every row in __init__ and opening the image only
in __getitem__ keeps memory small: a DataLoader asks for items one at a
time. Fix the list of class names in code, as the exercise does, so that the
numbering does not depend on which labels happen to appear in the file.
Why Class Balance Matters
Count the images per class before training. EuroSAT's classes hold between 2,000 and 3,000 tiles each, so the largest is 1.5 times the smallest. That is mild, but it sets the floor: a model that always answers one of the 3,000-tile classes is right on 3,000 of 27,000 tiles, 11.1%. Any accuracy must be read against that, and later lessons report results per class for the same reason.
Exercise: Load Three Kinds of Dataset
You will download EuroSAT into the practice data folder and count its
classes, generate a small labelled folder of images, and load it both with
ImageFolder and with a Dataset of your own.
Starting state: the course environment from the setup lesson; about 230 MB free disk for EuroSAT and a connection to huggingface.co for the first download.
Effects: downloads EuroSAT.zip (94.3 MB) once from huggingface.co into
~/cv-practice/data and unpacks it (about 230 MB in all), kept for later
lessons; creates shapes, labels.csv and eurosat_grid.png in the lesson
folder. Nothing is uploaded.
Output: Outputs shown below are illustrative. Counts, classes and shapes should match; the download progress and its time vary.
-
In a terminal with the course environment active and
TORCH_HOMEset (see Set up the pinned CPU environment), create the lesson folder. macOS and Linux:mkdir -p ~/cv-practice/load-eurosat-and-image-folders cd ~/cv-practice/load-eurosat-and-image-foldersWindows PowerShell:
mkdir $HOME\cv-practice\load-eurosat-and-image-folders cd $HOME\cv-practice\load-eurosat-and-image-folders -
Save this as
load_eurosat.py:"""Download EuroSAT once into the practice data folder, count its classes and save one tile per class.""" from collections import Counter from pathlib import Path import torch from torch.utils.data import DataLoader from torchvision import datasets from torchvision.transforms import v2 from torchvision.utils import make_grid, save_image data_dir = Path.home() / "cv-practice" / "data" to_tensor = v2.Compose([v2.ToImage(), v2.ToDtype(torch.float32, scale=True)]) eurosat = datasets.EuroSAT(root=data_dir, transform=to_tensor, download=True) print("tiles:", len(eurosat)) counts = Counter(eurosat.targets) for index, name in enumerate(eurosat.classes): print(f"{index} {name:<21} {counts[index]:>5}") print("largest class / smallest class:", max(counts.values()) / min(counts.values())) image, label = eurosat[0] print("first tile:", tuple(image.shape), image.dtype, "label", label, eurosat.classes[label]) loader = DataLoader(eurosat, batch_size=32, shuffle=True, generator=torch.Generator().manual_seed(0)) images, labels = next(iter(loader)) print("one batch:", tuple(images.shape), tuple(labels.shape)) first_of_each = [eurosat.targets.index(c) for c in range(len(eurosat.classes))] grid = make_grid([eurosat[i][0] for i in first_of_each], nrow=5, padding=4, pad_value=1.0) save_image(grid, "eurosat_grid.png") print("saved eurosat_grid.png:", tuple(grid.shape), "rows of 5 in class order")ToImagethenToDtypeturn each Pillow image into a float tensor as it is read.make_gridarranges a list of(3, H, W)tensors into one image with a white border of 4 pixels, andsave_imagewrites it as a PNG; both are intorchvision.utils. Run it withpython load_eurosat.py. The first run shows a percentage counting up to 100.0% while the archive downloads, which took 29 seconds when the lesson was tested; then:tiles: 27000 0 AnnualCrop 3000 1 Forest 3000 2 HerbaceousVegetation 3000 3 Highway 2500 4 Industrial 2500 5 Pasture 2000 6 PermanentCrop 2500 7 Residential 3000 8 River 2500 9 SeaLake 3000 largest class / smallest class: 1.5 first tile: (3, 64, 64) torch.float32 label 0 AnnualCrop one batch: (32, 3, 64, 64) (32,) saved eurosat_grid.png: (3, 140, 344) rows of 5 in class orderOpen
eurosat_grid.png: two rows of five tiles, AnnualCrop to Industrial on the top row and Pasture to SeaLake below. These first tiles show AnnualCrop as a patchwork of fields, Forest as dark green, HerbaceousVegetation as pinkish open ground, Highway as a pale diagonal road, Industrial as large white roofs, Pasture as green patches, PermanentCrop as rows of strips, Residential as a grid of small roofs, River as a dark band and SeaLake as almost uniform dark blue water. Other tiles of the same class can look quite different. -
Save this as
make_shapes.py:"""Generate a small labelled image set: 20 seeded 64-pixel images each of three shapes.""" import csv from pathlib import Path import numpy as np from PIL import Image, ImageDraw rng = np.random.default_rng(7) root = Path("shapes") rows = [] for shape in ["circle", "square", "triangle"]: (root / shape).mkdir(parents=True, exist_ok=True) for n in range(20): image = Image.new("RGB", (64, 64), tuple(int(v) for v in rng.integers(0, 80, 3))) draw = ImageDraw.Draw(image) size = int(rng.integers(20, 40)) x, y = (int(v) for v in rng.integers(4, 60 - size, 2)) colour = tuple(int(v) for v in rng.integers(150, 256, 3)) if shape == "circle": draw.ellipse([x, y, x + size, y + size], fill=colour) elif shape == "square": draw.rectangle([x, y, x + size, y + size], fill=colour) else: draw.polygon([(x + size // 2, y), (x + size, y + size), (x, y + size)], fill=colour) path = root / shape / f"{shape}_{n:02d}.png" image.save(path) rows.append((path.as_posix(), shape)) with open("labels.csv", "w", newline="") as f: writer = csv.writer(f) writer.writerow(["path", "label"]) writer.writerows(rows) print("wrote", len(rows), "images under shapes/ and labels.csv")It draws 20 images of each shape with a seeded generator, so every run makes the same files, and writes
labels.csvlisting each file with its label. Run it withpython make_shapes.py:wrote 60 images under shapes/ and labels.csv -
Save this as
load_folders.py:"""Load the generated shapes two ways: ImageFolder, and a Dataset written by hand over labels.csv.""" import csv from collections import Counter import torch from PIL import Image from torch.utils.data import DataLoader, Dataset from torchvision import datasets from torchvision.transforms import v2 to_tensor = v2.Compose([v2.ToImage(), v2.ToDtype(torch.float32, scale=True)]) folder = datasets.ImageFolder("shapes", transform=to_tensor) print("ImageFolder classes:", folder.class_to_idx) print("ImageFolder counts:", dict(Counter(folder.targets))) class ShapeFiles(Dataset): """Images listed in a CSV file with a path and a label name per row.""" def __init__(self, csv_path, classes, transform=None): with open(csv_path, newline="") as f: self.rows = [(row["path"], classes.index(row["label"])) for row in csv.DictReader(f)] self.classes = classes self.transform = transform def __len__(self): return len(self.rows) def __getitem__(self, index): path, label = self.rows[index] image = Image.open(path).convert("RGB") if self.transform is not None: image = self.transform(image) return image, label files = ShapeFiles("labels.csv", classes=["circle", "square", "triangle"], transform=to_tensor) print("ShapeFiles length:", len(files)) print("ShapeFiles counts:", dict(Counter(label for _, label in files.rows))) image, label = files[25] print("item 25:", tuple(image.shape), image.dtype, "label", label, files.classes[label]) loader = DataLoader(files, batch_size=8, shuffle=True, generator=torch.Generator().manual_seed(0)) images, labels = next(iter(loader)) print("one batch:", tuple(images.shape), labels.tolist())ShapeFilesreads the CSV once, turning each label name into its index in the fixedclasseslist.__getitem__opens one image, converts it to RGB and applies the transform. Run it withpython load_folders.py:ImageFolder classes: {'circle': 0, 'square': 1, 'triangle': 2} ImageFolder counts: {0: 20, 1: 20, 2: 20} ShapeFiles length: 60 ShapeFiles counts: {0: 20, 1: 20, 2: 20} item 25: (3, 64, 64) torch.float32 label 1 square one batch: (8, 3, 64, 64) [2, 0, 2, 2, 1, 1, 2, 1]
Reading the Result
Both datasets agree: three classes numbered in the same order, 20 images
each. Item 25 is a square because the CSV lists the 20 circles first. The
batch labels are a seeded shuffle, so you see the same eight labels; without
the generator they would change on every run.
Success: EuroSAT reports 27,000 tiles with the counts above, the grid shows one tile per class, and both shape datasets give the same classes and counts.
If something differs:
| What you see | Likely cause | Next step |
|---|---|---|
RuntimeError: Dataset not found. You can use download=True to download it | download=True missing, or a different root | Use the practice data folder with download=True |
| A connection error during the download | huggingface.co not reachable | Check the network and run again; torchvision checks the archive's checksum and downloads a partial file again |
| Fewer than 27,000 tiles | Unpacking was interrupted, so the folder exists but is incomplete | Remove ~/cv-practice/data/eurosat and run again |
FileNotFoundError: Found no valid file for the classes ... | An empty class folder under shapes | Remove it, or add images |
ValueError: 'hexagon' is not in list (Python 3.14: ValueError: list.index(x): x not in list) | A label in the CSV that is not in classes | Add the class to the list, or fix the CSV |
Reset: delete shapes and labels.csv and run python make_shapes.py
again. Leave ~/cv-practice/data in place: later lessons use EuroSAT.
Independent task: make a folder shapes/Hexagon and copy one circle
image into it. Predict class_to_idx from ImageFolder("shapes"), then
check. Remove the folder afterwards.
Hint 1: How does ImageFolder order the folder names it finds?
Hint 2: Python sorts strings by character code, and every capital letter comes before every lowercase one.
-
Clean up. macOS and Linux:
cd ~/cv-practice ls rm -rf load-eurosat-and-image-foldersWindows PowerShell:
cd $HOME\cv-practice ls Remove-Item -Recurse load-eurosat-and-image-foldersCheck that
lslistsload-eurosat-and-image-foldersbefore you remove it. The environment,weightsanddatastay for later lessons.
Check Your Understanding
- A folder holds
river,Forestandlakesubfolders, each with images. What index doesImageFoldergive each class? - You train a model on
ImageFolder("tiles"), save it, and later add a new class folder before predicting with the saved model. What can go wrong, and how do you prevent it?
Answer and Reasoning
Independent task
{'Hexagon': 0, 'circle': 1, 'square': 2, 'triangle': 3}
H sorts before every lowercase letter, so the new class takes index 0 and
pushes the others up by one. On Windows PowerShell, create the folder with
mkdir shapes\Hexagon and copy with Copy-Item shapes\circle\circle_00.png shapes\Hexagon\.
Understanding check
Forest0,lake1,river2. CapitalFcomes before every lowercase letter in the sort, thenlakebeforeriver.- The saved model outputs index numbers, not names. A new folder can
change which name each number stands for, so the model's answer 1 would
be read as a different class with no error. Save the class list
(
dataset.classes) with the model and use it, not a freshImageFolder, to name predictions; Reuse on a CPU does this when it saves a model.