Examples · PyTorch

U-Net for image segmentation in PyTorch

A U-Net gives every pixel of an image a class. Its encoder halves the image three times to understand what is in it, its decoder doubles it back to the full size, and skip connections hand the fine details of each level across to the decoder.

Open in the editor See the code

Code
PyTorch
Task
Segmentation
Input
3 × 64 × 64
Bricks
39
Trainable parameters
1,925,700

What the network does

The encoder has three levels of two 3×3 convolutions with ReLU, with 32, 64 and 128 filters, each followed by MaxPool2d: the 3 × 64 × 64 image becomes 128 × 8 × 8. A bottleneck of two convolutions with 256 filters works on this coarse view, where every value sees a large part of the image.

Each decoder level starts with ConvTranspose2d, a learned upsampling that doubles height and width. Concat then joins the result with the encoder’s output of the same size along the channels (for example 128 + 128 channels at 16 × 16), so the decoder gets back the details that pooling threw away. A last 1×1 convolution gives four channels, one score per class, for each of the 64 × 64 pixels.

All convolutions use padding=same, so only pooling and upsampling change the size. Height and width of the Input must therefore be divisible by 8; Brick DNN checks this and says what to change.

When to use it

  • For semantic segmentation: a class for every pixel, such as tissue in microscopy images, roads and buildings in aerial photos, defects on a surface or the background behind an object.
  • When there are few training images: U-Net was designed for small medical datasets, and the skip connections make it learn sharp outlines from a few hundred masks.
  • For two classes (foreground and background) set the last convolution to one channel; for more classes, one channel per class.

Layers, shapes and parameters

