假设我在 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-CNN 和 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),您都需要生成一些 ROIs < em="">candidates 包含感兴趣的对象。一旦您在一个小批量中获得了每个图像的这些 ROI,您就需要将它们组合成一个 [[batch_index, x1, y1, x2, y2]] 的 NDArray。这个维度意味着您基本上可以拥有任意数量的 ROI,并且对于每个 ROI,您必须指定批处理中要裁剪的图像(因此 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)
但是,如果您想使用类似于 Fast R-CNN 或 Faster 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)
关于python - 在 MxNet-Gluon 中将 ROIPooling 层与预训练的 ResNet34 模型结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48272913/
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou
我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-
为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar
我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test
我正在尝试从Postgresql表(table1)中获取数据,该表由另一个相关表(property)的字段(table2)过滤。在纯SQL中,我会这样编写查询:SELECT*FROMtable1JOINtable2USING(table2_id)WHEREtable2.propertyLIKE'query%'这工作正常:scope:my_scope,->(query){includes(:table2).where("table2.property":query)}但我真正需要的是使用LIKE运算符进行过滤,而不是严格相等。然而,这是行不通的:scope:my_scope,->(que
我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file
当我尝试安装Ruby时遇到此错误。我试过查看this和this但无济于事➜~brewinstallrubyWarning:YouareusingOSX10.12.Wedonotprovidesupportforthispre-releaseversion.Youmayencounterbuildfailuresorotherbreakages.Pleasecreatepull-requestsinsteadoffilingissues.==>Installingdependenciesforruby:readline,libyaml,makedepend==>Installingrub
我在新的Debian6VirtualBoxVM上安装RVM时遇到问题。我已经安装了所有需要的包并使用下载了安装脚本(curl-shttps://rvm.beginrescueend.com/install/rvm)>rvm,但以单个用户身份运行时bashrvm我收到以下错误消息:ERROR:Unabletocheckoutbranch.安装在这里停止,并且(据我所知)没有安装RVM的任何文件。如果我以root身份运行脚本(对于多用户安装),我会收到另一条消息:Successfullycheckedoutbranch''安装程序继续并指示成功,但未添加.rvm目录,甚至在修改我的.bas
下面的代码在我第一次运行它时就可以正常工作:require'rubygems'require'spreadsheet'book=Spreadsheet.open'/Users/me/myruby/Mywks.xls'sheet=book.worksheet0row=sheet.row(1)putsrow[1]book.write'/Users/me/myruby/Mywks.xls'当我再次运行它时,我会收到更多消息,例如:/Library/Ruby/Gems/1.8/gems/spreadsheet-0.6.5.9/lib/spreadsheet/excel/reader.rb:11