AI Logic

Architectures

U-Net

Updated:

The U-Net architecture. The left side shows the overall flow: starting from a 572×572 input tile, the contracting path in the left column repeats two 3×3 convolutions and a 2×2 max pooling four times, shrinking the map to 28×28×1024; the expanding path in the right column repeats four times a stage that doubles the size with a 2×2 up-convolution, crops and concatenates the features from the same level of the contracting path, and applies two 3×3 convolutions, and a final 1×1 convolution produces a 388×388×2 output. The right side shows the top stage of the expanding path: the center of the 64×64×512 contracting-path features is cropped to 56×56 and concatenated along the channel axis with the 28×28×1024 output of the next deeper level, upsampled by an up-convolution to 56×56×512, and two 3×3 convolution + ReLU layers turn the result into 52×52×512. Below are the weighted cross-entropy loss and the elastic-deformation data augmentation

Background and overview

U-Net is a network for semantic segmentation (the task of assigning each pixel of an image the class of the object or region it shows) that places a contracting path, which shrinks the image level by level to gather context, and an expanding path, which enlarges it level by level to refine locations, in a symmetric arrangement, and passes features from each level across and concatenates them, so that per-pixel classes come out with sharp boundaries. Drawn as a diagram, the architecture forms the letter U, which gave the network its name. Ronneberger and colleagues at the University of Freiburg in Germany proposed it in 2015 for biomedical (microscopy) image tasks (MICCAI 2015).

In biomedical imaging, experts must label every pixel by hand, so often only a few dozen images are available for training. Building on the "make everything a convolution and predict every pixel" design of FCN, U-Net gives the expanding path many channels as well, so that context is carried up to high resolutions, and combines this with elastic-deformation data augmentation and a weighted loss, making end-to-end training possible from very few images.

The main results of the paper are as follows.

  • On electron microscopy neuron segmentation (the challenge running since ISBI 2012), it outperformed the previous best method, a sliding-window CNN, using 30 training images, and ranked first on the warping error.
  • On light microscopy cell images (ISBI cell tracking challenge 2015), it reached IoU of 92.0% and 77.6% on two datasets, far ahead of the runner-up (83% and 46%).
  • Segmenting a 512×512 image takes less than a second on a GPU of the time.

The U-Net design of "connecting a shrinking path and an expanding path level by level" has spread far beyond biomedical imaging; it is also the backbone of the noise-prediction network in image-generating diffusion models (such as DDPM).

The problem: precise segmentation down to boundaries from few images

The problem U-Net solved is how to combine image-wide context with pixel-level localization when training images are scarce.

The leading approach before it was a sliding-window CNN (Ciresan et al., 2012) that classifies each pixel by cropping the small patch around it. Since every patch counts as a training sample, it could learn from few images and won the ISBI 2012 challenge, but the paper points out two drawbacks.

  • Slow: the network runs separately for every patch, and overlapping patches repeat the same computation many times.
  • A trade-off between localization accuracy and context: seeing a large patch requires stacking more max pooling layers, which coarsens localization. Smaller patches, in turn, see almost none of the surrounding context.

FCN solved the first drawback by passing the whole image through the network at once and compensated for coarse localization by adding predictions from shallow layers. U-Net takes this idea further: it gives the upsampling side as many channels and convolutions as the downsampling side, concatenates the shallow-layer features themselves, and rebuilds a finer output with convolutions after every upsampling step.

As an everyday analogy, the contracting path is the person who zooms out on a map to get the big picture ("this is a residential area, that is a river"), and the expanding path is the person who keeps that picture in mind while zooming back in, checking it against the original detailed map (the features at the same level) at each scale and redrawing down to the position of a single street.

Theory: connecting the contracting and expanding paths level by level

U-Net shrinks the input four times along the contracting path to gather context, enlarges it four times along the expanding path while concatenating the features from the same level of the contracting path at each step, and finally produces per-pixel class scores with a 1×1 convolution. The left side of the figure at the top of the article shows the overall flow, and the right side shows the inside of one expanding-path stage.

