AI Logic

Architectures

Faster R-CNN

Updated:

Faster R-CNN architecture. Left: the overall flow, in which the input image passes once through the convolutional layers (VGG-16), the resulting feature map is shared by the RPN and RoI pooling, and each of the roughly 300 candidate regions from the RPN goes through RoI pooling and two fully connected layers to output a class and box refinement. Right: the inside of the RPN, which applies a 3×3 convolution to the feature map, outputs per-anchor objectness (2k values) and offsets (4k values) with two 1×1 convolutions, and turns them into proposals via refinement and non-maximum suppression. Alongside: the 9 anchors placed at one location (3 areas × 3 aspect ratios) and the loss formula

Background and Overview

Faster R-CNN is an object detection method that generates candidate regions likely to contain objects with a small network that shares convolutional layers with the detector (the RPN, Region Proposal Network). It was proposed by Ren et al. at Microsoft Research in 2015 (NeurIPS 2015). It made the computation of candidate regions nearly free and merged everything from proposal generation to detection into a single network.

Two-stage detectors, which began with R-CNN, had already made detection itself fast with Fast R-CNN, which shares feature computation across regions. However, Selective Search, which generates the candidate regions, took 1–2 seconds per image on a CPU and had come to dominate detection time. Faster R-CNN replaced this proposal step with a trainable network.

The main results of the paper are:

  • With VGG-16, it detects objects in 198 ms per image (5 fps), including proposal generation. This is about 1/9 of the time with Selective Search (1830 ms).
  • With 300 proposals, fewer than Selective Search's 2000, mAP on PASCAL VOC 2007 rose from 66.9% to 69.9%.
  • Faster R-CNN with a ResNet-101 backbone is reported to have won first place in object detection at ILSVRC 2015 and COCO 2015.

The Faster R-CNN design (shared convolutional layers → RPN → per-region classification and box refinement) became the foundation for later models such as FPN and Mask R-CNN.

The Problem: Time Spent Generating Proposals

The problem Faster R-CNN solved is that as detection networks got faster, generating candidate regions came to take up most of the total time.

In the paper's measurements, Fast R-CNN with VGG-16 takes about 320 ms per image for detection, while Selective Search (a method that successively merges regions with similar color and texture) takes about 1.5 seconds on average on a CPU. Even the faster EdgeBoxes takes 0.2 seconds, about as long as the detection network.

One could reimplement proposal generation to run on the GPU, but then it still could not share computation with the detection network. The paper reasoned that the convolutional feature maps used for detection could also be used to find where objects are likely to be, and decided to generate proposals by adding just a few layers on top of the feature map.

As an everyday analogy, R-CNN and Fast R-CNN were a division of labor: one worker put sticky notes on places saying "check here," and the detection worker examined them. In Faster R-CNN, the detection worker, while looking over the photo once, also puts up the sticky notes for where to look.

Theory: The RPN and Anchors

The RPN is a fully convolutional network that places reference boxes (anchors) of different sizes and aspect ratios at each position of the feature map, and predicts for each whether it is an object and its offset to the object's box. The left side of the figure at the top of the article shows the overall flow, and the right side shows the inside of the RPN.

Faster R-CNN processes an image as follows.

  1. Rescale the image so its shorter side is 600 pixels, and pass it once through the convolutional layers (the 13 layers of VGG-16) to produce a feature map. One cell of the feature map corresponds to 16 pixels of the image.
  2. The RPN applies a 3×3 convolution at each position of the feature map to produce a 512-dimensional feature (followed by ReLU).
  3. That feature is fed into two sibling 1×1 convolutions.
    • The classification (cls) layer outputs 2k2k scores, object or background, for each of the kk anchors.
    • The regression (reg) layer outputs 4k4k offsets from each of the kk anchors to the object box.
  4. The anchors are refined with the offsets to form proposal boxes, non-maximum suppression (IoU threshold 0.7) is applied using the scores, and the top NN (300 at test time) are taken as candidate regions.
  5. From the same feature map, RoI pooling extracts a 7×7 feature for each candidate region.
  6. The features pass through fully connected layers, which output probabilities for K+1K+1 classes (KK object classes plus background) and per-class box refinements (this part is the same as Fast R-CNN).

There are k=9k = 9 anchors, combining three areas of 1282128^2, 2562256^2, and 5122512^2 pixels with three aspect ratios of 1:1, 1:2, and 2:1. If the feature map is W×HW \times H (about 2400 for a typical image), there are WHkWHk anchors in total.

