from copy import deepcopy
import numpy as np
import matplotlib.pyplot as plt
import torch
from torch import nn
from torch.nn import functional as F
from dlbook.segmentation import (
CoarseFCN, TinyUNet, evaluate, fit, make_microscopy, mask_metrics,
segmentation_loss, soft_dice_loss, transfer_model,
)
torch.set_num_threads(1)
x_train, y_train = make_microscopy(64, seed=601)
x_valid, y_valid = make_microscopy(24, seed=602)
assert x_train.shape == y_train.shape == (64, 1, 48, 48)21.1 Lab contract
The theory chapter explains why dense prediction needs context and location, how U-Net combines scales, and what encoder transfer changes. This notebook makes transfer learning and U-Net executable through a synthetic segmentation example. It runs independently using the teaching models in dlbook.segmentation. Keep the target unchanged: a binary semantic mask, not individual cell identities.
Try → understand → improve: compare a threshold, a coarse FCN, and U-Net on the same task; expose information loss and an alignment bug; verify the model; then conduct a paired skip ablation and a guided transfer comparison. The optional additional material extends the adaptation comparison with more controls. Allow about 4 hours if completing both the lab and the optional study, including interpretation.
Before running, write two predictions: where will the coarse representation fail, and what will access to high-resolution features change? Record what evidence would contradict each prediction.
21.2 Guided baseline: from a threshold to U-Net
The theory chapter separated the task, architecture, and evaluation rule. Here all models see the same generated binary masks. Fix the displayed examples before training, use the training fields for fitting, and use validation fields for comparison. The generator creates geometric cell-like phantoms with blur, variable illumination, noise, and bright debris; these are not real cell images.
21.2.1 A pixelwise threshold
A threshold sees one intensity at a time. Predict what will happen to dim cell regions and isolated bright debris at the chosen value. The all-background predictor is a useful check: it can have high pixel accuracy while finding no cells.
threshold = 0.45
fig, axes = plt.subplots(2, 3, figsize=(8, 5))
for row, index in enumerate((0, 1)):
panels = (x_train[index, 0], y_train[index, 0], x_train[index, 0] >= threshold)
for ax, panel, title in zip(axes[row], panels, ("Input", "Reference", "Threshold")):
ax.imshow(panel, cmap="gray", vmin=0, vmax=1)
ax.set_title(title)
ax.axis("off")
fig.tight_layout()
plt.show()
print("Training threshold:", mask_metrics(x_train >= threshold, y_train))
print("Training all-background:", mask_metrics(torch.zeros_like(y_train), y_train))
print("Validation threshold:", mask_metrics(x_valid >= threshold, y_valid))
print("Validation all-background:", mask_metrics(torch.zeros_like(y_valid), y_valid))
Training threshold: {'dice': 0.687931478023529, 'iou': 0.5289850831031799, 'pixel_accuracy': 0.9256320595741272}
Training all-background: {'dice': 0.0, 'iou': 0.0, 'pixel_accuracy': 0.8866509199142456}
Validation threshold: {'dice': 0.6692299246788025, 'iou': 0.5078754425048828, 'pixel_accuracy': 0.9304289817810059}
Validation all-background: {'dice': 0.0, 'iou': 0.0, 'pixel_accuracy': 0.9017650485038757}
21.2.2 A coarse fully convolutional model
The \(1\times1\) output head is the shared per-position classifier derived in the chapter. Verify that its channel-mixing computation matches the explicit affine formula before training a full model.
torch.manual_seed(60)
features = torch.randn(2, 5, 7, 9)
head = nn.Conv2d(5, 1, kernel_size=1)
manual = (features * head.weight[0, :, 0, 0][None, :, None, None]).sum(1, keepdim=True)
manual = manual + head.bias[None, :, None, None]
torch.testing.assert_close(head(features), manual)
assert head(features).shape == (2, 1, 7, 9)The coarse FCN uses two pooling steps, predicts on a \(12\times12\) grid, then resizes its logits to \(48\times48\). U-Net uses the same encoder scale pattern but combines saved \(24\times24\) and \(48\times48\) features in its decoder. Both receive the same training fields, loss, minibatch sequence, optimizer settings, and 120 updates. Their decoders and parameter counts differ, so this is an architectural progression rather than an isolated skip test.
torch.manual_seed(60)
coarse_model = CoarseFCN()
fit(coarse_model, x_train, y_train, steps=120, seed=61)
torch.manual_seed(60)
guided_unet = TinyUNet()
fit(guided_unet, x_train, y_train, steps=120, seed=61)
for name, model in (("Coarse FCN", coarse_model), ("U-Net", guided_unet)):
parameters = sum(p.numel() for p in model.parameters())
print(name, "parameters:", parameters, "validation:", evaluate(model, x_valid, y_valid))Coarse FCN parameters: 4573 validation: {'dice': 0.8683056831359863, 'iou': 0.7694589495658875, 'pixel_accuracy': 0.9746274352073669, 'loss': 0.22863265872001648}
U-Net parameters: 7465 validation: {'dice': 0.9007070660591125, 'iou': 0.8208422064781189, 'pixel_accuracy': 0.9808304309844971, 'loss': 0.1707606017589569}
with torch.no_grad():
coarse_p = coarse_model(x_valid).sigmoid()
unet_p = guided_unet(x_valid).sigmoid()
fig, axes = plt.subplots(2, 3, figsize=(8, 5))
for row, index in enumerate((0, 1)):
panels = (y_valid[index, 0], coarse_p[index, 0], unet_p[index, 0])
for ax, panel, title in zip(axes[row], panels, ("Reference", "Coarse FCN", "U-Net")):
ax.imshow(panel, cmap="gray", vmin=0, vmax=1)
ax.set_title(title)
ax.axis("off")
fig.tight_layout()
plt.show()
Write down one error the learned coarse model fixes relative to thresholding, and one boundary or small-object error that remains. Do not infer from this comparison alone that skip connections caused the entire U-Net difference; the paired ablation below tests access to skip features more directly.
21.3 1. A lost pixel cannot be restored by resizing — Core, 10 minutes
Two different input masks can have exactly the same max-pooled representation. If a decoder receives only that representation, there is no way to know which original was supplied. A learned prior may make a useful guess; it cannot uniquely invert a many-to-one operation.
a = torch.zeros(1, 1, 4, 4)
b = torch.zeros_like(a)
a[0, 0, 0, 0] = 1
b[0, 0, 1, 1] = 1
pooled_a, pooled_b = F.max_pool2d(a, 2), F.max_pool2d(b, 2)
assert not torch.equal(a, b)
assert torch.equal(pooled_a, pooled_b)
restored = F.interpolate(pooled_a, size=(4, 4), mode="nearest")
fig, axes = plt.subplots(1, 4, figsize=(9, 2.6))
for ax, tensor, title in zip(axes, (a, b, pooled_a, restored),
("Original A", "Original B", "Same pooled values", "Same resized values")):
ax.imshow(tensor[0, 0], cmap="gray", vmin=0, vmax=1)
ax.set_title(title, fontsize=10)
ax.axis("off")
fig.tight_layout()
plt.show()
Explain how a skip connection changes the information available to the decoder. Does concatenating a feature map force the decoder to use it well?
21.4 2. Diagnose an image–mask mismatch — Core, 15 minutes
A student independently augments the image and mask:
image = randomly_rotate(image)
mask = randomly_rotate(mask)Even if the two functions use the same distribution, they can draw different angles. The pair no longer describes the same geometry. Sample spatial transform parameters once and apply them to both. Intensity transforms apply only to the image.
image, mask = x_train[:1], y_train[:1]
# One declared geometric transform: rotate by 90 degrees, then flip horizontally.
image_aug = torch.flip(torch.rot90(image, 1, dims=(-2, -1)), dims=(-1,))
mask_aug = torch.flip(torch.rot90(mask, 1, dims=(-2, -1)), dims=(-1,))
assert image_aug.shape == mask_aug.shape
assert set(mask_aug.unique().tolist()) <= {0.0, 1.0}
# Invert the transform and recover the exact label map.
mask_back = torch.rot90(torch.flip(mask_aug, dims=(-1,)), -1, dims=(-2, -1))
torch.testing.assert_close(mask_back, mask)
# Brightness augmentation must not alter the label map.
image_aug = (image_aug * 0.9).clamp(0, 1)21.4.1 Resizing labels is not resizing photographs
small_mask = torch.tensor([[[[0., 1.], [1., 0.]]]])
nearest_mask = F.interpolate(small_mask, size=(7, 7), mode="nearest")
blurred_mask = F.interpolate(small_mask, size=(7, 7), mode="bilinear", align_corners=False)
assert set(nearest_mask.unique().tolist()) == {0., 1.}
assert ((blurred_mask > 0) & (blurred_mask < 1)).any()Use nearest-neighbor interpolation for categorical masks. Deliberately soft targets are a different modeling choice and must be documented; they are not a harmless consequence of reusing the image-resizing function. For multiclass masks, mixing numeric class IDs has no categorical meaning.
Data bridge. For real images, draw a split diagram in words: patient → specimen → slide → tile. At what level should the train/validation/test split happen? Why is a random tile split unsafe if adjacent tiles come from the same patient or field?
21.5 3. Verify the network before comparing scores — Core, 25 minutes
21.5.1 Shapes and gradient flow
Test rectangular and odd image dimensions. The model must return exactly one logit per input pixel. Then verify finite gradients in the encoder and both decoder stages, not merely a decreasing scalar loss.
torch.manual_seed(60)
probe_model = TinyUNet()
for height, width in ((48, 48), (47, 51), (32, 40)):
logits = probe_model(torch.randn(2, 1, height, width))
assert logits.shape == (2, 1, height, width)
probe_model.zero_grad()
objective = segmentation_loss(probe_model(x_train[:4]), y_train[:4])
objective.backward()
for module in (probe_model.encoder, probe_model.decode2, probe_model.decode1, probe_model.head):
grads = [p.grad for p in module.parameters()]
assert all(g is not None and torch.isfinite(g).all() for g in grads)
assert sum(g.abs().sum().item() for g in grads) > 0
print("All stages receive finite, nonzero aggregate gradients.")All stages receive finite, nonzero aggregate gradients.
Coding bridge: trace the concatenation shapes for a (2, 1, 47, 51) input. At the first decoder stage, how many channels are there before and after concatenation? Which exact height and width are used for resizing?
21.5.2 Test the metric convention
empty = torch.zeros(1, 1, 3, 3)
foreground = empty.clone()
foreground[0, 0, 1, 1] = 1
assert mask_metrics(empty, empty)["dice"] == 1
assert mask_metrics(empty, foreground)["dice"] == 0
assert mask_metrics(foreground, empty)["iou"] == 0
assert mask_metrics(foreground, foreground)["dice"] == 1
# Hard masks belong in evaluation; the training objective receives logits.
extreme_logits = torch.tensor([[[[-1000., 1000.]]]], requires_grad=True)
extreme_targets = torch.tensor([[[[1., 0.]]]])
stable_loss = segmentation_loss(extreme_logits, extreme_targets)
stable_loss.backward()
assert torch.isfinite(stable_loss) and torch.isfinite(extreme_logits.grad).all()Math bridge: derive the soft Dice derivative for one probability \(p_j\). With \(a=2\sum_i p_i y_i+\epsilon\) and \(b=\sum_i p_i+\sum_i y_i+\epsilon\), show that \(\partial(1-a/b)/\partial p_j=(a-2y_jb)/b^2\). Why does changing one probability influence the gradients at other pixels? Multiply by \(p_j(1-p_j)\) to obtain the derivative with respect to its logit.
21.6 4. Isolate access to high-resolution features — Core, 30 minutes
The chapter’s coarse FCN and U-Net differ in decoder depth and parameter count as well as skip connections. To isolate one mechanism more closely, keep the U-Net decoder and its channel counts fixed and replace the skip tensors by zeros in one condition.
Both conditions allocate the same parameters and start from exactly the same values. In the gated condition, some weights multiply zeros and have no useful input, so equal nominal parameter counts do not imply equal effective capacity. This experiment tests access to skip features within this graph, not all possible advantages of all U-Nets.
| Field | Predeclared choice |
|---|---|
| Hypothesis | Skip features improve localization under this fixed update budget. |
| Intervention | Pass encoder skip tensors or zero tensors at both scales |
| Fixed controls | Data, labels, architecture shapes, initial state per pair, batch order, loss, optimizer, threshold |
| Initialization seeds | 60, 61, 62; report all three |
| Training budget | 120 updates, batch size 8, Adam learning rate 0.003 |
| Primary metric | Mean per-image foreground Dice on all 24 validation fields |
| Secondary evidence | IoU, pixel accuracy, combined loss, fixed qualitative examples |
| Interpretation limit | Three initialization repeats on one synthetic split; not population uncertainty |
models, records = {}, []
for seed in (60, 61, 62):
torch.manual_seed(seed)
initial = TinyUNet()
for use_skips in (False, True):
model = deepcopy(initial)
model.use_skips = use_skips
fit(model, x_train, y_train, steps=120, seed=61)
metrics = evaluate(model, x_valid, y_valid)
models[seed, use_skips] = model
records.append({"seed": seed, "skips": use_skips, **metrics})
print(seed, "skips" if use_skips else "zeroed", {k: round(v, 4) for k, v in metrics.items()})60 zeroed {'dice': 0.859, 'iou': 0.756, 'pixel_accuracy': 0.9717, 'loss': 0.2385}
60 skips {'dice': 0.9007, 'iou': 0.8208, 'pixel_accuracy': 0.9808, 'loss': 0.1708}
61 zeroed {'dice': 0.8557, 'iou': 0.7506, 'pixel_accuracy': 0.9737, 'loss': 0.3593}
61 skips {'dice': 0.8785, 'iou': 0.7849, 'pixel_accuracy': 0.9766, 'loss': 0.3833}
62 zeroed {'dice': 0.8514, 'iou': 0.744, 'pixel_accuracy': 0.9724, 'loss': 0.2589}
62 skips {'dice': 0.8739, 'iou': 0.7789, 'pixel_accuracy': 0.9773, 'loss': 0.2133}
fig, ax = plt.subplots(figsize=(6, 4))
for seed in (60, 61, 62):
values = [next(r["dice"] for r in records if r["seed"] == seed and r["skips"] == setting)
for setting in (False, True)]
ax.plot([0, 1], values, "o-", label=f"seed {seed}")
ax.set(xticks=[0, 1], xticklabels=["Skip inputs zeroed", "Skip inputs present"],
ylabel="validation mean foreground Dice", ylim=(0, 1))
ax.legend()
fig.tight_layout()
plt.show()
Before averaging, inspect every paired difference. A failed initialization is part of the result; do not discard it because it weakens the story. Distinguish a mostly empty mask from misplaced boundaries by looking at predicted foreground fractions and probability maps.
If a run collapses to background: inspect loss components, logits, label encoding, gradient norms, and learning curves. Extending the update budget is a new controlled experiment: apply it to both members of each pair and report both budgets. Do not quietly train only the weaker condition longer or select the best seed after viewing test scores.
Write 150–200 words answering: what changed, what stayed fixed, how consistent was the effect, and which alternative explanations remain? A useful conclusion may be conditional or inconclusive.
21.7 5. Transposed convolution is a transpose, not an inverse — Math/coding depth, 15 minutes
For a convolution without bias, the mapping from input values to outputs is linear. Denote it by \(C\). A matching transposed convolution applies \(C^\top\) with compatible stride, padding, and shape. The identity
\[ \langle Cx,z\rangle=\langle x,C^\top z\rangle \]
characterizes the transpose; it does not say \(C^\top Cx=x\).
torch.manual_seed(65)
conv = nn.Conv2d(1, 1, kernel_size=3, stride=2, padding=1, bias=False).double()
transpose = nn.ConvTranspose2d(1, 1, kernel_size=3, stride=2, padding=1,
output_padding=1, bias=False).double()
with torch.no_grad():
transpose.weight.copy_(conv.weight)
x = torch.randn(1, 1, 8, 10, dtype=torch.float64)
z = torch.randn_like(conv(x))
assert transpose(z).shape == x.shape
torch.testing.assert_close((conv(x) * z).sum(), (x * transpose(z)).sum())
assert not torch.allclose(transpose(conv(x)), x)For one spatial axis, the output-size formula is
\[ H_{out}=(H_{in}-1)s-2p+d(k-1)+o+1, \]
where \(o\) is output_padding. It resolves output-size ambiguity for a strided operation; it does not restore lost observations. With this example’s \(H_{in}=4\), \(s=2\), \(p=1\), \(d=1\), \(k=3\), \(o=1\), verify that \(H_{out}=8\).
21.8 6. A high overlap score can hide an important mistake — Core, 10 minutes
A mask can miss an entire small object and still have high overlap because a large object dominates the foreground area. This is one reason to inspect small structures and match the evaluation to the downstream measurement.
yy, xx = torch.meshgrid(torch.arange(48), torch.arange(48), indexing="ij")
large = (xx - 17)**2 + (yy - 24)**2 <= 11**2
small = (xx - 39)**2 + (yy - 12)**2 <= 2**2
reference = (large | small)[None, None]
damaged = large[None, None]
print("Missing the whole small object:", mask_metrics(damaged, reference))
fig, axes = plt.subplots(1, 2, figsize=(5.5, 3))
for ax, panel, title in zip(axes, (reference, damaged), ("Reference", "Missed small object")):
ax.imshow(panel[0, 0], cmap="gray", vmin=0, vmax=1)
ax.set_title(title)
ax.axis("off")
fig.tight_layout()
plt.show()Missing the whole small object: {'dice': 0.9830508232116699, 'iou': 0.9666666388511658, 'pixel_accuracy': 0.9943576455116272}
If the downstream question is area, report area error too. If it is object counts, use instance-aware targets and evaluation. If boundaries matter, add an explicitly defined boundary metric with pixel spacing stated. An aggregate Dice is useful evidence, but does not answer all three questions.
21.9 7. Reuse a learned encoder — transfer and fine-tuning
The theory chapter distinguished architecture from initialization and trainability. Keep the U-Net architecture fixed now. First train a source model on 96 cleaner synthetic fields; copy only its encoder. Then compare scratch, frozen transfer, and full fine-tuning using the same 16 target training fields, validation fields, initial decoder seed, and 80 target updates. Predict the ordering before running the cells. Source training uses additional labels and updates, so equal target updates are not equal total resources.
source_x, source_y = make_microscopy(96, seed=610, domain="source")
target_x, target_y = x_train[:16], y_train[:16]
torch.manual_seed(71)
source_model = TinyUNet()
fit(source_model, source_x, source_y, steps=160, seed=72)
source_encoder = deepcopy(source_model.encoder.state_dict())
preview_results = {}
for regime in ("scratch", "frozen", "full"):
model = transfer_model(source_encoder, regime, seed=70)
encoder_before = deepcopy(model.encoder.state_dict())
fit(model, target_x, target_y, steps=80, seed=73)
if regime == "frozen":
for name, value in model.encoder.state_dict().items():
torch.testing.assert_close(value, encoder_before[name], rtol=0, atol=0)
preview_results[regime] = evaluate(model, x_valid, y_valid)
print(regime, {key: round(value, 3) for key, value in preview_results[regime].items()})scratch {'dice': 0.223, 'iou': 0.126, 'pixel_accuracy': 0.91, 'loss': 0.574}
frozen {'dice': 0.277, 'iou': 0.162, 'pixel_accuracy': 0.913, 'loss': 0.607}
full {'dice': 0.655, 'iou': 0.49, 'pixel_accuracy': 0.943, 'loss': 0.429}
Compare frozen versus full to discuss whether adapting source features helped under this budget. Compare full versus scratch to discuss the effect of starting from source weights, while accounting for the extra source resources. This single run does not establish a universal ranking. The optional additional material adds a random-frozen control, partial unfreezing, a diagnosis, and its own reserved test stream.
21.10 Final assessment: open the reserved test stream once
For this first lab, predeclare the primary model as the U-Net with seed 60, skips enabled, 120 updates, and threshold 0.5. It is chosen by the written protocol, not by selecting the best of the three validation repeats. Generate the reserved test fields only now. Do not tune further based on these scores.
primary_model = models[60, True]
x_test, y_test = make_microscopy(24, seed=603)
print("Frozen primary U-Net:", evaluate(primary_model, x_test, y_test))
print("Predeclared threshold baseline:", mask_metrics(x_test >= 0.45, y_test))
print("All-background baseline:", mask_metrics(torch.zeros_like(y_test), y_test))Frozen primary U-Net: {'dice': 0.9013239741325378, 'iou': 0.8224897980690002, 'pixel_accuracy': 0.9787688255310059, 'loss': 0.17469823360443115}
Predeclared threshold baseline: {'dice': 0.699943482875824, 'iou': 0.5437546968460083, 'pixel_accuracy': 0.9302662014961243}
All-background baseline: {'dice': 0.0, 'iou': 0.0, 'pixel_accuracy': 0.8905526399612427}
These are same-generator test fields. They do not test a new scanner, stain, patient population, or real biological morphology. The optional additional material studies a declared source/target generator change and the transfer protocol, still without claiming real-world validation.
21.11 Submission
Submit the executed notebook and a concise interpretation containing:
- Your original predictions and the observed threshold/coarse-model failures.
- Shape and alignment checks, the metric empty-mask convention, and one derivative explanation.
- All paired skip-ablation results with fixed controls, including unsuccessful runs.
- One case where the chosen overlap metric misses a relevant error.
- The frozen-model test result with the seed, threshold, update budget, and synthetic-data limitation.
- The guided transfer comparison above, distinguishing source compute from target compute. Include the extended comparison if you complete the optional additional material.
Coding bridge: annotate the channel and spatial dimensions at each concatenation. Math bridge: verify the Dice–IoU relation on one mask pair. Stretch: compare BCE alone against BCE plus soft Dice while keeping architecture and optimizer fixed; reserve fresh evaluation data if the original test results have already informed your choices.