在 MxNet-Gluon 中将 ROIPooling 层与预训练的 ResNet34 模型结合使用

Using ROIPooling layer with a pretrained ResNet34 model in MxNet-Gluon

假设我在 MXNet 中有一个 Resnet34 预保留模型,我想向其中添加 API:

中包含的预制 ROIPooling 层

https://mxnet.incubator.apache.org/api/python/ndarray/ndarray.html#mxnet.ndarray.ROIPooling

如果初始化Resnet的代码如下,如何在分类器之前的Resnet特征的最后一层添加ROIPooling?

实际上,一般如何在我的模型中使用 ROIPooling 函数?

如何在 ROIpooling 层中合并多个不同的 ROI?它们应该如何储存? 应该如何更改数据迭代器才能为我提供 ROIPooling 函数所需的 Batch 索引?

让我们假设我将它与 VOC 2012 数据集一起用于动作识别任务

batch_size = 40
num_classes = 11
init_lr = 0.001
step_epochs = [2]

train_iter, val_iter, num_samples = get_iterators(batch_size,num_classes)
resnet34 = vision.resnet34_v2(pretrained=True, ctx=ctx)

net = vision.resnet34_v2(classes=num_classes)

class ROIPOOLING(gluon.HybridBlock):
    def __init__(self):
        super(ROIPOOLING, self).__init__()

    def hybrid_forward(self, F, x):
        #print(x)
        a = mx.nd.array([[0, 0, 0, 7, 7]]).tile((40,1))
        return F.ROIPooling(x, a, (2,2), 1.0)

net_cl = nn.HybridSequential(prefix='resnetv20')
with net_cl.name_scope():
    for l in xrange(4):
        net_cl.add(resnet34.classifier._children[l])
    net_cl.add(nn.Dense(num_classes,  in_units=resnet34.classifier._children[-1]._in_units))

net.classifier = net_cl
net.classifier[-1].collect_params().initialize(mx.init.Xavier(rnd_type='gaussian', factor_type="in", magnitude=2), ctx=ctx)

net.features = resnet34.features
net.features._children.append(ROIPOOLING())

net.collect_params().reset_ctx(ctx)

ROIPooling 层通常用于对象检测网络,例如 R-CNN and its variants (Fast R-CNN and Faster R-CNN)。所有这些架构的基本部分是生成区域提案的组件(神经或经典 CV)。这些区域提案基本上是需要输入 ROIPooling 层的 ROI。 ROIPooling 层的输出将是一批张量,其中每个张量代表图像的一个裁剪区域。这些张量中的每一个都被独立处理以进行分类。例如,在 R-CNN 中,这些张量是 RGB 图像的裁剪,然后通过分类网络 运行。在 Fast R-CNN 和 Faster R-CNN 中,张量是来自卷积网络的特征,例如 ResNet34。

在您的示例中,无论是通过经典计算机视觉算法(如 R-CNN 和 Fast R-CNN)还是使用区域提议网络(如 Faster R-CNN),您需要生成一些 候选 的 ROI,以包含感兴趣的对象。一旦你在一个 mini-batch 中获得了每个图像的这些 ROI,你就需要将它们组合成一个 [[batch_index, x1, y1, x2, y2]] 的 NDArray。这个维度意味着你基本上可以拥有任意数量的 ROI,并且对于每个 ROI,你必须指定批处理中要裁剪的图像(因此 batch_index)以及裁剪的坐标(因此top-left-corner 的 (x1, y1) 和 bottom-right-corner 坐标的 (x2,y2))。

因此,基于上述内容,如果您要实现类似于 R-CNN 的功能,您会将图像直接传递到 RoiPooling 层:

class ClassifyObjects(gluon.HybridBlock):
    def __init__(self, num_classes, pooled_size):
        super(ClassifyObjects, self).__init__()
        self.classifier = gluon.model_zoo.vision.resnet34_v2(classes=num_classes)
        self.pooled_size = pooled_size

    def hybrid_forward(self, F, imgs, rois):
        return self.classifier(
            F.ROIPooling(
                imgs, rois, pooled_size=self.pooled_size, spatial_scale=1.0))


# num_classes are 10 categories plus 1 class for "no-object-in-this-box" category
net = ClassifyObjects(num_classes=11, pooled_size=(64, 64))
# Initialize parameters and overload pre-trained weights
net.collect_params().initialize()
pretrained_net = gluon.model_zoo.vision.resnet34_v2(pretrained=True)
net.classifier.features = pretrained_net.features

现在如果我们通过网络发送虚拟数据,你可以看到如果roi数组包含4个rois,输出将包含4个分类结果:

# Dummy forward pass through the network
imgs = x = nd.random.uniform(shape=(2, 3, 128, 128))  # shape is (batch_size, channels, height, width)
rois = nd.array([[0, 10, 10, 100, 100], [0, 20, 20, 120, 120],
                 [1, 15, 15, 110, 110], [1, 25, 25, 128, 128]])
out = net(imgs, rois)
print(out.shape)

输出:

(4, 11)

但是,如果您想使用类似于 Fast R-CNN 或 Faster R-CNN 模型的 ROIPooling,您需要在平均池化之前访问网络的特征。这些特征在被传递到分类之前被 ROIPooled。这里有一个例子,其中特征来自 pre-trained 网络,ROIPooling 的 pooled_size 是 4x4,并且一个简单的 GlobalAveragePooling 后跟一个 Dense 层用于 ROIPooling 之后的分类。请注意,由于图像通过 ResNet 网络 max-pooled 乘以 32 倍,因此 spatial_scale 设置为 1.0/32 让 ROIPooling 层自动补偿 rois。

def GetResnetFeatures(resnet):
    resnet.features._children.pop()  # Pop Flatten layer
    resnet.features._children.pop()  # Pop GlobalAveragePooling layer
    return resnet.features


class ClassifyObjects(gluon.HybridBlock):
    def __init__(self, num_classes, pooled_size):
        super(ClassifyObjects, self).__init__()
        # Add a placeholder for features block
        self.features = gluon.nn.HybridSequential()
        # Add a classifier block
        self.classifier = gluon.nn.HybridSequential()
        self.classifier.add(gluon.nn.GlobalAvgPool2D())
        self.classifier.add(gluon.nn.Flatten())
        self.classifier.add(gluon.nn.Dense(num_classes))
        self.pooled_size = pooled_size

    def hybrid_forward(self, F, imgs, rois):
        features = self.features(imgs)
        return self.classifier(
            F.ROIPooling(
                features, rois, pooled_size=self.pooled_size, spatial_scale=1.0/32))


# num_classes are 10 categories plus 1 class for "no-object-in-this-box" category
net = ClassifyObjects(num_classes=11, pooled_size=(4, 4))
# Initialize parameters and overload pre-trained weights
net.collect_params().initialize()
net.features = GetResnetFeatures(gluon.model_zoo.vision.resnet34_v2(pretrained=True))

现在如果我们通过网络发送虚拟数据,你可以看到如果roi数组包含4个rois,输出将包含4个分类结果:

# Dummy forward pass through the network
# shape of each image is (batch_size, channels, height, width)
imgs = x = nd.random.uniform(shape=(2, 3, 128, 128))
# rois is the output of region proposal module of your architecture
# Each ROI entry contains [batch_index, x1, y1, x2, y2]
rois = nd.array([[0, 10, 10, 100, 100], [0, 20, 20, 120, 120],
                 [1, 15, 15, 110, 110], [1, 25, 25, 128, 128]])
out = net(imgs, rois)
print(out.shape)

输出:

(4, 11)