20Lesson 6: Transfer Learning, Fine-Tuning, and U-Net
Reuse learned representations and combine features across spatial scales
This chapter studies two complementary ideas: transfer learning, which reuses knowledge learned on a source task or domain, and U-Net, an encoder–decoder architecture that combines features across spatial scales. Fine-tuning connects the two when we adapt a pretrained encoder inside a U-Net. Transfer learning applies across many architectures and tasks; U-Net can also be trained from scratch.
We use synthetic cell-like image segmentation as a running example to make the architecture, losses, and adaptation experiments concrete. The example is one application of the chapter’s methods.
20.1 Learning goals
After studying this chapter, a student should be able to:
Distinguish pretrained initialization, frozen feature extraction, linear probing, partial unfreezing, and full fine-tuning;
Trace shapes through a U-Net and distinguish its concatenation skips from ResNet addition;
Explain semantic segmentation, pixelwise training losses, and foreground metrics, including why pixel accuracy can be misleading; and
Design a comparison that distinguishes architecture effects from transfer effects under a limited target-label budget.
We assume familiarity with logits, binary cross-entropy, backpropagation, optimization, and validation, together with the previous chapter’s discussion of convolution, pooling, receptive fields, and ResNet shortcuts. We will extend these ideas to spatial prediction. Tensor shapes follow PyTorch’s channel-first convention, \(N\times C\times H\times W\), where \(N\) is the batch size.
The lab provides the core segmentation and transfer experiments. The optional additional material develops a more detailed adaptation study. The main explanations of both U-Net and transfer learning are contained in this concepts chapter.
20.2 A running example: why predict a mask?
Suppose we want to measure how much of a microscopy image is occupied by cells. The CNN classifiers from the previous chapter could tell us whether a cell is present, but that answer would not tell us which pixels to include in the measurement. To calculate the occupied area, we need to identify the cell region throughout the image.
A segmentation mask records this information. It assigns a label to each pixel, allowing us to distinguish the region of interest from the background. Once we have a mask, we can measure its area and inspect its boundaries. Similar tasks arise when measuring tissue in medical images or mapping flooded land in satellite images.
Code
from pathlib import Pathimport matplotlib.pyplot as pltreference = Path("chapters/06-transfer-unet/images/micronucleus-mask-genomicintegrity.png")fig, ax = plt.subplots(figsize=(9, 5.2))ax.imshow(plt.imread(reference))ax.axis("off")fig.tight_layout()plt.show()
Figure 20.1: A real cheek-cell image beside a manually drawn mask. Spatial labels identify regions that an image-level class label cannot locate.
Image: Genomicintegrity, Wikimedia Commons, CC BY 4.0, reproduced without modification. This illustration distinguishes several regions, including internal cell structures. Our teaching example below uses a simpler binary mask, and this real image is not part of its training data.
We will develop a system for predicting such masks through one running example. First, we will define the required output and examine why an ordinary classification CNN does not directly provide it. That will lead us to U-Net, an architecture that combines object recognition with spatial detail. After learning how to train and evaluate this network, we will return to a practical difficulty: annotated masks take time to produce, so our target dataset may be small. Transfer learning will then give us a way to investigate whether features learned elsewhere can help.
20.2.1 The running example
Our example uses one-channel, \(48\times48\) images containing synthetic cell-like objects. Each object is drawn as a disk, and the target mask marks the union of these disks as foreground. Every other pixel is background. Because we generate the images and masks together, the target boundaries are known exactly.
This simple setting lets us concentrate on the model and its training before dealing with uncertain annotations in real microscopy. The task is to predict which pixels belong to the objects, so the resulting foreground area answers our original measurement question. Later, we will introduce a second image collection to explore transfer learning. For now, we need only understand how one image becomes one mask.
20.3 From an image label to a pixelwise prediction
20.3.1 Define what the mask should represent
For one input image \(X\in\mathbb{R}^{C\times H\times W}\), our target is a binary mask \(Y\in\{0,1\}^{H\times W}\). A value of one means that the corresponding pixel belongs to a cell-like object; a value of zero means background. The model must therefore produce a prediction at every target location.
This task is binary semantic segmentation. The word semantic means that each pixel receives a category. It does not mean that each individual object receives a separate identity. If two objects touch, their foreground pixels form one connected region in our union mask.
Task
Output for one image
Question answered
Classification
One class or vector of class scores
Is a cell present?
Semantic segmentation
One category per pixel
Which pixels belong to cells?
Instance segmentation
A separate identity or mask for each object
Which pixels belong to each individual cell?
Our semantic mask supports total-area measurement. Counting touching cells would require additional information, such as instance annotations or a separately defined procedure for separating the objects. Defining the target first keeps the model’s output consistent with the measurement we want to make.
20.3.2 Extend a binary prediction across the image
In binary classification, the network produces an unrestricted real-valued logit, which a sigmoid converts into an estimated probability. For segmentation, we apply the same idea at every pixel. If \(z_{hw}\) is the logit at location \((h,w)\), then
We will begin with \(\tau=0.5\). A probability of \(0.9\) then produces a foreground label, while \(0.2\) produces a background label. Both \(0.51\) and \(0.99\) give the same hard label, so the binary mask hides differences in the model’s confidence. Inspecting the probability map can help us see uncertain boundaries, although the estimates are not automatically calibrated probabilities.
These representations serve different purposes. The network returns logits for a numerically stable training loss. Sigmoid converts them into probabilities for inspection or a smooth overlap loss. Thresholding gives a hard mask for evaluation and area measurement. For a batch of binary examples, logits have shape \(N\times1\times H\times W\).
20.3.3 Turn spatial features into pixelwise scores
A CNN already computes features on a spatial grid. At each position in a feature map, the channels form a vector describing a neighborhood of the input. Rather than reducing the entire grid to an image-level prediction, we can use the same prediction rule at every position.
A \(1\times1\) convolution with one output channel provides such a rule. If \(F_c(h,w)\) is feature channel \(c\) at position \((h,w)\), the convolution computes
\[
z_{hw}=b+\sum_{c=1}^{C_F}w_cF_c(h,w),
\]
where \(C_F\) is the number of feature channels. This is the affine score used in logistic regression, applied with shared weights across spatial positions. The layer is a prediction head: it converts the learned features into foreground scores.
The head’s \(1\times1\) kernel does not examine neighboring positions directly. Earlier layers must have encoded the neighborhood information needed to recognize an object. The feature grid must also have a useful resolution, since a head on a small grid produces only a small grid of scores.
Figure: Illustration of the UNet prediction head using 1x1 convolution applied to a feature map. Figure source.
A network that retains this spatial computation is called a fully convolutional network. Such networks can include pooling, resizing, nonlinearities, and skip connections as well as convolutions. The original FCN work developed this approach for dense prediction (Long et al. 2015). We now have a way to produce spatial scores, but we still need to understand what happens to their resolution as a CNN becomes deeper.
20.4 Combining recognition with localization
20.4.1 Why the network needs context
In our synthetic images, a single bright pixel might belong to an object, lie on a boundary, or be isolated noise. Its intensity alone may not resolve the ambiguity. A larger neighborhood can reveal whether it forms part of a coherent curved shape.
Deeper CNN features can use larger neighborhoods because their receptive fields grow through stacked convolutions and downsampling. Pooling also makes the spatial grid smaller. After two pooling steps, a \(48\times48\) image has a \(12\times12\) feature grid. A \(1\times1\) head on this grid would produce only \(12\times12\) foreground scores.
We could resize those scores back to \(48\times48\). This gives us a simple coarse segmentation model, but increasing the output size does not guarantee that its boundaries will be precise. To see why, consider what pooling can discard.
Max pooling maps both windows to the same value, \(1\). We know that a strong activation occurred somewhere in the window, but this pooled value no longer tells us which corner contained it. Other feature channels may preserve useful clues; this value alone cannot distinguish the two inputs.
Upsampling produces a larger grid from a smaller one. It cannot uniquely reconstruct information that was discarded. Precise segmentation therefore needs both the broader context used to recognize an object and finer evidence about where its boundary lies.
20.4.3 Divide the work between an encoder and a decoder
An encoder computes representations of the input, usually at progressively coarser resolutions. A decoder uses those representations to construct a prediction at the required output resolution. We can describe their combined computation as
\[
Z=D_\phi(E_\theta(X)),
\]
where \(\theta\) contains the encoder parameters and \(\phi\) contains the decoder parameters.
A simple decoder could start with only the encoder’s coarsest feature map and progressively upsample and refine it until the prediction reaches the input resolution. This map contains features computed from relatively large neighborhoods, which can help the model distinguish a cell-like object from isolated noise. However, its spatial grid is small, so it may provide limited evidence about the exact position of an object’s boundary. Enlarging the grid does not automatically restore details lost during downsampling.
The encoder has also computed finer feature maps at earlier stages, before successive pooling operations reduced their resolution. These maps can contain useful local evidence, such as edges and changes in intensity, represented on a denser spatial grid. If we save them, the decoder can use this evidence alongside the deeper features: broad context helps determine what a region represents, while finer features help determine where it begins and ends.
U-Net builds on this idea by connecting encoder and decoder stages with matching spatial resolutions. As the decoder upsamples its features, it also receives the corresponding saved encoder map. These skip connections allow the decoder to combine information from several scales, rather than constructing the entire mask from the coarsest representation alone.
20.5 Building U-Net step by step
20.5.1 Encode the image and save features at each scale
U-Net places an encoder, called its contracting path, beside a decoder, called its expanding path. Connections between corresponding resolutions let the decoder access encoder features at several scales (Ronneberger et al. 2015). In the encoder–decoder expression above, \(E_\theta(X)\) therefore supplies a collection of feature maps rather than only the coarsest map.
Our compact teaching model uses two downsampling steps. Each convolutional block contains two padded \(3\times3\) convolutions with ReLU activations. Padding preserves height and width within each block, while pooling halves them between blocks:
Pool by two, then two convolutions; save the result
\(8\times24\times24\)
\(B\)
Pool by two, then two convolutions
\(16\times12\times12\)
\(B\) is the bottleneck, the coarsest feature map. It is still a spatial grid, so the encoder retains information about different image regions. Its features can use a broader context than those in \(E_1\). Meanwhile, the saved maps \(E_1\) and \(E_2\) contain features computed before later pooling made the grid coarser.
Channel counts increase as the grid shrinks in this design. That gives the deeper stages room to represent more feature types while operating at a lower spatial resolution. The exact channel counts are a design choice; here, we keep them small so the shapes are easy to follow.
Figure 20.2: A U-Net architecture with contracting and expanding paths joined at matching spatial scales. The reference diagram has more levels than our compact teaching model.
20.5.2 Decode by resizing, combining, and refining
For this chapter, we use a resize-based U-Net variant: bilinear interpolation enlarges the feature maps, and standard convolutions then combine and refine their features. The original U-Net instead uses learned \(2\times2\) up-convolutions for upsampling and unpadded \(3\times3\) convolutions, which shrink the feature maps. Its encoder maps are cropped before concatenation, and its output mask is smaller than its input (Ronneberger et al. 2015). Our padded variant preserves spatial size within each block and predicts a mask at the input resolution. In either design, the decoder combines upsampled features with saved encoder features at corresponding spatial scales.
Our decoder starts with the bottleneck \(B\), whose shape is \(16\times12\times12\). First, bilinear resizing increases its spatial dimensions to \(24\times24\) while preserving its 16 channels. The decoder concatenates this resized map with \(E_2\) and applies a convolutional block. It then repeats the process at \(48\times48\) using \(E_1\):
Here, \(\operatorname{Up}\) denotes bilinear resizing to the spatial dimensions of the corresponding encoder map. It creates a larger grid by interpolating values from neighboring positions in the smaller grid. This increases resolution without introducing learned weights, although it does not automatically recover details lost during downsampling.
The square brackets mean concatenation along the channel axis. The resized decoder features and the saved encoder map must have the same height and width. Their channels are then stacked, allowing the following convolutions to access both deeper context and finer spatial evidence.
Each convolutional block contains two standard \(3\times3\) convolutions, each followed by ReLU. Both use stride one and padding one, so they preserve the height and width established by resizing. Each learned filter combines a \(3\times3\) neighborhood across all input channels, allowing the block to combine and refine information from both feature maps.
At the first stage, the 16 resized bottleneck channels join the eight channels from \(E_2\), producing \(24\times24\times24\) features. The two convolutions map the channels \(24\to8\to8\), producing \(D_2\) with shape \(8\times24\times24\). At the next stage, resizing increases the grid to \(48\times48\), and concatenation with the four channels from \(E_1\) gives 12 channels. The convolutions map \(12\to4\to4\), producing \(D_1\) with shape \(4\times48\times48\).
Thus, resizing increases spatial size, concatenation brings together features from both paths, and convolution learns how to combine them.
Decoder step
Resized features
Matching encoder map
Combined input
Block output
At \(24\times24\)
\(16\times24\times24\) from \(B\)
\(8\times24\times24\) from \(E_2\)
\(24\times24\times24\)
\(8\times24\times24\)
At \(48\times48\)
\(8\times48\times48\) from \(D_2\)
\(4\times48\times48\) from \(E_1\)
\(12\times48\times48\)
\(4\times48\times48\)
Prediction head
\(4\times48\times48\) from \(D_1\)
—
Four feature channels
\(1\times48\times48\) logits
The final \(1\times1\) convolution is the prediction head introduced earlier. It converts the four features at each position into one foreground logit. The result has the same spatial dimensions as the target mask.
20.5.3 Understand what the skip connections supply
The connections carrying \(E_1\) and \(E_2\) to the decoder are skip connections: they provide a route around the intervening deeper stages. A decoder can use a finer edge response to position a boundary while using deeper context to decide whether that edge belongs to an object or to noise. The convolutional blocks learn how to combine this information during training.
This relates to the ResNet shortcuts from the previous chapter, but the combination differs. A ResNet shortcut adds aligned tensors element by element. Our U-Net skips concatenate the channels of tensors with matching spatial dimensions. Concatenation preserves both sets of features as separate channels until subsequent convolutions combine them.
20.5.4 Match spatial grids, including odd input sizes
Concatenation requires equal height and width, but repeatedly doubling a pooled grid does not always recover them. A \(47\times51\) input becomes \(23\times25\) after one \(2\times2\), stride-two pooling layer and \(11\times12\) after another. Doubling the bottleneck gives \(22\times24\), which does not match the saved \(23\times25\) map. Our decoder explicitly resizes to each saved encoder map’s dimensions.
Matching tensor shapes is necessary, but image and mask coordinates must also agree. Apply the same geometric augmentation to both. Use nearest-neighbor interpolation for categorical masks so resizing does not invent fractional class labels; images can use bilinear interpolation. Intentional soft-label supervision is a separate choice. A fully convolutional design still has minimum-size and alignment constraints.
We now have a complete image-to-logit computation: encode at several scales, decode with access to the saved features, and apply a pixelwise prediction head. The architecture makes these information paths available, but its weights still need to learn which features are useful. That requires an objective built from the annotated masks.
20.6 Training and evaluating the segmentation model
20.6.1 Begin by learning from scratch
Our first training approach starts both the encoder and decoder from random weights. This is training from scratch. The annotated images must teach the encoder to extract useful representations and the decoder to turn those representations into a mask.
For each minibatch, the model produces logits, the loss compares them with the target labels, and backpropagation computes gradients through the prediction head, decoder, and encoder. The optimizer then updates the parameters. Repeating this process allows the whole network to learn the segmentation task together.
For binary segmentation in PyTorch, logits and floating-point targets should both have shape \((N,1,H,W)\). Keeping the channel dimension in the target aligns each foreground label with its corresponding logit.
20.6.2 Apply binary cross-entropy at every pixel
Each target pixel provides a binary label, so binary cross-entropy extends naturally from classification. For a minibatch containing \(M=NHW\) pixels, let \(p_{nhw}=\sigma(z_{nhw})\). The mean loss is
On a foreground pixel, the loss penalizes a low foreground probability. On a background pixel, it penalizes a high one. Signals from all these positions contribute to learning the shared convolutional filters.
In practice, BCEWithLogitsLoss takes logits directly and evaluates this loss more stably than a separate sigmoid followed by logarithms. We therefore leave sigmoid out of the model’s final layer when using this loss. We apply it separately when we need probability maps.
20.6.3 Evaluate the foreground region
A training loss tells us how closely predictions match the objective, but we also need to evaluate the masks used for measurement. Pixel accuracy can give a misleading impression when most pixels are background. If a \(10\times10\) target contains five foreground pixels, predicting background everywhere gives \(95\%\) accuracy while finding none of the object.
Two common foreground overlap measures are Dice and intersection over union, or IoU. Let \(P\) be the set of predicted foreground pixels and \(Y\) the set of true foreground pixels:
Here, \(TP\) counts correctly predicted foreground pixels, \(FP\) counts background pixels incorrectly marked foreground, and \(FN\) counts foreground pixels that were missed. Correctly predicted background pixels do not enter either score, so abundant background cannot hide a complete foreground failure.
Prediction for the five-pixel foreground target
\(TP\)
\(FP\)
\(FN\)
Pixel accuracy
Foreground Dice
Foreground IoU
Background everywhere
0
0
5
\(95\%\)
\(0\)
\(0\)
Find three foreground pixels and add one false positive
3
1
2
\(97\%\)
\(6/9=2/3\)
\(3/6=1/2\)
The second prediction changes accuracy only slightly, while the overlap scores reveal that it finds part of the object. In our experiments, we threshold probabilities at \(0.5\), calculate Dice and IoU for each image, and average over images. If both masks are empty, we assign a score of one; if exactly one is empty, we assign zero.
Figure: Visual depiction of IoU and Dice metrics (and loss). Figure source.
20.6.4 Explore interactively: what do segmentation metrics measure?
Largest nearest-boundary separation across both directions; sensitive to outliers.
Lower.
95th-percentile Hausdorff distance (HD95)
A percentile-based boundary distance that reduces the influence of extreme outliers.
Lower.
Normalized surface Dice (NSD)
Fraction of boundary within a chosen tolerance of the other mask’s boundary.
Higher; state the tolerance.
Try these controlled changes, keeping the reference mask fixed:
Copy the reference into the prediction, then drag the prediction sideways. Compare overlap and boundary scores.
Paint a small false-positive island far away. Which distance score changes most? Compare HD with HD95.
Erase a small structure. Can overlap remain high despite missing it?
Keep both masks fixed and change the NSD tolerance. Why does the score change without improving the prediction?
Record before/after values and explain which metric reflects the error that matters for the task. Distances and tolerances here use pixels; physical measurements also require pixel spacing. Empty-mask conventions can differ between implementations: check them before comparing values with our lab.
Dice measures the overlap we care about, so we might also want the training objective to encourage it directly. However, thresholding has zero derivative almost everywhere. We cannot use ordinary backpropagation through a hard binary decision to obtain a useful gradient.
Soft Dice replaces the hard predictions with probabilities. For image \(n\), its loss is
where \(\epsilon>0\) prevents division by zero. Assigning probability to true foreground contributes to the numerator; assigning it elsewhere increases the denominator without contributing to the foreground match. Unlike BCE, this loss links pixels through an image-level overlap ratio.
The teaching experiments combine the two objectives:
BCE provides a local learning signal, while soft Dice adds an explicit foreground overlap objective. Equal coefficients are the choice for this example; other tasks may need different weighting. Training uses continuous predictions, while the reported hard Dice evaluates thresholded masks. Improving the training objective therefore need not improve hard Dice at every step.
20.6.6 Put the first complete system together
We can now train a U-Net from scratch and evaluate it on unseen images. An input becomes encoder features, decoder features, and finally a logit map. The annotated mask supplies the training signal. After training, sigmoid and thresholding produce a predicted mask for overlap scoring and foreground-area measurement. The lab implements this complete U-Net workflow.
The next question concerns the training data. Each annotated image supplies many pixel labels, but neighboring pixels describe the same objects and are strongly related. A small collection of annotated images still offers limited variation. Could we begin with an encoder that has already learned useful patterns, instead of asking this collection to teach everything from random weights?
20.7 Learning with limited annotations: transfer learning
20.7.1 Reuse what a model has already learned
We have now built a segmentation model and explained how it can learn from annotated masks. Its encoder must learn useful representations, while its decoder must learn how to turn those representations into spatial predictions. Training both parts from random weights is possible, but it asks the target dataset to support all of this learning. When annotations are limited, some useful patterns may be difficult to learn reliably from that dataset alone.
Transfer learning offers another starting point: use knowledge learned in one setting to support learning in another. In neural networks, a common form of transfer is to reuse pretrained weights. These weights encode transformations learned through previous training, so the target model begins with representations that may already contain useful structure.
For images, such representations may capture edges, textures, shapes, or object-level patterns. For text, they may encode relationships between words and their contexts. For audio, they may represent acoustic patterns that support recognition. The details depend on the model and its training objective, but the central question stays the same: can something learned previously help the new task?
Transfer learning is a general learning strategy, not a segmentation architecture. It can support classification, regression, object detection, segmentation, speech recognition, text classification, and sequence generation, among other tasks. We use U-Net to make the idea concrete because its encoder and decoder are already familiar. The method also applies to other networks and data types.
Limited annotations are an important motivation, but they are not the only one. Reusing a trained model may reduce the target training effort or provide useful representations that would be expensive to learn again. These are potential benefits to evaluate, rather than outcomes guaranteed by loading a checkpoint.
20.7.2 Distinguish the source and target settings
The source task is the task through which the model first learns. The target task is the task we want to solve using some of that learning. Each task also has a domain: the kinds of inputs and conditions represented in its data. For images, domains can differ in subject matter, acquisition equipment, contrast, or noise. For text and speech, they can differ in vocabulary, writing style, language, or recording conditions.
The source and target may differ in their task, their domain, or both:
Transfer situation
What changes?
Illustrative application
Same task, different domain
Input conditions or data distribution
Adapt an image classifier to images acquired under different conditions.
Different target categories
Meaning or number of output labels
Reuse an image encoder to classify a new collection of object categories.
Different task, related inputs
Required output and prediction objective
Reuse a classification encoder inside a segmentation or detection model.
Pretraining without target-style labels
Initial learning objective and supervision
Adapt representations learned by predicting missing content to a supervised classification or regression task.
The source task does not have to use manually annotated labels. Self-supervised pretraining constructs a learning objective from the data itself, such as predicting missing portions of an input. The resulting representations can then be adapted to a downstream task. In supervised target training, we still need labels appropriate to the target output, even if the source representations were learned without such labels.
The running segmentation example illustrates domain change: features learned from one image collection may help segment another with different contrast or noise. However, transfer does not require keeping the segmentation task, the foreground definition, or even the same type of prediction head. What matters is whether the reused representations contain information useful for the target.
20.7.3 Specify what is transferred and what is newly learned
It helps to describe a model as a feature extractor followed by a task-specific prediction component:
\[
\widehat{Y}=G_\phi(E_\theta(X)).
\]
Here, \(E_\theta\) transforms the input into representations, and \(G_\phi\) maps them to the required output. The representation might be a feature vector, a collection of spatial feature maps, or a sequence of token representations. The prediction component might be a small head or a substantial decoder. Its design depends on the target task.
Target task
Possible prediction component
Required output
Classification
Classification head
Class scores
Regression
Regression head
Continuous values
Object detection
Detection head
Object locations and class scores
Segmentation
Spatial decoder and pixelwise head
A spatial map of predictions
Sequence generation
Sequence prediction component
Predictions for successive output tokens
This decomposition is useful for understanding transfer, although some models reuse most or all of their network rather than a separately named encoder. In U-Net, the encoder supplies feature maps at several resolutions, and the decoder uses them to produce the segmentation output.
A common transfer procedure copies source-trained feature-extractor weights \(\theta_s^*\) and initializes a new target prediction component:
The superscript \((0)\) denotes the start of target training, and \(\phi_t^0\) denotes fresh target weights. We transfer learned numerical weights and relevant saved model state. The feature extractor then computes new representations for each target input; we are not copying source labels or a fixed collection of source feature maps.
Replacing the prediction component is useful when the target requires different labels or a different output structure. A classifier’s image-level head, for example, cannot directly provide a segmentation mask. Its feature extractor may still be useful when connected to a suitable spatial decoder.
When the source and target prediction components are compatible, we can also reuse some or all of that component. Transferring an entire segmentation model is therefore possible, as is adapting a complete language model. Reusing only the feature extractor and reusing the whole model are different experimental choices, so we should state which parameters are transferred and which are initialized afresh.
Figure: A transfer learning setting where the feature extractor from a model trained on Task 1 is used in Task 2 with a new prediction head. Figure source.
20.7.4 Separate initialization from adaptation
Loading pretrained weights determines where target training starts. It does not determine which weights may change afterward. Freezing and fine-tuning control that second decision.
With a frozen feature extractor, target training updates only the prediction component:
Here, \(J_t\) is the target training objective. The prediction component learns to interpret fixed representations. In classification, this might mean training a new classification head. In segmentation, it might mean training a nonlinear decoder on fixed encoder maps. This approach is called feature extraction and does not require the trainable prediction component to be linear.
With full fine-tuning, target training can update both the reused feature extractor and the prediction component:
The pretrained representation now adapts to the target task and data. A new task may require different distinctions, while a new domain may require different responses to the input conditions. Fine-tuning allows target supervision to change these representations instead of learning only how to use them. The optimization expressions identify the trainable parameters; they do not imply that training finds a global minimum.
Partial fine-tuning updates selected parts of the pretrained network while keeping the others fixed. For an encoder, this may mean updating some blocks. Other designs may use small added trainable components while freezing most pretrained weights. The shared principle is to restrict the parts that adapt, rather than update the entire model.
Approach
Feature-extractor initialization
Feature-extractor updates
Target prediction component
Training from scratch
Random weights
All intended blocks
Trained from its initial weights
Frozen feature extraction
Pretrained weights
None
Trained on fixed representations
Partial fine-tuning
Pretrained weights
Selected parameters or blocks
Trained alongside the selected parameters
Full fine-tuning
Pretrained weights
All intended blocks
Trained alongside the feature extractor
Figure: Different transfer learning approaches. Figure generated using Google Nano Banana 2.1.
This table assumes a trainable target prediction component. Its initialization is another declared choice: the common procedure above uses fresh weights, while compatible source weights may also be reused.
20.7.5 Distinguish feature extraction from a linear probe
A linear probe freezes the representation and fits only a linear prediction rule. For segmentation, a \(1\times1\) convolution on a fixed feature grid supplies an affine logit at each location. A sigmoid may convert the logits into probabilities; linearity refers to the score as a function of the frozen features. If the grid is coarse, the probe also needs an explicitly specified output-alignment rule.
Our frozen-encoder U-Net trains a decoder containing multiple convolutions and ReLUs. It is frozen feature extraction, but it is not a linear probe. A randomly initialized frozen encoder is another distinct condition: it tests what can be learned from random fixed features, rather than from source-trained ones. Freezing alone does not create pretraining.
20.7.6 Freezing parameters and setting evaluation mode solve different problems
In PyTorch, requires_grad_(False) prevents gradients from being accumulated for those parameters. Build the optimizer from the intended trainable parameters; when unfreezing later, add the newly trainable parameters or rebuild the optimizer deliberately.
Calling eval() changes the behavior of modules such as dropout and BatchNorm. It does not disable gradients. Conversely, freezing parameters does not stop BatchNorm running statistics from changing in training mode. A frozen pretrained encoder may therefore need evaluation mode while its new decoder remains in training mode. Declare whether normalization statistics should adapt, and reapply the intended encoder mode if a training loop calls model.train(). Our tiny U-Net contains neither BatchNorm nor dropout, so these mode differences do not affect its encoder. See the PyTorch module documentation.
20.7.7 Decide how much adaptation the target needs
Freezing is useful when pretrained features already support the target task and target data are limited. Fine-tuning allows those features to change when the task or input conditions differ, but introduces more adjustable parameters and a greater risk of overfitting. Partial fine-tuning provides an intermediate choice.
A practical starting point is to train the new prediction component with the feature extractor frozen, then test whether unfreezing improves validation performance. When adapting pretrained parameters, a smaller learning rate than for freshly initialized parameters is a common starting choice. The best regime still depends on the target data.
20.7.8 Check whether transfer actually helps
Useful source performance does not guarantee useful target performance. Compare transfer with an appropriate baseline, such as the same architecture trained from scratch, using independent target data. Negative transfer occurs when reuse performs worse than the baseline under the stated training and tuning budget. Use validation results and representative errors to assess whether reuse and adaptation help.
20.7.9 Explore interactively: freezing and fine-tuning
Use Nipun Batra’s Freeze or Fine-tune? to change the adaptation strategy, frozen-block count, and target dataset size. Open the link separately if the embedded view does not load or needs more space.
Hold dataset size fixed and compare scratch training, a frozen backbone, and fine-tuning. Identify which blocks can update.
Change the freeze depth and inspect the trainable-parameter count.
Increase dataset size and compare the training and validation curves. What hypothesis about overfitting would you investigate in our lab?
These curves are generated illustrations, not measurements from neural-network training. Their ranking reflects the simulator’s assumptions. Dataset size alone does not determine the best strategy: source–target similarity, optimization, and tuning budgets also matter. Compare its suggested ranking with our controlled transfer experiment, including the frozen-transfer failure.
For an activity that actually trains a classifier, try Google’s Teachable Machine. Collect or upload two classes of ordinary objects, train, then test new views and backgrounds. Google’s companion codelab explains the pretrained MobileNet feature extractor and new classifier. This demonstrates classifier adaptation; use our lab for U-Net encoder adaptation and explicit freeze/unfreeze comparisons.
20.7.10 Applying transfer learning to our U-Net
In our U-Net, the encoder blocks produce \(E_1\), \(E_2\), and the bottleneck \(B\). The decoder blocks produce \(D_2\) and \(D_1\), followed by the pixelwise prediction head. Transfer learning can reuse the encoder while the target decoder learns to predict masks from its representations.
A direct way to obtain compatible pretrained weights is to train the same U-Net on a source segmentation dataset. We then copy the learned weights of its encoder blocks into the target U-Net and randomly initialize the decoder blocks and prediction head. This focuses the experiment on encoder reuse. If source and target outputs are compatible, transferring the decoder and head too is another possible choice.
The copied objects are weights, not the feature maps themselves. Each target image still produces its own \(E_1\), \(E_2\), and \(B\). The skip connections continue to supply those encoder maps to the decoder, including when the encoder weights are frozen.
We can now apply the adaptation regimes to specific parts of the network:
Regime
Encoder blocks
Decoder blocks and prediction head
Frozen transfer
Freeze all blocks producing \(E_1\), \(E_2\), and \(B\).
Train all.
Partial fine-tuning
For example, freeze the blocks producing \(E_1\) and \(E_2\), but update the block producing \(B\).
Train all.
Full fine-tuning
Update all pretrained encoder blocks.
Train all.
Training uses the pixelwise BCE plus soft Dice objective introduced earlier. Backpropagation updates the decoder and head, together with whichever encoder blocks are trainable. Evaluate the resulting masks using foreground Dice and IoU, and inspect their boundaries and missed objects. The image-to-mask computation stays the same; initialization and trainability determine how its parameters are learned.
20.8 Comparing the approaches fairly
For the transfer comparison, keep the target U-Net, data split, decoder initialization, loss, augmentation, and training budget consistent across regimes. Declare the optimizer settings and any separate learning rates. If regimes are tuned separately, give them comparable validation-search budgets. Report source pretraining resources separately from target training resources.
Split independent cases before extracting patches, and check that source pretraining does not include target evaluation cases. Use validation data to select the regime and settings, then assess the selected procedure on a reserved test set. Keep thresholds and metric conventions fixed. For area measurement, evaluate area error alongside overlap.
The lab implements scratch training, frozen encoder transfer, and full fine-tuning. The optional additional material extends the comparison with a random-frozen control, partial fine-tuning, and differential learning rates.
20.9 Generalization and dataset-related challenges
Many labeled pixels do not imply many independent examples. Images from the same patient or specimen can share acquisition artifacts and biological structure. Split at the independent-case level before tiling, and keep preprocessing estimates and model selection confined to training and validation data.
A classification-pretrained encoder can supply spatial features, but its original pooled classification head cannot directly predict a mask. A segmentation decoder needs suitable intermediate feature grids, compatible channel counts, and a declared input preprocessing policy. For example, transferring from RGB pretraining to one-channel microscopy requires an explicit input-channel adaptation; loading weights alone does not resolve that mismatch.
Overlap scores also have limits. A large correctly segmented object can dominate Dice while a small object is missed completely. A semantic union mask merges touching instances, so accurate foreground area does not establish accurate cell counts. Choose additional area, boundary, or instance-aware measures to match the intended task.
Finally, the synthetic source and target images in our exercises simplify real morphology and annotation uncertainty. Their results test the declared learning procedure under a controlled generator change. They do not establish performance on real microscopy or a universal ranking of transfer strategies.
20.10 Chapter summary
This chapter explained transfer learning and fine-tuning alongside the U-Net architecture. The running segmentation example showed how an encoder–decoder combines spatial features and how source-trained weights can be reused or adapted with limited target annotations.
Segmentation predicts where objects are. Semantic segmentation assigns a category to each pixel. It supports measurements such as occupied area, but a foreground union mask does not distinguish touching object instances.
U-Net combines context with spatial detail. The encoder builds progressively coarser representations. The decoder increases spatial resolution and combines its features with saved encoder maps through matching-scale skip connections.
Upsampling and convolution have different roles. In our teaching variant, bilinear resizing enlarges the feature grid. Padded, stride-one convolutions then combine and refine features while preserving that grid. Concatenation stacks channels and requires matching spatial dimensions.
Training and evaluation use different forms of the prediction. The head produces pixelwise logits. BCE and soft Dice provide training signals, while thresholded masks support foreground Dice, IoU, and measurements such as area error.
Transfer learning changes the starting weights and their adaptation. Our target U-Net can reuse the encoder blocks producing \(E_1\), \(E_2\), and \(B\), while learning a new decoder and prediction head. Freezing, partial fine-tuning, and full fine-tuning determine which encoder weights may change. Each target input still generates new feature maps.
Transfer learning extends beyond segmentation. Reused representations can support classification, regression, detection, and tasks involving text or audio. Their usefulness must be tested against an appropriate baseline on independent target cases; pretraining does not guarantee improvement.
20.11 Review questions
20.11.1 Explain the segmentation system
Why is an image-level class label insufficient for measuring the area occupied by cells? What additional information would instance segmentation provide?
Why does an encoder reduce spatial resolution? Explain what this helps the model represent and what information downsampling can discard.
Why can neither bilinear resizing nor a learned upsampling operation uniquely recover all information lost during pooling? How do encoder skips help?
Explain the sequence resize, concatenate, convolve in our decoder. Which operation increases height and width, which changes the input channel count, and which learns to combine features?
An upsampled decoder map has \(C_u\) channels and its matching encoder map has \(C_e\) channels. What must match before concatenation, and how many channels does the concatenated tensor contain?
Distinguish logits, probabilities, and hard masks. Why can an all-background prediction have high pixel accuracy but poor foreground Dice? Why is soft Dice more suitable for gradient-based training than thresholded Dice?
20.11.2 Explain transfer learning on our U-Net
Define source task, target task, and domain. Explain how transfer can change the image conditions, the prediction task, or both.
Describe how to initialize our target U-Net using a source-trained encoder. Identify which weights are copied and which components are newly initialized.
What happens to \(E_1\), \(E_2\), and \(B\) when a target image passes through a frozen encoder? Do the skip connections still supply features to the decoder?
Compare frozen feature extraction, partial fine-tuning, and full fine-tuning. Which parameters receive updates in each case? Why is loading pretrained weights a separate decision from freezing them?
Why is a nonlinear decoder on a frozen encoder not a linear probe? How do requires_grad_(False) and eval() differ?
How could a classification-trained encoder support segmentation? Explain the changes needed for the prediction component, intermediate features, and input compatibility. How would the same transfer principle support regression?
20.11.3 Apply and evaluate the ideas
Design a comparison of scratch training and fine-tuning using the same target U-Net. What should be controlled, how should independent cases be split, and what roles should validation and test data play?
Transfer achieves better training performance but worse validation performance than scratch training. What possible explanations would you investigate? How would you assess whether negative transfer occurred?
Two segmentation models have similar Dice scores but different errors in measured area and object boundaries. Why might this happen, and what additional evaluation would help choose between them?
20.12 Selected further reading
These resources follow the chapter’s progression: understand the architecture, implement reuse, then examine why transfer succeeds or fails.
20.12.1 Foundational papers
U-Net: Convolutional Networks for Biomedical Image Segmentation — Ronneberger, Fischer, and Brox (2015). Read the architecture section alongside its network diagram. Identify the contracting path, expanding path, and matching-scale connections. Compare the original design with our compact resize-based variant, particularly its upsampling and spatial alignment.
Fully Convolutional Networks for Semantic Segmentation — Long, Shelhamer, and Darrell (2015). Explains how classification networks can become dense predictors and how coarse and fine features can be combined. It provides a useful bridge between classification, segmentation, and transfer learning.
How transferable are features in deep neural networks? — Yosinski and colleagues (2014). Investigates feature reuse across tasks and layers. Focus on how task differences and interactions between layers affect transfer; use the results to question simple rules about always freezing early layers.
20.12.2 Practical tutorials and visual explanations
PyTorch: Transfer Learning for Computer Vision — official tutorial. Demonstrates fine-tuning and frozen feature extraction for classification. Follow the changes to the prediction head, trainable parameters, and optimizer, then explain how the same choices apply to our U-Net encoder and decoder.
CS231n: Transfer Learning — Stanford course notes. A concise explanation of pretrained feature extraction and fine-tuning. Read it when considering how target dataset size and similarity to the source setting might influence an adaptation strategy.
Deconvolution and Checkerboard Artifacts — Odena, Dumoulin, and Olah (2016). An illustrated article about uneven overlap in transposed convolutions and alternatives such as resizing followed by convolution. Use its visualizations to understand how an upsampling design can influence output artifacts.
20.13 More advanced topics
These topics extend the chapter rather than being prerequisites for understanding it.
20.13.1 Volumetric segmentation
A two-dimensional model processes image planes; volumetric data also contain structure across planes. 3D U-Net, by Çiçek and colleagues (2016), extends U-Net to volumetric segmentation. Investigate how three-dimensional operations change the available context, memory requirements, and treatment of unequal voxel spacing.
20.13.2 Configuring the complete segmentation pipeline
Architecture is only part of a segmentation method: preprocessing, patch sampling, resolution, training, and postprocessing also matter. nnU-Net, by Isensee and colleagues (2021), studies automatic configuration of this pipeline. Its official implementation offers a practical starting point for exploring dataset-dependent choices.
20.13.3 Pretraining without source annotations
Transfer learning can begin with unlabeled source data. SimCLR, by Chen and colleagues (2020), learns visual representations through a contrastive objective applied to augmented views. Explore how such an encoder could later support classification or segmentation, and which augmentations preserve information important to the target task.
20.13.4 Evaluation beyond a single overlap score
Different applications require different evidence: overlap, boundary placement, object detection, or measurement accuracy. Metrics Reloaded(Maier-Hein et al. 2024) provides a framework for selecting metrics from the problem’s requirements. Use the semantic-segmentation selection tool to design an evaluation, and the interactive metrics activity to investigate how those scores respond to different errors.
20.14 What to watch
Use these videos to reinforce the explanations, then return to the chapter or code to check your understanding.
Detection and Segmentation — Stanford CS231n, Lecture 11. A broader lecture that places semantic segmentation alongside detection and instance segmentation. Focus on dense prediction and upsampling. After watching, explain why predicting an image label, locating an object, and assigning pixel labels require different outputs.
PyTorch Image Segmentation Tutorial with U-NET — Aladdin Persson. A code walkthrough for implementing and training U-Net. Pause at each encoder and decoder stage to trace tensor shapes and skip concatenation. Compare its implementation choices with our teaching variant instead of assuming every U-Net uses identical blocks.
Transfer Learning — Andrew Ng, DeepLearning.AI. An accessible introduction to reusing learned representations for a new task. After watching, explain which parts of our U-Net would be reused, which would be newly trained, and how freezing differs from fine-tuning.
When following an implementation, identify its upsampling operation explicitly. Our decoder uses bilinear resizing followed by padded convolutions; other U-Net variants use learned transposed convolutions. Keep the roles of spatial enlargement and feature refinement distinct.
Long, Jonathan, Evan Shelhamer, and Trevor Darrell. 2015. “Fully Convolutional Networks for Semantic Segmentation.”Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, 3431–40. https://doi.org/10.1109/CVPR.2015.7298965.
Maier-Hein, Lena, Annika Reinke, Patrick Godau, et al. 2024. “Metrics Reloaded: Recommendations for Image Analysis Validation.”Nature Methods 21 (2): 195–212. https://doi.org/10.1038/s41592-023-02151-z.
Ronneberger, Olaf, Philipp Fischer, and Thomas Brox. 2015. “U-Net: Convolutional Networks for Biomedical Image Segmentation.”Medical Image Computing and Computer-Assisted Intervention.