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
| Brick | Type | Settings | Output | Parameters |
|---|---|---|---|---|
input | Input | shape=1×32×32 | 1 × 32 × 32 | 0 |
enc1_conv1 | Conv2d | out_channels=16 | 16 × 32 × 32 | 160 |
enc1_relu1 | Activation | function=relu | 16 × 32 × 32 | 0 |
enc1_conv2 | Conv2d | out_channels=16 | 16 × 32 × 32 | 2,320 |
enc1_relu2 | Activation | function=relu | 16 × 32 × 32 | 0 |
pool1 | MaxPool2d | defaults | 16 × 16 × 16 | 0 |
enc2_conv1 | Conv2d | out_channels=32 | 32 × 16 × 16 | 4,640 |
enc2_relu1 | Activation | function=relu | 32 × 16 × 16 | 0 |
enc2_conv2 | Conv2d | out_channels=32 | 32 × 16 × 16 | 9,248 |
enc2_relu2 | Activation | function=relu | 32 × 16 × 16 | 0 |
pool2 | MaxPool2d | defaults | 32 × 8 × 8 | 0 |
enc3_conv1 | Conv2d | out_channels=64 | 64 × 8 × 8 | 18,496 |
enc3_relu1 | Activation | function=relu | 64 × 8 × 8 | 0 |
enc3_conv2 | Conv2d | out_channels=64 | 64 × 8 × 8 | 36,928 |
enc3_relu2 | Activation | function=relu | 64 × 8 × 8 | 0 |
pool3 | MaxPool2d | defaults | 64 × 4 × 4 | 0 |
bottleneck_conv1 | Conv2d | out_channels=128 | 128 × 4 × 4 | 73,856 |
bottleneck_relu1 | Activation | function=relu | 128 × 4 × 4 | 0 |
bottleneck_conv2 | Conv2d | out_channels=128 | 128 × 4 × 4 | 147,584 |
bottleneck_relu2 | Activation | function=relu | 128 × 4 × 4 | 0 |
up3 | ConvTranspose2d | out_channels=64 | 64 × 8 × 8 | 32,832 |
skip3 | Concat | dim=0 | 128 × 8 × 8 | 0 |
dec3_conv1 | Conv2d | out_channels=64 | 64 × 8 × 8 | 73,792 |
dec3_relu1 | Activation | function=relu | 64 × 8 × 8 | 0 |
dec3_conv2 | Conv2d | out_channels=64 | 64 × 8 × 8 | 36,928 |
dec3_relu2 | Activation | function=relu | 64 × 8 × 8 | 0 |
up2 | ConvTranspose2d | out_channels=32 | 32 × 16 × 16 | 8,224 |
skip2 | Concat | dim=0 | 64 × 16 × 16 | 0 |
dec2_conv1 | Conv2d | out_channels=32 | 32 × 16 × 16 | 18,464 |
dec2_relu1 | Activation | function=relu | 32 × 16 × 16 | 0 |
dec2_conv2 | Conv2d | out_channels=32 | 32 × 16 × 16 | 9,248 |
dec2_relu2 | Activation | function=relu | 32 × 16 × 16 | 0 |
up1 | ConvTranspose2d | out_channels=16 | 16 × 32 × 32 | 2,064 |
skip1 | Concat | dim=0 | 32 × 32 × 32 | 0 |
dec1_conv1 | Conv2d | out_channels=16 | 16 × 32 × 32 | 4,624 |
dec1_relu1 | Activation | function=relu | 16 × 32 × 32 | 0 |
dec1_conv2 | Conv2d | out_channels=16 | 16 × 32 × 32 | 2,320 |
dec1_relu2 | Activation | function=relu | 16 × 32 × 32 | 0 |
pool | AdaptiveAvgPool2d | output_size=1×1 | 16 × 1 × 1 | 0 |
flatten | Flatten | defaults | 16 | 0 |
classifier | Linear | out_features=10 | 10 | 170 |
| Total | 481,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()
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.