The box offsets are parameterized relative to the anchor, as in R-CNN's bounding-box regression. Denoting the box center by (x,y)(x, y), its width and height by (w,h)(w, h), anchor values with subscript aa, and ground-truth values with ∗*, the prediction tt and the target t∗t^* are:

tx=x−xawa,ty=y−yaha,tw=log⁡wwa,th=log⁡hhat_x = \frac{x - x_a}{w_a}, \quad t_y = \frac{y - y_a}{h_a}, \quad t_w = \log\frac{w}{w_a}, \quad t_h = \log\frac{h}{h_a} tx∗=x∗−xawa,ty∗=y∗−yaha,tw∗=log⁡w∗wa,th∗=log⁡h∗hat^*_x = \frac{x^* - x_a}{w_a}, \quad t^*_y = \frac{y^* - y_a}{h_a}, \quad t^*_w = \log\frac{w^*}{w_a}, \quad t^*_h = \log\frac{h^*}{h_a}

The RPN loss for one image is:

L({pi},{ti})=1Ncls∑iLcls(pi,pi∗)+λ1Nreg∑ipi∗Lreg(ti,ti∗)L(\{p_i\}, \{t_i\}) = \frac{1}{N_{cls}} \sum_i L_{cls}(p_i, p^*_i) + \lambda \frac{1}{N_{reg}} \sum_i p^*_i L_{reg}(t_i, t^*_i)

ii is the anchor index and pip_i is the predicted probability that the anchor is an object. pi∗p^*_i is 1 for a positive anchor and 0 for a negative one. LclsL_{cls} is the two-class (object vs. background) cross-entropy, and LregL_{reg} is the Smooth L1 loss (the Huber loss with δ=1\delta = 1). Because it is multiplied by pi∗p^*_i, the box regression loss is computed only for positive anchors. In the paper's implementation, Ncls=256N_{cls} = 256 (the mini-batch size), Nreg≈2400N_{reg} \approx 2400 (the number of anchor locations), and λ=10\lambda = 10, so the two terms are weighted roughly equally.

Positives and negatives are determined by IoU (the overlap ratio of two boxes) with the ground-truth boxes.

  • Positive: Anchors with IoU above 0.7 with any ground-truth box, plus the anchor with the highest IoU for each ground-truth box. The latter is included for ground-truth boxes that have no anchor with IoU above 0.7.
  • Negative: Anchors with IoU below 0.3 with all ground-truth boxes.
  • Anchors that are neither are excluded from the loss.

Unlike R-CNN and Fast R-CNN, the RPN's regression does not refine boxes from "features extracted from regions of varying size." Every feature comes from the same 3×3 window, and size variation is handled by a separate regressor for each anchor (kk of them, not sharing weights). This is why a single image scale and a single window size are enough to propose objects of many sizes.

Training Procedure: Sharing Convolutional Layers Between the RPN and the Detector

If the RPN and the Fast R-CNN detector are trained separately, each modifies the convolutional layers in a different direction. The paper used a four-step procedure that trains the two networks alternately so that they end up sharing the same convolutional layers.

  1. Train the RPN, starting from weights trained on ImageNet.
  2. Train the Fast R-CNN detector on the proposals from the step-1 RPN. The detector also starts from ImageNet weights, so the convolutional layers are not shared at this point.
  3. Initialize the RPN with the detector's convolutional layers, freeze those layers, and fine-tune only the layers unique to the RPN. Now the two networks have the same convolutional layers.
  4. Keeping the convolutional layers frozen, fine-tune only the layers unique to Fast R-CNN.

The detailed settings for RPN training are as follows.

  • Sample 256 anchors per image, with a positive-to-negative ratio of up to 1:1. Negatives far outnumber positives, so computing the loss over all anchors would bias it toward negatives. If there are fewer than 128 positives, the batch is padded with negatives.
  • New layers are initialized from a Gaussian distribution with standard deviation 0.01.
  • On PASCAL VOC, training runs for 60k iterations at learning rate 0.001 and 20k at 0.0001. Momentum is 0.9 and Weight Decay is 0.0005.

The paper also tried merging the two networks into one and training them simultaneously (approximate joint training). This approximation ignores the gradients with respect to the proposal box coordinates, yet it gave results close to the four-step procedure and cut training time by 25–50%. Implementations such as torchvision use this joint-training form.

Anchors that cross the image boundary are ignored during training. A 1000×600 image has about 20,000 anchors, but only about 6,000 remain after removing the cross-boundary ones. According to the paper, including them in training introduces large, hard-to-correct errors, and training does not converge. At test time, the RPN is applied to the whole image, and cross-boundary proposals are clipped to the image boundary.

Why It Is Fast and Accurate