One stage of the contracting path does the following.

  1. Apply a 3×3 convolution (without padding) and a ReLU twice.
  2. Halve the height and width with a 2×2 max pooling (stride 2).
  3. Double the number of channels at the next level (64 → 128 → 256 → 512 → 1024).

One stage of the expanding path does the following.

  1. Double the feature map size with a 2×2 convolution (up-convolution), halving the number of channels.
  2. Crop the center of the feature map from the same level of the contracting path to the same size and concatenate it along the channel axis.
  3. Apply a 3×3 convolution (no padding) and a ReLU twice.

Finally, a 1×1 convolution maps each 64-channel feature vector to the number of classes in the task. The network has 23 convolutional layers in total and no fully connected layers.

Why cropping is needed: U-Net's 3×3 convolutions add no padding (valid), so each one shrinks the height and width by 2 pixels. The contracting-path features are still larger by the amount the map has shrunk on its way back through the expanding path, so their center is cropped to match. In the example in the figure (a 572×572 input), the top level crops 64×64 to 56×56, the bottom level crops 568×568 to 392×392, and the output is 388×388.

Choosing the input size: so that each pooling step halves the map evenly, the input size is chosen so that every feature map entering a 2×2 max pooling has even height and width.

With unpadded convolutions, every output pixel corresponds only to input pixels whose full surrounding context is available. To predict pixels at the image border, the missing context is filled in by mirroring the input image. This makes it possible to split a large image into tiles, predict them one at a time, and place the outputs side by side without seams (the paper's overlap-tile strategy). It is an essential trick for handling large images that do not fit in GPU memory.

U-Net differs from FCN in three ways.

  • How shallow-layer information is passed on: FCN also computes class scores from shallow layers and adds them, whereas U-Net concatenates the feature maps themselves and lets the following convolutions learn how to combine them.
  • Thickness of the upsampling side: FCN's upsampling only enlarges class scores (21 channels), whereas U-Net's expanding path carries 512 to 64 channels and applies two convolutions at each level. The result is a U shape that is nearly symmetric with the contracting path.
  • Number of upsampling steps: FCN-8s upsamples 8× in a single step at the end, whereas U-Net upsamples 2× four times and rebuilds the output with convolutions up to a resolution close to the input.

Training techniques: weighted loss and elastic deformation

Beyond the architecture, U-Net is trained with a weighted loss for separating touching cells and elastic-deformation data augmentation that makes the most of few images.

Loss: a pixel-wise softmax is applied to the final feature map, and the cross-entropy is summed after multiplying by a per-pixel weight w(x)w(\mathbf{x}). With ak(x)a_k(\mathbf{x}) the value of channel kk at pixel x\mathbf{x}, KK the number of classes, ℓ(x)\ell(\mathbf{x}) the true class, and Ω\Omega the set of pixels, the loss is

pk(x)=exp⁡(ak(x))∑k′=1Kexp⁡(ak′(x)),E=−∑x∈Ωw(x)log⁡pℓ(x)(x)p_k(\mathbf{x}) = \frac{\exp(a_k(\mathbf{x}))}{\sum_{k'=1}^{K} \exp(a_{k'}(\mathbf{x}))}, \qquad E = -\sum_{\mathbf{x} \in \Omega} w(\mathbf{x}) \log p_{\ell(\mathbf{x})}(\mathbf{x})

Equation (1) in the paper omits the minus sign, but as a loss to be minimized it takes the form above.

Weight map: when cells of the same class touch, the background between them is a thin line only a few pixels wide, which an ordinary loss barely learns. So the following weight is precomputed for each ground-truth map.

w(x)=wc(x)+w0⋅exp⁡(−(d1(x)+d2(x))22σ2)w(\mathbf{x}) = w_c(\mathbf{x}) + w_0 \cdot \exp\left(-\frac{(d_1(\mathbf{x}) + d_2(\mathbf{x}))^2}{2\sigma^2}\right)

wcw_c is a weight that balances the class frequencies, d1d_1 is the distance to the border of the nearest cell, and d2d_2 is the distance to the border of the second nearest cell. The narrower the gap between two cells, the smaller d1+d2d_1 + d_2 and the larger the weight. The paper uses w0=10w_0 = 10 and σ≈5\sigma \approx 5 pixels.

