【发布时间】:2018-05-22 01:04:44
【问题描述】:
我正在阅读有关 MxNet 的教程。作者使用“mxnet.gluon.nn.Sequential()”作为容器来存储一些块(参见代码 1);然后,他们重写了“def forward(self, x)”中的块连接(参见代码 2 和 3)。这样做有什么副作用吗?顺便说一下,‘Sequential()’和‘HybridSequential()’有什么区别。我尝试使用一个列表来替换“顺序”,并且在初始化过程中收到以下警告。
“ToySSD.downsamplers”是一个带有块的容器。请注意,列表、元组或字典中的块不会自动注册。 确保使用 register_child() 注册它们或切换到 nn.Sequential/nn.HybridSequential 代替。'
据我所知,如果你在 'mxnet.gluon.nn.Sequential()' 或 'mxnet.gluon.nn.HybridSequential()' 中放入一些块,这个动作是告诉计算机这些块是连接的.但是,如果您在“前进”功能中设计块的关系,您就是在告诉计算机以另一种方式连接这些块。会不会造成混乱?如果我只在'forward'中设计一些块连接,'Sequential()'中没有在'forward'函数中设计的其他块的关系是什么?
整个教程可以在here找到。
代码1:
def toy_ssd_model(num_anchors, num_classes):
downsamplers = nn.Sequential()
for _ in range(3):
downsamplers.add(down_sample(128))
class_predictors = nn.Sequential()
box_predictors = nn.Sequential()
for _ in range(5):
class_predictors.add(class_predictor(num_anchors, num_classes))
box_predictors.add(box_predictor(num_anchors))
model = nn.Sequential()
model.add(body(), downsamplers, class_predictors, box_predictors)
return model
代码 2:
def toy_ssd_forward(x, model, sizes, ratios, verbose=False):
body, downsamplers, class_predictors, box_predictors = model
anchors, class_preds, box_preds = [], [], []
# feature extraction
x = body(x)
for i in range(5):
# predict
anchors.append(MultiBoxPrior(
x, sizes=sizes[i], ratios=ratios[i]))
class_preds.append(
flatten_prediction(class_predictors[i](x)))
box_preds.append(
flatten_prediction(box_predictors[i](x)))
if verbose:
print('Predict scale', i, x.shape, 'with',
anchors[-1].shape[1], 'anchors')
# down sample
if i < 3:
x = downsamplers[i](x)
elif i == 3:
x = nd.Pooling(
x, global_pool=True, pool_type='max',
kernel=(x.shape[2], x.shape[3]))
# concat data
return (concat_predictions(anchors),
concat_predictions(class_preds),
concat_predictions(box_preds))
代码 3:
from mxnet import gluon
class ToySSD(gluon.Block):
def __init__(self, num_classes, verbose=False, **kwargs):
super(ToySSD, self).__init__(**kwargs)
# anchor box sizes and ratios for 5 feature scales
self.sizes = [[.2,.272], [.37,.447], [.54,.619],
[.71,.79], [.88,.961]]
self.ratios = [[1,2,.5]]*5
self.num_classes = num_classes
self.verbose = verbose
num_anchors = len(self.sizes[0]) + len(self.ratios[0]) - 1
# use name_scope to guard the names
with self.name_scope():
self.model = toy_ssd_model(num_anchors, num_classes)
def forward(self, x):
anchors, class_preds, box_preds = toy_ssd_forward(
x, self.model, self.sizes, self.ratios,
verbose=self.verbose)
# it is better to have class predictions reshaped for softmax computation
class_preds = class_preds.reshape(shape=(0, -1, self.num_classes+1))
return anchors, class_preds, box_preds
【问题讨论】:
标签: python deep-learning computer-vision mxnet