Training a classifier in PyTorch
Cracks in solar cells — a ResNet, a data pipeline, a trainer with validation and checkpoints, and what the loss curves say.
- Organise a PyTorch project into dataset, model, trainer and entry point
- Match the loss function to a multi-label problem
- Read overfitting from a pair of loss curves and choose remedies
With the framework built by hand, 04_classification_using_pytorch switches to PyTorch for a real task: decide, for each electroluminescence image of a solar cell, whether it shows a crack and whether it has an inactive region. Two independent yes/no answers per image make this a multi-label problem.
Data
data.csv lists 2,000 images. Counting its columns shows how lopsided the labels are: 443 cells (22%) are cracked, 122 (6%) have an inactive region, 110 have both, and 1,545 (77%) have neither. A model that always answers “no” is right 77% of the time on both labels together, which is why the trainer reports an F1 score instead of accuracy.
ChallengeDataset reads a greyscale image, copies it into three channels so a standard ResNet stem can take it, and normalises with the training set’s mean and standard deviation. It defines a separate train_transform, but both modes call val_transform, and the two are identical anyway — so no augmentation ever runs. Random flips are a natural first addition here, since a crack is still a crack when mirrored.
Model
model.py is a compact ResNet: a 7×7 stride-2 stem and max pool, four residual blocks (64 → 512 channels, three of them stride 2), average pooling, dropout and a two-unit linear layer with a sigmoid — one probability per label. The pooling kernel is hard-coded to 10, which fits exactly one input size. For 300×300 images the feature map shrinks 300 → 150 → 74 → 74 → 37 → 19 → 10, and AvgPool2d(kernel_size=10) reduces it to 1×1. nn.AdaptiveAvgPool2d(1) would accept any size.
Trainer
trainer.py holds the loop from lesson 2, wrapped for a full project: train_epoch in model.train() mode, val_test under model.eval() and torch.no_grad(), a checkpoint whenever the validation loss improves, and an ONNX export for deployment.
def train_step(self, x, y):
self._optim.zero_grad()
out = self._model(x)
loss = self._crit(out, y.float())
loss.backward()
self._optim.step()
return loss.item()
train.py trains with t.nn.MSELoss() on the sigmoid outputs. For independent yes/no labels the matching loss is binary cross-entropy — export_onnx.py already names t.nn.BCELoss() — and nn.BCEWithLogitsLoss on the raw outputs (dropping the final sigmoid) is the numerically stable form. With a 77% “neither” majority, its pos_weight argument can also up-weight the rare positives.
Reading the curves
The gap is textbook overfitting: from about epoch 8, the model is memorising the 1,600 training images rather than learning anything that transfers. The remedies are the ones this lesson has already pointed at — augmentation, a loss suited to the labels, and stopping early.
The trainer has an early-stopping option, but its rule compares only two epochs: it stops if the latest validation loss is worse than the one patience epochs earlier. The usual rule is to stop when the best validation loss has not improved for patience epochs. fit also returns val_metric — the last epoch’s score — where the list val_metrics was clearly intended.
Try it yourself. Switch the loss to BCEWithLogitsLoss (and remove the final nn.Sigmoid, thresholding the logits at 0 instead of 0.5), add RandomHorizontalFlip and RandomVerticalFlip to the training transform, and rewrite early stopping as “no improvement in the best validation loss for 5 epochs”. Compare the epoch at which validation loss bottoms out before and after.