机器学习 / A LEAF IN THE GARDEN

锚框

机器学习 · 动手深度学习。来自 Daily Learning 的学习笔记。

简介

一类目标检测算法基于锚框

  • 提出多个锚框区域
  • 预测每个锚框里是否含有关注物体
  • 如果是,预测从锚框到真实边缘框的偏移

IoU 交并比

IoU 用来计算两个框之间的相似度

iou

是 Jacquard 指数的一个特例 J(A,B)=∣A∩B∣∣A∪B∣J(A, B) = \frac{|A \cap B|}{|A \cup B|}

锚框标号

  • 每个锚框是一个训练样本
  • 锚框要么标注成背景、要么关联到一个真实边缘框
  • 生成大量锚框,其中大量负类样本

一种方法是算 锚框-边缘框 的交叉 IoU,每次取最大值做关联,并屏蔽掉其所在行、列,继续下一轮。 anchor

非极大值抑制(NMS)

每个锚框预测一个边缘框,预测的锚框可能有很多重叠,NMS 合并相似的预测

  • 选中非背景类的最大预测值
  • 去掉所有与它的 IoU 大于阈值 θ\theta 的预测
  • 重复直到没有预测

锚框实现

代码 4 · In [3]
%matplotlib inline
import torch
import util
import matplotlib.pyplot as plt
torch.set_printoptions(2) # 设置打印精度

锚框的宽度和高度分别是 wsrws\sqrt r 和 hsr\cfrac{hs}{\sqrt r},其中 ss 是缩放比例,rr 是长宽比。

考虑组合 (s1,r1),(s1,r2),...,(s1,rm),(s2,r1),...,(sn,r1)(s_1, r_1), (s_1, r_2), ..., (s_1, r_m), (s_2, r_1), ..., (s_n, r_1)

代码 6 · In [16]
def multibox_prior(data, sizes, ratios):
    """生成一个像素点上的不同形状的锚框"""
    in_height, in_width = data.shape[-2:]
    device, num_sizes, num_ratios = data.device, len(sizes), len(ratios)
    boxes_per_pixel = (num_sizes + num_ratios - 1)
    size_tensor = torch.tensor(sizes, device=device)
    ratio_tensor = torch.tensor(ratios, device=device)
    # 偏移是为了将锚框移动到像素的中心。由于像素的高度=1,宽度=1,将中心偏移 0.5
    offset_h, offset_w = 0.5, 0.5
    steps_h = 1.0 / in_height  # 缩放后的 y 轴步长
    steps_w = 1.0 / in_width  # 缩放后的 x 轴步长
    # 生成所有锚框的中心点
    center_h = (torch.arange(in_height, device=device) + offset_h) * steps_h
    center_w = (torch.arange(in_width, device=device) + offset_w) * steps_w
    shift_y, shift_x = torch.meshgrid(center_h, center_w, indexing='ij')
    shift_y, shift_x = shift_y.reshape(-1), shift_x.reshape(-1)
    # 生成 `boxes_per_pixel` 个高度和宽度,之后将用于创建锚框的角坐标 (xmin, xmax, ymin, ymax),来计算锚框的宽度和高度
    w = torch.cat((size_tensor * torch.sqrt(ratio_tensor[0]),
                   sizes[0] * torch.sqrt(ratio_tensor[1:])))\
                   * in_height / in_width  # Handle rectangular inputs
    h = torch.cat((size_tensor / torch.sqrt(ratio_tensor[0]),
                   sizes[0] / torch.sqrt(ratio_tensor[1:])))
    # 除以 2 得到锚框的半高和半宽
    anchor_manipulations = torch.stack((-w, -h, w, h)).T.repeat(
                                        in_height * in_width, 1) / 2
    # 每个中心点将有 `boxes_per_pixel` 个锚框,因此生成一个包含所有锚框中心的网格,并重复 `boxes_per_pixel` 次
    out_grid = torch.stack([shift_x, shift_y, shift_x, shift_y],
                dim=1).repeat_interleave(boxes_per_pixel, dim=0)
    output = out_grid + anchor_manipulations
    return output.unsqueeze(0)

返回的锚框变量 Y 的形状

代码 8 · In [17]
img = plt.imread('./images/catdog.jpg')
h, w = img.shape[:2]

print('输入形状', h, w)
X = torch.rand(size=(1, 3, h, w)) # (B, C , H, W)
Y = multibox_prior(X,
                   sizes=[0.75, 0.5, 0.25], # 75%, 50%, 25% 三种缩放比例锚框
                   ratios=[1, 2, 0.5]) # 1:1, 2:1, 1:2 三种长宽比锚框
