Algorithmadvanced
Faster R-CNN
Also called region proposal network.
Fast R-CNN with a region proposal network that scores and refines anchors on the shared feature map, making detection one trainable network.
- Time
- O(A log A + N P + K P^2) worst
- Space
- O(A + P K) extra
- Where
- A = the number of anchors; K = the number of object classes; N = the number of boxes kept before NMS; P = the number of proposals
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Shaoqing Ren, Kaiming He, Ross Girshick, Jian Sun, 2015
Faster R-CNN is a two-stage detector in which the proposals come from the network itself. The first stage, the region proposal network (RPN), slides a small network over the convolutional feature map. At each position it looks at anchor boxes of fixed sizes and shapes, 9 in the paper, and for each anchor predicts an objectness score and four offsets in the encoding of bounding box regression. The decoded boxes are clipped to the image, ranked, and thinned by non-maximum suppression at IoU 0.7, and the best few hundred become the proposals. The second stage is Fast R-CNN on the same feature map. Since both stages share the convolutional layers, a proposal costs almost nothing, and with VGG16 the whole detector runs at 5 frames per second on a GPU. "Region proposal network" is the name of the first stage only, not of the detector.
In plain words
Fast R-CNN was quick, but it still needed a slow outside method to suggest where objects might be. Faster R-CNN lets the same network make those suggestions. It places a fixed set of boxes, the anchors, at every cell of the feature map: small, medium and large, and wide, square and tall. For each anchor a small layer answers two questions: is there an object here, and how should this box move and stretch to fit it? The best few hundred moved boxes, with near copies removed, go to the second stage. That stage pools the features under each box, names the object, and fixes the box once more. Both stages read one feature map, so the suggestions are almost free.
The problem
The input is an image and a trained network: a backbone that gives a feature map of stride pixels (16 for VGG16), an RPN head that gives, for each of the anchors at each cell, an objectness score and four offsets, and a Fast R-CNN head that gives class scores and offsets for each proposal. The output is a list of boxes with a class and a score. The quality depends on the training and is measured by detection mean average precision. This page gives the steps that are not learned and proves facts about them; the network is outside.
The algorithm
FASTER-R-CNN-DETECT(I, network, N_pre, N_post, τ_rpn, τ)- 1
F ← backbone(I); (o_a, δ_a) ← RPN head on F for every anchor a ▷ network, outside - 2
A ← the k anchors at the center of every cell of F - 3
B_a ← CLIP(DECODE(a, δ_a)) to the image, for every a ∈ A - 4
drop every box with a side below the minimum size - 5
keep the N_pre boxes of highest o_a - 6
P ← greedy NMS at IoU τ_rpn = 0.7, keeping at most N_post boxes - 7
for each r ∈ P: RoI pooling on F, class scores p_r and offsets t_r ▷ Fast R-CNN head - 8
return, for each class, NMS at τ of the boxes DECODE(r, t_r^k) with scores p_{r,k}
Anchors. The paper uses 3 sizes, areas , and pixels, and 3 aspect ratios, 1:1, 1:2 and 2:1, so anchors at each cell. For a feature map of cells there are anchors, about 20000 for an image of about pixels. The anchors and the head are the same at every cell, so a shifted object gives a shifted proposal. The anchor boxes page treats the choice of sizes and shapes.
Training the RPN. An anchor is positive if its IoU with some ground truth box is above 0.7, or if it is the anchor of largest IoU for some ground truth box, so that every box has at least one positive. It is negative if its IoU is below 0.3 with every box, and ignored otherwise. Anchors that cross the image border are ignored in training, which leaves about 6000 of the 20000. Each image gives a mini-batch of 256 anchors with up to half positives, filled with negatives. The loss is
with the log loss for , smooth L1 for , for positives, , the number of anchor locations (about 2400) and . The anchor assignment page compares this rule with those of SSD, RetinaNet and ATSS.
Sharing the features. The paper trains the two stages in four steps: train the RPN, train Fast R-CNN on its proposals, fix the shared layers and fine-tune the RPN layers, and then fine-tune the Fast R-CNN layers. The paper also describes an approximate joint training of both losses at once, which gives close results with 25 to 50 percent less training time and is in its released Python code.
Proposals at test time. The cross-border boxes are clipped, not dropped. NMS at 0.7 leaves about 2000 proposals per image; the detector is trained on 2000 and tested with the best 300.
Example
Take an image of pixels and four anchors of in a row, centered at : , , and . Let the RPN give the scores 0.9, 0.8, 0.3 and 0.6 and zero offsets.
- Clipping makes the first box and the last ; the middle two are inside.
- With a minimum size of 16 all four stay.
- NMS at the paper's keeps all four, since next boxes overlap by IoU and the others less. The proposals are the four boxes in the order 0.9, 0.8, 0.6, 0.3.
- With instead, NMS keeps , drops at IoU 0.4, keeps , and drops at IoU 0.4 with it.
If the offsets of the third anchor are , its center moves by half a width to and its width doubles to 64, giving before the clip and after.
For training, take the image , anchors , , , and , and ground truth boxes and . The IoUs with their best box are 3/7, 9/11, 1/4, 4/25, and the last anchor crosses the border. The labels are: ignored, positive, negative, positive (it is the best anchor of the small box, though 4/25 is below 0.3), ignored.
Correctness
The network has no correctness theorem; its accuracy is measured. The proof page shows for the steps that are not learned:
- Anchors. The anchors at a cell have the stated areas and aspect ratios and are centered on the cell, so a shift of the image by a multiple of shifts the anchor set onto itself.
- Proposals. The output has at most boxes, sorted by score, inside the image, no smaller than the minimum, and with pairwise IoU at most .
- Labels. Every ground truth box with an inside anchor of positive IoU has at least one positive anchor, positives and negatives are disjoint, and anchors across the border are ignored.
- Sampling. The batch has at most half positives and at most 256 anchors, and every sampled label agrees with the label rule.
Proof: The anchors tile the feature map with the stated shapes, the proposal step returns sorted, clipped, large enough and non-overlapping boxes, and the RPN labels and sampling follow their rulesfull
The backbone and the two heads are learned and outside the claims. The claims are about the steps of the page that are not learned, as the Python code does them. A box is .
Claim 1 (anchors). For sizes and ratios , the code makes the shape , at the center of cell . Each anchor has area and aspect ratio . If shifts the plane by with integers and , every anchor at a cell for which is a cell of the map is mapped by onto the anchor of the same shape at that cell.
Proof. and . The anchors at a cell are the shapes placed at the cell center, and moves the center of cell to , the center of cell , without changing the shape.
Since the head has the same weights at every cell, the scores and offsets of a shifted image are, away from the borders and up to the receptive field, the shifted scores and offsets, and the proposals shift with the image. This is the translation property of the paper; it is a property of the convolution, and the claim gives the part that the anchors add.
Claim 2 (proposals). The proposal step returns at most boxes, in order of non-increasing score, each inside with both sides at least the minimum size , and with pairwise IoU at most .
Proof. Line L3 clips every coordinate to the image, so every box is inside. Line L4 keeps only boxes with both sides at least , and the later steps only remove boxes. Line L5 sorts by score with ties by index. Line L6 visits the boxes in that order and adds a box only if its IoU with every box kept so far is at most , and stops at boxes. So the output is a subsequence of a sorted list, its size is at most , and any two kept boxes were compared when the later one was added.
Clipping happens after decoding: a box that crosses the border keeps its regressed inside part. If clipping came first the offsets would apply to a different box than the one the network was trained on.
Claim 3 (labels). Let the label of an anchor that crosses the image border be "ignored". For the other anchors, let the label be positive if the IoU with some ground truth box is at least or if the anchor reaches the largest IoU, when positive, among the inside anchors for some box; negative if it is not positive and every IoU is below ; and ignored otherwise. The code gives these labels, and every ground truth box with an inside anchor of positive IoU has a positive anchor, one of largest IoU with it.
Proof. The code first sets, for each inside anchor, the label 0 when its best IoU is below , and then 1 when it is at least ; since at most one of the two applies. Then for each ground truth box with a largest IoU over the inside anchors, it sets every inside anchor with IoU to 1 and matches it to . An anchor that reaches is positive by the rule, and the code may overwrite a 0 there, as the rule asks, since a forced positive is not negative. Anchors that cross the border are never touched and stay at . The last statement holds because the anchors that reach are set to 1 and nothing later sets a label back to 0 or .
The match is a fine point. If one anchor reaches the largest IoU for two boxes, it is positive for both but matched, for its regression target, to the later one in the code, so the earlier box can have a positive anchor that does not regress towards it. The rule of the paper does not say which box wins; this page keeps the later box.
Claim 4 (sampling). With positives and negatives, the sampled batch has positives and negatives, all other anchors ignored. So it has at most anchors, at most half of them positive, and each sampled label equals the label of Claim 3.
Proof. The code samples without replacement from the list of positives and then from the list of negatives, with these counts, and keeps the labels of the sampled anchors.
Claim 5 (RPN loss). The loss of the code is with the number of sampled anchors, which is the formula of the paper with as the indicator of a positive.
Proof. The code sums the log loss of for positives and of for negatives over the sampled anchors, divides by their number, and adds times the smooth L1 terms of the positives only.
Complexity
The backbone and the heads are outside the page. Decoding and clipping cost for anchors, the minimum-size filter , and the sort (a selection of the top would give ). Greedy NMS that stops after kept boxes compares each of the candidates with at most kept boxes, . The second stage costs the RoI pooling of Fast R-CNN and for NMS of each class. With VGG16 the paper reports 198 ms per image for the whole system, 10 ms of it in the proposal layers, which is about 5 frames per second.
Properties
- Shared features. The proposals and the detection read the same feature map, so proposals add little time.
- Translation-equivariant anchors. The same anchors and weights at every cell.
- Learned proposals. Unlike selective search, the proposals are trained for the classes of the data and improve with the backbone.
- Two stages. The second stage pools features again for each proposal, which costs more than a one-stage detector such as SSD or YOLO, but is usually more accurate on small objects.
- Deterministic at test time; not exact, since it is a learned method.
Variants and improvements
- Feature pyramid network. FPN puts anchors of one size on each level of a feature pyramid and pools each RoI from the level that fits its size.
- Mask R-CNN. Mask R-CNN adds a mask branch and replaces RoI pooling with RoIAlign.
- R-FCN and Cascade R-CNN. R-FCN moves most of the second stage before the pooling. Cascade R-CNN runs several second stages with rising IoU thresholds.
- RPN alone. The RPN is also a fast class-agnostic proposal method in its own right, and a one-class RPN is a simple detector.
- Other assignment rules. ATSS and other rules of the anchor assignment page replace the fixed 0.7 and 0.3.
When to use it
Use Faster R-CNN, usually with an FPN, when accuracy matters more than speed, for small objects, and as a strong baseline that is well understood. Use a one-stage detector when the time budget is tight, and a set-based detector such as DETR when NMS and anchors are to be avoided.
Pitfalls
- Anchor sizes that do not fit the data. An object much smaller than the smallest anchor gets low IoU with every anchor and is learned only through the "best anchor" rule.
- Border anchors. The paper reports that with the anchors that cross the border in training, large error terms that are hard to correct appear and training does not converge. At test time the boxes are clipped instead.
- Thresholds of two kinds. The RPN uses NMS at 0.7 to keep many proposals, and the detector uses about 0.3 per class; swapping them loses recall or adds duplicates.
- Proposals that differ between training and test. The detector is trained on 2000 proposals and tested on 300 from the same RPN. In Table 2 of the paper, a detector trained on selective search proposals and tested on 300 RPN proposals reaches 56.8 percent mAP, against 59.9 percent when both stages use shared RPN proposals.
- Ties in the "best anchor" rule. Several anchors with the same largest IoU all become positive.
- Clipping order. Clip after decoding, then apply the minimum size; clipping first loses the regression of boxes that cross the border.
Implementations
The network is outside this page: the Python code takes the RPN scores and offsets and the second-stage head as inputs, and the tests build them by hand or from the ground truth with a fixed seed. The code implements the anchors, the proposal step of lines L2 to L6, the second-stage decoding and NMS of each class, the anchor labels with the border rule, the sampling of 256 anchors, and the RPN loss. The tests check the anchor shapes and centers, the proposal example above with its variants, the label example, the label rule against its definition on random boxes, the RPN loss on hand values, the properties of the proposals on random outputs, and a run of the whole pipeline that recovers a known box.
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/faster-r-cnn/. The authors are listed in prov/5WFTBK.jsonl.
"""Faster R-CNN around given network outputs.
The backbone, the region proposal network (RPN) head and the detection head
are not part of this file. The caller passes the RPN outputs as dicts keyed
by anchor index: an objectness score and four offsets per anchor. The tests
build them by hand or with a fixed seed. This file has the parts that are not
learned: the anchors, the proposal step (decode, clip, drop small boxes,
top-N, NMS, top-N), the anchor labels and the mini-batch sampling for RPN
training, the RPN loss, and the second-stage decoding and NMS on given class
scores and offsets.
Boxes are (x1, y1, x2, y2) in pixels of the scaled image. Standard library only.
"""
import math
from fractions import Fraction
def area(b):
return max(0, b[2] - b[0]) * max(0, b[3] - b[1])
def iou(a, b):
"""Intersection over union; exact Fractions on integer boxes."""
iw = min(a[2], b[2]) - max(a[0], b[0])
ih = min(a[3], b[3]) - max(a[1], b[1])
if iw <= 0 or ih <= 0:
return 0
inter = iw * ih
union = area(a) + area(b) - inter
if isinstance(inter, int) and isinstance(union, int):
return Fraction(inter, union)
return inter / union
def anchors(feat_w, feat_h, stride, sizes=(128, 256, 512), ratios=(0.5, 1, 2)):
"""k = len(sizes) * len(ratios) anchors at each feature cell, centered on the cell.
A ratio is height / width, and an anchor of size s has area s^2. The order is
row, column, then the k shapes, so anchor index = (row * feat_w + col) * k + shape."""
shapes = []
for r in ratios:
for s in sizes:
w, h = s / math.sqrt(r), s * math.sqrt(r)
shapes.append((w, h))
out = []
for row in range(feat_h):
for col in range(feat_w):
cx, cy = (col + 0.5) * stride, (row + 0.5) * stride
for w, h in shapes:
out.append((cx - w / 2, cy - h / 2, cx + w / 2, cy + h / 2))
return out
def decode(a, t):
w, h = a[2] - a[0], a[3] - a[1]
x, y = a[0] + w / 2, a[1] + h / 2
gx, gy, gw, gh = x + w * t[0], y + h * t[1], w * math.exp(t[2]), h * math.exp(t[3])
return (gx - gw / 2, gy - gh / 2, gx + gw / 2, gy + gh / 2)
def encode(a, g):
w, h = a[2] - a[0], a[3] - a[1]
gw, gh = g[2] - g[0], g[3] - g[1]
return ((g[0] + g[2] - a[0] - a[2]) / 2 / w, (g[1] + g[3] - a[1] - a[3]) / 2 / h,
math.log(gw / w), math.log(gh / h))
def clip(b, img_w, img_h):
return (min(max(b[0], 0), img_w), min(max(b[1], 0), img_h),
min(max(b[2], 0), img_w), min(max(b[3], 0), img_h))
def greedy_nms(boxes, scores, thr, max_keep=None):
order = sorted(range(len(boxes)), key=lambda i: (-scores[i], i))
keep = []
for i in order:
if max_keep is not None and len(keep) >= max_keep:
break
if all(iou(boxes[i], boxes[k]) <= thr for k in keep):
keep.append(i)
return keep
def rpn_proposals(anchor_list, scores, deltas, img_w, img_h, min_size=16, pre_nms=6000,
nms_thr=0.7, post_nms=300):
"""The proposal step of the RPN. Returns a list of (score, box), best first."""
boxes = [clip(decode(a, d), img_w, img_h) for a, d in zip(anchor_list, deltas)] # @line L3
cand = [i for i, b in enumerate(boxes)
if b[2] - b[0] >= min_size and b[3] - b[1] >= min_size] # @line L4
cand.sort(key=lambda i: (-scores[i], i))
cand = cand[:pre_nms] # @line L5
keep = greedy_nms([boxes[i] for i in cand], [scores[i] for i in cand], nms_thr, post_nms) # @line L6
return [(scores[cand[j]], boxes[cand[j]]) for j in keep]
def detect(proposals, head, img_w, img_h, nms_thr=0.3, score_thr=0.05):
"""Second stage on the proposals. head(box) returns (class probabilities with
background first, K lists of 4 offsets). Returns {class: [(score, box)]}."""
outs = [head(b) for _, b in proposals] # @line L7
if not outs:
return {}
out = {}
for k in range(1, len(outs[0][0])):
cand = [i for i, (p, _) in enumerate(outs) if p[k] > score_thr]
boxes = [clip(decode(proposals[i][1], outs[i][1][k - 1]), img_w, img_h) for i in cand]
scores = [outs[i][0][k] for i in cand]
out[k] = [(scores[j], boxes[j]) for j in greedy_nms(boxes, scores, nms_thr)]
return out # @line L8
def faster_rcnn(feat_w, feat_h, stride, rpn_scores, rpn_deltas, head, img_w, img_h, **kw):
"""The whole test-time pipeline on given network outputs."""
# rpn_scores and rpn_deltas are the outputs of the backbone and the RPN head.
assert len(rpn_scores) == len(rpn_deltas) # @line L1
a = anchors(feat_w, feat_h, stride, kw.get("sizes", (128, 256, 512)),
kw.get("ratios", (0.5, 1, 2))) # @line L2
props = rpn_proposals(a, rpn_scores, rpn_deltas, img_w, img_h, kw.get("min_size", 16),
kw.get("pre_nms", 6000), kw.get("rpn_nms", 0.7), kw.get("post_nms", 300))
return props, detect(props, head, img_w, img_h, kw.get("nms", 0.3), kw.get("score_thr", 0.05))
def label_anchors(anchor_list, gts, img_w, img_h, pos_thr=0.7, neg_thr=0.3):
"""RPN training labels: 1 positive, 0 negative, -1 ignored, and the matched truth.
Anchors that cross the image border are ignored. A positive has IoU >= pos_thr
with some truth, or is an anchor of largest IoU for some truth (if that IoU is
above zero); a negative has IoU < neg_thr with every truth."""
inside = [a[0] >= 0 and a[1] >= 0 and a[2] <= img_w and a[3] <= img_h for a in anchor_list]
labels = [-1] * len(anchor_list)
match = [None] * len(anchor_list)
if not gts:
return [0 if ok else -1 for ok in inside], match
ious = [[iou(a, g) for g in gts] if ok else None for a, ok in zip(anchor_list, inside)]
for i, row in enumerate(ious):
if row is None:
continue
j = max(range(len(gts)), key=lambda k: (row[k], -k))
match[i] = j
if row[j] < neg_thr:
labels[i] = 0
if row[j] >= pos_thr:
labels[i] = 1
for j in range(len(gts)):
best = max((row[j] for row in ious if row is not None), default=0)
if best > 0:
for i, row in enumerate(ious):
if row is not None and row[j] == best:
labels[i], match[i] = 1, j
return labels, match
def sample_anchors(labels, rng, batch=256):
"""Up to batch / 2 positives, the rest negatives; the others become ignored (-1)."""
pos = [i for i, v in enumerate(labels) if v == 1]
neg = [i for i, v in enumerate(labels) if v == 0]
pos = set(rng.sample(pos, min(len(pos), batch // 2)))
neg = set(rng.sample(neg, min(len(neg), batch - len(pos))))
return [v if (i in pos or i in neg) else -1 for i, v in enumerate(labels)]
def smooth_l1(x):
return 0.5 * x * x if abs(x) < 1 else abs(x) - 0.5
def rpn_loss(probs, deltas, labels, targets, n_reg, lam=10.0):
"""(1/N_cls) sum log loss + lam (1/N_reg) sum over positives of smooth L1, where
N_cls is the number of sampled anchors and n_reg the number of anchor locations."""
used = [i for i, v in enumerate(labels) if v >= 0]
if not used:
return 0.0
cls = -sum(math.log(probs[i] if labels[i] == 1 else 1 - probs[i]) for i in used) / len(used)
reg = sum(smooth_l1(a - b) for i in used if labels[i] == 1 for a, b in zip(deltas[i], targets[i]))
return cls + lam * reg / n_reg
test_faster_r_cnn.py 135 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/faster-r-cnn/. The authors are listed in prov/5WFTBK.jsonl.
import math
import random
from fractions import Fraction
from faster_r_cnn import (
anchors,
decode,
encode,
faster_rcnn,
iou,
label_anchors,
rpn_loss,
rpn_proposals,
sample_anchors,
)
ROW = [(-8, 0, 24, 32), (8, 0, 40, 32), (24, 0, 56, 32), (40, 0, 72, 32)]
ZERO = [(0.0, 0.0, 0.0, 0.0)] * 4
def test_anchor_shapes():
a = anchors(5, 3, 16)
assert len(a) == 5 * 3 * 9
for k, b in enumerate(a):
w, h = b[2] - b[0], b[3] - b[1]
size = (128, 256, 512)[k % 3]
ratio = (0.5, 1, 2)[(k % 9) // 3]
assert abs(w * h - size * size) < 1e-6 and abs(h / w - ratio) < 1e-9
cell = k // 9
assert abs((b[0] + b[2]) / 2 - (cell % 5 + 0.5) * 16) < 1e-9
assert abs((b[1] + b[3]) / 2 - (cell // 5 + 0.5) * 16) < 1e-9
def test_page_example_proposals():
scores = [0.9, 0.8, 0.3, 0.6]
out = rpn_proposals(ROW, scores, ZERO, 64, 32, min_size=16, nms_thr=0.3)
assert out == [(0.9, (0, 0, 24, 32)), (0.6, (40, 0, 64, 32))]
assert iou((0, 0, 24, 32), (8, 0, 40, 32)) == Fraction(2, 5)
out = rpn_proposals(ROW, scores, ZERO, 64, 32, min_size=16, nms_thr=0.7)
assert [s for s, _ in out] == [0.9, 0.8, 0.6, 0.3]
# A minimum size of 32 drops the two clipped boxes, which are 24 wide.
out = rpn_proposals(ROW, scores, ZERO, 64, 32, min_size=32, nms_thr=0.7)
assert [b for _, b in out] == [(8, 0, 40, 32), (24, 0, 56, 32)]
# Offsets move the box before the clip: shift anchor 2 right by half its width and double its width.
out = rpn_proposals(ROW[2:3], [1.0], [(0.5, 0.0, math.log(2), 0.0)], 64, 32, min_size=1)
assert out == [(1.0, (24.0, 0.0, 64, 32.0))]
def test_page_example_labels():
anchor_list = [(0, 0, 10, 10), (5, 0, 15, 10), (10, 0, 20, 10), (20, 0, 30, 10), (35, 0, 45, 10)]
gts = [(4, 0, 14, 10), (21, 0, 25, 4)]
labels, match = label_anchors(anchor_list, gts, 40, 10)
assert labels == [-1, 1, 0, 1, -1]
assert match[1] == 0 and match[3] == 1
assert iou(anchor_list[0], gts[0]) == Fraction(3, 7) and iou(anchor_list[3], gts[1]) == Fraction(4, 25)
def test_labels_match_the_definition():
rng = random.Random(1)
def rbox(lo, hi):
x, y = rng.randint(lo, hi), rng.randint(lo, hi)
return (x, y, x + rng.randint(2, 16), y + rng.randint(2, 16))
for _ in range(80):
anchor_list = [rbox(-6, 34) for _ in range(20)]
gts = [rbox(0, 24) for _ in range(rng.randint(1, 3))]
labels, match = label_anchors(anchor_list, gts, 40, 40)
inside = [a[0] >= 0 and a[1] >= 0 and a[2] <= 40 and a[3] <= 40 for a in anchor_list]
best_gt = [max((iou(a, g) for a, ok in zip(anchor_list, inside) if ok), default=0) for g in gts]
for i, a in enumerate(anchor_list):
if not inside[i]:
assert labels[i] == -1
continue
o = [iou(a, g) for g in gts]
forced = any(best_gt[j] > 0 and o[j] == best_gt[j] for j in range(len(gts)))
if forced or max(o) >= Fraction(7, 10):
assert labels[i] == 1 and o[match[i]] > 0
elif max(o) < Fraction(3, 10):
assert labels[i] == 0
else:
assert labels[i] == -1
sampled = sample_anchors(labels, rng, batch=8)
assert sum(1 for v in sampled if v == 1) <= 4 and sum(1 for v in sampled if v >= 0) <= 8
assert all(v == -1 or v == labels[i] for i, v in enumerate(sampled))
def test_rpn_loss_value():
probs = [0.9, 0.2, 0.5]
deltas = [(0.5, 0.0, 0.0, 2.0), (9.0, 9.0, 9.0, 9.0), (0.0, 0.0, 0.0, 0.0)]
targets = [(0.0, 0.0, 0.0, 0.0)] * 3
labels = [1, 0, -1]
want = -(math.log(0.9) + math.log(0.8)) / 2 + 10 * (0.125 + 1.5) / 50
assert abs(rpn_loss(probs, deltas, labels, targets, n_reg=50) - want) < 1e-12
def test_proposals_properties_on_random_outputs():
rng = random.Random(2)
for _ in range(6):
fw, fh = rng.randint(2, 5), rng.randint(2, 4)
a = anchors(fw, fh, 16, sizes=(16, 32), ratios=(0.5, 1, 2))
scores = [rng.random() for _ in a]
deltas = [tuple(rng.gauss(0, 0.2) for _ in range(4)) for _ in a]
out = rpn_proposals(a, scores, deltas, fw * 16, fh * 16, min_size=4, nms_thr=0.7, post_nms=10)
assert len(out) <= 10
assert [s for s, _ in out] == sorted((s for s, _ in out), reverse=True)
for _, b in out:
assert 0 <= b[0] and b[2] <= fw * 16 and 0 <= b[1] and b[3] <= fh * 16
assert b[2] - b[0] >= 4 and b[3] - b[1] >= 4
for i in range(len(out)):
for j in range(i):
assert iou(out[i][1], out[j][1]) <= 0.7
def test_whole_pipeline():
truth = (20.0, 12.0, 44.0, 36.0)
a = anchors(4, 3, 16, sizes=(16, 32), ratios=(1,))
# An RPN that likes anchors near the truth and points them at it.
scores = [float(iou(b, truth)) for b in a]
deltas = [encode(b, truth) if iou(b, truth) > 0.3 else (0.0, 0.0, 0.0, 0.0) for b in a]
def head(box):
o = float(iou(box, truth))
return [1 - o, o], [encode(box, truth)]
props, dets = faster_rcnn(4, 3, 16, scores, deltas, head, 64, 48, sizes=(16, 32), ratios=(1,),
min_size=8)
assert all(abs(x - y) < 1e-9 for x, y in zip(props[0][1], truth))
assert len(dets[1]) == 1
s, b = dets[1][0]
assert s > 0.99 and all(abs(x - y) < 1e-9 for x, y in zip(b, truth))
assert all(abs(x - y) < 1e-9 for x, y in zip(decode(a[5], encode(a[5], truth)), truth))
History
R-CNN (2014) and Fast R-CNN (2015) depended on selective search, which took about 2 seconds per image on a CPU, more than the detector itself. MultiBox (Erhan et al. 2014) had learned proposals with a network, but not shared with the detector and without translation-invariant anchors. Ren, He, Girshick and Sun put Faster R-CNN on arXiv in June 2015 and presented it at NIPS 2015, with the extended version in IEEE TPAMI in 2017. It reached 73.2 percent mAP on VOC 2007 with VGG16 trained on VOC 2007 and 2012, at 5 frames per second, and its RPN and anchors became the base of the feature pyramid network, Mask R-CNN and most two-stage detectors, and through them of the one-stage SSD and RetinaNet as well.
References
- Shaoqing Ren, Kaiming He, Ross Girshick and Jian Sun, Faster R-CNN: towards real-time object detection with region proposal networks, IEEE Transactions on Pattern Analysis and Machine Intelligence 39(6), 2017, 1137-1149, Section 3.1, Region proposal networks (3.1.1 Anchors: k = 9 from 3 scales and 3 aspect ratios; 3.1.2 Loss function: IoU above 0.7 or the best anchor for a box, below 0.3 negative, lambda = 10; 3.1.3 Training RPNs: 256 anchors per image, up to 1:1); Section 3.2, Sharing features (4-step alternating training); Section 3.3, Implementation details (cross-boundary anchors ignored in training, NMS at 0.7, about 2000 proposals); Section 4.1, Experiments on PASCAL VOC (Table 3: mAP 69.9 on VOC 2007 test trained on 07, 73.2 on 07+12; Table 5: 198 ms per image with VGG16, 10 ms for the proposals, 5 fps)
- Shaoqing Ren, Kaiming He, Ross Girshick and Jian Sun, Faster R-CNN: towards real-time object detection with region proposal networks, NIPS 2015 (arXiv 1506.01497), the conference version, with the same Section 3
- Ross Girshick, Fast R-CNN, ICCV 2015, 1440-1448, Section 2, the detection network that Faster R-CNN keeps as its second stage
- Richard Szeliski, Computer Vision, Algorithms and Applications, second edition, Springer, 2022, Section 6.3, Object detection
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 5WFTBK Edit this page History Report an error Markdown