The reasons Faster R-CNN achieves higher accuracy than Selective Search with fewer proposals can be summarized from the paper's experiments as follows.

  • Sharing convolutional layers makes proposals nearly free: The only computation unique to the RPN is a 3×3 and a 1×1 convolution, which takes 10 ms per image with VGG-16. Because there are only 300 proposals, the per-region fully connected computation also shrinks.
  • Learning how to propose lets it benefit from good features: Selective Search is a fixed procedure, whereas the RPN learns from detection data. Just switching the RPN from ZF net (a small CNN with 5 convolutional layers) to VGG-16 improved proposal quality and raised mAP with the same detector from 56.8% to 59.2%.
  • The top-scoring proposals are accurate: Using only the top 100 proposals ranked by the RPN's classification score still gave 55.1% mAP, not much different from 56.8% with 300. Removing the classification layer and picking 100 random proposals dropped it to 44.6%, showing that the classification score is effective at ranking proposals.
  • Box regression corrects proposal positions: Removing the regression layer and using the anchors directly as proposals dropped mAP to 52.1%. Anchors alone are not enough for accurate detection.
  • Simply varying anchor sizes handles objects of many sizes: Unlike earlier approaches that rescale the image many times (image pyramids) or vary the window size (filter pyramids), it needs only one image scale and one feature map, so it stays fast.

Placing a proposal stage before the detection stage also matters. The paper tried a one-stage scheme (close to OverFeat) that applies the detector directly to densely tiled anchors instead of the RPN, but mAP fell from 58.7% to 53.9% (ZF net). Narrowing down candidates in a proposal stage and then re-classifying and refining with features from those regions was more accurate.

Experimental Results

PASCAL VOC 2007 test: comparison of proposal methods (detector is Fast R-CNN, mAP %)

Proposal methodTest proposalsZF netVGG-16
Selective Search200058.766.9
EdgeBoxes200058.6―
RPN (unshared convolutional layers)30058.768.5
RPN (shared convolutional layers)30059.969.9

With more training data, Faster R-CNN with VGG-16 reached 73.2% on PASCAL VOC 2007 test (trained on VOC 2007+2012) and 78.8% (also trained on COCO).

Time per image (K40 GPU, ms; Selective Search alone runs on CPU)

CNNMethodConvolutionProposalsPer-region computationTotalSpeed
VGG-16Selective Search + Fast R-CNN146151017418300.5 fps
VGG-16RPN + Fast R-CNN14110471985 fps
ZFRPN + Fast R-CNN313255917 fps

Anchor settings (VGG-16, PASCAL VOC 2007 test, mAP %)

AnchorsmAP
One type (area 1282128^2, 1:1)65.8
One type (area 2562256^2, 1:1)66.7
Area 1282128^2 with 3 aspect ratios68.8
3 areas with aspect ratio 1:169.8
3 areas × 3 aspect ratios (default)69.9

Using a single anchor type lowers mAP by 3–4 points. For the loss weight λ\lambda in the range 1–100, mAP varied by only about 1 point, so it is not very sensitive.

COCO test-dev (VGG-16, %)