Data augmentation: microscopy images call for invariance to shifts and rotations and robustness to deformations and changes in brightness. Above all, the paper states that random elastic deformations are the key to learning segmentation from few images.

  1. Draw a displacement for each point of a coarse 3×3 grid from a normal distribution with a standard deviation of 10 pixels.
  2. Compute smooth per-pixel displacements by bicubic interpolation.
  3. Warp the image and the ground-truth map with the same displacements.

Tissue deformation is the most common variation in biological images and can be simulated realistically, so the network learns deformations that do not appear in the labeled images. In addition, the Dropout layer at the end of the contracting path acts as implicit data augmentation.

Other settings

  • Training uses SGD in Caffe. To spend GPU memory on large input tiles, the mini-batch is a single image, and to compensate, momentum is set high at 0.99 so that many past training samples influence each update.
  • Initial weights are drawn from a normal distribution with standard deviation 2/N\sqrt{2/N} (NN is the number of inputs to one neuron; for a 3×3 convolution after a 64-channel layer, N=9⋅64=576N = 9 \cdot 64 = 576). This is the same as He initialization and keeps the variance of each feature map close to 1.
  • Training takes about 10 hours on an NVIDIA Titan GPU (6 GB).

Experimental results

Electron microscopy neuron images (EM segmentation challenge, 30 training images, 512×512)

The task is to separate serial-section images of Drosophila larva neural tissue into cells and membranes. The output membrane probability map is binarized at 10 thresholds and evaluated with three errors (lower is better). U-Net averages predictions over 7 rotated versions of the input and submits them without any pre- or post-processing.

