假设我在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数据集一起用于 Action 识别任务

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及其变体(Fast R-CNNFaster R-CNN)。所有这些体系结构的必要部分是一个生成区域建议的组件(神经或经典CV)。这些区域建议基本上是需要注入(inject)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)) -left-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,然后再传递给分类。在此示例中,功能来自预先训练的网络,ROIPooling的pooled_size为4x4,并且在ROIPooling之后使用简单的GlobalAveragePooling和Dense层进行分类。请注意,由于通过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))

现在,如果我们通过网络发送虚拟数据,则可以看到,如果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)

关于python - 在MxNet-Gluon中将ROIPooling层与经过预训练的ResNet34模型一起使用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48272913/

10-12 07:16