Examples · PyTorch

U-Net as an image classifier in PyTorch

The same encoder, decoder and skip connections as the U-Net for segmentation, but ending in one answer per image: global average pooling and a Linear layer turn the full-size feature maps into ten class scores for Fashion-MNIST.

Open in the editor See the code

Code
PyTorch
Task
Classification
Input
1 × 32 × 32
Bricks
41
Trainable parameters
481,898

What the network does

The 28×28 images of Fashion-MNIST are resized to 32×32 on the way in, so that three halvings fit (32 → 16 → 8 → 4). The filters are half those of the segmentation example, 16, 32 and 64 with a bottleneck of 128, so that the network trains on a CPU server.

After the decoder, AdaptiveAvgPool2d averages each of the 16 feature maps of 32 × 32 to one value, Flatten makes a vector of 16, and the last Linear layer, with only 170 parameters, gives the ten class scores. The whole network has 481,898 parameters.

When to use it

  • To see how a segmentation architecture becomes a classifier, and that the head is the only part that differs.
  • Not as the best choice for this task: for small images with one label, the small CNN is smaller and faster.
  • As a starting point for tasks that need both: the same encoder and decoder can feed a mask and a class.

Layers, shapes and parameters

Diagram of the example U-Net classifierInput (1 × 32 × 32), Conv2d (16 × 32 × 32), Activation (16 × 32 × 32), Conv2d (16 × 32 × 32), Activation (16 × 32 × 32), MaxPool2d (16 × 16 × 16), Conv2d (32 × 16 × 16), Activation (32 × 16 × 16), Conv2d (32 × 16 × 16), Activation (32 × 16 × 16), MaxPool2d (32 × 8 × 8), Conv2d (64 × 8 × 8), Activation (64 × 8 × 8), Conv2d (64 × 8 × 8), Activation (64 × 8 × 8), MaxPool2d (64 × 4 × 4), Conv2d (128 × 4 × 4), Activation (128 × 4 × 4), Conv2d (128 × 4 × 4), Activation (128 × 4 × 4), ConvTranspose2d (64 × 8 × 8), Concat (128 × 8 × 8), Conv2d (64 × 8 × 8), Activation (64 × 8 × 8), Conv2d (64 × 8 × 8), Activation (64 × 8 × 8), ConvTranspose2d (32 × 16 × 16), Concat (64 × 16 × 16), Conv2d (32 × 16 × 16), Activation (32 × 16 × 16), Conv2d (32 × 16 × 16), Activation (32 × 16 × 16), ConvTranspose2d (16 × 32 × 32), Concat (32 × 32 × 32), Conv2d (16 × 32 × 32), Activation (16 × 32 × 32), Conv2d (16 × 32 × 32), Activation (16 × 32 × 32), AdaptiveAvgPool2d (16 × 1 × 1), Flatten (16), Linear (10)Input1 × 32 × 32Conv2d16 × 32 × 32160 parametersActivation16 × 32 × 32Conv2d16 × 32 × 322,320 parametersActivation16 × 32 × 32MaxPool2d16 × 16 × 16Conv2d32 × 16 × 164,640 parametersActivation32 × 16 × 16Conv2d32 × 16 × 169,248 parametersActivation32 × 16 × 16MaxPool2d32 × 8 × 8Conv2d64 × 8 × 818,496 parametersActivation64 × 8 × 8Conv2d64 × 8 × 836,928 parametersActivation64 × 8 × 8MaxPool2d64 × 4 × 4Conv2d128 × 4 × 473,856 parametersActivation128 × 4 × 4Conv2d128 × 4 × 4147,584 parametersActivation128 × 4 × 4ConvTranspose2d64 × 8 × 832,832 parametersConcat128 × 8 × 8Conv2d64 × 8 × 873,792 parametersActivation64 × 8 × 8Conv2d64 × 8 × 836,928 parametersActivation64 × 8 × 8ConvTranspose2d32 × 16 × 168,224 parametersConcat64 × 16 × 16Conv2d32 × 16 × 1618,464 parametersActivation32 × 16 × 16Conv2d32 × 16 × 169,248 parametersActivation32 × 16 × 16ConvTranspose2d16 × 32 × 322,064 parametersConcat32 × 32 × 32Conv2d16 × 32 × 324,624 parametersActivation16 × 32 × 32Conv2d16 × 32 × 322,320 parametersActivation16 × 32 × 32AdaptiveAvgPool2d16 × 1 × 1Flatten16Linear10170 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 diagram is wider than the screen: scroll it sideways.
The bricks of U-Net classifier: settings, output shape and parameters, computed by Brick DNN's shape inference
BrickTypeSettingsOutputParameters
inputInputshape=1×32×321 × 32 × 320
enc1_conv1Conv2dout_channels=1616 × 32 × 32160
enc1_relu1Activationfunction=relu16 × 32 × 320
enc1_conv2Conv2dout_channels=1616 × 32 × 322,320
enc1_relu2Activationfunction=relu16 × 32 × 320
pool1MaxPool2ddefaults16 × 16 × 160
enc2_conv1Conv2dout_channels=3232 × 16 × 164,640
enc2_relu1Activationfunction=relu32 × 16 × 160
enc2_conv2Conv2dout_channels=3232 × 16 × 169,248
enc2_relu2Activationfunction=relu32 × 16 × 160
pool2MaxPool2ddefaults32 × 8 × 80
enc3_conv1Conv2dout_channels=6464 × 8 × 818,496
enc3_relu1Activationfunction=relu64 × 8 × 80
enc3_conv2Conv2dout_channels=6464 × 8 × 836,928
enc3_relu2Activationfunction=relu64 × 8 × 80
pool3MaxPool2ddefaults64 × 4 × 40
bottleneck_conv1Conv2dout_channels=128128 × 4 × 473,856
bottleneck_relu1Activationfunction=relu128 × 4 × 40
bottleneck_conv2Conv2dout_channels=128128 × 4 × 4147,584
bottleneck_relu2Activationfunction=relu128 × 4 × 40
up3ConvTranspose2dout_channels=6464 × 8 × 832,832
skip3Concatdim=0128 × 8 × 80
dec3_conv1Conv2dout_channels=6464 × 8 × 873,792
dec3_relu1Activationfunction=relu64 × 8 × 80
dec3_conv2Conv2dout_channels=6464 × 8 × 836,928
dec3_relu2Activationfunction=relu64 × 8 × 80
up2ConvTranspose2dout_channels=3232 × 16 × 168,224
skip2Concatdim=064 × 16 × 160
dec2_conv1Conv2dout_channels=3232 × 16 × 1618,464
dec2_relu1Activationfunction=relu32 × 16 × 160
dec2_conv2Conv2dout_channels=3232 × 16 × 169,248
dec2_relu2Activationfunction=relu32 × 16 × 160
up1ConvTranspose2dout_channels=1616 × 32 × 322,064
skip1Concatdim=032 × 32 × 320
dec1_conv1Conv2dout_channels=1616 × 32 × 324,624
dec1_relu1Activationfunction=relu16 × 32 × 320
dec1_conv2Conv2dout_channels=1616 × 32 × 322,320
dec1_relu2Activationfunction=relu16 × 32 × 320
poolAdaptiveAvgPool2doutput_size=1×116 × 1 × 10
flattenFlattendefaults160
classifierLinearout_features=1010170
Total481,898

