class Net(HybridBlock):
def __init__(self):
super(Net, self).__init__()
self.op = nn.Conv2D(10, kernel_size=5, strides=1, padding=1)
self.p = mx.gluon.Parameter(name='ppp', shape=(1))
def hybrid_forward(self, F, x):
return self.op(x) * self.p
if __name__ == '__main__':
img = mx.nd.zeros((2,3,28,28))
model = Net()
print(model.collect_params())
model.collect_params().initialize()
out = model(img)
print(model.collect_params())
I got the Error
RuntimeError: Parameter 'ppp' 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
So how to register the self defined Parameters self.p in mxnet? so that the model.collect_params() will contain the self.p
import mxnet as mx
from mxnet import gluon, nd
from mxnet.gluon import nn
class MyDense(nn.HybridBlock):
# units: the number of outputs in this layer; in_units: the number of
# inputs in this layer
def __init__(self, units, in_units, **kwargs):
super(MyDense, self).__init__(**kwargs)
self.weight = self.params.get('weight', shape=(in_units, units))
self.bias = self.params.get('bias', shape=(units,))
def hybrid_forward(self, F, x, weight, bias):
linear = F.dot(x, weight) + bias
return F.relu(linear)
net = MyDense(20,20)
net.initialize()
net(mx.nd.ones(shape=(20,)))