Exercise: segmentation networks

Goal

By the end of this exercise you should be able to:

  • compute the per-pixel cross-entropy and the soft Dice of a probability map, and explain why they disagree under class imbalance,
  • upsample a signal by hand (nearest neighbour, transposed convolution),
  • follow sizes, channels and weights through a small U-Net, and say what its receptive field is,
  • read the errors of a segmentation, compare it with a threshold, and recognise when the input is outside the training range.

The questions under By hand and Explore are for everyone. The Math questions (derive, prove) are for students who want the full treatment.

Background

Word Meaning
Encoder–decoder convolutions and pooling down to small maps, then upsampling and convolutions back to full size
U-Net an encoder–decoder with skip connections: encoder maps copied to the decoder and concatenated (channels add up)
Transposed convolution each input value stamps a scaled copy of the kernel into the output, s positions apart: output length (n - 1)s + k - 2p
Per-pixel cross-entropy -\frac1N\sum_i\big[g_i\ln p_i + (1 - g_i)\ln(1 - p_i)\big], g_i \in \{0, 1\} the true mask
Soft Dice D = 2\sum_i p_ig_i/(\sum_i p_i + \sum_i g_i); Dice loss = 1 - D
Dice, IoU (masks) 2\,\text{TP}/(2\,\text{TP} + \text{FP} + \text{FN}), \text{TP}/(\text{TP} + \text{FP} + \text{FN})

By hand

B1. A 3 \times 3 probability map and its true mask:

p = \begin{bmatrix} 0.9&0.8&0.1\\ 0.7&0.6&0.2\\ 0.1&0.2&0.1 \end{bmatrix}, \qquad g = \begin{bmatrix} 1&1&0\\ 1&1&0\\ 0&0&0 \end{bmatrix}

  1. Compute the mean per-pixel cross-entropy.
  2. Compute the soft Dice. Then threshold at 0.5 and compute the ordinary Dice of the mask.
  3. A 20 \times 20 image contains one nucleus of 20 pixels (5 %). A network outputs p = 0.01 everywhere. Compute the pixel accuracy (threshold 0.5), the cross-entropy, the soft Dice and the Dice of the mask. Which of these numbers notices that the network is useless?

B2. Upsampling the 1D signal (1, 2, 3) by a factor 2. (a) Nearest neighbour. (b) Nearest neighbour followed by the correlation with (\tfrac14, \tfrac12, \tfrac14) (zeros beyond the ends, keep 6 values). (c) A transposed convolution with stride 2 and kernel (\tfrac12, 1, \tfrac12) (7 values). What kind of interpolation is it? (d) Which kernel, with stride 2, gives exactly nearest-neighbour upsampling?

B3. The U-Net of the demo on a 1 \times 64 \times 64 input (all convolutions 3 \times 3 with padding 1): encoder 1: conv 1→8, conv 8→8; pool; encoder 2: conv 8→16, conv 16→16; pool; bottleneck: conv 16→32, conv 32→32; upsample, concatenate with encoder 2, conv →16, conv 16→16; upsample, concatenate with encoder 1, conv →8, conv 8→8; 1 \times 1 conv 8→1. (a) Give the size (channels × height × width) after every block, including the two concatenations. (b) Count the weights of every layer and in total. (c) Without skip connections the two decoder convolutions after upsampling get only 32 and 16 channels. How many weights fewer?

B4. Receptive field of the same network. (a) Compute the receptive field of one bottleneck unit (conv, conv, pool, conv, conv, pool, conv, conv). (b) Can it see a whole nucleus of 20 pixels? (c) Upsampling does not enlarge the field, but the decoder’s convolutions do. Roughly how large is the field of one output pixel?

B5. A U-Net segments 7 nuclei perfectly, but 3 pairs of them touch. How many objects does connected-component labelling (day 14) find in the mask? Name two ways to get 7.

B6. The U-Net’s probability map as the data term of a graph cut (day 27): D_p(\ell) = -\ln p_p(\ell). Compute D_p(\text{object}) and D_p(\text{background}) for a pixel with p = 0.9, and for one with p = 0.5. What will the smoothness term decide?

