在MxNet-Gluon中使用带有预训练ResNet34模型的ROIPooling层

obe*_*lix 9 python deep-learning resnet mxnet

假设我在MXNet中有一个Resnet34预备模型,我想在其中添加API中包含的预制ROIPooling层:

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

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

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

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

让我们假设我将此与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)
Run Code Online (Sandbox Code Playgroud)

小智 2

ROIPooling 层通常用于目标检测网络,例如R-CNN及其变体(Fast R-CNNFaster 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出于兴趣。一旦您在一个小批量中获得了每个图像的这些 ROI,您就需要将它们合并到一个 NDArray 中[[batch_index, x1, y1, x2, y2]]。这种尺寸标注意味着您基本上可以拥有任意数量的 ROI,并且对于每个 ROI,您必须指定批次中要裁剪的图像(因此是 )batch_index以及在什么坐标处裁剪它(因此对于(x1, y1)左上角-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
Run Code Online (Sandbox Code Playgroud)

现在,如果我们通过网络发送虚拟数据,您可以看到,如果 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)
Run Code Online (Sandbox Code Playgroud)

输出:

(4, 11)
Run Code Online (Sandbox Code Playgroud)

但是,如果您想将 ROIPooling 与 Fast R-CNN 或 Faster R-CNN 模型类似,则需要在平均池化之前访问网络的特征。然后将这些特征进行 ROIPooled,然后再进行分类。这里是一个示例,其中特征来自预训练网络,ROIPoolingpooled_size是 4x4,简单的 GlobalAveragePooling 后跟 Dense 层用于在 ROIPooling 后进行分类。请注意,由于图像通过 ResNet 网络进行了 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))
Run Code Online (Sandbox Code Playgroud)

现在,如果我们通过网络发送虚拟数据,您可以看到,如果 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)
Run Code Online (Sandbox Code Playgroud)

输出:

(4, 11)
Run Code Online (Sandbox Code Playgroud)