假设我在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)
答案 0 :(得分:3)
ROIPooling图层通常用于对象检测网络,例如R-CNN及其变体(Fast R-CNN和Faster R-CNN)。所有这些架构的基本部分是生成区域提议的组件(神经或经典CV)。这些区域提案基本上是需要输入ROIPooling层的ROI。 ROIPooling层的输出将是一批张量,其中每个张量代表图像的一个裁剪区域。这些张量中的每一个都被独立处理以进行分类。例如,在R-CNN中,这些张量是RGB图像的裁剪,然后通过分类网络运行。在快速R-CNN和更快的R-CNN中,张量是卷积网络中的特征,例如ResNet34。
在您的示例中,无论是通过经典计算机视觉算法(如在R-CNN和快速R-CNN中)还是使用区域提案网络(如在快速R-CNN中),您都需要生成一些< em>候选人包含感兴趣的对象。在一个小批量中为每个图像获得这些ROI后,您需要将它们组合成一个[[batch_index, x1, y1, x2, y2]]
的NDArray。这个尺寸标注的意思是您基本上可以拥有任意数量的投资回报率,并且对于每个投资回报率,您必须指定批次中要裁剪的图像(因此batch_index
)以及要裁剪的坐标(因此左上角的(x1, y1)
和右下角坐标的(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)
但是,如果您希望使用类似于快速R-CNN或更快的R-CNN模型的ROIPooling,则需要在平均合并之前访问网络的功能。然后,这些功能在传递到分类之前进行ROIPooled。这里是一个示例,其中的功能来自预先训练的网络,ROIPooling的pooled_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))
现在,如果我们通过网络发送虚拟数据,您可以看到如果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)