B1. (a) Object pixels: -\ln 0.9 - \ln 0.8 - \ln 0.7 - \ln 0.6 = 0.105 + 0.223 + 0.357 + 0.511; background pixels: -\ln 0.9 - \ln 0.8 - \ln 0.9 - \ln 0.8 - \ln 0.9 = 3 \cdot 0.105 + 2 \cdot 0.223. Total 1.958, mean over 9 pixels 0.218. (b) \sum p_ig_i = 0.9 + 0.8 + 0.7 + 0.6 = 3.0, \sum p_i = 3.7, \sum g_i = 4: D = 6/7.7 = 0.779. At threshold 0.5 the mask equals g exactly (TP 4, FP 0, FN 0): Dice 1. The soft Dice still rewards making the probabilities more confident. (c) Accuracy 380/400 = 95 %. Cross-entropy (380 \cdot 0.01005 + 20 \cdot 4.605)/400 = 0.240: below the 0.693 of a coin toss, so it does not look alarming. Soft Dice 2 \cdot 0.01 \cdot 20/(4 + 20) = 0.017; mask Dice 0. Only the Dice numbers show that not a single nucleus pixel is found.

B2. (a) (1, 1, 2, 2, 3, 3). (b) (0.75, 1.25, 1.75, 2.25, 2.75, 2.25). (c) 1 \cdot (\tfrac12, 1, \tfrac12) at positions 0–2, 2 \cdot (\ldots) at 2–4, 3 \cdot (\ldots) at 4–6: (0.5, 1, 1.5, 2, 2.5, 3, 1.5): linear interpolation (with half values at the open ends). (d) The kernel (1, 1) with stride 2: each value is stamped twice, side by side.

B3. (a) 8 \times 64 \times 64 → pool 8 \times 32 \times 32 → 16 \times 32 \times 32 → pool 16 \times 16 \times 16 → 32 \times 16 \times 16 → upsample 32 \times 32 \times 32 → concatenate 48 \times 32 \times 32 → 16 \times 32 \times 32 → upsample 16 \times 64 \times 64 → concatenate 24 \times 64 \times 64 → 8 \times 64 \times 64 → 1 \times 64 \times 64. (b) 9C_\text{in}C_\text{out} + C_\text{out}: 80, 584, 1168, 2320, 4640, 9248 (encoder and bottleneck), 6928, 2320, 1736, 584 (decoder), 8 + 1 = 9 (the 1 \times 1 conv): 29,617. (c) 9 \cdot 16 \cdot 16 = 2304 fewer in the first (48 \to 32 input channels) and 9 \cdot 8 \cdot 8 = 576 in the second (24 \to 16): 2880 fewer, 26,737 in total.

B4. (a) r = 3, 5, 6, 10, 14, 16, 24, 32: 32 pixels (jump 4). (b) Yes, 32 > 20. (c) After the bottleneck, two convolutions at jump 2 add 2 \cdot 2 \cdot 2 = 8, two at jump 1 add 4: about 44 pixels (the paths through the skip connections see less).

B5. 4 objects (3 merged pairs + 1 single). Split them: train with a third class “boundary between touching nuclei” and label the interiors; or use the distance transform and the watershed on the mask (days 13–15); or networks that predict separate objects directly (day 41).

B6. p = 0.9: D(\text{object}) = -\ln 0.9 = 0.105, D(\text{background}) = -\ln 0.1 = 2.303: a strong preference. p = 0.5: both \ln 2 = 0.693: no preference, so the neighbours (through the smoothness term) decide.

Math questions

B7. (math) Derive \partial D/\partial p_j for the soft Dice. Evaluate it for B1 at an object pixel and at a background pixel. Which pixels does a gradient step on the Dice loss push up, and which down?

B8. (math) Let A be the matrix of a 1D strided convolution (kernel k, stride s, no padding) and T the transposed convolution with the same kernel. Show that \langle A\mathbf x, \mathbf y\rangle = \langle\mathbf x, T\mathbf y\rangle for all \mathbf x, \mathbf y, i.e. T = A^\top.

