TExcelTAD
Home › Computer Vision: Images to Detection, Segmentation & Tracking › Two-Stage Detectors: R-CNN to Faster R-CNN

Two-Stage Detectors: R-CNN to Faster R-CNN

Sliding a classifier over every window is too slow (detection basics). The two-stage answer, developed between 2014 and 2017 in four papers, is: first propose a few hundred places where an object might be, then look closely at each of those with a second network that classifies it and corrects its box. The result, Faster R-CNN with a feature pyramid, was the standard accurate detector for years, is still the reference in torchvision and Detectron2, and its second stage became Mask R-CNN (instance segmentation). This lesson follows the history to see why each piece exists, builds the key operation (RoI pooling and RoI Align) from scratch, and inspects torchvision's model.

From R-CNN to Faster R-CNN

Model (year) Proposals Features What it fixed
R-CNN (2014) ~2,000 from Selective Search (hand-made grouping of superpixels) a CNN run on every warped proposal (227 x 227) CNN features instead of HOG: a large jump in VOC mAP
SPP-net (2014) Selective Search CNN run once, features pooled per proposal 2,000 CNN passes become 1
Fast R-CNN (2015) Selective Search once per image, RoI pooling, classifier and box regressor trained jointly one network, one training stage
Faster R-CNN (2015) a region proposal network (RPN) on the same features shared with the RPN proposals learned and almost free; Selective Search took about 2 s per image on a CPU
+ FPN (2017) RPN on every pyramid level a feature pyramid small objects
Mask R-CNN (2017) as above RoI Align instead of RoI pooling, plus a mask head sub-pixel alignment, masks

The thread through the table is sharing computation: run the expensive CNN once per image and make every later step a cheap operation on its feature map.

image backbone+ FPN feature maps stage 1: RPNobjectness + boxNMS 0.7, top-n RoI Align7 x 7 per proposal stage 2: box head2 FC layersclass + box per class NMS per class proposals

Stage 1: the region proposal network

