The R-CNN family: sharing work between candidate regions
R-CNN 系列
Compare R-CNN, Fast R-CNN and the original Faster R-CNN; derive box offsets and gated losses, then run RoI pooling and a small proposal network.
rcnnHow many times should we examine the same pixels?
Suppose a detector considers a thousand overlapping candidate regions. Many contain almost the same pavement, wheel or sleeve. Running a large convolutional network independently on every crop repeats much of the visual work. The R-CNN family makes this repetition a useful design question: which computation can candidates share, and which decisions must remain specific to a region?
The names mark different answers. Original R-CNN shares a region’s extracted features across class-specific classifiers, but runs the CNN for each warped region. Fast R-CNN computes an image feature map once and pools different regions from it. Faster R-CNN also uses shared image features to generate proposals. “R” here refers to regions; it is not a recurrent neural network.
| Method | Where candidates come from | What is shared | Region-level output |
|---|---|---|---|
| R-CNN | An external proposal method | Each region’s CNN features across classes | Linear class scores and box refinement |
| Fast R-CNN | External proposals | Convolutional image features across regions | Class probabilities and class-specific offsets |
| Faster R-CNN | A region proposal network (RPN) | Image features used by proposals and detection | Proposal objectness, then a Fast-style detector |
This chapter follows the CVPR2014 R-CNN paper, ICCV2015 Fast R-CNN paper and the June 2015 first preprint of Faster R-CNN. The R-CNN paper itself dates its first technical report to November 2013. The arXiv submission history gives the v1 date as 11 November 2013. Conference publication and first disclosure are different events. Original submission record, R-CNN overview and footnote, Fast R-CNN §2, Faster R-CNN v1
From a region to a refined box
Original R-CNN: reuse features across classes
The original system obtains roughly 2,000 category-independent proposals using selective search’s fast mode. It warps each region to a fixed CNN input and uses a 4,096-dimensional feature vector for class-specific linear SVM scoring. Its stated feature extractor takes mean-subtracted 227×227 RGB input. Different aspect ratios are warped into the same input dimensions; this is not aspect-ratio-preserving resizing. R-CNN §§2.1–2.2
If a region feature is a vector of length D, scoring it against C linear classifiers costs O(DC). The expensive per-region feature extraction is separate from that matrix multiplication. Sharing features across classes therefore does not imply that neighboring regions share a CNN forward pass. The paper also uses per-class suppression and box refinement. The role of NMS is to filter scored candidates, not to replace feature extraction.
For feature learning, the original system uses supervised ILSVRC pretraining followed by fine-tuning on PASCAL detection data. The class-specific linear classifiers then operate on these learned region features. This connects the proposal pipeline to transfer learning, rather than assuming the detector learns all visual features from its smaller detection dataset. R-CNN overview
Fast R-CNN: extract once, pool many regions
A shared feature map has height H, width W and F channels. Each region of interest (RoI) identifies a rectangle in that map. RoI max pooling splits the rectangle into a fixed grid and takes a maximum independently within each bin and channel. A 2×2 pooling grid produces 2×2×F values regardless of the original RoI size. Subsequent fully connected layers can therefore accept fixed-size region representations. Fast R-CNN §§2–2.1
The program uses an explicit teaching convention: floor the region’s start, ceil its end, and form half-open bins with floor/ceil boundaries. It receives RoIs already expressed in feature coordinates. In a full detector, image boxes must first be mapped using the backbone’s spatial geometry. Our quantization is not claimed to match every detail of the original Caffe implementation or RoIAlign.
Quantization matters. On a 4×4 map, regions (0.1, 0.1, 3.1, 3.1) and (0.2, 0.2, 3.2, 3.2) fall into the same integer extent under this convention and give identical pooled values. A small coordinate shift can become invisible until it crosses a bin boundary. Max pooling also summarizes features rather than retaining every pixel of the region.
Predict a correction relative to a reference box
Let a reference box have center , width and height , all in one coordinate system with positive dimensions. For a target center and size , define:
Dividing a center shift by the reference size makes it relative: a shift of 2 pixels is large for a 4-pixel box but small for a 100-pixel box. A log ratio turns multiplicative resizing into an additive target; doubling width gives log 2 regardless of the starting width. A common translation of target and reference leaves all four targets unchanged. Scaling both boxes by the same positive factor also preserves them.
Invert these transformations to decode a prediction:
Return to xyxy using center minus/plus half the size. With reference (0, 0, 4, 2) and target (1, 1, 7, 5), the reference center is (2, 1), the target center is (4, 3), and the encoded vector is (0.5, 1, log 1.5, log 2). The example verifies its round trip. These reference-relative coordinates are described in the Faster R-CNN v1 parameterization.
A background region has no target box to refine
Fast R-CNN predicts a distribution p over C foreground classes plus background class 0, and C sets of four regression outputs. For a labeled region, let u be its true class and v its regression target in the chosen training representation. Its loss combines classification with foreground-only localization:
The localization penalty is smooth L1:
Near zero it is quadratic; outside that region its derivative has magnitude one. For an error of -0.5, the penalty is 0.125 and its derivative is -0.5. For background u=0, the localization indicator is zero: there is no foreground object’s box to use as its target. Classification still contributes to the gradient. Fast R-CNN equations 1–3
The paper standardizes regression targets and uses λ=1. Our numerical example instead supplies raw targets directly, without training-set statistics. If a trained model uses standardized targets, its predictions need the corresponding inverse transformation before geometric decoding. Mixing those representations would give wrong boxes even when each formula is implemented correctly.
Run the components and a complete small RPN
An RPN slides a small learned network over shared image features. In the first Faster R-CNN preprint, a 3×3 convolution followed by ReLU feeds two 1×1 heads. For A anchor shapes per location, the heads emit 2A object/background logits and 4A offsets. An H×W feature map therefore provides HWA anchors. Objectness answers foreground-versus-background membership, not the final object’s category. Faster R-CNN v1 §3
Anchors are reference rectangles with selected sizes and aspect ratios. Their geometry is not a detection result; the learned heads provide scores and corrections. Our two-anchor toy uses width/height pairs (2, 2) and (4, 2), with centers spaced by stride 2. The first reference can lie inside the scene while its wider neighbor crosses the boundary.
For training labels, v1 uses an anchor with the best IoU for a ground-truth box or IoU above 0.7 as a positive. A non-positive anchor below 0.3 for every ground-truth box is negative; the rest are ignored. Our exact-tie policy marks every tied best anchor positive, an explicit local choice. A best anchor can still be a poor match. This label assignment uses ground truth during training; ground truth is unavailable during inference.
The v1 per-anchor loss uses binary classification and localization only for positives:
Here is 1 for a positive anchor and 0 for a negative one; ignored anchors contribute neither term. This version states λ=10, distinct from the Fast R-CNN example’s default 1. The original training pipeline excludes cross-boundary anchors. At inference it clips out-of-image proposals, applies suppression and selects ranked proposals for the detection head. Those pipeline steps are outside our small RPN function. Faster R-CNN v1 physical pages 3–5
The standalone code below needs Python 3.12 and NumPy 1.26.4. It runs the entire small RPN forward on supplied features, plus box transforms, RoI pooling and Fast output-level losses/gradients. It does not include a pretrained image backbone, a final trained classifier or full-network backpropagation. Its RPN heads have no biases; their random objectness weights are evaluated, while zero regression weights make the initial proposals equal the anchors.
"""Original R-CNN-family teaching operators on supplied features, not a trained detector."""
import numpy as np
def box(value):
value = np.asarray(value, dtype=float)
if value.shape != (4,) or not np.isfinite(value).all():
raise ValueError('expected four finite xyxy coordinates')
with np.errstate(over='ignore'):
size = value[2:] - value[:2]
if not np.isfinite(size).all() or (size <= 0).any():
raise ValueError('box dimensions must be finite and positive')
return value
def center_size(value):
b = box(value)
size = b[2:] - b[:2]
return b[:2] + size/2, size
def encode(anchor, target):
a, size = center_size(anchor)
t, target_size = center_size(target)
with np.errstate(over='ignore', invalid='ignore'):
result = np.r_[(t-a)/size, np.log(target_size)-np.log(size)]
if not np.isfinite(result).all():
raise ValueError('box deltas exceed the supported numerical range')
return result
def decode(anchor, delta):
a, size = center_size(anchor)
delta = np.asarray(delta, dtype=float)
if delta.shape != (4,) or not np.isfinite(delta).all():
raise ValueError('expected four finite deltas')
with np.errstate(over='ignore', invalid='ignore', under='ignore'):
center = a + delta[:2]*size
new_size = np.exp(np.log(size)+delta[2:])
result = np.r_[center-new_size/2, center+new_size/2]
return box(result)
def roi_pool(features, region, output=(2, 2)):
"""Explicit floor/ceil half-open bins; not bit-identical to original Caffe quantization."""
f = np.asarray(features, dtype=float)
if f.ndim != 3 or min(f.shape) < 1 or not np.isfinite(f).all():
raise ValueError('features must be a finite HWC array')
if len(output) != 2 or any(type(n) is not int or n < 1 for n in output):
raise ValueError('output dimensions must be positive integers')
x0, y0, x1, y1 = box(region)
if x0 < 0 or y0 < 0 or x1 > f.shape[1] or y1 > f.shape[0]:
raise ValueError('RoI must lie within feature coordinates')
x0, y0, x1, y1 = int(np.floor(x0)), int(np.floor(y0)), int(np.ceil(x1)), int(np.ceil(y1))
rows, cols = output
pooled = np.empty((rows, cols, f.shape[2]))
for y in range(rows):
lo_y = y0 + int(np.floor(y*(y1-y0)/rows))
hi_y = y0 + int(np.ceil((y+1)*(y1-y0)/rows))
for x in range(cols):
lo_x = x0 + int(np.floor(x*(x1-x0)/cols))
hi_x = x0 + int(np.ceil((x+1)*(x1-x0)/cols))
pooled[y, x] = f[lo_y:hi_y, lo_x:hi_x].max(axis=(0, 1))
return pooled
def fast_loss(logits, deltas, label, target=None, weight=1.0):
"""Fast R-CNN loss and output gradients; raw targets, background class zero."""
logits, deltas = np.asarray(logits, float), np.asarray(deltas, float)
if logits.ndim != 1 or len(logits) < 2 or deltas.shape != (len(logits)-1, 4):
raise ValueError('K+1 logits and K-by-4 regression values required')
if not np.isfinite(logits).all() or not np.isfinite(deltas).all():
raise ValueError('outputs must be finite')
if type(label) is not int or not 0 <= label < len(logits):
raise ValueError('invalid target class')
if not np.isfinite(weight) or weight < 0:
raise ValueError('loss weight must be finite and nonnegative')
with np.errstate(over='ignore'):
shifted = logits - logits.max()
if not np.isfinite(shifted).all():
raise ValueError('logit differences exceed the supported range')
p = np.exp(shifted); p /= p.sum()
loss = np.log(np.exp(shifted).sum()) - shifted[label]
dlogit = p.copy(); dlogit[label] -= 1
dbox = np.zeros_like(deltas)
if label:
target = np.asarray(target, float)
if target.shape != (4,) or not np.isfinite(target).all():
raise ValueError('foreground needs four finite regression targets')
with np.errstate(over='ignore'):
error = deltas[label-1] - target
if not np.isfinite(error).all():
raise ValueError('regression errors exceed the supported range')
magnitude = np.abs(error)
clipped = np.minimum(magnitude, 1)
loss += weight*(.5*clipped**2 + (magnitude-clipped)).sum()
dbox[label-1] = weight*np.clip(error, -1, 1)
return float(loss), dlogit, dbox
def anchors(height, width, sizes=((2., 2.), (4., 2.)), stride=2.):
if type(height) is not int or type(width) is not int or min(height, width) < 1:
raise ValueError('positive integer grid dimensions required')
sizes = np.asarray(sizes, float)
if sizes.ndim != 2 or sizes.shape[1] != 2 or len(sizes) == 0:
raise ValueError('anchor sizes must be K-by-2 width/height pairs')
if not np.isfinite(sizes).all() or (sizes <= 0).any() or not np.isfinite(stride) or stride <= 0:
raise ValueError('sizes and stride must be finite and positive')
result = []
for y in range(height):
for x in range(width):
center = np.array([(x+.5)*stride, (y+.5)*stride])
for size in sizes:
result.append(box(np.r_[center-size/2, center+size/2]))
return np.stack(result)
def iou(a, b):
a, b = box(a), box(b)
sizes = np.r_[a[2:]-a[:2], b[2:]-b[:2]]
scale = sizes.max(); sizes /= scale
inter = np.maximum(0, np.minimum(a[2:], b[2:])-np.maximum(a[:2], b[:2]))/scale
intersection = inter.prod()
union = sizes[:2].prod()+sizes[2:].prod()-intersection
if not np.isfinite(union) or union <= 0:
raise ValueError('unsupported box-area range')
return float(intersection/union)
def anchor_labels(candidate_boxes, truth):
"""1 positive, 0 negative, -1 ignored; all exact best ties are positive by local policy."""
candidate_boxes, truth = [box(a) for a in candidate_boxes], [box(b) for b in truth]
if not candidate_boxes:
return np.empty(0, dtype=int)
if not truth:
return np.zeros(len(candidate_boxes), dtype=int)
overlaps = np.array([[iou(a, b) for b in truth] for a in candidate_boxes])
best = overlaps.max(axis=1)
result = np.full(len(candidate_boxes), -1)
result[best < .3] = 0
result[(best > .7) | (overlaps == overlaps.max(axis=0)).any(axis=1)] = 1
return result
def rpn(features, spatial, object_head, box_head, sizes=((2.,2.),(4.,2.)), stride=2.):
"""3x3 same convolution + ReLU + two 1x1 heads; no biases, clipping or NMS."""
f = np.asarray(features, float)
spatial, object_head, box_head = (np.asarray(w,float) for w in (spatial, object_head, box_head))
if f.ndim != 3 or min(f.shape) < 1 or not np.isfinite(f).all():
raise ValueError('features must be finite HWC')
if spatial.ndim != 4 or spatial.shape[:3] != (3,3,f.shape[2]) or spatial.shape[3] < 1:
raise ValueError('spatial weights must have shape 3,3,C,D')
base = anchors(f.shape[0], f.shape[1], sizes, stride)
k, hidden = len(sizes), spatial.shape[3]
if object_head.shape != (hidden,2*k) or box_head.shape != (hidden,4*k):
raise ValueError('head shapes must be D-by-2K and D-by-4K')
if not all(np.isfinite(w).all() for w in [spatial,object_head,box_head]):
raise ValueError('weights must be finite')
padded = np.pad(f,((1,1),(1,1),(0,0)))
z = np.empty((f.shape[0],f.shape[1],hidden))
for y in range(f.shape[0]):
for x in range(f.shape[1]):
z[y,x] = np.einsum('ijc,ijcd->d',padded[y:y+3,x:x+3],spatial)
z = np.maximum(z,0)
logits = (z @ object_head).reshape(-1,2)
shifted = logits-logits.max(axis=1,keepdims=True)
probabilities = np.exp(shifted); probabilities /= probabilities.sum(axis=1,keepdims=True)
delta = (z @ box_head).reshape(-1,4)
proposals = np.stack([decode(a,d) for a,d in zip(base,delta)])
return base, probabilities[:,1], proposals
if __name__ == '__main__':
anchor, target = (0,0,4,2), (1,1,7,5)
delta = encode(anchor,target)
print('delta:', np.round(delta,6).tolist())
print('decoded:', np.round(decode(anchor,delta),6).tolist())
f = np.arange(32,dtype=float).reshape(4,4,2)/32
print('pooled channel 0:', roi_pool(f,(0,0,4,4))[:,:,0].tolist())
loss, _, gradient = fast_loss([0,1,-1],np.zeros((2,4)),1,[.5,0,0,0])
print('Fast loss:', round(loss,6), 'box gradient:', gradient[0].tolist())
rng = np.random.default_rng(17)
base, scores, proposals = rpn(f,rng.normal(0,.2,(3,3,2,3)),rng.normal(0,.2,(3,4)),np.zeros((3,8)))
print('RPN shapes:', base.shape, scores.shape, proposals.shape)
print('labels:',anchor_labels([(0,0,1,1),(0,0,.7,1),(0,0,.2,1)],[(0,0,1,1)]).tolist())
Expected output:
delta: [0.5, 1.0, 0.405465, 0.693147]
decoded: [1.0, 1.0, 7.0, 5.0]
pooled channel 0: [[0.3125, 0.4375], [0.8125, 0.9375]]
Fast loss: 0.532606 box gradient: [-0.5, 0.0, 0.0, 0.0]
RPN shapes: (32, 4) (32,) (32, 4)
labels: [1, -1, 0]
The smooth-L1 implementation sets and evaluates . The parentheses preserve the small quadratic term: at e=1e-20, subtracting a only after adding it to that tiny term can round the result to zero. A dedicated test checks the expected 5e-41.
| Operation | Toy input or setting | Result |
|---|---|---|
| RoI pooling | 4×4×2 features, 2×2 output | Four maxima per channel |
| Fast loss | 3 logits, 2×4 offsets, foreground label 1 | Scalar loss and output gradients |
| Spatial RPN layer | 4×4×2 features, 3 hidden channels | 4×4×3 hidden map |
| RPN heads | 2 anchors per location | 32 objectness values and 32 boxes |
For a backbone costing B per image and R regions, original per-region CNN extraction is roughly R times its crop cost; shared extraction pays B once, followed by region-dependent work. These are operation-count distinctions, not promised speed ratios. For the RPN’s supplied H×W×F input, hidden width D and A anchors, the 3×3 layer uses about 9HWFD multiply-accumulates, and the two heads about 6HWDA. Pooling also visits each region’s bins; overlapping regions still incur region-level work after backbone sharing.
The label helper constructs an N×G IoU table for N anchors and G ground-truth boxes. Its time and memory are O(NG); this table can dominate the helper’s memory as the grid grows.
Sharing computation does not remove the remaining choices
The June 2015 Faster R-CNN preprint uses four-step alternating training: train an RPN; train a separate detector from its proposals; initialize the RPN from detector features while fixing shared convolutions; then train detector-specific fully connected layers with those shared convolutions fixed. This is a particular historical training scheme. It should not be rewritten as an unspecified modern joint-training recipe. Faster R-CNN v1, shared-feature training
Proposal quality still limits the downstream classifier: a region that never reaches it cannot be repaired by that classifier. Anchor sizes, feature resolution, candidate limits and suppression affect which objects survive. Coarse pooling can discard localization detail; many overlapping RoIs can still make the second stage expensive. Examine errors and runtime under the actual data distribution rather than infer a universal ranking from the names “Fast” and “Faster.”
The program is an operator-level teaching model. Its label function has no image-size argument and therefore does not exclude boundary-crossing anchors. The caller would need that filtering to follow the original training protocol. Its pooling quantization, unstandardized targets and untrained small heads are all deliberate, documented differences. The checks establish arithmetic and shape behavior, not VOC accuracy or a detector trained to recognize objects.
For alternative detection designs, continue to YOLO, SSD and DETR. For pixel-level outputs from regions, Mask R-CNN is a separate topic. Compare their candidate representations and training-target assignments.
Check the geometry and the accounting
1. Double the coordinate scale
Multiply every coordinate of reference (0, 0, 4, 2) and target (1, 1, 7, 5) by 2. What happens to the encoded offsets?
Answer: They remain (0.5, 1, log 1.5, log 2). Both the center displacement and its normalizing reference size double; width and height ratios remain unchanged. This assumes the same coordinate convention and a positive common scale.
2. What can move without changing pooled features?
Under our pooling convention, compare RoIs (0.1, 0.1, 3.1, 3.1) and (0.2, 0.2, 3.2, 3.2) on the same 4×4 feature map.
Answer: Both quantize to (0, 0, 4, 4), so their pooled values are identical. This demonstrates quantization, not translation invariance of the complete detector. A shift across an integer boundary can change the selected bins.
3. Is a background region useless for training?
For u=0, which output gradients vanish and which can remain nonzero? Should we invent a target box such as (0, 0, 0, 0)?
Answer: All regression-output gradients vanish because localization is gated off. The softmax classification gradient can remain nonzero and teaches background rejection. No foreground target box should be invented; a zero-width, zero-height box also violates the geometric contract.
4. Count the heads, then question the score
A feature map is 4×4 and uses two anchors per location. How many proposals and output channels are produced? Does a high objectness score tell us the object is a dog?
Answer: There are 32 anchors/proposals before filtering. The classification head has 4 channels per location and the regression head 8. Objectness distinguishes foreground membership from background; category identification comes from the detection head. High random-model objectness is not evidence of recognition.
Keep the three papers and their versions separate
-
R-CNN, CVPR2014: overview, November 2013 report footnote, feature extraction and test-time region/class processing. The complete training and supplementary material were not audited.
-
Fast R-CNN, ICCV2015: architecture, RoI pooling and multi-task loss; equations 1–3 on physical page 3 were visually checked. Original Caffe rounding behavior was not reproduced.
-
Faster R-CNN, arXiv v1, 4 June 2015: RPN structure, anchor labels, parameterization and alternating training; physical page 4 equations were visually checked. Later revisions can change details and require separate version checks.
-
R-CNN arXiv submission history: the v1 entry independently fixes the first-submission day. The current page also describes later versions; their abstract results are not used as evidence for the original method here.
All numerical examples and code here are original. The preparatory tests include literal pooling references, finite differences for output gradients, a hand-computable RPN and box round trips. Each result is scoped to the teaching implementation; paper-reported training performance remains a separate claim.
Make a prediction, then check
For a background RoI (u=0), which part of the Fast R-CNN loss remains active?
Learning objectives
- Compare which computations are shared in R-CNN, Fast R-CNN and the original Faster R-CNN.
- Derive reference-relative box parameters, RoI pooling behavior and foreground-only localization gradients.
- Run a small RPN and separate anchor labels, objectness, proposals and final detection classes.
Prerequisites & connections
Explore related knowledge →References
- Rich feature hierarchies for accurate object detection and semantic segmentation — CVPR2014 method
Ross Girshick; Jeff Donahue; Trevor Darrell; Jitendra Malik · 2014 - Fast R-CNN — ICCV2015 architecture and multi-task loss
Ross Girshick · 2015 - Faster R-CNN: Towards Real-Time Object Detection with Region Proposal Networks — arXiv v1
Shaoqing Ren; Kaiming He; Ross Girshick; Jian Sun · 2015 - R-CNN arXiv submission history — first version dated 11 November 2013
arXiv; Ross Girshick and coauthors · 2013
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-07 · Codex single-AI-author technical check: bounded original papers, explicit first-version dates, box/gradient references, small RPN computation and corresponding bilingual reasoning. Not independent human review, full-network training or benchmark reproduction.
- Checked analytic and random box round trips, translation/common-scale invariance, literal RoI maxima and quantization, Fast classification/localization gradients by finite differences, background gate, tiny-residual precision, anchor tiling/labels and literal/full small RPN results. Eleven numerical tests plus bilingual structural test.
- Compared both languages section by section: three versions, dimensions, box derivation, gated losses, four-step training, computational scope, examples and four answers. Five displayed equations and the full program match. Original report day checked separately against arXiv history.
- Final completeness review added the supervised ILSVRC pretraining/PASCAL fine-tuning context from the already-read CVPR overview in both languages. Frozen initial wording retained; formulas, examples, code and answers unchanged. Adjacent chronology source links separated after visual inspection.
Source locations checked:
- Rich feature hierarchies for accurate object detection and semantic segmentation — CVPR2014 method · CVPR2014 physical page 2 overview/footnote and page 3 feature-extraction/test-time opening.
- Fast R-CNN — ICCV2015 architecture and multi-task loss · ICCV2015 physical pages 2–3, architecture/RoI pooling/multi-task loss; physical page 3 equations 1–3 visually checked.
- Faster R-CNN: Towards Real-Time Object Detection with Region Proposal Networks — arXiv v1 · arXiv1506.01497v1 physical pages 2–5 before experiments, page 4 equations visually checked; page 1 date footer read.
- R-CNN arXiv submission history — first version dated 11 November 2013 · arXiv1311.2524 submission history: v1 Mon, 11 Nov 2013 18:43:49 UTC; overview denotes current v5, separated from method evidence.
Related topics