B9. (math) Weighted cross-entropy with weights w_1 for object pixels and w_0 for background pixels. If the object share is f, show that choosing w_c \propto 1/(\text{share of class } c) makes both classes contribute equally to the loss of a network that outputs the constant p. Give the weights for f = 0.05, normalised so that w_0 = 1.

B7. (math) With I = \sum_i p_ig_i and S = \sum_i p_i + \sum_i g_i: D = 2I/S, \partial I/\partial p_j = g_j, \partial S/\partial p_j = 1, so \partial D/\partial p_j = (2g_jS - 2I)/S^2. For B1: S = 7.7, I = 3: object pixels (15.4 - 6)/59.29 = 0.159, background pixels -6/59.29 = -0.101. The Dice loss 1 - D has the opposite gradient: a step pushes object pixels up and background pixels down, with the same size for every object pixel, however confident it already is.

B8. (math) (A\mathbf x)_i = \sum_u k_u x_{is + u}, so \langle A\mathbf x, \mathbf y\rangle = \sum_i\sum_u k_ux_{is + u}y_i. The transposed convolution stamps: (T\mathbf y)_t = \sum_i\sum_u [is + u = t]\,k_uy_i, so \langle\mathbf x, T\mathbf y\rangle = \sum_t x_t\sum_{i,u}[is + u = t]k_uy_i = \sum_{i,u}k_ux_{is+u}y_i. The two sums are equal.

B9. (math) For a constant output p the loss is -\big[w_1f\ln p + w_0(1 - f)\ln(1 - p)\big]: the classes contribute with the factors w_1f and w_0(1 - f), equal when w_1/w_0 = (1 - f)/f. With w_c \propto 1/\text{share}: w_1 = c/f, w_0 = c/(1 - f), so w_1f = w_0(1 - f) = c. For f = 0.05: w_0 = 1, w_1 = 0.95/0.05 = 19. The minimum of this weighted loss over constant outputs is then at p = \tfrac12 instead of p = f.

Explore: a U-Net segments nuclei

A tiny U-Net (8, 16 and 32 channels, 29,617 weights) was trained on 4000 synthetic 64 \times 64 fluorescence-like images: nuclei of different sizes and brightness, some touching, an illumination gradient and noise. The demo draws new images from the same generator (new image). Panels: the input, the nucleus probability of every pixel, the mask at the threshold, the errors against the true mask (white = correct nucleus, red = false positive, blue = false negative) with Dice and IoU, and Otsu’s threshold (thresholding day) as the baseline. Click a block of the architecture to see its feature maps. The sliders move the input away from the training images: extra noise, a stronger illumination gradient, a brightness factor, larger or smaller nuclei. Weight sets: U-Net (trained with per-pixel cross-entropy), no skip connections, and trained with Dice loss.

U1. Preset a typical image. Read Dice, IoU and the error counts of the U-Net and the Dice of Otsu. Where are the U-Net’s errors? Move the threshold from 0.1 to 0.9: how much does Dice change?

U2. Preset U-Net vs Otsu on uneven illumination (the same image with an illumination gradient of 100 grey levels). Compare the two error images. Why does Otsu fail, and why not the U-Net?

U3. Click the five blocks of the architecture. How many maps of which size does each have? What do the bottleneck maps look like compared with those of encoder 1?

U4. Preset no skips: small nuclei (nuclei half the usual size). Compare the Dice of no skip connections and U-Net on this image, and the number of uncertain pixels (0.1 < p < 0.9). Then press back to training conditions and compare the two weight sets on a few new images. When do the skip connections matter?

U5. Preset touching nuclei merge. How many nuclei are there (readout), and how many separate white regions does the mask have? Is that an error of the network?

U6. Preset too noisy: outside the training range (extra noise with standard deviation 30). What happens to the U-Net and to Otsu? Try 15.

U7. Preset dimmer microscope: domain shift (the whole image ×0.5). Compare the U-Net with Otsu, and with the same image at brightness 1. Lower the threshold: does it help much? Then try brightness 2.

