Skip to content

Image understanding, generation, and 3D reconstruction · Object detection · VIS007 · Architecture

Detection Transformer (DETR)

DETR frames object detection as direct prediction of an unordered set of objects. Bipartite matching assigns predicted queries to ground-truth objects, avoiding the original anchor-generation and NMS pipeline.

Runs as a notebook Complete calculation CodeSplash's run and the reference's record

In CodeSplash

No method yet, but the reference's example runs here as a notebook.

Do it in CodeSplash Open the reference's example as a Python or R notebook.

Availability
Runs as a notebook
Code example
Complete calculation
Who ran it
CodeSplash's run and the reference's record
CodeSplash's run
The reference's example ran in Python and R here, and they agree.
The reference's record
Python: Ran in the reference's review. The report doesn't record which version of the code ran. R: Reviewed but not run: R wasn't available to the reference's authors.

Purpose

DETR frames object detection as direct prediction of an unordered set of objects. Bipartite matching assigns predicted queries to ground-truth objects, avoiding the original anchor-generation and NMS pipeline.

Question / hypotheses

Can one-to-one set prediction learn accurate boxes and object counts without anchor design or NMS? This is a modeling/evaluation question, not a formal null-hypothesis test.

Architecture / computational structure

A CNN backbone feeds transformer encoder features; a fixed bank of decoder queries outputs class/no-object scores and normalized boxes. Hungarian assignment provides a one-to-one training correspondence.

Assumptions

Queries are prediction slots, not persistent object identities. One-to-one matching can be difficult early in training, and small-object performance depends on feature resolution. Padding masks and coordinate normalization must be correct.

Formula / computational definition

σ^=arg⁡min⁡σ∑iLmatch(yi,y^σ(i))\hat\sigma=\arg\min_\sigma\sum_i\mathcal L_{match}(y_i,\hat y_{\sigma(i)}). Training sums matched classification, L1 box and generalized-IoU losses, with no-object targets for unmatched queries. The matching cost and optimized loss need not be numerically identical.

Parameters and notation

Notation: Here y_i denotes a ground-truth object and y-hat_j a query prediction; sigma is a one-to-one assignment, L_match its matching cost, and sigma-hat the minimizing assignment. Generalized IoU adds enclosure information to ordinary box IoU.

Learned or estimated: Backbone, encoder/decoder projections and MLPs, learned object queries, classification and box heads.

Hyperparameters and effects: Query count, depth/width, matching weights, no-object weight, box-loss weights and learning-rate schedule. Too few queries limit object count; original DETR training can require long schedules.

Fitting, fine-tuning, and adaptation

Replace target label heads and initialize compatible backbone/transformer weights. Fit heads or decoder first, then unfreeze higher backbone layers with a smaller rate. Keep matching and no-object weights consistent with new class/object-count distributions. Validate source retention and object-count behavior after fine-tuning.

How to use and calibrate

Split by independent image source, scene, subject or capture sequence before augmentation; keep near-duplicate frames and crops in the same split. Measure AP, cardinality error, duplicate/missed detections, convergence and small-object recall. Compare training and inference budgets separately; removing NMS does not remove all preprocessing or output filtering.

Example application

Predict a set of object boxes directly without manually specifying anchor shapes. This is a proposed use case, not a claim of validated performance on supplied real data.

Interpretation / pitfalls

Watch out

A training loss, confidence score or attention map is not a p-value or causal explanation. Confidence calibration, annotation quality and distribution-shift performance need separate assessment. A correct component calculation does not validate the full architecture, checkpoint or deployment pipeline.

Python and R code examples

Scope: Exact tiny one-to-one query/target assignment by enumerating permutations, equivalent to solving this assignment problem; production DETR uses an efficient solver. Use the shared setup. Dependencies: NumPy / base R. Validation: Python executed; R unexecuted.

Full-model route: Python: official DETR or a verified library. R: custom native torch plus an assignment solver, or bridge. The example enumerates a tiny assignment problem exactly; production Hungarian matching scales more efficiently.

Python and R

The reference's own programs, shown as written. A component demo shows one central piece of the method; it doesn't train a full model.

Python

Complete calculation — Exact tiny one-to-one query/target assignment by enumerating permutations, equivalent to solving this assignment problem; production DETR uses an efficient solver. Use the shared setup.

Shared setup for this chapter
import numpy as np
from itertools import permutations
def softmax(x):
    x=np.asarray(x,dtype=float)
    e=np.exp(x-x.max(axis=-1,keepdims=True))
    return e/e.sum(axis=-1,keepdims=True)
def bilinear(a,y,x):
    y=float(np.clip(y,0,a.shape[0]-1)); x=float(np.clip(x,0,a.shape[1]-1))
    y0=int(np.floor(y)); x0=int(np.floor(x))
    y1=min(y0+1,a.shape[0]-1); x1=min(x0+1,a.shape[1]-1)
    dy=y-y0; dx=x-x0
    return (1-dy)*((1-dx)*a[y0,x0]+dx*a[y0,x1])+dy*((1-dx)*a[y1,x0]+dx*a[y1,x1])
cost=np.array([[.3,2.0],[1.1,.2],[.7,.9]]) # three queries, two targets
assignments=list(permutations(range(3),2))
totals=np.array([sum(cost[q,t] for t,q in enumerate(a)) for a in assignments])
best=assignments[int(np.argmin(totals))]
unmatched=sorted(set(range(3))-set(best))
assert best==(0,1) and unmatched==[2]
print('query for each target (zero-based):',best,'cost:',totals.min(),'background queries:',unmatched)
R

Complete calculation — Exact tiny one-to-one query/target assignment by enumerating permutations, equivalent to solving this assignment problem; production DETR uses an efficient solver. Use the shared setup.

Shared setup for this chapter
softmax <- function(x) {
  if(is.null(dim(x))) {e<-exp(x-max(x)); return(e/sum(e))}
  t(apply(x,1,function(v) {e<-exp(v-max(v)); e/sum(e)}))
}
bilinear <- function(a,y,x) {
  y<-min(max(y,0),nrow(a)-1); x<-min(max(x,0),ncol(a)-1)
  y0<-floor(y); x0<-floor(x); y1<-min(y0+1,nrow(a)-1); x1<-min(x0+1,ncol(a)-1)
  dy<-y-y0; dx<-x-x0
  (1-dy)*((1-dx)*a[y0+1,x0+1]+dx*a[y0+1,x1+1])+dy*((1-dx)*a[y1+1,x0+1]+dx*a[y1+1,x1+1])
}
cost<-matrix(c(.3,2,1.1,.2,.7,.9),nrow=3,byrow=TRUE)
assignments<-rbind(c(1,2),c(1,3),c(2,1),c(2,3),c(3,1),c(3,2))
totals<-apply(assignments,1,function(a) sum(cost[cbind(a,1:2)]))
best<-assignments[which.min(totals),]; unmatched<-setdiff(1:3,best)
stopifnot(all(best==c(1,2)),unmatched==3)
print(list(query_for_target_zero_based=best-1,cost=min(totals),background_queries=unmatched-1))

Sources

From the CodeSplash reference, entry VIS007.