Sub topic 11
Beyond IoU: GIoU, DIoU, and CIoU
This chapter assumes you can compute plain IoU (Intersection over Union) for two axis-aligned boxes in (x1, y1, x2, y2) form. It also assumes you know what a loss function and a gradient are. You do not need to have trained a detector. The ideas are explained from the box geometry.
Earlier chapters used IoU for two jobs: deciding whether a detection matches a ground-truth box, and deciding which duplicates non-maximum suppression (NMS) removes. IoU is a good yardstick for those jobs. It is a poor training signal, and the metrics in this chapter were designed to fix that.
Where IoU falls short
Training a box regressor means turning "how wrong is this box" into a number the optimizer can reduce. Directly minimizing 1 - IoU is attractive because it matches the evaluation metric. It has three problems:
- No signal for disjoint boxes. If the predicted and ground-truth boxes do not overlap, IoU is 0 whatever the distance between them. The loss is flat, so the gradient with respect to the box coordinates is zero. The optimizer gets no hint about which way to move.
- No sense of how the boxes overlap. Many different arrangements give the same IoU. A small box in the corner of a large one and a small box in its center can have identical IoU, yet the centered one is clearly the better prediction.
- No direct preference for shape. Two predictions with the same IoU can have very different aspect ratios.
The three variants each add a penalty term to IoU that addresses one of these problems.
| Metric | Formula | Fixes | Column | Column | Column | Column | Column | Column |
|---|---|---|---|---|---|---|---|---|
| IoU | `inter / union` | Baseline | ||||||
| GIoU | `IoU - ( | C | - | union | ) / | C | ` | Zero gradient for disjoint boxes |
| DIoU | `IoU - ρ² / c²` | Slow convergence, ignores center offset | ||||||
| CIoU | `IoU - ρ² / c² - α·v` | Also ignores aspect ratio |
Here C is the smallest axis-aligned box that encloses both boxes, ρ is the distance between the two box centers, and c is the diagonal length of C.
Generalized IoU (GIoU)
GIoU compares the union of the two boxes to the smallest box C that contains both:
GIoU = IoU - (|C| - |A ∪ B|) / |C|
The subtracted fraction is the share of C that neither box covers. Several properties follow:
- GIoU is at most IoU, and it equals IoU only when the union fills
Ccompletely. - For disjoint boxes, the penalty shrinks as the boxes move closer together. The loss therefore has a gradient that pulls the prediction toward the target.
- GIoU ranges from -1 (very far apart) to 1 (identical boxes).
- The loss form is
1 - GIoU, which ranges from 0 to 2.
GIoU has a weakness. When one box lies fully inside the other, C is the outer box and the union is also the outer box. The penalty is then 0 and GIoU equals IoU. In that case it cannot tell a centered inner box from a cornered one. Training with GIoU also tends to first enlarge the predicted box to overlap the target, and only then adjust it, which can slow convergence.
Distance IoU (DIoU)
DIoU penalizes the distance between box centers directly:
DIoU = IoU - ρ²(b, b_gt) / c²
where b and b_gt are the two center points and c is the diagonal of the enclosing box. Dividing by c² makes the penalty scale-free. It stays between 0 and 1 for any pair of boxes.
DIoU gives a gradient even when one box contains the other, because the centers can still differ. It also pulls the centers together without first needing the boxes to overlap, which usually speeds up convergence. DIoU ranges from -1 to 1.
Complete IoU (CIoU)
CIoU adds an aspect-ratio consistency term to DIoU:
CIoU = IoU - ρ² / c² - α·v
with
v = (4 / π²) · (atan(w_gt / h_gt) - atan(w / h))²α = v / ((1 - IoU) + v)
The term v measures the difference between the two box aspect ratios, using the angle of each box diagonal. The weight α is small when IoU is low. This means that early in training the center and overlap terms dominate, and the aspect-ratio term matters more once the boxes overlap well.
In the original paper, α is treated as a constant when computing gradients. If you implement CIoU in an autograd framework and want to follow that behavior, detach α from the graph.
Computing all four in Python
The function below takes a predicted box and a ground-truth box. It returns IoU, GIoU, DIoU, and CIoU. A small eps avoids division by zero for degenerate boxes.
import math
def box_metrics(pred, gt, eps=1e-9):
"""IoU, GIoU, DIoU, CIoU for boxes given as (x1, y1, x2, y2)."""
pw, ph = pred[2] - pred[0], pred[3] - pred[1]
gw, gh = gt[2] - gt[0], gt[3] - gt[1]
# Intersection and union
ix1, iy1 = max(pred[0], gt[0]), max(pred[1], gt[1])
ix2, iy2 = min(pred[2], gt[2]), min(pred[3], gt[3])
inter = max(0.0, ix2 - ix1) * max(0.0, iy2 - iy1)
union = pw * ph + gw * gh - inter
iou = inter / (union + eps)
# Smallest enclosing box C
cx1, cy1 = min(pred[0], gt[0]), min(pred[1], gt[1])
cx2, cy2 = max(pred[2], gt[2]), max(pred[3], gt[3])
cw, ch = cx2 - cx1, cy2 - cy1
c_area = cw * ch
giou = iou - (c_area - union) / (c_area + eps)
# Squared center distance over squared enclosing diagonal
pcx, pcy = (pred[0] + pred[2]) / 2, (pred[1] + pred[3]) / 2
gcx, gcy = (gt[0] + gt[2]) / 2, (gt[1] + gt[3]) / 2
rho2 = (pcx - gcx) ** 2 + (pcy - gcy) ** 2
c2 = cw ** 2 + ch ** 2 + eps
diou = iou - rho2 / c2
# Aspect-ratio term
v = (4 / math.pi ** 2) * (math.atan(gw / (gh + eps)) - math.atan(pw / (ph + eps))) ** 2
alpha = v / ((1 - iou) + v + eps)
ciou = diou - alpha * v
return {"iou": iou, "giou": giou, "diou": diou, "ciou": ciou}
def show(label, pred, gt):
print(label, {k: round(x, 4) for k, x in box_metrics(pred, gt).items()})
gt = (0, 0, 10, 10)
show("partial overlap", (5, 5, 15, 15), gt)
show("disjoint ", (20, 20, 30, 30), gt)
show("corner inside ", (0, 0, 5, 5), gt)
show("centered inside", (2.5, 2.5, 7.5, 7.5), gt)
s = 50 ** 0.5 # a square with area 50
show("wide, IoU 0.5 ", (0, 2.5, 10, 7.5), gt)
show("square, IoU 0.5", (5 - s / 2, 5 - s / 2, 5 + s / 2, 5 + s / 2), gt)Running it prints:
partial overlap {'iou': 0.1429, 'giou': -0.0794, 'diou': 0.0317, 'ciou': 0.0317}
disjoint {'iou': 0.0, 'giou': -0.7778, 'diou': -0.4444, 'ciou': -0.4444}
corner inside {'iou': 0.25, 'giou': 0.25, 'diou': 0.1875, 'ciou': 0.1875}
centered inside {'iou': 0.25, 'giou': 0.25, 'diou': 0.25, 'ciou': 0.25}
wide, IoU 0.5 {'iou': 0.5, 'giou': 0.5, 'diou': 0.5, 'ciou': 0.4968}
square, IoU 0.5 {'iou': 0.5, 'giou': 0.5, 'diou': 0.5, 'ciou': 0.5}Each row shows one failure of the earlier metric:
- Disjoint: IoU is 0, but GIoU, DIoU, and CIoU are negative and change as the boxes move. The loss has a gradient.
- Corner versus centered inside: IoU and GIoU are both 0.25 in both cases. Only DIoU and CIoU tell them apart.
- Wide versus square: Both predictions are concentric with the target and have IoU 0.5. Only CIoU penalizes the wide box for its mismatched aspect ratio.
Using them as losses
For training, each metric becomes a loss as 1 - metric. A typical detector computes this loss over the predicted boxes that were matched to ground truth during training, then averages it. Some practical points:
- The loss is only as good as the matching. A prediction matched to the wrong ground-truth box produces a large loss that no variant fixes.
- IoU-based losses are scale invariant. A 5-pixel error is a big deal for a small box and negligible for a large one. Older L1 and L2 coordinate losses do not have this property.
- Many detectors combine an IoU-family loss with a separate classification loss and weight the two with a tuned constant.
DIoU in non-maximum suppression
DIoU also works inside NMS. Standard NMS removes any box whose IoU with a higher-scored kept box exceeds a threshold. In crowded scenes, two neighboring objects can have heavily overlapping boxes, and plain NMS wrongly removes one of them. DIoU-NMS suppresses a box only if IoU - ρ²/c² exceeds the threshold. Boxes whose centers are far apart are less likely to be treated as duplicates.
Append this to the same file as box_metrics:
def nms(boxes, scores, threshold, metric="iou"):
"""Greedy NMS. metric is 'iou' or 'diou'. Returns indices of kept boxes."""
order = sorted(range(len(boxes)), key=lambda i: -scores[i])
keep = []
while order:
best = order.pop(0)
keep.append(best)
order = [j for j in order
if box_metrics(boxes[j], boxes[best])[metric] <= threshold]
return keep
boxes = [(0, 0, 10, 10), (4, 0, 14, 10), (8, 0, 18, 10)]
scores = [0.9, 0.8, 0.7]
print(nms(boxes, scores, 0.4, "iou")) # [0, 2]
print(nms(boxes, scores, 0.4, "diou")) # [0, 1, 2]The middle box has IoU 0.43 with the first, which is above the 0.4 threshold, so plain NMS removes it. Its DIoU is about 0.37 because the centers are 4 units apart, so DIoU-NMS keeps it.
What this means for evaluation
These metrics change how a model is trained and, sometimes, how duplicates are filtered. They do not change how a detector is scored. The mAP protocols from the earlier chapters, both Pascal VOC and COCO, still use plain IoU to decide whether a detection is a true positive. This has several consequences:
- A model trained with CIoU can score a higher mAP than one trained with L1 loss. The improvement shows up through better-localized boxes, especially at strict IoU thresholds such as 0.75 and above.
- You should not report GIoU, DIoU, or CIoU values as if they were IoU. They can be negative, and they cannot be compared with IoU thresholds like 0.5.
- If you compare two papers, check which NMS variant each used. Swapping NMS from IoU to DIoU can change AP without any change to the network.
- Gains from a better loss are often small and uneven. They are largest at high IoU thresholds, so look at [email protected] and AP@[0.5:0.95] before concluding that a loss helps.
Common errors
- Using the wrong box format. The code assumes
(x1, y1, x2, y2). Passing(x, y, w, h)produces silently wrong values, including negative areas. - Forgetting the empty-box case. A zero-area box makes
atan(w / h)unstable. Keep a smalleps, or filter degenerate boxes before computing the loss. - Backpropagating through
α. If you follow the original CIoU recipe, detachαfrom the graph. - Mixing up metric and loss. The metric is larger when boxes agree. The loss is
1 - metric. - Using the penalized value for matching in evaluation. Matching in mAP uses plain IoU. Using GIoU there changes the threshold's meaning.
- Assuming CIoU always wins. The aspect-ratio term can slightly hurt when ground-truth boxes are noisy or inconsistent in shape. Compare on your own data.
Exercise
A predicted box (0, 0, 4, 4) and a ground-truth box (6, 0, 10, 4) do not overlap. Compute IoU and GIoU. Then explain which of the two gives a useful training gradient.
Show answer
Each box has area 16, so the union is 32 and the intersection is 0, giving IoU = 0. The enclosing box is (0, 0, 10, 4) with area 40. GIoU = 0 - (40 - 32) / 40 = -0.2. IoU is 0 for every position of the prediction that stays disjoint from the target, so its gradient is zero and gives no direction. GIoU changes as the boxes move, because the enclosing box grows or shrinks. Moving the boxes closer reduces the penalty, so GIoU gives a useful gradient.
Exercise
A ground-truth box is (0, 0, 10, 10). Prediction P1 is (0, 0, 5, 5). Prediction P2 is (2.5, 2.5, 7.5, 7.5). Both have IoU 0.25. Which of IoU, GIoU, and DIoU can tell them apart, and why?
Show answer
Only DIoU can. For both predictions the enclosing box is the ground-truth box, so |C| equals the union and the GIoU penalty is 0, giving GIoU = IoU = 0.25 for both. For DIoU, P2 has the same center as the ground truth, so its penalty is 0 and DIoU = 0.25. P1 has center (2.5, 2.5) against (5, 5), so ρ² = 12.5 and c² = 200, which gives a penalty of 0.0625 and DIoU = 0.1875. DIoU prefers the centered prediction P2.
Exercise
Why does the original CIoU definition make α smaller when IoU is low?
Show answer
α = v / ((1 - IoU) + v). When IoU is low, (1 - IoU) is close to 1 and dominates the denominator, so α is small and the aspect-ratio term barely contributes. The loss is then driven by overlap and center distance, which matter more when the boxes are far from matching. As IoU rises, (1 - IoU) shrinks and α grows, so the shape term gains weight.