Examples · PyTorch

CNN for MNIST in PyTorch

A small convolutional network that reaches about 99 % test accuracy on handwritten digits: two blocks of convolution, ReLU and max pooling find strokes and shapes, and a dense head turns them into ten class scores.

Open in the editor See the code

Code
PyTorch
Task
Classification
Input
1 × 28 × 28
Bricks
12
Trainable parameters
421,642

What the network does

Each Conv2d slides 3×3 filters over the image. The first one has 32 filters, so the 1 × 28 × 28 image becomes 32 × 28 × 28 feature maps; padding=same keeps height and width. MaxPool2d with a 2×2 window halves them, to 32 × 14 × 14. The second block repeats this with 64 filters and ends at 64 × 7 × 7.

Flatten turns these 3,136 values into a vector for the head: a Linear layer with 128 units, ReLU, Dropout with p = 0.25 and the last Linear layer with ten outputs. The first dense layer holds 401,536 of the 421,642 parameters, while the convolutions need only 18,816 together, because a filter is shared across the whole image.

When to use it

  • For small grayscale or colour images with one label each: digits, clothing (Fashion-MNIST), symbols, small product photos.
  • As the standard first CNN in a course: it shows how convolution and pooling change the shape, and how few parameters a convolution has compared with a dense layer.
  • As a starting point for your own images: set the Input to 3, 64, 64 for colour images and add a third block if the images are larger.

Layers, shapes and parameters

Diagram of the example Small CNN for MNISTInput (1 × 28 × 28) → Conv2d (32 × 28 × 28) → Activation (32 × 28 × 28) → MaxPool2d (32 × 14 × 14) → Conv2d (64 × 14 × 14) → Activation (64 × 14 × 14) → MaxPool2d (64 × 7 × 7) → Flatten (3136) → Linear (128) → Activation (128) → Dropout (128) → Linear (10)Input1 × 28 × 28Conv2d32 × 28 × 28320 parametersActivation32 × 28 × 28MaxPool2d32 × 14 × 14Conv2d64 × 14 × 1418,496 parametersActivation64 × 14 × 14MaxPool2d64 × 7 × 7Flatten3136Linear128401,536 parametersActivation128Dropout128Linear101,290 parameters
The network as it is laid out in the editor. Each box shows the output shape (without the batch dimension) and the number of parameters.
The bricks of Small CNN for MNIST: settings, output shape and parameters, computed by Brick DNN's shape inference
BrickTypeSettingsOutputParameters
inputInputshape=1×28×281 × 28 × 280
conv1Conv2dout_channels=32 kernel_size=3×332 × 28 × 28320
relu1Activationfunction=relu32 × 28 × 280
pool1MaxPool2dkernel_size=2×232 × 14 × 140
conv2Conv2dout_channels=64 kernel_size=3×364 × 14 × 1418,496
relu2Activationfunction=relu64 × 14 × 140
pool2MaxPool2dkernel_size=2×264 × 7 × 70
flattenFlattendefaults31360
fc1Linearout_features=128128401,536
relu3Activationfunction=relu1280
dropDropoutp=0.251280
fc2Linearout_features=10101,290
Total421,642

Training it in Brick DNN

Choose MNIST or Fashion-MNIST in the training panel; both fit the Input 1, 28, 28 and have ten classes. A folder of your own images (a ZIP file with one folder per class) also works: images are converted to the Input’s channels and resized to its height and width. The run view shows loss and accuracy per epoch, then the confusion matrix and per-class precision and recall on the test images.

The generated code

This is the PyTorch script that the editor’s code dialog generates from the graph above (cnn_mnist.py): an nn.Module with one attribute per layer and a forward method, plus a check that runs a random batch through it. It needs nothing but PyTorch.

# Built with Brick DNN: https://brickdnn.com, https://github.com/alexanderKuehling/brick-dnn
"""NeuralNetwork: generated with Brick DNN.

Input: (batch, 1, 28, 28)
Output: (batch, 10)
Trainable parameters: 421,642

Print the model and run it on a random batch:

    python this_file.py
"""

import torch
import torch.nn as nn


class NeuralNetwork(nn.Module):
    def __init__(self) -> None:
        super().__init__()
        self.conv2d_1 = nn.Conv2d(1, 32, kernel_size=3, padding='same')
        self.relu_1 = nn.ReLU()
        self.maxpool2d_1 = nn.MaxPool2d(kernel_size=2)
        self.conv2d_2 = nn.Conv2d(32, 64, kernel_size=3, padding='same')
        self.relu_2 = nn.ReLU()
        self.maxpool2d_2 = nn.MaxPool2d(kernel_size=2)
        self.flatten_1 = nn.Flatten()
        self.linear_1 = nn.Linear(3136, 128)
        self.relu_3 = nn.ReLU()
        self.dropout_1 = nn.Dropout(p=0.25)
        self.linear_2 = nn.Linear(128, 10)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        x = self.conv2d_1(x)
        x = self.relu_1(x)
        x = self.maxpool2d_1(x)
        x = self.conv2d_2(x)
        x = self.relu_2(x)
        x = self.maxpool2d_2(x)
        x = self.flatten_1(x)
        x = self.linear_1(x)
        x = self.relu_3(x)
        x = self.dropout_1(x)
        x = self.linear_2(x)
        return x


def count_parameters(model: nn.Module) -> int:
    return sum(p.numel() for p in model.parameters() if p.requires_grad)


def main() -> None:
    model = NeuralNetwork()
    print(model)
    print(f"Trainable parameters: {count_parameters(model):,}")

    # Check the model with a random batch of 2 samples.
    model.eval()
    x = torch.randn(2, 1, 28, 28)
    with torch.no_grad():
        out = model(x)
    print("Output shape:", tuple(out.shape))  # expected (2, 10)


if __name__ == "__main__":
    main()

Open in the editor

Guides