U8. Preset Dice loss: probabilities near 0 or 1. Compare the probability maps and the readouts (cross-entropy, soft Dice, uncertain pixels) of trained with Dice loss and U-Net. Move the threshold from 0.1 to 0.9 for both.

U1. U-Net: Dice 0.986, IoU 0.972, TP 446, FP 2, FN 11; Otsu: 0.975. The few errors lie on the nucleus boundaries (blue rims: the U-Net’s nuclei are a little too small), where even the truth is a matter of half pixels. Dice is 0.980 at threshold 0.1, 0.986 at 0.5, 0.974 at 0.9: the probabilities are close to 0 or 1 except at the boundaries, so the threshold matters little.

U2. Otsu (threshold 81) labels the whole bright right side as nucleus: Dice 0.349 (a large red region). One global threshold cannot separate nuclei from a background that is brighter on one side than the dim nuclei on the other. The U-Net sees each nucleus in its neighbourhood (a bright blob is brighter than its surroundings) and was trained on images with gradients up to 100: Dice 0.987, the same as without the gradient.

U3. Encoder 1: 8 maps of 64 \times 64; encoder 2: 16 of 32 \times 32; bottleneck: 32 of 16 \times 16; decoder 2: 16 of 32 \times 32; decoder 1: 8 of 64 \times 64. Encoder-1 maps look like filtered versions of the image (edges, blobs, background); the bottleneck maps are coarse blobs that mark where the nuclei are, with blocky outlines.

U4. On this image: no skips Dice 0.936 (FP 27, 41 uncertain pixels), U-Net 0.954 (FP 19, 28 uncertain pixels): without skips the small nuclei come out too large and blurred. On typical images the difference is small (validation Dice 0.965 against 0.968): these smooth, fairly large blobs can be located from the 16 \times 16 bottleneck maps. Skip connections matter for small objects and fine boundaries; over 40 test images with half-size nuclei the Dice is 0.904 without and 0.925 with skips.

U5. 7 nuclei, but the mask has 4 connected regions: several nuclei touch. The network did what it was trained for (Dice 0.986): label pixels as nucleus or not. Separating touching nuclei needs another step (B5).

U6. Noise 30 (training noise was 3–10): the U-Net drops to Dice 0.943 and its mask breaks into 9 pieces (specks in the background, holes); Otsu drops to 0.729. At noise 15 both are still good (0.978 and 0.951). The network degrades gracefully here, but its errors are of a new kind (scattered specks).

U7. At brightness ×0.5 the U-Net misses most of the nuclei: Dice 0.269 (TP 143, FN 776), while Otsu still reaches 0.705. At brightness 1 the same image gives 0.951. Lowering the threshold to 0.1 helps little (0.335): the probabilities themselves are low, the network has never seen nuclei this dim. At brightness ×2: 0.930. A network can be beaten by a simple threshold as soon as the input leaves its training range; it gives no warning. Augmenting the brightness during training, or normalising the images, would help.

U8. The Dice-trained network gives almost only probabilities near 0 or 1: 16 uncertain pixels against 285 for the cross-entropy network. Its Dice hardly depends on the threshold (0.904–0.906 from 0.1 to 0.9); the cross-entropy network peaks at 0.5 (0.909) and drops to 0.851 at 0.1 and 0.856 at 0.9. The Dice-trained network’s cross-entropy is high (0.491 against 0.108): where it is wrong it is confidently wrong. Its probabilities are not calibrated: “0.99” does not mean “right 99 % of the time”.

Code

Write the algorithms of this unit yourself, in Rust. Setup, and how to run and check your code: coding exercises: getting started. Your code goes in neuralnets/src/unet/exercise.rs.

C1. pixel_cross_entropy(p, g): the mean per-pixel cross-entropy of a probability map against the true mask. The checks are B1(a) and B1(c).

C2. soft_dice(p, g): 2\sum_i p_ig_i/(\sum_i p_i + \sum_i g_i). For a map of only 0 and 1 it is the Dice of a mask. The checks are B1(b) and B1(c).