Y.shape
已保存输出
输入形状 561 728
已保存输出
torch.Size([1, 2042040, 4])

访问一个锚框

代码 10 · In [18]
boxes = Y.reshape(h, w, 5, 4) # (H, W, 锚框数量, 4)
boxes[250, 250, 0, :] # (250, 250) 像素的第一个锚框
已保存输出
tensor([-0.08, -0.20,  0.50,  0.55])

显示图像中一个像素的所有锚框

代码 12 · In [21]
util.set_figsize()
bbox_scale = torch.tensor((w, h, w, h))
fig = plt.imshow(img)
util.show_bboxes(fig.axes, boxes[250, 250, :, :] * bbox_scale, [
    's=0.75, r=1', 's=0.5, r=1', 's=0.25, r=1', 's=0.75, r=2', 's=0.75, r=0.5'
])

代码 12 的已保存图表

交并比

代码 14 · In [22]
def box_iou(boxes1, boxes2):
    """计算两个锚框或边缘框列表之间的成对 IoU"""
    box_area = lambda boxes: ((boxes[:, 2] - boxes[:, 0]) *
                              (boxes[:, 3] - boxes[:, 1]))
    # 计算每个边缘框的面积
    areas1 = box_area(boxes1)
    areas2 = box_area(boxes2)
    # 计算交集的左上角和右下角坐标
    inter_upperlefts = torch.max(boxes1[:, None, :2], boxes2[:, :2])
    inter_lowerrights = torch.min(boxes1[:, None, 2:], boxes2[:, 2:])
    inters = (inter_lowerrights - inter_upperlefts).clamp(min=0)
    # 计算交集大小
    inter_areas = inters[:, :, 0] * inters[:, :, 1]
    # 并集就是两个边缘框的面积之和减去交集
    union_areas = areas1[:, None] + areas2 - inter_areas
    return inter_areas / union_areas # 交并比

真实边界分配给锚框

代码 16 · In [23]
def assign_anchor_to_bbox(ground_truth, anchors, device, iou_threshold=0.5):
    """把最接近的锚框分配给每个真实边界框"""
    num_anchors, num_gt_boxes = anchors.shape[0], ground_truth.shape[0]
    # 在第 i 行和第 j 列的元素 x_ij 是锚框 i 和真实边界框 j 的 IoU
    jaccard = box_iou(anchors, ground_truth)
    # 初始化一个张量来保存每个锚框分配的真实边界框
    anchors_bbox_map = torch.full((num_anchors,), -1, dtype=torch.long, device=device)
    # IoU >= 阈值的锚框直接配给对应真实框
    max_ious, indices = torch.max(jaccard, dim=1)
    anc_i = torch.nonzero(max_ious >= iou_threshold).reshape(-1)
    box_j = indices[max_ious >= iou_threshold]
    anchors_bbox_map[anc_i] = box_j
    col_discard = torch.full((num_anchors,), -1, dtype=torch.long, device=device)
    row_discard = torch.full((num_gt_boxes,), -1, dtype=torch.long, device=device)
    # 保证每个真实框至少有一个锚框负责
    for _ in range(num_gt_boxes):
        max_idx = torch.argmax(jaccard)  # 找到最大 IoU 的索引
        box_idx = (max_idx % num_gt_boxes).long()
        anc_idx = (max_idx / num_gt_boxes).long()
        anchors_bbox_map[anc_idx] = box_idx
        # 将该锚框和真实边界框的行和列设置为 -1,以便在下一次迭代中忽略它们
        jaccard[:, box_idx] = col_discard
        jaccard[anc_idx, :] = row_discard
    return anchors_bbox_map

标记类和偏移

  • 中心偏移用锚框自身宽高归一化 —— (真实中心 - 锚框中心) / 锚框宽高。无论框大小,“偏移 20%“都是同一个量级。
  • 宽高比用 log —— log(真实宽/锚框宽)。
    • 比例必须为正,log 后网络输出任意实数都合法
    • log 让”放大 2 倍”和”缩小 2 倍”变成对称的 +ln2 和 -ln2,回归误差不偏袒某一方向。
