Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

CNN classification

Building a CNN

Now that we understand convolution, and why we should care about it, we are almost ready to implement a CNN. In general, a CNN architecture contains:

  • Convolution layers which execute a discrete convolution with a learnable weighting or kernel function

  • Pooling layers which perform spatial downsampling (mimicking the role of complex cells in a visual cortex)

  • Fully-connected layers which make determinations based on the high-level features at the end of the network

Dataset: MNIST

For this example, we’ll use MNIST. But since we’re using torch now, we can use the MNIST located in torchvision

CNN definition

CNN training

Model inference

CNN classification with a more complicated dataset

Dataset: STL10

Another dataset: CIFAR10

Visualization

Image transforms

We don’t have that much training data, only 5,000 images. So we apply transformations to augment our dataset. This can do several things. Like SGD, it may introduce stochasticity to improve model training and avoid local minima. But it may also improve our model’s ability to generalize by making it more robust to particular transformations

Create train, validation, datasets, check augmentations

CNN definition

Different classifier heads

Aside on weight sharing

The model above has fewer than 100,000 trainable parameters. This is pretty small! As a comparison, let’s look at a multi-layer perceptron which directly goes from the image to a 128-dimensional hidden layer, and from that to an output

CNN training

Model inference