C3. soft_dice_gradient(p, g): \partial D/\partial p_j for every pixel, with I = \sum_i p_ig_i and S = \sum_i p_i + \sum_i g_i: (2g_jS - 2I)/S^2. The check is B7, and a finite difference.

C4. upsample_nearest(img, factor): every pixel becomes a factor × factor block. The check is B2(a).

C5. transposed_conv(img, kernel, s): every input pixel stamps a copy of the kernel, scaled by its value, into the output, s pixels apart:

out = zeros of size ((w − 1)·s + kw) × ((h − 1)·s + kh)
for every input pixel (x, y):
    for every kernel position (u, v):
        out(s·x + u, s·y + v) = out(s·x + u, s·y + v) + I(x, y) · k(u, v)

The checks are B2(c) and B2(d).

Then cargo run -p neuralnets -- unet and open the pictures in out/unet/. There is no training: the program builds a tiny encoder–decoder by hand and scores it with your losses. The input is a synthetic fluorescence image with 30 nuclei and an illumination gradient (brighter to the right). The encoder averages 4 \times 4 blocks (64 \times 64 maps) and estimates the background there as the darkest value within 4 coarse pixels (context much larger than a nucleus). The decoder brings the background back to full size with a transposed convolution (a 7 \times 7 tent kernel, stride 4: linear interpolation). The output is a probability: a sigmoid of the pixel’s brightness above its background. With a skip connection the brightness comes from the full-size input; without, only from the coarse 64 \times 64 map, upsampled by nearest neighbour. The baseline is one global threshold.

C6. Compare p-skip.png, p-no-skip.png and p-global-threshold.png with truth.png, and the printed scores. Explain what goes wrong in each of the two worse ones.

C7. The last line scores p = 0.01 everywhere. Compare its numbers with B1(c). Why is its cross-entropy much larger here than there?

C8. dice-gradient.png shows \partial D/\partial p for the skip output (0 is mid-grey). Where does a step on the Dice loss push the probabilities up, and where down? Does it matter how confident a pixel already is?

The model solution is neuralnets/src/unet/solution.rs in the download.

C6. 20.4 % of the pixels are nucleus. With the skip connection: cross-entropy 0.040, soft Dice 0.963, Dice of the mask 0.968; the outlines match the truth. Without it: 0.149, 0.920, 0.922; the nuclei are found in the right places (the context is the same), but every outline is made of 4 \times 4 blocks, because the detail was lost in the encoder. One global threshold: 0.427, 0.720, 0.724: on the left it finds the nuclei, but the right third of the image, where the background is brighter, is a field of noise “nuclei”. A pixel must be compared with its own surroundings, which is what the context from the coarse level provides. Context from below, detail from the side: the U-Net in miniature.

C7. Cross-entropy 0.949, soft Dice 0.019, Dice of the mask 0. In B1(c) the cross-entropy was 0.240, below the 0.693 of a coin toss, because only 5 % of the pixels were nucleus. Here 20 % are, and each of them costs -\ln 0.01 = 4.6: the cross-entropy depends on the share of object pixels, the Dice numbers show that nothing was found in both cases.

C8. Up (bright) at every nucleus pixel, down (dark) at every background pixel, with one value for all nucleus pixels and one for all background pixels: (2S - 2I)/S^2 and -2I/S^2. How confident a pixel already is does not matter, unlike for the cross-entropy, whose gradient vanishes for pixels that are already right. This is why a network trained with the Dice loss pushes its probabilities to 0 and 1 (demo question U8).

Where this leads

The evaluation day (day 38) asks how to measure segmentations honestly: object-level matching, test sets from new sources, and the statistics of comparing methods. Modern deep learning (day 41) splits touching nuclei with networks, uses pretrained models that need fewer annotations, and generates images; the VAE day (day 39) shows networks that learn to make images rather than label them. Learned image restoration (denoising, deconvolution with networks) is discussed on the deconvolution day (denoising) and with diffusion models.