Sub topic 8
Training: Gaussian targets, losses and augmentation
This chapter assumes you know how heatmaps represent keypoints and how they are decoded, and that you are comfortable with PyTorch-style training loops, loss functions and basic image augmentation. It covers how to turn COCO-style annotations into training targets, which losses to use, and which augmentations are safe for keypoints.
From annotation to training target
A pose model needs a target for every training image. For a heatmap model, the target is a stack of K maps, one per keypoint. Each map is small, often 64×48 for a 256×192 input, so the stride between input and heatmap is 4.
The recipe for one keypoint is:
- Take the labelled position (x, y) in input pixels.
- Divide by the stride to get a position in heatmap coordinates.
- Place a 2D Gaussian with standard deviation sigma centered at that position.
- If the keypoint is not labelled, leave the map all zeros.
The Gaussian is used instead of a single hot pixel for two reasons. A single positive pixel among thousands of zeros gives a very sparse learning signal. Annotation noise also means the "true" position is uncertain by a few pixels, so a soft peak reflects the data better than a hard one.
import numpy as np
def make_target(keypoints, visibility, stride, out_hw, sigma=2.0):
"""keypoints: (K, 2) x,y in input pixels. visibility: (K,) COCO flags.
Returns targets (K, H, W) and weights (K,)."""
h, w = out_hw
k = keypoints.shape[0]
targets = np.zeros((k, h, w), dtype=np.float32)
weights = (visibility > 0).astype(np.float32)
ys, xs = np.mgrid[0:h, 0:w]
for i in range(k):
if weights[i] == 0:
continue
cx, cy = keypoints[i] / stride
if cx < 0 or cy < 0 or cx >= w or cy >= h:
weights[i] = 0.0 # keypoint fell outside the crop
continue
d2 = (xs - cx) ** 2 + (ys - cy) ** 2
targets[i] = np.exp(-d2 / (2 * sigma ** 2))
return targets, weights
kps = np.array([[100.0, 60.0], [0.0, 0.0]])
vis = np.array([2, 0])
t, wts = make_target(kps, vis, stride=4, out_hw=(64, 48))
print(t.shape, wts, t[0].max())The function returns weights next to the targets. They matter for the loss, as described below.
Choosing sigma
Sigma is measured in heatmap pixels. It sets a trade-off.
| Sigma | Effect |
|---|---|
| Small (1 to 1.5) | Precise peaks, but sparse signal and harder optimization. Sensitive to label noise. |
| Medium (2 to 3) | Common default for 4x stride heatmaps. |
| Large (4 or more) | Easy to train, but peaks overlap and localization gets blurry. |
Sigma interacts with the stride. At a higher resolution heatmap, the same physical blur needs a larger sigma in heatmap pixels. Some methods scale sigma per keypoint type, because a hip is harder to place than an eye.
Sub-pixel error from quantization
The labelled position rarely lands on a heatmap pixel center. If you round it to the nearest pixel before drawing the Gaussian, you add a systematic error of up to half a stride (2 input pixels at stride 4). The code above avoids this by keeping the float center cx, cy. This is sometimes called unbiased data processing. Keep the same discipline at decode time: use the arg-max plus a small shift toward the larger neighbor, or a Gaussian fit, as covered in the decoding chapter.
The heatmap loss
The standard loss is mean squared error (MSE) between predicted and target heatmaps:
import torch
def heatmap_mse(pred, target, weights):
"""pred, target: (B, K, H, W). weights: (B, K) with 0 for unlabelled keypoints."""
per_kp = ((pred - target) ** 2).mean(dim=(2, 3)) # (B, K)
return (per_kp * weights).sum() / weights.sum().clamp(min=1.0)The weights mask out keypoints with visibility 0. Without the mask, the model is trained to predict an empty map for a joint that exists but was never labelled, which teaches it to suppress real joints.
Keypoints with visibility 1 (labelled but occluded) are usually treated as supervised. The annotator guessed where the joint is, and the model learns to infer hidden joints from context. Some pipelines use a lower weight for them.
Why MSE has a weakness here
Most heatmap pixels are background. A model can reach a low MSE by predicting values near zero everywhere and producing a weak, flat peak. Two common fixes are:
- Hard keypoint mining (OHKM). Compute the loss per keypoint, then back-propagate only through the top-k worst keypoints in each sample. This pushes the model to work on difficult joints such as wrists and ankles.
- Target weighting. Multiply the per-pixel error by a factor that is larger where the target is high, for example
1 + alpha * target.
Another family of losses, such as focal-style losses from CornerNet and CenterNet, treat the heatmap as a per-pixel classification problem and down-weight easy background pixels. Those appear in bottom-up and single-stage systems.
Regression-based losses
Direct coordinate regression models use L1 or smooth L1 loss on the coordinates, with the same visibility mask. Residual log-likelihood methods model the error distribution instead of assuming a fixed Gaussian, which closes much of the gap to heatmap methods. Heatmap supervision remains the stronger baseline for most uses.
Multi-stage and auxiliary supervision
Some architectures produce heatmaps at several stages or resolutions. The total loss is the sum of the losses at each output, which is called intermediate supervision. It gives gradients to early layers directly and helps deep stacks train. Bottom-up models add a second target, such as part affinity fields or embedding tags, with their own losses. Those are covered in the bottom-up chapter.
Augmentation
Augmentation matters a great deal for pose, because datasets are small compared with the variety of real scenes. Every geometric transform must be applied to the keypoints as well as to the image.
| Augmentation | Applied to keypoints | Notes |
|---|---|---|
| Random scale (about 0.65 to 1.35) | Scale coordinates | Simulates different distances. |
| Random rotation (about ±40°) | Rotate coordinates | Keep smaller for datasets with mostly upright people. |
| Random crop or translation | Shift coordinates | Update visibility for points that leave the crop. |
| Horizontal flip | Mirror x and swap left/right indices | Easy to get wrong, see below. |
| Color jitter, blur | None | Photometric only. |
| Half-body crop | Drop the lower or upper keypoints | Prepares the model for cropped people. |
The flip trap
A horizontal flip must do two things: mirror the x coordinate (x' = width - 1 - x) and swap each left keypoint with its right counterpart. If you only mirror x, the "left wrist" label ends up on the person's right wrist in the new image. The model then learns inconsistent labels, which produces the left-right swaps that you will see in the failure-modes chapter.
import numpy as np
# COCO 17-keypoint order: nose, eyes, ears, shoulders, elbows, wrists, hips, knees, ankles
FLIP_PAIRS = [(1, 2), (3, 4), (5, 6), (7, 8), (9, 10), (11, 12), (13, 14), (15, 16)]
def flip_keypoints(kps, vis, width):
"""kps: (17, 2), vis: (17,). Returns flipped copies."""
kps = kps.copy()
vis = vis.copy()
kps[:, 0] = width - 1 - kps[:, 0]
for a, b in FLIP_PAIRS:
kps[[a, b]] = kps[[b, a]]
vis[[a, b]] = vis[[b, a]]
return kps, visSwap visibility along with coordinates, or the flags no longer match the points.
Crops and visibility
After a crop or rotation, a keypoint can land outside the image. Set its weight to zero rather than clipping its position to the border. Clipping creates a fake label at the edge. The make_target function above does this check.
Training schedule and practical settings
- Input size and aspect ratio. Top-down models use a fixed crop such as 256×192. Resize the person box to this aspect ratio before cropping, padding the box rather than stretching the person.
- Box jitter. At test time the crop comes from a detector, which makes imperfect boxes. During training, perturb the ground-truth box (shift, scale) so the model sees similar noise.
- Optimizer. Adam or AdamW with a learning rate near 1e-3, decayed in steps or by cosine schedule, is a common setup. Pretrained backbones often use a smaller rate.
- Pretraining. Initialize the backbone from ImageNet weights. Pose datasets are too small to train a deep network from scratch reliably.
- Monitoring. Track the loss, but also compute keypoint accuracy on a validation set (OKS-based AP). A falling MSE does not guarantee better localization.
Common training errors
- Flat predictions. Heatmaps are nearly zero everywhere. Check that targets are scaled to a peak of 1.0, that sigma is not too small, and that the loss mask is not zeroing everything.
- Systematic offset. Predictions are shifted by a consistent amount. Check the stride used when building targets against the stride used when decoding.
- Left-right swaps in predictions. Check the flip augmentation first.
- Good training loss, poor AP. Check box jitter and whether validation uses detector boxes that differ from the ground-truth boxes used in training.
Exercise
A training sample is flipped horizontally with the image width at 192 pixels. The right wrist (index 10) was at x = 40 and the left wrist (index 9) at x = 150. Give the new x coordinate stored at index 9 and index 10 after a correct flip, and say what goes wrong if you skip the index swap.
Show answer
Mirroring gives x' = 191 - x. The old right wrist becomes 191 - 40 = 151 and the old left wrist becomes 191 - 150 = 41. After the left-right swap, index 9 (left wrist) stores 151 and index 10 (right wrist) stores 41. In the flipped image the person's left wrist is now at x = 151, so this is correct. Without the swap, index 9 would hold 41, which is the person's right wrist in the new image. The model would receive contradictory labels for "left wrist" and learn to produce left-right swaps.
Exercise
Why does the heatmap loss multiply each keypoint's error by a weight that is 0 for visibility 0, and what happens if you leave the weight out?
Show answer
Visibility 0 means the keypoint is not labelled, so the all-zero target does not say the joint is absent from the image. Without the weight, the loss penalizes any activation at that location and trains the model to suppress real joints that annotators simply did not label. The weight removes those keypoints from the loss, so they provide no gradient.