这是根据沐神的
动手学深度学习 PyTorch版
中的第42讲做的笔记。
以下部分是代码实现部分(包括注释),使用的是jupyter notebook.
%matplotlib inline
import torch
from d2l import torch as d2l
torch.set_printoptions(2) # 精简打印精度
代码中的 w = s * r \sqrt{r} r * h w \frac{h}{w} wh, h = s r \frac{s}{\sqrt{r}} rs ,中的宽高比应为:r, 锚框的面积为: s2 (占原始图像的面积比)
可以参考下面的链接:https://fkjkkll.github.io/2021/11/23/%E7%9B%AE%E6%A0%87%E6%A3%80%E6%B5%8BSSD/#more
#@save
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 # Scaled steps in y axis
steps_w = 1.0 / in_width # Scaled steps in x axis
# 生成锚框的所有中心点
center_h = (torch.arange(in_height, device=device) + offset_h) * steps_h
center_w = (torch.arange(in_width, device=device) + offset_w) * steps_w
# 生成网格(注意:通过缩放之后,其值都在0-1之间)
shift_y, shift_x = torch.meshgrid(center_h, center_w)
# 把二维的tensor转化为一维的tensor (注意:按行展开)
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”个锚框,
# 最终得到的锚框的坐标:左上、右下的表示方式
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的形状是(批量大小,锚框的数量, 4)。
img = d2l.plt.imread('./img/catdog.jpg')
h, w = img.shape[:2]
print(h, w)
X = torch.rand(size=(1, 3, h, w))
Y = multibox_prior(X, sizes=[0.75, 0.5, 0.25], ratios=[1, 2, 0.5])
Y.shape
# 输出的结果为:
# 561 728
# torch.Size([1, 2042040, 4])
将Y的形状进行reshape(h, w, 5, 4)
boxes = Y.reshape(h, w, 5, 4)
boxes[250, 250, 0, :]
# 输出为:tensor([0.06, 0.07, 0.63, 0.82])
为了显示以图像中的某个像素为中心的所有锚框,我们定义了下面的show_bboxes函数来在图像上绘制多个锚框。
#@save
def show_bboxes(axes, bboxes, labels=None, colors=None):
"""显示所有边界框。"""
def _make_list(obj, default_values=None):
if obj is None:
obj = default_values
elif not isinstance(obj, (list, tuple)):
obj = [obj]
return obj
labels = _make_list(labels)
colors = _make_list(colors, ['b', 'g', 'r', 'm', 'c'])
for i, bbox in enumerate(bboxes):
color = colors[i % len(colors)]
# detach()相当于data() 且 requires_grad = False
rect = d2l.bbox_to_rect(bbox.detach().numpy(), color)
axes.add_patch(rect)
if labels and len(labels) > i:
text_color = 'k' if color == 'w' else 'w'
axes.text(rect.xy[0], rect.xy[1], labels[i],
va='center', ha='center', fontsize=9, color=text_color,
bbox=dict(facecolor=color, lw=0))
现在绘制出以(250, 250)为中心的锚框,如下所示:
d2l.set_figsize()
bbox_scale = torch.tensor((w, h, w, h))
print(bbox_scale)
fig = d2l.plt.imshow(img)
# boxes[250, 250, :, :]的shape的形状为(5, 4)
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'])
#@save
def box_iou(boxes1, boxes2):
"""计算锚框和真实框的交并比(有点类似于笛卡尔积)。"""
box_area = lambda boxes: ((boxes[:, 2] - boxes[:, 0]) *
(boxes[:, 3] - boxes[:, 1]))
# `boxes1`, `boxes2`, `areas1`, `areas2`的形状:
# `boxes1`:(boxes1的数量, 4),
# `boxes2`:(boxes2的数量, 4),
# `areas1`:(boxes1的数量,),
# `areas2`:(boxes2的数量,)
areas1 = box_area(boxes1)
areas2 = box_area(boxes2)
# `inter_upperlefts`, `inter_lowerrights`, `inters`的形状:
# (boxes1的数量, boxes2的数量, 2)
# 这里使用了广播机制:boxes1[:, None, :2], (即增加了一个维度:相当于boxes1.unsqueeze(1))
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) # clamp限制最小值为0
# `inter_areas` and `union_areas`的形状: (boxes1的数量, boxes2的数量)
inter_areas = inters[:, :, 0] * inters[:, :, 1]
# 这里也使用了广播机制 areas1[:, None]
union_areas = areas1[:, None] + areas2 - inter_areas
return inter_areas / union_areas
此功能是由下面的assign_anchor_to_bbox函数实现。
我认为这个实现的代码分为两个阶段,第一个阶段就是先找出每行中最大的值以及其对应的GT的编号,如果最大值大于阈值,则分配GT编号,否则,值为-1(即为背景);第二个阶段就是如下图所示的,和NMS
有那么几分相似。
#@save
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)
# 根据阈值,决定是否分配真实边界框
max_ious, indices = torch.max(jaccard, dim=1)
anc_i = torch.nonzero(max_ious >= 0.5).reshape(-1)
box_j = indices[max_ious >= 0.5] # true, false列表
# anchors_bbox_map中索引为anc_i分配边界框box_j
anchors_bbox_map[anc_i] = box_j
col_discard = torch.full((num_anchors,), -1)
row_discard = torch.full((num_gt_boxes,), -1)
for _ in range(num_gt_boxes):
# 找出最大值的索引 jaccard是一个二维的tensor.
max_idx = torch.argmax(jaccard)
box_idx = (max_idx % num_gt_boxes).long()
anc_idx = (max_idx / num_gt_boxes).long()
anchors_bbox_map[anc_idx] = box_idx
jaccard[:, box_idx] = col_discard
jaccard[anc_idx, :] = row_discard
return anchors_bbox_map
现在我们可以为每个锚框标记类别和偏移了。假设一个锚框A被分配了一个真实边界框B。一方面,锚框A的类别将被标记与B的相同;另一方面,锚框A的偏移量将根据B和A的中心坐标的相对位置以及这两个框的大小进行标记。给定框A和B,中心坐标分别为 ( x x xa, y y ya)和( x x xb, y y yb), 宽度分别为 w w wa和 w w wb,高度分别为 h h ha和 h h hb。
我们可以将A的偏移量标记为:
( x b − x a w a − μ x σ x , y b − y a w a − μ y σ y , log w b w a − μ w σ w , log h b h a − μ h σ h ) (\frac{\frac{x_{b} - x_{a}}{w_{a}} - \mu_{x}}{\sigma_{x}},\frac{\frac{y_{b} - y_{a}}{w_{a}} - \mu_{y}}{\sigma_{y}},\frac{\log\frac{w_{b}}{w_{a}} - \mu_{w}}{\sigma_{w}}, \frac{\log\frac{h_{b}}{h_{a}} - \mu_{h}}{\sigma_{h}}) (σxwaxb−xa−μx,σywayb−ya−μy,σwlogwawb−μw,σhloghahb−μh)
其中常量的默认值为 μ x \mu_{x} μx = μ y \mu_{y} μy = μ w \mu_{w} μw= μ h \mu_{h} μh = 0, σ x \sigma_{x} σx = σ y \sigma_{y} σy = 0.1, σ w \sigma_{w} σw = σ h \sigma_{h} σh = 0.2这种转换在下面的 offset_boxes
函数中实现。
#@save
# offset.shape == anchors.shape
def offset_boxes(anchors, assigned_bb, eps=1e-6):
"""对锚框偏移量的转换。"""
c_anc = d2l.box_corner_to_center(anchors)
c_assigned_bb = d2l.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
如果一个锚框没有被分配真实边界框,我们只需将锚框的类别标记为“背景”(background)。 背景类别的锚框通常被称为“负类”锚框,其余的被称为“正类”锚框。 我们使用真实边界框(labels
参数)实现以下multibox_target
函数,来标记锚框(anchors
参数)的类别和偏移量。 此函数将背景类别的索引设置为零,然后将新类别的整数索引递增一。
#@save
# 代码的注释是以下面的例子为背景的。
def multibox_target(anchors, labels):
"""使用真实边界框标记锚框。"""
# 参数labels是真实框
# anchors[1, 5, 4] labels[1, 2, 5] batch_size = 1
batch_size, anchors = labels.shape[0], anchors.squeeze(0)
# anchors[5, 4]
batch_offset, batch_mask, batch_class_labels = [], [], []
# num_anchors = 5
device, num_anchors = anchors.device, anchors.shape[0]
for i in range(batch_size):
# label[2, 5]
label = labels[i, :, :]
anchors_bbox_map = assign_anchor_to_bbox(
label[:, 1:], anchors, device)
# bbox_mask.shape = [num_anchors, 4] (是由1, 0构成的矩阵)
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)
# 使用真实边界框来标记锚框的类别。
# 如果一个锚框没有被分配,我们标记其为背景(值为零)
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都设置为0
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)
# 按行进行stack() stack()一定会对维度进行扩充
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)
例子:
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 = d2l. plt.imshow(img)
show_bboxes(fig.axes, ground_truth[:, 1:] * bbox_scale, ['dog', 'cat'], 'k')
show_bboxes(fig.axes, anchors * bbox_scale, ['0', '1', '2', '3', '4']);
运行例子之后的代码
labels = multibox_target(anchors.unsqueeze(dim=0), ground_truth.unsqueeze(dim=0))
返回的结果为:
锚框和真实框的偏移
labels[0][0].reshape(-1, 4)
"""
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]])
"""
锚框的掩码(1表示非背景类,0表示背景类)
labels[1][0].reshape(-1, 4)
"""
tensor([[0., 0., 0., 0.],
[1., 1., 1., 1.],
[1., 1., 1., 1.],
[0., 0., 0., 0.],
[1., 1., 1., 1.]])
"""
锚框分配的类别
labels[2]
# 0表示背景, 1表示狗, 2表示猫
# tensor([[0, 1, 2, 0, 2]])
以下是预测的部分:
offset_inverse
函数:输入锚框和偏移量去预测真实的边界框
#@save
def offset_inverse(anchors, offset_preds):
"""根据带有预测偏移量的锚框来预测边界框"""
anc = d2l.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.cat((pred_bbox_xy, pred_bbox_wh), axis=1)
predicted_bbox = d2l.box_center_to_corner(pred_bbox)
return predicted_bbox
NMS
函数的实现:
对于下面的函数可以举一个简单的例子理解:
假设scores
=[0.90, 0.80, 0.91, 0.85], scores
其实就是每个框预测的softmax
值,假设预测的类别label
为[1, 1, 2, 2], 那么最后能不能只剩下[0.90, 0.91]这两个值呢?(即keep=[0, 2] 0和2为保留下来的锚框对应的索引)。
我们来按下面的nms
函数走一遍流程:
scores = [0.90, 0.80, 0.91, 0.85]
B = [2, 0, 3, 1] 假设box2和box0、3、1的iou为[0.4, 0.6, 0.3]
keep = []
i = B[0] = 2
keep = [2]
inds = [0, 2]
B = B[1, 3] = [0, 1] 假设box0和box1的交并比为0.6
i = 0
keep = [2, 0]
B = B[[]]=[] # 终止了
#@save
def nms(boxes, scores, iou_threshold):
"""对预测边界框的置信度进行排序。"""
B = torch.argsort(scores, dim=-1, descending=True)
keep = [] # 保留预测边界框的指标
# numel:元素的个数
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)
B = B[inds + 1]
return torch.tensor(keep, device=boxes.device)
multibox_detection
函数如下:
#@save
def multibox_detection(cls_probs, offset_preds, anchors, nms_threshold=0.5,
pos_threshold=0.009999999):
"""使用非极大值抑制来预测边界框。"""
# cls_prob.shape:[1, 3, 4] offset_preds.shape:[1, 16] anchors.shape:[1, 4, 4]
# batch_size = 1
device, batch_size = cls_probs.device, cls_probs.shape[0]
anchors = anchors.squeeze(0)
# num_classes = 3, num_anchors = 4
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:], dim=0)
predicted_bb = offset_inverse(anchors, offset_pred)
keep = nms(predicted_bb, conf, nms_threshold)
# 找到所有的 non_keep 索引,并将类设置为背景 ## 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.shape: (4, 6)
pred_info = torch.cat((class_id.unsqueeze(1),
conf.unsqueeze(1),
predicted_bb), dim=1)
out.append(pred_info)
return torch.stack(out) # out.shape:(1, 4, 6)
例子:
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]]) # 猫的预测概率
我们可以在图像上绘制这些预测边界框和置信度。
fig = d2l.plt.imshow(img)
show_bboxes(fig.axes, anchors * bbox_scale,
['dog=0.9', 'dog=0.8', 'dog=0.7', 'cat=0.9'])
现在调用multibox_detection
函数来执行非极大值抑制,其中阈值为0.5。请注意,我们在实例的张量输入中添加了维度。
output = multibox_detection(cls_probs.unsqueeze(dim=0),
offset_preds.unsqueeze(dim=0),
anchors.unsqueeze(dim=0),
nms_threshold=0.5)
output
# out.shape: (batch_size, num_anchors, 6)
# 类别 置信度 预测的框
"""
tensor([[[ 0.00, 0.90, 0.10, 0.08, 0.52, 0.92],
[ 1.00, 0.90, 0.55, 0.20, 0.90, 0.88],
[-1.00, 0.80, 0.08, 0.20, 0.56, 0.95],
[-1.00, 0.70, 0.15, 0.30, 0.62, 0.91]]])
"""
删除 -1类别(背景类)的预测框后,我们可以输出由非极大值抑制保存的最终的预测边界框。
fig = d2l.plt.imshow(img)
# 取batch_size = 0
for i in output[0].detach().numpy():
if i[0] == -1:
continue
label = ('dog=', 'cat=')[int(i[0])] + str(i[1])
show_bboxes(fig.axes, [torch.tensor(i[2:]) * bbox_scale], label)
跟李沐学AI>动手学深度学习 PyTorch版>第42讲锚框
教材地址:https://zh-v2.d2l.ai/