Sub topic 4
Direct coordinate regression and its limits
This chapter covers the simplest way to predict keypoints: have a network output the coordinates directly. It also explains why most modern systems moved to heatmaps. It assumes you know basic Python and NumPy, how a CNN classifier is built, and how training loss works. It also assumes you know the COCO 17-keypoint layout from earlier chapters.
The idea: pose as a regression problem
A pose with K keypoints is a vector of 2K numbers, an (x, y) pair per joint. Direct coordinate regression treats this as an ordinary regression task. A backbone CNN reads the image, global pooling collapses the spatial grid into one feature vector, and a fully connected head outputs 2K values.
For COCO, the output has 34 numbers. DeepPose (2014) was an early system built this way. It also refined its predictions with a cascade of regressors on crops.
Normalizing the targets
Raw pixel coordinates make poor targets. Their scale depends on the crop size, and large values slow training. The usual fix is to express each coordinate relative to the input crop, so every value lies in [0, 1].
import numpy as np
def normalize_keypoints(xy, width, height):
"""xy: (K, 2) pixel coords in the crop. Returns coords in [0, 1]."""
return np.asarray(xy, dtype=np.float32) / np.array([width, height], dtype=np.float32)
def denormalize_keypoints(norm_xy, width, height):
"""Inverse of normalize_keypoints."""
return np.asarray(norm_xy, dtype=np.float32) * np.array([width, height], dtype=np.float32)
gt = np.array([[96.0, 40.0], [100.0, 36.0]])
n = normalize_keypoints(gt, 192, 256)
print(n)
print(denormalize_keypoints(n, 192, 256))Because the targets are normalized, the network must predict the person's position relative to the crop. This is why regression is normally used in a top-down setting, where a detector has already produced a box around one person.
Choosing a loss
The loss decides how the network treats errors of different sizes.
| Loss | Behavior | Practical effect |
|---|---|---|
| L2 (mean squared error) | Penalizes large errors quadratically | Sensitive to outliers. Pulls predictions toward the mean when the answer is ambiguous. |
| L1 (mean absolute error) | Penalizes errors linearly | More robust, and was found to work better than L2 for pose regression. |
| Smooth L1 | Quadratic near zero, linear far away | Stable gradients early and late in training. |
Only labelled keypoints should contribute to the loss. COCO marks each keypoint with a visibility flag of 0 (not labelled), 1 (labelled but occluded) or 2 (labelled and visible). A masked loss ignores the flag-0 keypoints, because their coordinates are meaningless placeholders.
import numpy as np
def masked_l1_loss(pred, target, visibility):
"""pred, target: (K, 2) normalized coords. visibility: (K,) COCO flags."""
mask = (visibility > 0).astype(np.float32)[:, None] # (K, 1)
err = np.abs(pred - target) * mask
denom = mask.sum() * 2 + 1e-9 # 2 values per labelled keypoint
return float(err.sum() / denom)
pred = np.array([[0.50, 0.15], [0.52, 0.14], [0.10, 0.90]])
target = np.array([[0.50, 0.16], [0.51, 0.14], [0.00, 0.00]])
vis = np.array([2, 2, 0])
print(masked_l1_loss(pred, target, vis))The third keypoint is unlabelled, so its large apparent error is excluded. Without the mask, the network would be trained to predict (0, 0) for joints that simply were not annotated.
A minimal regression model
The following PyTorch model shows the structure. It is complete enough to run, and it uses a small ResNet backbone with no pretrained weights so the example has no download step.
import torch
import torch.nn as nn
import torchvision
class RegressionPoseNet(nn.Module):
def __init__(self, num_keypoints=17):
super().__init__()
backbone = torchvision.models.resnet18(weights=None)
self.features = nn.Sequential(*list(backbone.children())[:-1]) # up to global pool
self.head = nn.Linear(512, num_keypoints * 2)
self.num_keypoints = num_keypoints
def forward(self, x):
f = self.features(x).flatten(1) # (B, 512)
out = self.head(f) # (B, 2K)
return out.view(-1, self.num_keypoints, 2) # (B, K, 2)
model = RegressionPoseNet()
x = torch.randn(2, 3, 256, 192)
pred = model(x)
target = torch.rand(2, 17, 2)
loss = nn.functional.l1_loss(pred, target)
loss.backward()
print(pred.shape, float(loss))The head is a single linear layer that maps a 512-number summary of the whole image to 34 outputs. No part of the model is tied to a specific image location. That design choice causes most of the limits below.
Limits of direct regression
The spatial structure is thrown away
Global pooling discards where features occurred. The network must then recover precise positions from a position-free summary. A convolutional feature map is spatially organized, and a linear layer on a pooled vector does not use that organization. Heatmap methods keep the spatial grid until the very end.
The mapping is highly nonlinear
A small shift of an arm in the image must become a precise change in specific output numbers. The fully connected layer has to learn this mapping from data alone. This needs many examples and tends to generalize poorly to poses that are rare in the training set.
Translation equivariance is lost
Convolutions are translation equivariant, which means shifting the input shifts the feature map by the same amount. A fully connected output layer does not have this property. A shifted person produces an unrelated change in the output vector. Heatmaps recover the property, because a shifted person shifts the heat peak.
Precision is limited at strict thresholds
Regression can locate the rough layout of a body, but its pixel-level error is usually larger than that of heatmap models. Metrics such as keypoint AP at a high OKS threshold (covered in a later chapter) expose this gap.
Ambiguity averages out
Suppose a wrist could plausibly be at one of two places, for example when a left-right ambiguity cannot be resolved. A model trained with L2 loss minimizes error by predicting the midpoint, which is wrong in both cases. A heatmap can show two peaks and keep the ambiguity visible. L1 loss behaves like a median, which reduces the problem but does not remove it.
Output is tied to one person
A fixed-size vector holds exactly one pose. Regression therefore does not handle crowds by itself. It needs a detector to supply crops, or a different design that predicts one pose per candidate location.
No natural confidence
A heatmap peak value gives a per-keypoint score. A regression head outputs coordinates and nothing else. Getting a confidence needs an extra output or a method such as predicting an error distribution.
What regression still does well
Regression is not obsolete. It has real advantages.
- It is fully differentiable from the image to the coordinates, with no arg-max or decoding step.
- It is fast and small, because the head is one linear layer and no high-resolution feature maps are needed.
- It has no quantization error from a grid. Heatmap coordinates are limited by the heatmap resolution unless corrected.
- It extends naturally to 3D, where an output of (x, y, z) per joint is just a longer vector.
Modern work has narrowed the accuracy gap. Integral regression takes a soft-argmax over heatmaps, so the model keeps spatial maps but is trained with a coordinate loss. Residual log-likelihood estimation (RLE) models the error as a learned distribution, which improves accuracy and also provides confidence. These methods combine the two ideas, and they show that the limits above come from the design of a plain pooled-and-linear head, not from regression as an objective.
import numpy as np
def soft_argmax(heatmap, beta=1.0):
"""heatmap: (H, W). Returns the expected (x, y) under a softmax of the map."""
h, w = heatmap.shape
flat = heatmap.reshape(-1) * beta
p = np.exp(flat - flat.max())
p /= p.sum()
p = p.reshape(h, w)
xs = np.arange(w)
ys = np.arange(h)
x = (p.sum(axis=0) * xs).sum()
y = (p.sum(axis=1) * ys).sum()
return float(x), float(y)
hm = np.zeros((8, 8))
hm[3, 5] = 10.0
print(soft_argmax(hm))Unlike a hard arg-max, this function is differentiable and can return positions between grid cells.
Choosing between them
| Situation | Better fit |
|---|---|
| Tight latency or memory budget, coarse accuracy acceptable | Direct regression |
| High accuracy at strict OKS thresholds | Heatmap-based |
| Need sub-pixel output with end-to-end coordinate loss | Integral regression or RLE |
| Need per-keypoint confidence for filtering | Heatmap-based, or regression with an uncertainty output |
| 3D joint output from a 2D pose | Regression head on 2D keypoints |
Common mistakes
- Forgetting to normalize targets, which makes training slow or unstable.
- Training on unlabelled keypoints without a visibility mask.
- Flipping an image for augmentation without also flipping the coordinates and swapping left and right keypoints. A left wrist in the flipped image must be labelled as the right wrist.
- Evaluating in normalized units and reporting the result as pixels. Always denormalize with the crop size before comparing to ground truth.
Exercise
A regression model is trained with L2 loss. In some training images, a person's wrist is equally likely to be on the left or right side of the torso because the image is ambiguous. What does the model tend to predict for those images, and which change reduces the effect?
Show answer
With L2 loss the best single prediction is the mean of the possible answers, so the model predicts a point between the two locations, which is correct in neither case. Switching to L1 loss moves the prediction toward the median and reduces the effect. Using a heatmap representation, which can hold two peaks, or an RLE-style output that models a distribution, handles the ambiguity better.
Exercise
You apply a horizontal flip to a 192-pixel-wide crop as augmentation. A normalized keypoint has x = 0.25 and is labelled "left_elbow". What are its new x value and its new label?
Show answer
The new x value is 1 - 0.25 = 0.75, because the flip mirrors the horizontal axis. The new label is "right_elbow", because the body part that was on the left side of the image is now on the right side, so left and right keypoint indices must be swapped along with the coordinates.