The RPN is a small convolutional head (a 3×33 \times 3 convolution, then two 1×11 \times 1 convolutions) run on every pyramid level. At every position and for each of its kk anchors it outputs one objectness logit (object or not, class-agnostic) and four box offsets (tx,ty,tw,th)(t_x, t_y, t_w, t_h). Training uses the anchor-matching rules (IoU ≥0.7\ge 0.7 positive, <0.3< 0.3 negative) and a sampled batch of 256 anchors per image, half positive at most. At inference the decoded boxes with the best objectness are kept per level, NMS at IoU 0.7 removes duplicates, and the top 1,000 (in torchvision's default test setting) go to stage 2 as proposals. The RPN does not need to be precise; it needs high recall, because an object missed here cannot be recovered.

Stage 2: RoI pooling and RoI Align

The second stage needs a fixed-size input per proposal, but proposals have every size and shape. RoI pooling (Fast R-CNN) maps the proposal onto the feature map, rounds its corners to whole feature cells, cuts it into a 7×77 \times 7 grid of bins (again with rounding) and max-pools each bin. On a stride-16 feature map one cell is 16 image pixels, so the rounding can move a box edge by up to 8 pixels: harmless for classification, harmful for precise boxes and fatal for pixel masks.

RoI Align (Mask R-CNN) removes all rounding. Each bin keeps its exact fractional position, a few regularly spaced sample points inside the bin are read with bilinear interpolation from the four surrounding feature cells, and the samples are averaged:

f(x,y)=∑i∈{⌊x⌋,⌊x⌋+1}  ∑j∈{⌊y⌋,⌊y⌋+1}(1−∣x−i∣)(1−∣y−j∣) F[j,i]f(x, y) = \sum_{i \in \{\lfloor x \rfloor, \lfloor x \rfloor + 1\}} \; \sum_{j \in \{\lfloor y \rfloor, \lfloor y \rfloor + 1\}} (1 - \lvert x - i \rvert)(1 - \lvert y - j \rvert) \, F[j, i]

With aligned=True the box is shifted by half a cell first, so that a feature cell's value sits at the centre of the pixels it covers. Both operations from scratch, on an 8×88 \times 8 feature map (stride 4, so a 32 x 32 image) whose value is 10⋅row+column10 \cdot \text{row} + \text{column}, which makes it easy to see where values come from:

python · try it yourself
import numpy as np

F = (10 * np.arange(8)[:, None] + np.arange(8)[None, :]).astype(float)   # value = 10 * row + col

def roi_pool(F, box, out=2, scale=0.25):
    """Fast R-CNN RoI max pooling as in torchvision: corners rounded, x2/y2 inclusive, bins floor/ceil."""
    x1, y1, x2, y2 = [int(np.floor(v * scale + 0.5)) for v in box]
    h, w = max(y2 - y1 + 1, 1), max(x2 - x1 + 1, 1)
    res = np.zeros((out, out))
    for ph in range(out):
        for pw in range(out):
            hs = min(max(int(np.floor(ph * h / out)) + y1, 0), F.shape[0]); he = min(max(int(np.ceil((ph + 1) * h / out)) + y1, 0), F.shape[0])
            ws = min(max(int(np.floor(pw * w / out)) + x1, 0), F.shape[1]); we = min(max(int(np.ceil((pw + 1) * w / out)) + x1, 0), F.shape[1])
            res[ph, pw] = F[hs:he, ws:we].max() if he > hs and we > ws else 0.0
    return res, (x1, y1, x2, y2)

def bilinear(F, y, x):
    H, W = F.shape
    if y < -1 or y > H or x < -1 or x > W:
        return 0.0
    y, x = max(y, 0.0), max(x, 0.0)
    y0, x0 = int(y), int(x)
    y1 = y0 + 1 if y0 < H - 1 else y0; x1 = x0 + 1 if x0 < W - 1 else x0
    if y0 >= H - 1: y = float(y0)
    if x0 >= W - 1: x = float(x0)
    ly, lx = y - y0, x - x0
    return (1 - ly) * (1 - lx) * F[y0, x0] + (1 - ly) * lx * F[y0, x1] + ly * (1 - lx) * F[y1, x0] + ly * lx * F[y1, x1]

def roi_align(F, box, out=2, scale=0.25, samples=2, aligned=True):
    off = 0.5 if aligned else 0.0
    x1, y1, x2, y2 = [v * scale - off for v in box]
    bw, bh = (x2 - x1) / out, (y2 - y1) / out
    res = np.zeros((out, out))
    for ph in range(out):
        for pw in range(out):
            pts = [bilinear(F, y1 + ph * bh + (iy + 0.5) * bh / samples, x1 + pw * bw + (ix + 0.5) * bw / samples)
                   for iy in range(samples) for ix in range(samples)]
            res[ph, pw] = np.mean(pts)
    return res

box = [5, 3, 19, 15]                       # image pixels; on the feature map: [1.25, 0.75, 4.75, 3.75]
pooled, cells = roi_pool(F, box)
print("box in feature cells:", [v * 0.25 for v in box], "| RoI pooling rounds it to cells", cells)
print("RoI pooling 2 x 2:", pooled.tolist())
print("RoI Align  2 x 2:", roi_align(F, box).round(3).tolist())
for shift in [0, 1, 2, 3, 4]:
    b = [box[0] + shift, box[1], box[2] + shift, box[3]]
    print(f"box moved right by {shift} px: RoI pool top-left {roi_pool(F, b)[0][0, 0]:.0f}, RoI Align top-left {roi_align(F, b)[0, 0]:.3f}")
box in feature cells: [1.25, 0.75, 4.75, 3.75] | RoI pooling rounds it to cells (1, 1, 5, 4)
RoI pooling 2 x 2: [[23.0, 25.0], [43.0, 45.0]]
RoI Align  2 x 2: [[11.625, 13.375], [26.625, 28.375]]
box moved right by 0 px: RoI pool top-left 23, RoI Align top-left 11.625
box moved right by 1 px: RoI pool top-left 23, RoI Align top-left 11.875
box moved right by 2 px: RoI pool top-left 23, RoI Align top-left 12.125
box moved right by 3 px: RoI pool top-left 24, RoI Align top-left 12.375
box moved right by 4 px: RoI pool top-left 24, RoI Align top-left 12.625

The box covers feature cells 1.25 to 4.75 horizontally. RoI pooling rounds that to cells 1 to 5 (inclusive, a convention inherited from the original Caffe code) and takes maxima, so its top-left bin reports 23, a value from row 2, column 3. RoI Align reports 11.625, the interpolated value at row 1.0, column 1.625 (the mean of its four sample points; the feature map is linear, so the average is exact), inside the box where it should be. The shift test shows the real difference: moving the box right by 1, 2, 3, 4 pixels moves RoI Align's output smoothly by 0.25 per pixel (one pixel is a quarter of a feature cell), while RoI pooling does not react to the first two pixels and then jumps. A box head fed by RoI pooling cannot see small displacements, so it cannot learn to correct them; RoI Align gave Mask R-CNN a few points of mask AP and helped box AP too.

torchvision has both operations in torchvision.ops, with the same conventions (spatial_scale is 1/stride, sampling_ratio the number of samples per bin side). Comparing them with the NumPy versions on random feature maps and random boxes (a recorded example, run with PyTorch in Docker):

python · try it yourself
import numpy as np
import torch
from torchvision.ops import roi_align as tv_roi_align, roi_pool as tv_roi_pool

def roi_pool(F, box, out=2, scale=0.25):
    x1, y1, x2, y2 = [int(np.floor(v * scale + 0.5)) for v in box]
    h, w = max(y2 - y1 + 1, 1), max(x2 - x1 + 1, 1)
    res = np.zeros((out, out))
    for ph in range(out):
        for pw in range(out):
            hs = min(max(int(np.floor(ph * h / out)) + y1, 0), F.shape[0]); he = min(max(int(np.ceil((ph + 1) * h / out)) + y1, 0), F.shape[0])
            ws = min(max(int(np.floor(pw * w / out)) + x1, 0), F.shape[1]); we = min(max(int(np.ceil((pw + 1) * w / out)) + x1, 0), F.shape[1])
            res[ph, pw] = F[hs:he, ws:we].max() if he > hs and we > ws else 0.0
    return res

def bilinear(F, y, x):
    H, W = F.shape
    if y < -1 or y > H or x < -1 or x > W:
        return 0.0
    y, x = max(y, 0.0), max(x, 0.0)
    y0, x0 = int(y), int(x)
    y1 = y0 + 1 if y0 < H - 1 else y0; x1 = x0 + 1 if x0 < W - 1 else x0
    if y0 >= H - 1: y = float(y0)
    if x0 >= W - 1: x = float(x0)
    ly, lx = y - y0, x - x0
    return (1 - ly) * (1 - lx) * F[y0, x0] + (1 - ly) * lx * F[y0, x1] + ly * (1 - lx) * F[y1, x0] + ly * lx * F[y1, x1]

def roi_align(F, box, out=2, scale=0.25, samples=2, aligned=True):
    off = 0.5 if aligned else 0.0
    x1, y1, x2, y2 = [v * scale - off for v in box]
    bw, bh = (x2 - x1) / out, (y2 - y1) / out
    res = np.zeros((out, out))
    for ph in range(out):
        for pw in range(out):
            pts = [bilinear(F, y1 + ph * bh + (iy + 0.5) * bh / samples, x1 + pw * bw + (ix + 0.5) * bw / samples)
                   for iy in range(samples) for ix in range(samples)]
            res[ph, pw] = np.mean(pts)
    return res

rng = np.random.default_rng(0)
F = rng.normal(size=(16, 16))                                    # one channel, stride 4 -> a 64 x 64 image
xy = rng.uniform(0, 48, (50, 2)); wh = rng.uniform(4, 30, (50, 2))
boxes = np.c_[xy, np.minimum(xy + wh, 64)]
Ft = torch.tensor(F)[None, None]
rois = torch.tensor(np.c_[np.zeros(50), boxes])                  # (batch index, x1, y1, x2, y2)
tv_a = tv_roi_align(Ft, rois, output_size=7, spatial_scale=0.25, sampling_ratio=2, aligned=True)[:, 0].numpy()
tv_p = tv_roi_pool(Ft, rois, output_size=7, spatial_scale=0.25)[:, 0].numpy()
np_a = np.stack([roi_align(F, b, out=7) for b in boxes]); np_p = np.stack([roi_pool(F, b, out=7) for b in boxes])
print("50 random boxes, 7 x 7 output")
print("RoI Align: max difference torchvision vs NumPy", f"{np.abs(tv_a - np_a).max():.1e}")
print("RoI pool : max difference torchvision vs NumPy", f"{np.abs(tv_p - np_p).max():.1e}")
50 random boxes, 7 x 7 output
RoI Align: max difference torchvision vs NumPy 0.0e+00
RoI pool : max difference torchvision vs NumPy 0.0e+00

Both agree with the NumPy versions to the last bit on 50 random boxes, so the half-cell aligned offset, the border rules and the inclusive corners of RoI pooling above are exactly what torchvision does. A real detector runs this on 256 channels and a few hundred boxes at once, and on a pyramid: torchvision's MultiScaleRoIAlign first picks the level for each box by its size (larger boxes read from coarser levels).

Faster R-CNN in torchvision

torchvision builds the whole detector in one call. Its pretrained COCO weights are a download and are not available offline here, so this recorded example builds the small fasterrcnn_mobilenet_v3_large_320_fpn with random weights (weights=None, weights_backbone=None) and 3 classes plus background. Random weights mean the boxes it outputs are meaningless; the example is about structure, settings and output format.

python · try it yourself
import numpy as np
import torch
from torchvision.models.detection import fasterrcnn_mobilenet_v3_large_320_fpn
import numpy as np, cv2

CLASSES = ["square", "circle", "triangle"]

def make_scene(rng, size=64, max_objects=3):
    """Noisy grey background with 1..max_objects shapes that do not touch.
    Returns RGB uint8 image, boxes (n, 4) as [x1, y1, x2, y2] with x2, y2 exclusive,
    labels (n,) indices into CLASSES, masks (n, size, size) bool."""
    img = rng.normal(110, 12, (size, size, 3)).clip(0, 255).astype(np.uint8)
    n = int(rng.integers(1, max_objects + 1))
    boxes, labels, masks = [], [], []
    for _ in range(100):
        if len(boxes) == n:
            break
        s = int(rng.integers(12, 25)); x = int(rng.integers(0, size - s)); y = int(rng.integers(0, size - s))
        if any(x < b[2] + 2 and b[0] < x + s + 2 and y < b[3] + 2 and b[1] < y + s + 2 for b in boxes):
            continue
        c = int(rng.integers(0, 3)); m = np.zeros((size, size), np.uint8)
        if c == 0:
            cv2.rectangle(m, (x, y), (x + s - 1, y + s - 1), 1, -1)
        elif c == 1:
            cv2.circle(m, (x + s // 2, y + s // 2), s // 2, 1, -1)
        else:
            cv2.fillPoly(m, [np.array([[x + s // 2, y], [x, y + s - 1], [x + s - 1, y + s - 1]], np.int32)], 1)
        img[m > 0] = rng.integers(0, 256, 3)
        ys, xs = np.nonzero(m)
        boxes.append([int(xs.min()), int(ys.min()), int(xs.max()) + 1, int(ys.max()) + 1])
        labels.append(c); masks.append(m > 0)
    return img, np.array(boxes).reshape(-1, 4), np.array(labels), np.array(masks)

torch.manual_seed(0)
model = fasterrcnn_mobilenet_v3_large_320_fpn(weights=None, weights_backbone=None, num_classes=4)   # background + 3 shapes
count = lambda m: sum(p.numel() for p in m.parameters())
print(f"parameters: total {count(model):,} | backbone + FPN {count(model.backbone):,} | RPN {count(model.rpn):,} | RoI heads {count(model.roi_heads):,}")
ag = model.rpn.anchor_generator
print("RPN anchor sizes per level:", ag.sizes, "| ratios:", ag.aspect_ratios[0], "| anchors per position:", ag.num_anchors_per_location())
print("RPN: pre-NMS top-n", model.rpn._pre_nms_top_n, "| post-NMS top-n", model.rpn._post_nms_top_n, "| NMS IoU", model.rpn.nms_thresh)
print("RoI heads: pooler", type(model.roi_heads.box_roi_pool).__name__, "output", model.roi_heads.box_roi_pool.output_size,
      "| predictor", model.roi_heads.box_predictor.cls_score, model.roi_heads.box_predictor.bbox_pred)
print("box coder weights", model.roi_heads.box_coder.weights, "| score thr", model.roi_heads.score_thresh,
      "| NMS IoU", model.roi_heads.nms_thresh, "| max detections", model.roi_heads.detections_per_img)
print("input resize: min_size", model.transform.min_size, "max_size", model.transform.max_size)

rng = np.random.default_rng(0)
scenes = [make_scene(rng) for _ in range(2)]
images = [torch.tensor(img).permute(2, 0, 1).float() / 255 for img, _, _, _ in scenes]
targets = [{"boxes": torch.tensor(b, dtype=torch.float32), "labels": torch.tensor(l + 1)} for _, b, l, _ in scenes]

model.train()
losses = model(images, targets)                       # training mode: needs targets, returns the four losses
print("training losses:", {k: round(v.item(), 3) for k, v in losses.items()})
model.eval()
with torch.no_grad():
    out = model(images)                               # eval mode: a list with one dict per image
print("eval output keys:", list(out[0].keys()), "| boxes", tuple(out[0]["boxes"].shape), "| labels", tuple(out[0]["labels"].shape),
      "| boxes inside the 64 x 64 image:", bool((out[0]["boxes"] >= 0).all() and (out[0]["boxes"] <= 64).all()))
parameters: total 18,964,879 | backbone + FPN 4,439,344 | RPN 609,355 | RoI heads 13,916,180
RPN anchor sizes per level: ((32, 64, 128, 256, 512), (32, 64, 128, 256, 512), (32, 64, 128, 256, 512)) | ratios: (0.5, 1.0, 2.0) | anchors per position: [15, 15, 15]
RPN: pre-NMS top-n {'training': 2000, 'testing': 150} | post-NMS top-n {'training': 2000, 'testing': 150} | NMS IoU 0.7
RoI heads: pooler MultiScaleRoIAlign output (7, 7) | predictor Linear(in_features=1024, out_features=4, bias=True) Linear(in_features=1024, out_features=16, bias=True)
box coder weights (10.0, 10.0, 5.0, 5.0) | score thr 0.05 | NMS IoU 0.5 | max detections 100
input resize: min_size (320,) max_size 640
training losses: {'loss_classifier': 1.401, 'loss_box_reg': 0.123, 'loss_objectness': 0.69, 'loss_rpn_box_reg': 0.001}
eval output keys: ['boxes', 'labels', 'scores'] | boxes (100, 4) | labels (100,) | boxes inside the 64 x 64 image: True

What the output says about the design:

  • Where the parameters are. The RoI heads hold 13.9 million of the 19.0 million parameters, because the box head is two fully connected layers on a flattened 7×7×2567 \times 7 \times 256 RoI feature (12,544⋅102412{,}544 \cdot 1024 weights in the first layer alone). The MobileNetV3 backbone plus FPN is only 4.4 million, and the RPN 0.6 million. The second stage is the expensive part per box, which is one reason the number of proposals is capped.
  • Anchors. This mobile variant uses 15 anchors per position (5 sizes x 3 ratios) on each of its 3 feature levels; the ResNet-50 FPN version uses one size per level on 5 levels.
  • Settings from the lessons. RPN NMS at IoU 0.7, the second stage's box coder weights (10,10,5,5)(10, 10, 5, 5) from box encoding, score threshold 0.05 and class-wise NMS at IoU 0.5, at most 100 detections. This "320" model keeps only 150 proposals at test time (the ResNet-50 FPN model keeps 1,000) and resizes images so that the shorter side is 320 pixels.
  • Two modes. In training mode the model needs targets and returns a dict of four losses: loss_objectness and loss_rpn_box_reg for stage 1, loss_classifier and loss_box_reg for stage 2, summed for the backward pass. With random weights the classifier loss is about ln⁡4≈1.39\ln 4 \approx 1.39 (four equally likely classes, 1.401 here) and the objectness loss about ln⁡2≈0.69\ln 2 \approx 0.69, as expected for a network that knows nothing. In eval mode it returns per image a dict with boxes (in the original image's pixels, [x1, y1, x2, y2]), labels and scores: 100 boxes here, all junk.

Labels start at 1: torchvision reserves class 0 for background, so num_classes is your number of classes plus one. Forgetting the +1 is a classic bug.

To train it for real you start from COCO-pretrained weights, replace the box predictor with one for your classes and fine-tune (transfer learning, fine-tuning recipe). That needs the weight download and hours of compute, so it is shown but not run here:

python
# Not run here: needs the COCO weights (a download) and a GPU for hours of training.
import torch
from torchvision.models.detection import fasterrcnn_resnet50_fpn_v2, FasterRCNN_ResNet50_FPN_V2_Weights
from torchvision.models.detection.faster_rcnn import FastRCNNPredictor

model = fasterrcnn_resnet50_fpn_v2(weights=FasterRCNN_ResNet50_FPN_V2_Weights.DEFAULT)
in_features = model.roi_heads.box_predictor.cls_score.in_features          # 1024
model.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_classes=1 + 3)   # background + your classes

params = [p for p in model.parameters() if p.requires_grad]
optimizer = torch.optim.SGD(params, lr=0.01, momentum=0.9, weight_decay=1e-4)
scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=[16, 22], gamma=0.1)

for epoch in range(26):
    model.train()
    for images, targets in train_loader:        # targets: [{"boxes": FloatTensor[N, 4] x1y1x2y2, "labels": Int64Tensor[N]}]
        losses = model(images, targets)
        loss = sum(losses.values())
        optimizer.zero_grad(); loss.backward(); optimizer.step()
    scheduler.step()
    evaluate(model, val_loader)                 # COCO-style mAP on the validation split

Two-stage or one-stage?

The two-stage design looks at each proposal with its own aligned features, which made it the most accurate design for a long time, especially for small objects and precise boxes. Its costs are a second network pass per proposal and a more complicated pipeline. One-stage detectors (SSD, RetinaNet, YOLO) predict classes and boxes directly from the dense feature map, and since about 2020 they match two-stage accuracy at a fraction of the latency, which is why most new projects start with a YOLO-family model. Faster R-CNN remains a strong, well-understood baseline, the natural choice when you also need masks (Mask R-CNN) or keypoints from the same framework, and the easiest detector to read end to end in torchvision's source.

Pitfalls

  • num_classes without background. torchvision's detection models count background as class 0; labels in the targets must start at 1.
  • Box format and dtype of targets. Boxes are float [x1, y1, x2, y2] in pixels of the input image (not normalised), labels int64; a box with x2≤x1x_2 \le x_1 raises an error in training.
  • Images in the wrong range. torchvision detection models normalise internally and expect float images in [0,1][0, 1], (C, H, W), RGB. Passing 0 to 255 values or BGR silently ruins pretrained weights.
  • Calling the model in the wrong mode. model(images) in training mode without targets raises an error; with targets it returns losses, not detections; only in eval mode does it return detections. (With pretrained weights torchvision freezes the backbone's batch-norm layers as FrozenBatchNorm2d; a model built with plain BatchNorm2d would also keep updating its statistics in training mode.)
  • Too few proposals for crowded images. With 150 or 1,000 proposals and many small objects, recall is capped by stage 1; raise rpn_post_nms_top_n_test and box_detections_per_img.
  • Using RoI pooling for precise tasks. For masks or keypoints use RoI Align; the quantisation error is up to half a feature cell per edge.

Practice

  1. A proposal is [100, 60, 300, 260] in image pixels on a stride-16 feature map. Which feature-map region does RoI Align (with aligned=True) read, and what does RoI pooling round it to?
Answer

Scaled by 1/16: [6.25, 3.75, 18.75, 16.25]; RoI Align subtracts 0.5: [5.75, 3.25, 18.25, 15.75], no rounding. RoI pooling rounds the scaled corners to [6, 4, 19, 16] and treats x2x_2, y2y_2 as inclusive, so it reads cells 6 to 19 and 4 to 16: image pixels 96 to 320 and 64 to 272 instead of 100 to 300 and 60 to 260. The right edge is off by 20 pixels.

  1. Why does the RPN only predict "object or not", and not the class?
Answer

Its job is high recall of anything object-like at low cost; the class decision is made in stage 2 with better, aligned features. A class-agnostic RPN also transfers across class sets and keeps the head small (one logit per anchor instead of one per class).

  1. In the recorded example the first fully connected layer of the box head has about 12.8 million weights. Compute it from the RoI feature size.
Answer

7⋅7⋅256=12,5447 \cdot 7 \cdot 256 = 12{,}544 inputs times 1,024 outputs =12,845,056= 12{,}845{,}056 weights plus 1,024 biases. The second layer adds 1024⋅1024+10241024 \cdot 1024 + 1024, the predictor 1024⋅(4+16)+201024 \cdot (4 + 16) + 20; together about 13.9 million, matching the printed RoI-heads count.

Test yourself

What was the main speed-up from R-CNN to Fast R-CNN?

  1. A smaller backbone
  2. Running the CNN once per image and pooling features per proposal, instead of once per proposal
  3. Removing NMS
  4. Using fewer classes

What does Faster R-CNN's region proposal network replace?

  1. The backbone
  2. Selective Search, the hand-made proposal algorithm
  3. The box head
  4. Non-maximum suppression

In the shift test, why did RoI pooling not react when the box moved by 1 or 2 pixels?

  1. It uses bilinear interpolation
  2. It rounds the box to whole feature cells (4 pixels each here), so small moves land on the same cells
  3. The feature map was constant
  4. It averages over the whole image

A torchvision Faster R-CNN for 3 object classes needs which num_classes?

  1. 2
  2. 3
  3. 4
  4. 80