A CNN with a custom Dataset and DataLoader

AdvancedConvolutional networksImage classification

Goal: Building a data pipeline in the standard PyTorch style and training a convolutional network.

Python — example.py
import torch
from torch import nn
from torch.utils.data import DataLoader, Dataset

class Lines(Dataset):
    def __init__(self, n, seed):
        g = torch.Generator().manual_seed(seed)
        self.y = torch.randint(0, 2, (n,), generator=g)
        self.x = torch.rand(n, 1, 16, 16, generator=g) * 0.3
        pos = torch.randint(2, 14, (n,), generator=g)
        for i in range(n):
            if self.y[i] == 0: self.x[i, 0, pos[i], :] += 1   # horizontal
            else:              self.x[i, 0, :, pos[i]] += 1   # vertical
    def __len__(self): return len(self.y)
    def __getitem__(self, i): return self.x[i], self.y[i]

torch.manual_seed(0)
train = DataLoader(Lines(800, 1), batch_size=32, shuffle=True)
test = DataLoader(Lines(200, 2), batch_size=100)
net = nn.Sequential(nn.Conv2d(1, 8, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2),
                    nn.Conv2d(8, 16, 3, padding=1), nn.ReLU(), nn.AdaptiveAvgPool2d(1),
                    nn.Flatten(), nn.Linear(16, 2))
opt = torch.optim.Adam(net.parameters(), 1e-2)
for epoch in range(3):
    for xb, yb in train:
        loss = nn.functional.cross_entropy(net(xb), yb)
        opt.zero_grad(); loss.backward(); opt.step()
    with torch.no_grad():
        acc = sum((net(xb).argmax(1) == yb).sum().item() for xb, yb in test) / 200
    print(f"epoch {epoch + 1}: loss={loss.item():.4f} test_acc={acc:.3f}")
print("Number of parameters:", sum(p.numel() for p in net.parameters()))

Code explanation

We define a Dataset that generates 16×16 images containing a horizontal or vertical line, and use a DataLoader for batching and shuffling. The network has two Conv2d layers with pooling, then a linear layer. The same structure is used with real images by changing __getitem__ only.

Requirements

Shell
pip install torch

How to run

Save the code in a file example.py then run it:

Shell
python example.py

Output recorded during testing

epoch 1: loss=0.3398 test_acc=1.000
epoch 2: loss=0.0026 test_acc=1.000
epoch 3: loss=0.0005 test_acc=1.000
Number of parameters: 1282

This example was actually run and tested on 21 November 2026 on a CPU — torch 2.15.0, python 3.13.18

Libraries used

Related examples

ResearchPyTorchRun and tested

A capsule layer with dynamic routing

Implementing the squash function and the routing-by-agreement algorithm between capsules as in the paper by Sabour et al. (2017).

Convolutional networks · Scientific research