代码 18 · In [24]
def offset_boxes(anchors, assigned_bb, eps=1e-6):
    """标记每个锚框的偏移量"""
    c_anc = util.box_corner_to_center(anchors)
    c_assigned_bb = util.box_corner_to_center(assigned_bb)
    offset_xy = 10 * (c_assigned_bb[:, :2] - c_anc[:, :2]) / c_anc[:, 2:]
    offset_wh = 5 * torch.log(eps + c_assigned_bb[:, 2:] / c_anc[:, 2:])
    offset = torch.cat([offset_xy, offset_wh], axis=1)
    return offset

def multibox_target(anchors, labels):
    """使用真实边界框标记锚框"""
    batch_size, anchors = labels.shape[0], anchors.squeeze(0)
    batch_offset, batch_mask, batch_class_labels = [], [], []
    device, num_anchors = anchors.device, anchors.shape[0]
    for i in range(batch_size):
        label = labels[i, :, :]
        anchors_bbox_map = assign_anchor_to_bbox(
            label[:, 1:], anchors, device)
        bbox_mask = ((anchors_bbox_map >= 0).float().unsqueeze(-1)).repeat(
            1, 4)
        # 初始化锚框的类别标签和分配的边界框坐标为零
        class_labels = torch.zeros(num_anchors, dtype=torch.long, device=device)
        assigned_bb = torch.zeros((num_anchors, 4), dtype=torch.float32, device=device)
        # 锚框的类别标签使用其分配的真实边界框进行标记。如果锚框没有分配任何边界框,标为背景(值为0)
        indices_true = torch.nonzero(anchors_bbox_map >= 0)
        bb_idx = anchors_bbox_map[indices_true]
        class_labels[indices_true] = label[bb_idx, 0].long() + 1
        assigned_bb[indices_true] = label[bb_idx, 1:]
        # offset transformation
        offset = offset_boxes(anchors, assigned_bb) * bbox_mask
        batch_offset.append(offset.reshape(-1))
        batch_mask.append(bbox_mask.reshape(-1))
        batch_class_labels.append(class_labels)
    bbox_offset = torch.stack(batch_offset)
    bbox_mask = torch.stack(batch_mask)
    class_labels = torch.stack(batch_class_labels)
    return (bbox_offset, bbox_mask, class_labels)

在图像中绘制这些真实边框和锚框

代码 20 · In [25]
ground_truth = torch.tensor([[0, 0.1, 0.08, 0.52, 0.92],
                             [1, 0.55, 0.2, 0.9, 0.88]])
anchors = torch.tensor([[0, 0.1, 0.2, 0.3], [0.15, 0.2, 0.4, 0.4],
                        [0.63, 0.05, 0.88, 0.98], [0.66, 0.45, 0.8, 0.8],
                        [0.57, 0.3, 0.92, 0.9]])
fig = plt.imshow(img)
# 黑色的是真实边框
util.show_bboxes(fig.axes, ground_truth[:, 1:] * bbox_scale, ['dog', 'cat'], 'k')
# 彩色的锚框
util.show_bboxes(fig.axes, anchors * bbox_scale, ['0', '1', '2', '3', '4']);

代码 20 的已保存图表

根据真实边界,标注锚框的类别和偏移量

代码 22 · In [26]
labels = multibox_target(anchors.unsqueeze(dim=0), # 加入 batch 维度
                         ground_truth.unsqueeze(dim=0))
labels[2] # 类别标签, 0 是背景,1 是狗,2 是猫
已保存输出
tensor([[0, 1, 2, 0, 2]])
代码 23 · In [27]
labels[1] # 偏移量掩码, 1 表示该锚框分配了真实边界框,0 表示没有
已保存输出
tensor([[0., 0., 0., 0., 1., 1., 1., 1., 1., 1., 1., 1., 0., 0., 0., 0., 1., 1.,
         1., 1.]])
代码 24 · In [28]
labels[0] # 偏移量, 只有分配了真实边界框的锚框才有偏移量
已保存输出
tensor([[-0.00e+00, -0.00e+00, -0.00e+00, -0.00e+00,  1.40e+00,  1.00e+01,
          2.59e+00,  7.18e+00, -1.20e+00,  2.69e-01,  1.68e+00, -1.57e+00,
         -0.00e+00, -0.00e+00, -0.00e+00, -0.00e+00, -5.71e-01, -1.00e+00,
          4.17e-06,  6.26e-01]])

逆偏移变换返回预测的边界坐标