MethodProposalsmAP@0.5mAP@[.5, .95]
Fast R-CNN (paper's reimplementation)2000 from Selective Search39.319.3
Faster R-CNN300 from RPN42.121.5

Even on mAP@[.5, .95], which uses stricter IoU thresholds, the gain is 2.2 points, showing that RPN proposals improve localization accuracy. On COCO val, simply replacing VGG-16 with ResNet-101 raised the scores from 41.5% / 21.2% to 48.4% / 27.2%.

Practical Considerations

Keep the following points in mind when using Faster R-CNN.

  • Weak on small objects: The last convolutional layer is a coarse grid with a 16-pixel stride, so features of small objects are hard to preserve. The paper also notes that a finer stride could improve accuracy. On COCO, an anchor of area 64264^2 is added for small objects. For tasks with many small objects, combining it with FPN is the usual approach.
  • Choose anchor sizes and aspect ratios to suit your data: The paper's settings (1282128^2 to 5122512^2) assume images rescaled so the shorter side is 600 pixels. For data with very different image sizes or object shapes, revisit the anchor settings.
  • The number of proposals trades speed for accuracy: Fewer test proposals make it faster, and in the paper even 300 gave sufficient accuracy. Defaults differ by implementation (torchvision uses 1000), so be careful when comparing with the paper's settings.
  • Coordinate rounding in RoI pooling: Proposal coordinates are rounded to the feature-map grid, which shifts positions slightly. For tasks where pixel-level positions matter, such as masks, use RoIAlign.

torchvision's fasterrcnn_resnet50_fpn and similar models are not the paper's VGG-16 version but an improved version that uses ResNet-50 with FPN and RoIAlign instead of RoI pooling. Also, num_classes must include the background (21 for 20 object classes). In model.train() mode the model returns a dictionary of losses, and in model.eval() mode it returns detections, so always switch to model.eval() before evaluation.

Comparison with Other Methods

Within the lineage of two-stage detectors that began with R-CNN, Faster R-CNN replaced the last hand-crafted component (Selective Search) with a learned network. Lined up from the same perspective, they compare as follows (times are as reported in each paper and are only rough guides, since the GPUs differ).

MethodCandidate regionsHow candidate features are extractedOutputDetection time per image (reported)
R-CNNSelective Search (about 2000)Crop the image for each candidate and pass it through the CNNClass and box13 s (AlexNet-style), 47 s (VGG-16)
SPP-netSelective SearchSpatial pyramid pooling from the whole-image feature mapClass and box10–100× faster than R-CNN
Fast R-CNNSelective SearchRoI pooling from the whole-image feature mapClass and box0.32 s + about 1.5 s for proposals (VGG-16)
Faster R-CNNRPN (shares the feature map, 300)RoI poolingClass and box0.198 s (VGG-16)
Faster R-CNN + FPNRPN at each level of the feature pyramidChoose the level by RoI size, then RoI poolingClass and box0.148 s (ResNet-50)
Mask R-CNNRPN (with FPN)RoIAlignClass, box, and mask0.195 s (ResNet-101-FPN)

Improvements after Faster R-CNN mainly went in two directions.

  • Handling objects of different sizes: FPN builds a feature pyramid by adding ResNet's stage-wise feature maps from top to bottom, and uses the RPN and the detector at each level of the pyramid. It improved COCO accuracy while also shortening the time per image.
  • Output finer than boxes: Mask R-CNN added a branch to Faster R-CNN that predicts object shapes (masks) and replaced RoI pooling with RoIAlign.

Guidelines for choosing:

  • Bounding-box object detection with an emphasis on accuracy: Faster R-CNN (with FPN) is the standard starting point. Pre-trained weights are also widely available.
  • Many small objects: Combine it with FPN.
  • Object outlines (instance segmentation) are also needed: Use Mask R-CNN.
  • Speed is the top priority: One-stage detectors without a proposal stage (such as YOLO and SSD) are also candidates.

PyTorch example

Show code
python
import torch
import torch.nn as nn
from torchvision import datasets, transforms
from torchvision.models import vgg16, VGG16_Weights
from torchvision.models.detection import FasterRCNN
from torchvision.models.detection.rpn import AnchorGenerator
from torchvision.ops import MultiScaleRoIAlign
from torch.utils.data import DataLoader
from tqdm import tqdm

'''
Object detection on PASCAL VOC. Build torchvision's FasterRCNN with the paper's settings (VGG-16, anchors with 3 areas × 3 aspect ratios,
RPN IoU 0.7 / 0.3, etc.). Training uses joint training of the RPN and detector (the approximate joint training of Section 3.2), not the 4-step alternating procedure
'''

device = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'
VOC_CLASSES = ['aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable',
               'dog', 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor']
epochs = 16                 # About 80k updates over VOC 2007 trainval (about 5000 images), one image at a time
learning_rate = 0.001       # Section 3.1.3 of the paper (PASCAL VOC)

# Shared convolutional layers: the 13 layers of VGG-16 (drop the last max pooling to get a 1/16-scale feature map)
backbone = vgg16(weights=VGG16_Weights.IMAGENET1K_V1).features[:-1]
backbone.out_channels = 512

# Anchors: 9 of them, with areas 128², 256², 512² and aspect ratios (height / width) 0.5, 1, 2
anchor_generator = AnchorGenerator(sizes=((128, 256, 512),), aspect_ratios=((0.5, 1.0, 2.0),))
# The paper uses RoI pooling (7 × 7). torchvision's FasterRCNN accepts the RoIAlign form, so use that
roi_pool = MultiScaleRoIAlign(featmap_names=['0'], output_size=7, sampling_ratio=2)

model = FasterRCNN(
  backbone,
  num_classes=len(VOC_CLASSES) + 1,        # Include the background (20 + 1)
  rpn_anchor_generator=anchor_generator,
  box_roi_pool=roi_pool,
  min_size=600, max_size=1000,             # Rescale so the shorter side is 600 pixels
  rpn_fg_iou_thresh=0.7, rpn_bg_iou_thresh=0.3,          # RPN positives and negatives
  rpn_batch_size_per_image=256, rpn_positive_fraction=0.5,  # 256 per image, at most half positive
  rpn_nms_thresh=0.7,                      # Non-maximum suppression of proposals
  rpn_post_nms_top_n_train=2000,          # 2000 proposals for training the detector (Section 3.3 of the paper)
  rpn_post_nms_top_n_test=300,            # 300 proposals at test time (torchvision's default is 1000)
).to(device)


# Convert PASCAL VOC annotations into the form torchvision detection models expect (boxes and labels)
def to_target(annotation):
  objects = annotation['annotation']['object']
  boxes = [[float(o['bndbox'][k]) for k in ('xmin', 'ymin', 'xmax', 'ymax')] for o in objects]
  labels = [VOC_CLASSES.index(o['name']) + 1 for o in objects]   # 0 is the background
  return {'boxes': torch.tensor(boxes), 'labels': torch.tensor(labels)}


dataset = datasets.VOCDetection('./data', year='2007', image_set='trainval', download=True,
                                transform=transforms.ToTensor(), target_transform=to_target)
loader = DataLoader(dataset, batch_size=1, shuffle=True, collate_fn=lambda b: tuple(zip(*b)))  # One image at a time (same as the paper)

params = [p for p in model.parameters() if p.requires_grad]
optimizer = torch.optim.SGD(params, lr=learning_rate, momentum=0.9, weight_decay=0.0005)
scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=[12], gamma=0.1)  # Drop to 1/10 after about 60k updates

for epoch in tqdm(range(epochs)):
  model.train()                            # Returns a dictionary of losses during training
  for images, targets in loader:
    images = [img.to(device) for img in images]
    targets = [{k: v.to(device) for k, v in t.items()} for t in targets]
    losses = model(images, targets)        # loss_objectness, loss_rpn_box_reg (RPN); loss_classifier, loss_box_reg (detector)
    loss = sum(losses.values())
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
  scheduler.step()

model.eval()                               # In evaluation, returns lists of boxes, labels, and scores
with torch.no_grad():
  image, _ = dataset[0]
  detections = model([image.to(device)])[0]
  keep = detections['scores'] > 0.5
  for box, label in zip(detections['boxes'][keep], detections['labels'][keep]):
    print(VOC_CLASSES[label - 1], [round(v) for v in box.tolist()])

# The pre-trained improved version (ResNet-50 + FPN, trained on COCO) loads in one line
from torchvision.models.detection import fasterrcnn_resnet50_fpn, FasterRCNN_ResNet50_FPN_Weights
coco_model = fasterrcnn_resnet50_fpn(weights=FasterRCNN_ResNet50_FPN_Weights.COCO_V1)

FAQ

Q. What is an anchor?
A.

A reference box with a fixed size and aspect ratio placed at each position of the feature map. Faster R-CNN places 9 at each location (3 areas × 3 aspect ratios), and the RPN predicts for each anchor "whether it is an object" and "its offset to the object's box." Rather than producing boxes from scratch, it learns offsets from nearby anchors, so objects of many sizes can be predicted from the same features.

Q. What is the difference between Fast R-CNN and Faster R-CNN?
A.

How the candidate regions are generated. Fast R-CNN takes proposals made by Selective Search (1–2 seconds per image on a CPU), whereas Faster R-CNN generates proposals with an RPN that shares convolutional layers with the detector. Processing after receiving the proposals (RoI pooling, fully connected layers, classification and box refinement) is the same. With VGG-16, total time went from 1830 ms to 198 ms.

Q. How does Faster R-CNN differ from YOLO and SSD?
A.

Faster R-CNN is split into two stages: one that generates candidate regions, and one that re-classifies and refines the box for each candidate. YOLO and SSD are one-stage detectors that output classes and boxes directly from the feature map without a proposal stage. In general, two-stage detectors make it easier to improve localization accuracy, while one-stage detectors make it easier to be fast.

References

  1. Ren, S., He, K., Girshick, R., & Sun, J. (2015). Faster R-CNN: Towards Real-Time Object Detection with Region Proposal Networks. Advances in Neural Information Processing Systems (NeurIPS) 28. arXiv:1506.01497.
  2. Girshick, R. (2015). Fast R-CNN. Proceedings of the IEEE International Conference on Computer Vision (ICCV), 1440–1448. arXiv:1504.08083.
  3. Girshick, R., Donahue, J., Darrell, T., & Malik, J. (2014). Rich feature hierarchies for accurate object detection and semantic segmentation. CVPR 2014. arXiv:1311.2524.
  4. PyTorch. torchvision.models.detection.fasterrcnn_resnet50_fpn.