Search code examples
pythondeep-learningmxnet

Mxnet version 1.0.0 gluon KeyError: 'shape'


I have installed the newest mxnet version 1.0.0 from pip. When I print the Layer's weight, it assert a KeyError: "Shape". I'm new in mxnet and everything I have followed with the mxnet official tutorial.

import mxnet
from mxnet import nd,gluon,autograd

net=gluon.nn.Dense(10,in_units=30)
print (net.weight)

The error is:

Traceback (most recent call last):
  File "/home/user/docs/mxnet/mtcnn/tmp/learn_mxnet.py", line 5, in <module>
    print (net.weight)
  File "/usr/local/lib/python2.7/dist-packages/mxnet/gluon/parameter.py", line 120, in __repr__
    return s.format(**self.__dict__)
KeyError: 'shape'

I think it may be the problem of the version 1.0.0.


Solution

  • To check the weights, you first need to initialize them as follows: net.collect_params().initialize(mx.init.Xavier(), ctx=mx.cpu())

    In your case, because you didn't specify input size to layers in Net's constructor, the shape of parameters cannot be determined at this point. So, if you access net.weight.data() now, an exception will be raised:

    Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python2.7/dist-packages/mxnet-0.12.1-py2.7.egg/mxnet/gluon/parameter.py", line 389, in data return self._check_and_get(self._data, ctx) File "/usr/local/lib/python2.7/dist-packages/mxnet-0.12.1-py2.7.egg/mxnet/gluon/parameter.py", line 189, in _check_and_get "nested child Blocks"%(self.name)) RuntimeError: Parameter dense0_weight has not been initialized. Note that you should initialize parameters and create Trainer with Block.collect_params() instead of Block.params because the later does not include Parameters of nested child Blocks

    You can initialize the weights as follows: net.collect_params().initialize(mxnet.init.Xavier(), ctx=mxnet.cpu()) print (net.weight.data())