RankTeamWarping errorRand errorPixel error
―Human0.0000050.00210.0010
1U-Net0.0003530.03820.0611
2DIVE-SCI0.0003550.03050.0584
3IDSIA (Ciresan et al.'s sliding-window CNN)0.0004200.05040.0613
4DIVE0.0004300.05450.0582
10IDSIA-SCI0.0006530.01890.1027

The rankings are as of March 6, 2015, ordered by warping error. The only methods with a better Rand error than U-Net apply dataset-specific post-processing to Ciresan et al.'s probability maps (according to a footnote in the paper, one of them was obtained by submitting 78 different solutions).

Light microscopy cell images (ISBI cell tracking challenge 2015, IoU)

MethodPhC-U373 (phase contrast, 35 training images)DIC-HeLa (differential interference contrast, 20 training images)
IMCB-SG (2014)0.26690.2935
KTH-SE (2014)0.79530.4607
HOUS-US (2014)0.5323―
2015 runner-up0.830.46
U-Net (2015)0.92030.7756

Both datasets consist of a few dozen partially annotated training images, yet U-Net far outperformed the runner-up. DIC-HeLa in particular is a difficult dataset in which cells appear touching each other, exactly the situation where the weighted loss pays off. IoU (the overlap between ground truth and prediction divided by their union) becomes mIoU when averaged over classes.

Practical considerations

Keep the following points in mind when using U-Net.

  • Padding changes the output size: with the paper's unpadded convolutions, the output is smaller than the input (572 → 388), and the ground-truth map must also be center-cropped to match. Many implementations add padding 1 to the 3×3 convolutions so that the output has the same size as the input (in that case no cropping is needed).
  • Input height and width: so that four poolings divide evenly, use a height and width that are multiples of 16 (or, without padding, a size for which every map before pooling is even).
  • Memory: even the high-resolution levels close to the input hold 64-channel features, which are kept until the expanding path uses them, so large images consume a lot of memory. This is why the paper used a mini-batch of one image and split large images into tiles.
  • Match augmentation and loss to the task: elastic deformation works for microscopy images, where tissue deformation is the main variation, and the weight map is designed for tasks where touching objects must be separated. They do not necessarily carry over to other tasks.

The original U-Net has no batch normalization, uses a mini-batch of one image, and uses momentum 0.99. Most U-Nets in common use today are improved versions with padding-1 convolutions and batch normalization, so their numbers cannot be compared directly with the paper's. The paper also does not state the learning rate or the Dropout rate, so these must be tuned. PyTorch's torchvision has no built-in U-Net, so either build one or use an external library.

Comparison with other methods

U-Net is FCN's "make everything a convolution" design with a thick expanding path and level-by-level concatenation added. Arranged by how they produce fine outputs, the methods compare as follows.

MethodHow the output is refinedUse of shallow-layer featuresMain strengths and weaknesses
Sliding-window CNNCrops the patch around each pixel and classifies it―Learns from little data, but repeats overlapping computation and is slow
FCN-8sUpsamples with transposed convolutions and adds shallow-layer predictionsAdds class scores computed on pool3 and pool4Simple and fast. Boundaries tend to blur because of the final 8× upsampling
U-NetA thick expanding path that upsamples 2× four timesConcatenates the feature maps of each level and combines them with convolutionsSharp boundaries and easy to train with little data. High-resolution levels use a lot of memory
DeepLab v3Reduces downsampling with dilated convolutions― (upsamples at the end with bilinear interpolation)Keeps resolution while preserving the receptive field and gathers multi-scale context. No decoder
DeepLab v3+Dilated convolutions plus a simple decoderConcatenates features at 1/4 resolution at a single levelTargets both context and boundaries. Its expanding path is thinner than U-Net's

Rough guidelines for choosing are as follows.

  • Biomedical images and similar cases with few training images where boundary precision matters: U-Net is the first candidate. Combine it with augmentations such as elastic deformation.
  • Large images such as street scenes where image-wide context matters: the DeepLab family is a better fit. It can directly reuse large classification networks pretrained on ImageNet and similar datasets.
  • Learning how segmentation works or building a quick baseline: FCN or U-Net is a simple, easy-to-handle choice.

PyTorch example

Show code
python
import numpy as np
import torch
import torch.nn as nn
from scipy import ndimage

"""
A small implementation of U-Net built as described in Sections 2 and 3 of the paper.
3×3 convolutions are unpadded (valid), so the output is smaller than the input (572×572 → 388×388).
Many implementations use padding=1 so that input and output have the same size (then no cropping is needed)
"""


def double_conv(c_in, c_out):
  """3×3 convolution (unpadded) + ReLU, twice"""
  return nn.Sequential(
    nn.Conv2d(c_in, c_out, 3), nn.ReLU(inplace=True),
    nn.Conv2d(c_out, c_out, 3), nn.ReLU(inplace=True),
  )


def center_crop(x, size):
  """Crop the center of a contracting-path feature map to the expanding-path size"""
  h, w = x.shape[-2:]
  top, left = (h - size[0]) // 2, (w - size[1]) // 2
  return x[..., top:top + size[0], left:left + size[1]]


class UNet(nn.Module):
  def __init__(self, in_channels=1, num_classes=2, dropout=0.5):
    super().__init__()
    chs = [64, 128, 256, 512, 1024]
    self.down = nn.ModuleList()
    c = in_channels
    for ch in chs:                                   # contracting path: 64 → 128 → 256 → 512 → 1024
      self.down.append(double_conv(c, ch))
      c = ch
    self.pool = nn.MaxPool2d(2, stride=2)
    self.drop = nn.Dropout2d(dropout)                # Dropout at the end of the contracting path (the paper does not give the rate)
    self.up = nn.ModuleList()
    self.up_conv = nn.ModuleList()
    for ch in reversed(chs[:-1]):                    # expanding path: 512 → 256 → 128 → 64
      self.up.append(nn.ConvTranspose2d(ch * 2, ch, 2, stride=2))   # upsample 2x and halve the channels
      self.up_conv.append(double_conv(ch * 2, ch))                  # two convolutions after concatenation
    self.head = nn.Conv2d(64, num_classes, 1)        # 1×1 convolution to class scores
    for m in self.modules():                         # normal distribution with std sqrt(2/N) (He initialization)
      if isinstance(m, nn.Conv2d):
        nn.init.kaiming_normal_(m.weight, mode='fan_in', nonlinearity='relu')
        nn.init.zeros_(m.bias)

  def forward(self, x):                              # x: (N, C, 572, 572), etc.
    skips = []
    for i, block in enumerate(self.down):
      x = block(x)
      if i < len(self.down) - 1:
        skips.append(x)                              # pass same-level features to the expanding path
        x = self.pool(x)
    x = self.drop(x)
    for up, conv, skip in zip(self.up, self.up_conv, reversed(skips)):
      x = up(x)
      x = torch.cat([center_crop(skip, x.shape[-2:]), x], dim=1)   # crop and concatenate
      x = conv(x)
    return self.head(x)                              # (N, num_classes, 388, 388)


def weight_map(labels, wc, w0=10.0, sigma=5.0):
  """Weight map of Eq. (2). labels is an integer map numbering each cell 1, 2, ... (background is 0);
  wc is the class-frequency balancing map. For background pixels, uses the distances d1 and d2 to the borders of the two nearest cells"""
  ids = [i for i in np.unique(labels) if i != 0]
  if len(ids) < 2:
    return wc
  dists = np.stack([ndimage.distance_transform_edt(labels != i) for i in ids])   # distance to each cell
  dists.sort(axis=0)
  d1, d2 = dists[0], dists[1]
  border = w0 * np.exp(-((d1 + d2) ** 2) / (2 * sigma ** 2))
  return wc + border * (labels == 0)


model = UNet(in_channels=1, num_classes=2)
criterion = nn.CrossEntropyLoss(reduction='none')   # compute per-pixel losses, weight them, then sum
# mini-batch of 1 image, momentum 0.99 (Section 3 of the paper). The paper does not give the learning rate, so this is an example value
optimizer = torch.optim.SGD(model.parameters(), lr=1e-2, momentum=0.99)

image = torch.randn(1, 1, 572, 572)
target = torch.randint(0, 2, (1, 388, 388))          # the ground-truth map is also sized to the output (central 388×388)
w = torch.ones(1, 388, 388)                          # in practice, precompute with weight_map

model.train()                                        # Dropout is active
loss = (criterion(model(image), target) * w).sum()   # E = -Σ w(x) log p_l(x)(x)
optimizer.zero_grad()
loss.backward()
optimizer.step()

model.eval()                                         # disable Dropout
with torch.no_grad():
  pred = model(image).argmax(1)                      # (1, 388, 388): per-pixel classes

FAQ

Q. What is the difference between U-Net and FCN?
A.

Both make every layer a convolution and predict every pixel, but they differ in how they use shallow layers and in the thickness of the upsampling side. FCN computes class scores from shallow layers, adds them to the scores from deep layers, and upsamples by 8× or so in a single step at the end. U-Net concatenates the shallow-layer feature maps themselves into the expanding path, upsamples 2× four times, and rebuilds a finer output with two convolutions each time. Because the expanding path has about as many channels as the contracting path, the architecture takes a U shape.

Q. Why are the contracting-path features cropped before concatenation?
A.

The original U-Net adds no padding to its 3×3 convolutions, so each convolution shrinks the height and width by 2 pixels. The contracting-path feature maps are larger by the amount the map has shrunk before it returns through the expanding path, so their center is cropped to match (for example, 64×64 → 56×56). Implementations that add padding 1 to the convolutions keep the size unchanged and need no cropping.

Q. Why can U-Net learn from so few training images?
A.

The paper names strong data augmentation, especially random elastic deformations, as the key. Shifting the points of a coarse 3×3 grid with a standard deviation of 10 pixels and smoothly warping the whole image produces an unlimited number of images close to natural tissue deformations. In addition, because the whole image passes through the network at once and the loss covers every pixel, a single image provides a learning signal from many pixels. In the paper, it achieved first-place results in each challenge with 30, 35, and 20 training images respectively.

References

  1. Ronneberger, O., Fischer, P., & Brox, T. (2015). U-Net: Convolutional Networks for Biomedical Image Segmentation. Medical Image Computing and Computer-Assisted Intervention (MICCAI 2015). arXiv:1505.04597.
  2. Long, J., Shelhamer, E., & Darrell, T. (2015). Fully Convolutional Networks for Semantic Segmentation. CVPR 2015. arXiv:1411.4038.
  3. Ho, J., Jain, A., & Abbeel, P. (2020). Denoising Diffusion Probabilistic Models. NeurIPS 2020. arXiv:2006.11239.