Diagram of the example U-Net for segmentationInput (3 × 64 × 64), Conv2d (32 × 64 × 64), Activation (32 × 64 × 64), Conv2d (32 × 64 × 64), Activation (32 × 64 × 64), MaxPool2d (32 × 32 × 32), Conv2d (64 × 32 × 32), Activation (64 × 32 × 32), Conv2d (64 × 32 × 32), Activation (64 × 32 × 32), MaxPool2d (64 × 16 × 16), Conv2d (128 × 16 × 16), Activation (128 × 16 × 16), Conv2d (128 × 16 × 16), Activation (128 × 16 × 16), MaxPool2d (128 × 8 × 8), Conv2d (256 × 8 × 8), Activation (256 × 8 × 8), Conv2d (256 × 8 × 8), Activation (256 × 8 × 8), ConvTranspose2d (128 × 16 × 16), Concat (256 × 16 × 16), Conv2d (128 × 16 × 16), Activation (128 × 16 × 16), Conv2d (128 × 16 × 16), Activation (128 × 16 × 16), ConvTranspose2d (64 × 32 × 32), Concat (128 × 32 × 32), Conv2d (64 × 32 × 32), Activation (64 × 32 × 32), Conv2d (64 × 32 × 32), Activation (64 × 32 × 32), ConvTranspose2d (32 × 64 × 64), Concat (64 × 64 × 64), Conv2d (32 × 64 × 64), Activation (32 × 64 × 64), Conv2d (32 × 64 × 64), Activation (32 × 64 × 64), Conv2d (4 × 64 × 64)Input3 × 64 × 64Conv2d32 × 64 × 64896 parametersActivation32 × 64 × 64Conv2d32 × 64 × 649,248 parametersActivation32 × 64 × 64MaxPool2d32 × 32 × 32Conv2d64 × 32 × 3218,496 parametersActivation64 × 32 × 32Conv2d64 × 32 × 3236,928 parametersActivation64 × 32 × 32MaxPool2d64 × 16 × 16Conv2d128 × 16 × 1673,856 parametersActivation128 × 16 × 16Conv2d128 × 16 × 16147,584 parametersActivation128 × 16 × 16MaxPool2d128 × 8 × 8Conv2d256 × 8 × 8295,168 parametersActivation256 × 8 × 8Conv2d256 × 8 × 8590,080 parametersActivation256 × 8 × 8ConvTranspose2d128 × 16 × 16131,200 parametersConcat256 × 16 × 16Conv2d128 × 16 × 16295,040 parametersActivation128 × 16 × 16Conv2d128 × 16 × 16147,584 parametersActivation128 × 16 × 16ConvTranspose2d64 × 32 × 3232,832 parametersConcat128 × 32 × 32Conv2d64 × 32 × 3273,792 parametersActivation64 × 32 × 32Conv2d64 × 32 × 3236,928 parametersActivation64 × 32 × 32ConvTranspose2d32 × 64 × 648,224 parametersConcat64 × 64 × 64Conv2d32 × 64 × 6418,464 parametersActivation32 × 64 × 64Conv2d32 × 64 × 649,248 parametersActivation32 × 64 × 64Conv2d4 × 64 × 64132 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 for segmentation: settings, output shape and parameters, computed by Brick DNN's shape inference
BrickTypeSettingsOutputParameters
inputInputshape=3×64×643 × 64 × 640
enc1_conv1Conv2dout_channels=3232 × 64 × 64896
enc1_relu1Activationfunction=relu32 × 64 × 640
enc1_conv2Conv2dout_channels=3232 × 64 × 649,248
enc1_relu2Activationfunction=relu32 × 64 × 640
pool1MaxPool2ddefaults32 × 32 × 320
enc2_conv1Conv2dout_channels=6464 × 32 × 3218,496
enc2_relu1Activationfunction=relu64 × 32 × 320
enc2_conv2Conv2dout_channels=6464 × 32 × 3236,928
enc2_relu2Activationfunction=relu64 × 32 × 320
pool2MaxPool2ddefaults64 × 16 × 160
enc3_conv1Conv2dout_channels=128128 × 16 × 1673,856
enc3_relu1Activationfunction=relu128 × 16 × 160
enc3_conv2Conv2dout_channels=128128 × 16 × 16147,584
enc3_relu2Activationfunction=relu128 × 16 × 160
pool3MaxPool2ddefaults128 × 8 × 80
bottleneck_conv1Conv2dout_channels=256256 × 8 × 8295,168
bottleneck_relu1Activationfunction=relu256 × 8 × 80
bottleneck_conv2Conv2dout_channels=256256 × 8 × 8590,080
bottleneck_relu2Activationfunction=relu256 × 8 × 80
up3ConvTranspose2dout_channels=128128 × 16 × 16131,200
skip3Concatdim=0256 × 16 × 160
dec3_conv1Conv2dout_channels=128128 × 16 × 16295,040
dec3_relu1Activationfunction=relu128 × 16 × 160
dec3_conv2Conv2dout_channels=128128 × 16 × 16147,584
dec3_relu2Activationfunction=relu128 × 16 × 160
up2ConvTranspose2dout_channels=6464 × 32 × 3232,832
skip2Concatdim=0128 × 32 × 320
dec2_conv1Conv2dout_channels=6464 × 32 × 3273,792
dec2_relu1Activationfunction=relu64 × 32 × 320
dec2_conv2Conv2dout_channels=6464 × 32 × 3236,928
dec2_relu2Activationfunction=relu64 × 32 × 320
up1ConvTranspose2dout_channels=3232 × 64 × 648,224
skip1Concatdim=064 × 64 × 640
dec1_conv1Conv2dout_channels=3232 × 64 × 6418,464
dec1_relu1Activationfunction=relu32 × 64 × 640
dec1_conv2Conv2dout_channels=3232 × 64 × 649,248
dec1_relu2Activationfunction=relu32 × 64 × 640
maskConv2dout_channels=4 kernel_size=1×14 × 64 × 64132
Total1,925,700

Training it in Brick DNN

Press Train, choose Built-in → Shapes and start: the generated dataset (400 training and 100 test images of squares, circles and triangles, with a mask for each) fits the network as it is, and ten epochs reach about 80 % mean IoU on a CPU. Your own data is a ZIP file with the folders images/ and masks/. Every epoch reports mean IoU, Dice and pixel accuracy, and the run shows predicted masks next to the true ones. The segmentation guide goes through it step by step.

The generated code

This is the PyTorch script that the editor’s code dialog generates from the graph above (unet.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, 3, 64, 64)
Output: (batch, 4, 64, 64)
Trainable parameters: 1,925,700

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

    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)
        conv2d_15 = self.conv2d_15(relu_14)
        return conv2d_15


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, 3, 64, 64)
    with torch.no_grad():
        out = model(x)
    print("Output shape:", tuple(out.shape))  # expected (2, 4, 64, 64)


if __name__ == "__main__":
    main()

Open in the editor

Guides