Custom symbol with parameters?


#1

I was just wondering if it was possible to make a custom symbol with parameter, the docs shot a simple functions but typical layers must have parameters to work so I’m sure it can be done but not sure how. Is it the same code used by the gluon blocks or must other elements be implemented ?

Thanks again!


#2

Hi,

this is an example for Gluon of a custom layer (thus also can work for Symbol) that consists of the series: conv2D–>BN–>conv2D–>BN. It is built upon gluon HybridBlock (for my needs). It takes as input number of filters (channels) and kernel size.

Am pretty sure you can use SymbolBlock as well to make it work with symbols.


from mxnet import gluon
from mxnet.gluon import HybridBlock

class UNet_block(HybridBlock):
     def __init__(self, _nfilters,_kernel_size,**kwards):
        super(UNet_block,self).__init__(**kwards)

        # This is where you add the parameters
        self.nfilters = _nfilters
        self.kernel_size = _kernel_size # assume that kernel_size is a tuple or list

        with self.name_scope():

            # Ensures padding = 'SAME' for ODD kernel selection 
            p0 = (self.kernel_size[0] - 1)/2
            p1 = (self.kernel_size[1] - 1)/2
            p  = (p0,p1)


            self.conv1 = gluon.nn.Conv2D(self.nfilters,kernel_size = self.kernel_size, padding=p, use_bias=False,prefix="conv1_")
            self.BN1 = gluon.nn.BatchNorm(axis=1,prefix="BN1_")

            self.conv2 = gluon.nn.Conv2D(self.nfilters,kernel_size = self.kernel_size, padding=p, use_bias=False, prefix="conv2_")
            self.BN2 = gluon.nn.BatchNorm(axis=1,prefix="BN2_")



    def hybrid_forward(self,F,_xl):

        x = self.conv1(_xl)
        x = self.BN1(x)

        x = self.conv2(x)
        x = self.BN2(x)

        return x


hope this helps.