代码 26 · In [29]
def offset_inverse(anchors, offset_preds):
    """根据带有预测偏移量的锚框来预测边界框"""
    anc = util.box_corner_to_center(anchors)
    pred_bbox_xy = (offset_preds[:, :2] * anc[:, 2:] / 10) + anc[:, :2]
    pred_bbox_wh = torch.exp(offset_preds[:, 2:] / 5) * anc[:, 2:]
    pred_bbox = torch.concat((pred_bbox_xy, pred_bbox_wh), axis=1)
    predicted_bbox = util.box_center_to_corner(pred_bbox)
    return predicted_bbox

nms 按降序对置信度排序并返回索引

代码 28 · In [30]
def nms(boxes, scores, iou_threshold):
    """对预测边界框的置信度进行排序"""
    B = torch.argsort(scores, dim=-1, descending=True) # 降序排序
    keep = []
    while B.numel() > 0:
        i = B[0]
        keep.append(i) # 保留当前最高置信度框
        if B.numel() == 1: break
        iou = box_iou(boxes[i, :].reshape(-1, 4),
                      boxes[B[1:], :].reshape(-1, 4)).reshape(-1)
        inds = torch.nonzero(iou <= iou_threshold).reshape(-1) # 找到 IoU 小于阈值的索引
        B = B[inds + 1] # 更新 B,去掉与当前框 IoU 大于阈值的框
    return torch.tensor(keep, device=boxes.device)

预测

代码 30 · In [31]
def multibox_detection(cls_probs, offset_preds, anchors, nms_threshold=0.5,
                       pos_threshold=0.009999999):
    """使用非极大值抑制来预测边界框"""
    device, batch_size = cls_probs.device, cls_probs.shape[0]
    anchors = anchors.squeeze(0)
    num_classes, num_anchors = cls_probs.shape[1], cls_probs.shape[2]
    out = []
    for i in range(batch_size):
        cls_prob, offset_pred = cls_probs[i], offset_preds[i].reshape(-1, 4)
        conf, class_id = torch.max(cls_prob[1:], 0)
        predicted_bb = offset_inverse(anchors, offset_pred)
        keep = nms(predicted_bb, conf, nms_threshold)
        # 找到所有的non_keep索引,并将类设置为背景
        all_idx = torch.arange(num_anchors, dtype=torch.long, device=device)
        combined = torch.cat((keep, all_idx))
        uniques, counts = combined.unique(return_counts=True)
        non_keep = uniques[counts == 1]
        all_id_sorted = torch.cat((keep, non_keep))
        class_id[non_keep] = -1
        class_id = class_id[all_id_sorted]
        conf, predicted_bb = conf[all_id_sorted], predicted_bb[all_id_sorted]
        # pos_threshold是一个用于非背景预测的阈值
        below_min_idx = (conf < pos_threshold)
        class_id[below_min_idx] = -1
        conf[below_min_idx] = 1 - conf[below_min_idx]
        pred_info = torch.cat((class_id.unsqueeze(1),
                               conf.unsqueeze(1),
                               predicted_bb), dim=1)
        out.append(pred_info)
    return torch.stack(out)

上述算法应用到 4 个锚框的实例

代码 32 · In [32]
anchors = torch.tensor([[0.1, 0.08, 0.52, 0.92], [0.08, 0.2, 0.56, 0.95],
                        [0.15, 0.3, 0.62, 0.91], [0.55, 0.2, 0.9, 0.88]])
offset_preds = torch.tensor([0] * anchors.numel())
cls_probs = torch.tensor([[0] * 4,  # 预测背景可能性
                          [0.9, 0.8, 0.7, 0.1],  # 预测狗的可能性
                          [0.1, 0.2, 0.3, 0.9]])  # 预测猫的可能性

绘制图像

代码 34 · In [33]
fig = plt.imshow(img)
util.show_bboxes(fig.axes, anchors * bbox_scale, ['dog=0.9', 'dog=0.8', 'dog=0.7', 'cat=0.9']);

代码 34 的已保存图表

用 nms

代码 36 · In [34]
fig = plt.imshow(img)
output = multibox_detection(cls_probs.unsqueeze(dim=0),
                            offset_preds.unsqueeze(dim=0),
                            anchors.unsqueeze(dim=0),
                            nms_threshold=0.5)
for i in output[0].detach().numpy():
    if i[0] == -1:
        continue
    label = ('dog=', 'cat=')[int(i[0])] + str(i[1])
    util.show_bboxes(fig.axes, [torch.tensor(i[2:]) * bbox_scale], label)

代码 36 的已保存图表