ML Explainer

How Neural Networks Detect Contrails

A visual guide to semantic segmentation, convolutional encoders, attention-based decoders, and the training pipeline — with minimal code and maximal intuition.

01 — The Task

Pixel-Level Segmentation

Detecting contrails in satellite imagery is a semantic segmentation problem: given a 2D image formed from multiple infrared bands, the goal is to assign every single pixel a label — contrail or background. This is more demanding than image classification, which only answers "does this scene contain a contrail?", and more precise than bounding-box detection, which merely localizes a region.

Contrails appear as thin, bright linear features embedded in a complex scene of cirrus clouds, thermal gradients, and sensor noise. Their width, persistence, and opacity carry geophysical meaning — a wide, diffuse contrail has spread as ice crystals settled over hours, while a narrow, crisp one is freshly formed. Pixel-level labels let us measure these properties directly from the output mask. A bounding box would include too much background; a single label would throw away all spatial information.

The model receives a multi-channel image formed from several VIIRS infrared channels (M15 or I5, mapped to a standard input format) and outputs a probability map of exactly the same spatial size — one probability per pixel indicating the model's confidence that the pixel is part of a contrail.

raw satellite scene contrail pixels pixel-level segmentation mask
Left: a raw infrared satellite scene containing a contrail (white diagonal feature). Right: the corresponding segmentation mask — each blue cell is one image pixel labeled as "contrail". The model's job is to produce the right panel from the left.
02 — Building Blocks

How Models See Images

The fundamental building block of nearly every modern image model is the convolutional filter. A filter is a small grid of learnable weights — typically 3×3 numbers — that slides across an image and computes a dot product with every patch it encounters. The output is a feature map: a 2D array whose value at each location encodes how strongly that particular pattern appears there.

A single filter detects one pattern. A convolutional layer applies many filters in parallel — 64, 128, or more — stacking their outputs into a tensor. At each layer, every "channel" of this tensor is the response of one filter to the input. These stacks of feature maps form the model's internal representation of the image at each level of abstraction.

The key insight is that the filters are learned from data, not hand-designed. After training on thousands of labeled images, filters in early layers spontaneously learn to detect simple patterns — horizontal edges, vertical edges, color transitions. Deeper layers recombine these simple responses to detect more complex structures: corners, textures, curved lines. By the final encoder layers, each "pixel" in the feature map effectively summarizes a large patch of the original image in terms of high-level semantic content.

For satellite imagery, this hierarchy goes from: brightness gradients → edge-like structures → thin-line features → contrail-like patterns. The model never explicitly looks for lines — it discovers the representation that best predicts the training labels.

Why not use edge detectors? Classical computer vision would design specific filters (Sobel, Canny) to find lines and then match them. Neural networks instead learn whatever filter bank the data requires — which turns out to be far more powerful for complex scenes with variable illumination, cloud interference, and sensor-specific noise.
03 — The Encoder

ResNet-18: Learning to Compress

The encoder is the "perception" half of the model. It takes the raw input image and produces a compact, information-rich representation by progressively reducing spatial resolution while extracting increasingly abstract features. Our model uses ResNet-18, developed by He et al. (2016), which introduced residual connections — arguably the single most consequential architectural innovation in modern deep learning.

ResNet-18 is organized into five stages. At each stage transition, a strided convolution halves the spatial resolution (height and width) while typically doubling the number of feature channels. Starting from a 3-channel input (the satellite bands), the network progressively builds: 64 channels at half resolution, 64 channels at quarter resolution, 128 at one-eighth, 256 at one-sixteenth, and finally 512 channels at 1/32nd of the original resolution. A 1024×1024 input becomes a 32×32×512 tensor. Each "pixel" of this small feature map represents what the network has learned about a 32×32 patch of the original scene.

Why residual connections? Training very deep networks was notoriously unreliable before ResNets. The core problem: gradients propagated backward through many layers tend to shrink exponentially (the vanishing gradient problem), causing early layers to learn extremely slowly. A residual block sidesteps this by adding the input directly to the output of a two-convolution stack:

Residual connection
$$\mathbf{y} = \mathcal{F}(\mathbf{x},\, \{W_i\}) + \mathbf{x}$$

where $\mathbf{x}$ is the block input, $\mathcal{F}(\mathbf{x})$ is the transformation learned by the two convolutions, and $\mathbf{y}$ is the block output. The skip path adds $\mathbf{x}$ directly to the transformed features.

