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
| Brick | Type | Settings | Output | Parameters |
|---|---|---|---|---|
input | Input | shape=3×64×64 | 3 × 64 × 64 | 0 |
enc1_conv1 | Conv2d | out_channels=32 | 32 × 64 × 64 | 896 |
enc1_relu1 | Activation | function=relu | 32 × 64 × 64 | 0 |
enc1_conv2 | Conv2d | out_channels=32 | 32 × 64 × 64 | 9,248 |
enc1_relu2 | Activation | function=relu | 32 × 64 × 64 | 0 |
pool1 | MaxPool2d | defaults | 32 × 32 × 32 | 0 |
enc2_conv1 | Conv2d | out_channels=64 | 64 × 32 × 32 | 18,496 |
enc2_relu1 | Activation | function=relu | 64 × 32 × 32 | 0 |
enc2_conv2 | Conv2d | out_channels=64 | 64 × 32 × 32 | 36,928 |
enc2_relu2 | Activation | function=relu | 64 × 32 × 32 | 0 |
pool2 | MaxPool2d | defaults | 64 × 16 × 16 | 0 |
enc3_conv1 | Conv2d | out_channels=128 | 128 × 16 × 16 | 73,856 |
enc3_relu1 | Activation | function=relu | 128 × 16 × 16 | 0 |
enc3_conv2 | Conv2d | out_channels=128 | 128 × 16 × 16 | 147,584 |
enc3_relu2 | Activation | function=relu | 128 × 16 × 16 | 0 |
pool3 | MaxPool2d | defaults | 128 × 8 × 8 | 0 |
bottleneck_conv1 | Conv2d | out_channels=256 | 256 × 8 × 8 | 295,168 |
bottleneck_relu1 | Activation | function=relu | 256 × 8 × 8 | 0 |
bottleneck_conv2 | Conv2d | out_channels=256 | 256 × 8 × 8 | 590,080 |
bottleneck_relu2 | Activation | function=relu | 256 × 8 × 8 | 0 |
up3 | ConvTranspose2d | out_channels=128 | 128 × 16 × 16 | 131,200 |
skip3 | Concat | dim=0 | 256 × 16 × 16 | 0 |
dec3_conv1 | Conv2d | out_channels=128 | 128 × 16 × 16 | 295,040 |
dec3_relu1 | Activation | function=relu | 128 × 16 × 16 | 0 |
dec3_conv2 | Conv2d | out_channels=128 | 128 × 16 × 16 | 147,584 |
dec3_relu2 | Activation | function=relu | 128 × 16 × 16 | 0 |
up2 | ConvTranspose2d | out_channels=64 | 64 × 32 × 32 | 32,832 |
skip2 | Concat | dim=0 | 128 × 32 × 32 | 0 |
dec2_conv1 | Conv2d | out_channels=64 | 64 × 32 × 32 | 73,792 |
dec2_relu1 | Activation | function=relu | 64 × 32 × 32 | 0 |
dec2_conv2 | Conv2d | out_channels=64 | 64 × 32 × 32 | 36,928 |
dec2_relu2 | Activation | function=relu | 64 × 32 × 32 | 0 |
up1 | ConvTranspose2d | out_channels=32 | 32 × 64 × 64 | 8,224 |
skip1 | Concat | dim=0 | 64 × 64 × 64 | 0 |
dec1_conv1 | Conv2d | out_channels=32 | 32 × 64 × 64 | 18,464 |
dec1_relu1 | Activation | function=relu | 32 × 64 × 64 | 0 |
dec1_conv2 | Conv2d | out_channels=32 | 32 × 64 × 64 | 9,248 |
dec1_relu2 | Activation | function=relu | 32 × 64 × 64 | 0 |
mask | Conv2d | out_channels=4 kernel_size=1×1 | 4 × 64 × 64 | 132 |
| Total | 1,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()
Guides
Image segmentation with a U-Net: from masks to a trained model
From a ZIP file of images and masks to a trained U-Net, with mean IoU, Dice and the predicted masks.