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, 64for colour images and add a third block if the images are larger.
Layers, shapes and parameters
| Brick | Type | Settings | Output | Parameters |
|---|---|---|---|---|
input | Input | shape=1×28×28 | 1 × 28 × 28 | 0 |
conv1 | Conv2d | out_channels=32 kernel_size=3×3 | 32 × 28 × 28 | 320 |
relu1 | Activation | function=relu | 32 × 28 × 28 | 0 |
pool1 | MaxPool2d | kernel_size=2×2 | 32 × 14 × 14 | 0 |
conv2 | Conv2d | out_channels=64 kernel_size=3×3 | 64 × 14 × 14 | 18,496 |
relu2 | Activation | function=relu | 64 × 14 × 14 | 0 |
pool2 | MaxPool2d | kernel_size=2×2 | 64 × 7 × 7 | 0 |
flatten | Flatten | defaults | 3136 | 0 |
fc1 | Linear | out_features=128 | 128 | 401,536 |
relu3 | Activation | function=relu | 128 | 0 |
drop | Dropout | p=0.25 | 128 | 0 |
fc2 | Linear | out_features=10 | 10 | 1,290 |
| Total | 421,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()
Guides
Build a neural network without code and export it to PyTorch
Connect layers on a canvas, let Brick DNN check every shape, and download a PyTorch script that runs on its own.
GDPR-compliant deep learning: training neural networks with data in Europe
Which data needs care under the GDPR, where brickdnn.com stores and trains in Switzerland, and what to do with data that has to stay personal.
Common PyTorch shape errors and how to fix them
The exact messages of the most common PyTorch shape errors, what causes each one and how to fix it.