If the optimal transformation at a given block happens to be the identity (pass input through unchanged), the block only needs to learn $\mathcal{F}(\mathbf{x}) = \mathbf{0}$ — a much easier task than learning an arbitrary transformation from scratch. More importantly, the skip connection gives gradients a direct path back through the network during training, enabling reliable optimization of dozens or hundreds of layers.

The encoder is initialized from weights pretrained on ImageNet — a dataset of ~1.2 million photographs of everyday objects. Pretraining on a very different domain might seem counterproductive, but the learned feature detectors transfer remarkably well: edges, textures, and spatial relationships are useful whether the subject is a dog, a car, or an infrared cloud scene. In the fine-tuning pipeline, the encoder weights are kept frozen — the pretrained features are treated as given, and only the final classification layer is retrained on contrail-labeled satellite data.

Linear separability check: Before fine-tuning, a quick PCA on the frozen encoder's output features tells us whether the pretrained representation already places contrail pixels in a different region of feature space from background pixels. If it does, fine-tuning only the final layer is enough. This is a principled way to avoid unnecessary computation and overfitting.
04 — The Decoder

MAnet: Reconstructing Space

After the encoder, the feature map is semantically rich but spatially coarse — 32× smaller than the input in each dimension. For segmentation, predictions are needed at every pixel of the original image. The decoder reconstructs spatial resolution progressively, stage by stage, until the original resolution is restored.

Our model uses MAnet (Multi-scale Attention network). Like the classic U-Net architecture it builds on, MAnet uses a symmetric decoder that mirrors the encoder's five stages. At each upsampling step, the decoder doubles the spatial dimensions and blends information from two sources:

1. Upsampled features from the previous decoder stage — these carry semantic content (what kind of thing is in this region?) but at coarse resolution.

2. Skip connections from the corresponding encoder stage — these re-inject high-resolution spatial detail (exactly where is the boundary?) that was lost during downsampling. Without skip connections, the decoder would need to hallucinate the fine-grained spatial structure from the compressed bottleneck alone — an impossible task for thin features like contrails.

What distinguishes MAnet from a plain U-Net is attention gates applied to the skip connections. Before merging encoder features into the decoder, an attention gate computes a spatial weight map $\boldsymbol{\alpha} \in [0,1]^{H \times W}$ that suppresses irrelevant activations and amplifies the features most useful for segmentation at that scale:

Attention gate
$$\alpha_i = \sigma_2\!\left(\psi^\top \sigma_1\!\left(W_x\,\mathbf{x}_i^l + W_g\,\mathbf{g}_i + b_g\right) + b_\psi\right)$$

$\mathbf{x}_i^l$ — skip-connection features from encoder level $l$ at location $i$
$\mathbf{g}_i$ — gating signal from the decoder (semantic context)
$W_x, W_g, \psi$ — learned weight matrices; $b_g, b_\psi$ — biases
$\sigma_1$ — ReLU; $\sigma_2$ — sigmoid (outputs a value in $[0,1]$)

The gated skip features become $\hat{\mathbf{x}}_i = \alpha_i \cdot \mathbf{x}_i^l$ — the encoder features weighted by their learned relevance.

In practice, the attention gates learn to focus on regions where contrail-like structures appear, suppressing irrelevant cloud backgrounds and reducing false positives. This is especially valuable in the VIIRS domain, where cold-topped cirrus clouds have infrared signatures similar to contrails.

ENCODER (ResNet-18) DECODER (MAnet) Input image · 3 channels H × W Stage 1 · 64 ch H/2 × W/2 Stage 2 · 64 ch H/4 × W/4 Stage 3 · 128 ch H/8 × W/8 Stage 4 · 256 ch H/16 × W/16 Bottleneck · 512 ch H/32 × W/32 Segmentation Head · 2 ch H × W → prediction Upsample ×2 · 32 ch H/2 × W/2 Upsample ×2 · 64 ch H/4 × W/4 Upsample ×2 · 128 ch H/8 × W/8 Upsample ×2 · 256 ch H/16 × W/16 ⊗ ⊗ ⊗ ⊗
Full MAnet encoder–decoder architecture. The encoder (left) progressively downsamples the input through 5 ResNet-18 stages, compressing spatial resolution while building richer feature representations. The decoder (right) upsamples back to the original resolution using both the bottleneck features (gold arc) and skip connections from each encoder stage. Attention gates (⊗) learn to weight each skip connection by relevance at that spatial scale.
06 — Training

Focal Loss and Class Imbalance

Training requires a loss function — a number that measures how wrong the current predictions are, and whose gradient tells the optimizer which direction to nudge the weights. The natural starting point for classification is cross-entropy loss:

