A capstone deck: assemble everything from the chapter (augmentation, fine-tuning, modern CNN architectures) and take a Kaggle competition. CIFAR-10 has been done to death, but it’s the right size for a teaching example — small enough to fit in memory, big enough that augmentation and ensembling matter.
Kaggle CIFAR-10 competition page.
Downloading
Tiny demo subset for the book; swap in the full dataset for the actual competition:
d2l.DATA_HUB['cifar10_tiny'] = (d2l.DATA_URL +'kaggle_cifar10_tiny.zip','2068874e4b9a9f0fb07ebe0ad2b29754449ccacd')# If you use the full dataset downloaded for the Kaggle competition, set# `demo` to Falsedemo =Trueif demo: data_dir = d2l.download_extract('cifar10_tiny')else: data_dir ='../data/cifar-10/'
Organizing the dataset
Kaggle ships everything in one folder; most vision toolkits expect the folder-per-class layout (train/<class>/img.png). Build that layout from the labels.csv:
def read_csv_labels(fname):"""Read `fname` to return a filename to label dictionary."""withopen(fname, 'r') as f:# Skip the file header line (column name) lines = f.readlines()[1:] tokens = [l.rstrip().split(',') for l in lines]returndict(((name, label) for name, label in tokens))labels = read_csv_labels(os.path.join(data_dir, 'trainLabels.csv'))print('# training examples:', len(labels))print('# classes:', len(set(labels.values())))
# training examples: 1000
# classes: 10
Organizing the dataset (cont.)
Copy every training image into its class folder; reorg_train_valid first sizes the validation split from the rarest class:
def copyfile(filename, target_dir):"""Copy a file into a target directory.""" os.makedirs(target_dir, exist_ok=True) shutil.copy(filename, target_dir)def reorg_train_valid(data_dir, labels, valid_ratio):"""Split the validation set out of the original training set."""# The number of examples of the class that has the fewest examples in the# training dataset n = collections.Counter(labels.values()).most_common()[-1][1]# The number of examples per class for the validation set n_valid_per_label =max(1, math.floor(n * valid_ratio))
Splitting off a validation set
Each class contributes the same number of validation images; the rest go to train, and all of them to train_valid:
The unlabeled test images go into a single unknown folder:
def reorg_test(data_dir):"""Organize the testing set for data loading during prediction."""for test_file in os.listdir(os.path.join(data_dir, 'test')): copyfile(os.path.join(data_dir, 'test', test_file), os.path.join(data_dir, 'train_valid_test', 'test','unknown'))
Standard recipe — random crop, flip, normalize for train; just normalize for eval:
transform_train = torchvision.transforms.Compose([# Scale the image up to a square of 40 pixels in both height and width torchvision.transforms.Resize(40),# Randomly crop a square image of 40 pixels in both height and width to# produce a small square of 0.64 to 1 times the area of the original# image, and then scale it to a square of 32 pixels in both height and# width torchvision.transforms.RandomResizedCrop(32, scale=(0.64, 1.0), ratio=(1.0, 1.0)), torchvision.transforms.RandomHorizontalFlip(), torchvision.transforms.ToTensor(),# Standardize each channel of the image torchvision.transforms.Normalize([0.4914, 0.4822, 0.4465], [0.2023, 0.1994, 0.2010])])
No transfer learning this time — CIFAR-10 is small enough to train from scratch. The model is the ResNet-18 of the ResNet chapter: four residual stages that halve the resolution and widen the channels, global average pooling, and a dense layer that emits 10 class logits.
Framework model contract
get_net returns a ResNet-18 that maps a minibatch of CIFAR-10 images to logits of shape (batch, 10); cross-entropy is the training loss.
SGD with momentum + weight decay + LR step decay is the classic small-image vision recipe. The long helper mainly adapts that recipe to each framework, so teach the invariant loop:
augment and load a minibatch;
compute logits and cross-entropy;
backpropagate with momentum and weight decay;
step the learning-rate schedule;
log validation accuracy for model selection.
Train
Validation accuracy shows whether augmentation and the schedule help:
Augmentation matters more than model tweaks at the CIFAR-10 scale.
ResNet-18 from scratch + standard recipe is a strong baseline; the chapter techniques (mixup, cutmix, cosine schedule, longer training) push it higher.
This pipeline scales to ImageNet — only the model size and training time change.