Training it in Brick DNN

Choose Fashion-MNIST: its 28×28 grayscale images are resized to the Input 1, 32, 32 automatically. The run reports accuracy per epoch and the confusion matrix of the ten clothing classes at the end, which shows which ones the network confuses (shirts and T-shirts, typically).

The generated code

This is the PyTorch script that the editor’s code dialog generates from the graph above (unet_classifier.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, 32, 32)
Output: (batch, 10)
Trainable parameters: 481,898

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, 16, kernel_size=3, padding='same')
        self.relu_1 = nn.ReLU()
        self.conv2d_2 = nn.Conv2d(16, 16, kernel_size=3, padding='same')
        self.relu_2 = nn.ReLU()
        self.maxpool2d_1 = nn.MaxPool2d(kernel_size=2)
        self.conv2d_3 = nn.Conv2d(16, 32, kernel_size=3, padding='same')
        self.relu_3 = nn.ReLU()
        self.conv2d_4 = nn.Conv2d(32, 32, kernel_size=3, padding='same')
        self.relu_4 = nn.ReLU()
        self.maxpool2d_2 = nn.MaxPool2d(kernel_size=2)
        self.conv2d_5 = nn.Conv2d(32, 64, kernel_size=3, padding='same')
        self.relu_5 = nn.ReLU()
        self.conv2d_6 = nn.Conv2d(64, 64, kernel_size=3, padding='same')
        self.relu_6 = nn.ReLU()
        self.maxpool2d_3 = nn.MaxPool2d(kernel_size=2)
        self.conv2d_7 = nn.Conv2d(64, 128, kernel_size=3, padding='same')
        self.relu_7 = nn.ReLU()
        self.conv2d_8 = nn.Conv2d(128, 128, kernel_size=3, padding='same')
        self.relu_8 = nn.ReLU()
        self.upconv_1 = nn.ConvTranspose2d(128, 64, kernel_size=2, stride=2)
        self.conv2d_9 = nn.Conv2d(128, 64, kernel_size=3, padding='same')
        self.relu_9 = nn.ReLU()
        self.conv2d_10 = nn.Conv2d(64, 64, kernel_size=3, padding='same')
        self.relu_10 = nn.ReLU()
        self.upconv_2 = nn.ConvTranspose2d(64, 32, kernel_size=2, stride=2)
        self.conv2d_11 = nn.Conv2d(64, 32, kernel_size=3, padding='same')
        self.relu_11 = nn.ReLU()
        self.conv2d_12 = nn.Conv2d(32, 32, kernel_size=3, padding='same')
        self.relu_12 = nn.ReLU()
        self.upconv_3 = nn.ConvTranspose2d(32, 16, kernel_size=2, stride=2)
        self.conv2d_13 = nn.Conv2d(32, 16, kernel_size=3, padding='same')
        self.relu_13 = nn.ReLU()
        self.conv2d_14 = nn.Conv2d(16, 16, kernel_size=3, padding='same')
        self.relu_14 = nn.ReLU()
        self.avgpool_1 = nn.AdaptiveAvgPool2d(1)
        self.flatten_1 = nn.Flatten()
        self.linear_1 = nn.Linear(16, 10)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        conv2d_1 = self.conv2d_1(x)
        relu_1 = self.relu_1(conv2d_1)
        conv2d_2 = self.conv2d_2(relu_1)
        relu_2 = self.relu_2(conv2d_2)
        maxpool2d_1 = self.maxpool2d_1(relu_2)
        conv2d_3 = self.conv2d_3(maxpool2d_1)
        relu_3 = self.relu_3(conv2d_3)
        conv2d_4 = self.conv2d_4(relu_3)
        relu_4 = self.relu_4(conv2d_4)
        maxpool2d_2 = self.maxpool2d_2(relu_4)
        conv2d_5 = self.conv2d_5(maxpool2d_2)
        relu_5 = self.relu_5(conv2d_5)
        conv2d_6 = self.conv2d_6(relu_5)
        relu_6 = self.relu_6(conv2d_6)
        maxpool2d_3 = self.maxpool2d_3(relu_6)
        conv2d_7 = self.conv2d_7(maxpool2d_3)
        relu_7 = self.relu_7(conv2d_7)
        conv2d_8 = self.conv2d_8(relu_7)
        relu_8 = self.relu_8(conv2d_8)
        upconv_1 = self.upconv_1(relu_8)
        concat_1 = torch.cat([relu_6, upconv_1], dim=1)
        conv2d_9 = self.conv2d_9(concat_1)
        relu_9 = self.relu_9(conv2d_9)
        conv2d_10 = self.conv2d_10(relu_9)
        relu_10 = self.relu_10(conv2d_10)
        upconv_2 = self.upconv_2(relu_10)
        concat_2 = torch.cat([relu_4, upconv_2], dim=1)
        conv2d_11 = self.conv2d_11(concat_2)
        relu_11 = self.relu_11(conv2d_11)
        conv2d_12 = self.conv2d_12(relu_11)
        relu_12 = self.relu_12(conv2d_12)
        upconv_3 = self.upconv_3(relu_12)
        concat_3 = torch.cat([relu_2, upconv_3], dim=1)
        conv2d_13 = self.conv2d_13(concat_3)
        relu_13 = self.relu_13(conv2d_13)
        conv2d_14 = self.conv2d_14(relu_13)
        relu_14 = self.relu_14(conv2d_14)
        avgpool_1 = self.avgpool_1(relu_14)
        flatten_1 = self.flatten_1(avgpool_1)
        linear_1 = self.linear_1(flatten_1)
        return linear_1


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, 32, 32)
    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