Standard cross-entropy
$$\mathcal{L}_\text{CE} = -\log\, p_t$$

where $p_t$ is the predicted probability for the correct class. The loss is 0 when the model is perfectly confident ($p_t = 1$) and grows without bound as confidence approaches 0.

Cross-entropy has a critical weakness for contrail segmentation: class imbalance. In a typical VIIRS granule, contrail pixels account for well under 1% of the image. A model that predicts "background" for every single pixel achieves an extremely low average cross-entropy loss — yet is completely useless. The model has an easy escape hatch that the loss does not penalize.

Focal loss (Lin et al. 2017) was designed to solve exactly this problem. It modifies cross-entropy by adding a modulating factor that down-weights easy, well-classified examples:

Focal loss
$$\mathcal{L}_\text{focal} = -\alpha\,(1 - p_t)^\gamma \log\, p_t$$

$(1 - p_t)^\gamma$ is the modulating factor. When $p_t \approx 1$ (model is correct and confident), the factor is near zero — the loss contribution of that example is suppressed. When $p_t \ll 1$ (model is wrong or uncertain), the factor is near 1 — the full loss signal is preserved.

$\gamma = 2$ (focusing parameter) — controls how steeply easy examples are down-weighted.
$\alpha = 0.25$ (class weight) — gives additional emphasis to the rare contrail class.

In practice: background pixels that the model already classifies correctly with high confidence contribute nearly zero gradient — they are boring to the optimizer. Rare contrail pixels — which the model must work hard to learn — receive nearly the full gradient signal. The optimizer's attention is automatically redirected toward the hard, rare cases.

0 1 2 0.2 0.4 0.6 0.8 1.0 predicted probability for correct class, p_t Loss Cross-Entropy Focal Loss (γ=2) easy examples down-weighted here → 0 at high p_t
Focal loss (blue) vs. standard cross-entropy (red) as a function of the predicted probability for the correct class $p_t$. The shaded region shows the range where focal loss strongly suppresses the contribution of easy, correctly-classified examples — predominantly background pixels — while preserving the full learning signal for uncertain or misclassified predictions. With $\gamma = 2$, a well-classified pixel ($p_t = 0.9$) contributes less than 1% of the loss it would under standard cross-entropy.
07 — Inference

From Probability Map to Detection

At inference time, the trained model processes a full satellite scene and produces a continuous probability map: one value in $(0,1)$ per pixel, representing the model's confidence that the pixel is part of a contrail. This probability map is the model's primary output — a richer representation than a binary mask, because it encodes uncertainty.

To obtain a binary detection mask (each pixel is either "contrail" or "background"), a detection threshold $\tau$ is applied:

Threshold decision
$$\hat{y}_{ij} = \begin{cases} 1 & \text{if } p_{ij} \geq \tau \\ 0 & \text{otherwise} \end{cases}$$

where $\hat{y}_{ij} = 1$ labels pixel $(i,j)$ as a contrail, and $\tau \in (0,1)$ is a chosen threshold.

The threshold $\tau$ controls a fundamental trade-off between precision and recall:

High threshold ($\tau \to 1$): Only the most confident predictions are labeled as contrails. The detector is conservative — few false positives, but many real contrail pixels are missed. This is appropriate when downstream analysis needs clean, reliable detections.

Low threshold ($\tau \to 0$): Many pixels are labeled as contrails, including uncertain ones. Recall is high — almost all real contrails are detected — but precision is low, with more false positives. This is appropriate when completeness matters more than purity.

The Precision-Recall curve traces this entire trade-off by sweeping $\tau$ from 0 to 1. The area under this curve (PR-AUC) summarizes performance in a single number that accounts for the class imbalance: a perfect detector has PR-AUC = 1.0; a random detector has PR-AUC equal to the fraction of positive pixels (near zero for contrails).

The ROC curve is another standard evaluation tool. It plots the true positive rate against the false positive rate across thresholds. At low false positive rates (which is where we operate for rare contrail pixels), the PR curve is more informative — the ROC curve's AUC can be misleadingly high for heavily imbalanced problems, because a model can achieve low false positive rate simply by being conservative, without actually finding contrails well.

The optimal threshold depends on the application. For contrail avoidance, recall matters more — missing a persistent contrail means a missed opportunity to reroute. For climate model validation, precision matters more — false positives contaminate the comparison between observed and predicted contrail coverage. The probability map preserves the information needed for both use cases; the threshold is chosen separately for each task.