Search code examples
pythonneural-networkmxnet

MXNet Gluon - programmatically accessing neural net layer dimensions?


Let's begin by creating a very basic deep neural network in MXNet Gluon (inspired by this tutorial):

import mxnet as mx
from mxnet import gluon

ctx = mx.cpu()

net = gluon.nn.Sequential()
with net.name_scope():
    net.add(gluon.nn.Conv2D(channels=20, kernel_size=5, activation='relu'))
    net.add(gluon.nn.MaxPool2D(pool_size=2, strides=2))

Now, if we want to print out the dimensions of a layer, all we have to do is...

print(net[0])
  # prints: Conv2D(None -> 20, kernel_size=(5, 5), stride=(1, 1), Activation(relu))

print(net[1])
  # prints: MaxPool2D(size=(2, 2), stride=(2, 2), padding=(0, 0), ceil_mode=False)

However, instead of printing it out, what if we want to programmatically inspect the padding of net[1]?

  • When I try net[1].padding, I get the error AttributeError: 'MaxPool2D' object has no attribute 'padding'.
  • When I try net[1]['padding'], I get the error TypeError: 'MaxPool2D' object is not subscriptable.

So, what's the right way to programmatically access the dimensions of a neural network layer in MXNet Gluon?


Solution

  • print(net[1]._kwargs["pad"])

    Try getting them from kwargs dictionary. Look for other keys at this source.

    This is the Colab link for the code.

    Other keys are kernel for kernel size, stride for stride, .

    For getting all the keys and values:

    for k, v in net[1]._kwargs.items():
        print(k, v)