Source code for mxnet.gluon.nn.basic_layers

# Licensed to the Apache Software Foundation (ASF) under one# or more contributor license agreements. See the NOTICE file# distributed with this work for additional information# regarding copyright ownership. The ASF licenses this file# to you under the Apache License, Version 2.0 (the# "License"); you may not use this file except in compliance# with the License. You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing,# software distributed under the License is distributed on an# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY# KIND, either express or implied. See the License for the# specific language governing permissions and limitations# under the License.# coding: utf-8# pylint: disable= arguments-differ"""Basic neural network layers."""__all__=['Sequential','HybridSequential','Dense','Dropout','Embedding','BatchNorm','InstanceNorm','LayerNorm','Flatten','Lambda','HybridLambda']importwarningsimportnumpyasnpfrom.activationsimportActivationfrom..blockimportBlock,HybridBlockfrom..utilsimport_indentfrom...importnd,sym

defadd(self,*blocks):"""Adds block on top of the stack."""forblockinblocks:self.register_child(block)defforward(self,x):forblockinself._children.values():x=block(x)returnxdef__repr__(self):s='{name}(\n{modstr}\n)'modstr='\n'.join([' ({key}): {block}'.format(key=key,block=_indent(block.__repr__(),2))forkey,blockinself._children.items()])returns.format(name=self.__class__.__name__,modstr=modstr)def__getitem__(self,key):layers=list(self._children.values())[key]ifisinstance(layers,list):net=type(self)(prefix=self._prefix)withnet.name_scope():net.add(*layers)returnnetelse:returnlayersdef__len__(self):returnlen(self._children)defhybridize(self,active=True,**kwargs):"""Activates or deactivates `HybridBlock` s recursively. Has no effect on non-hybrid children. Parameters ---------- active : bool, default True Whether to turn hybrid on or off. **kwargs : string Additional flags for hybridized operator. """ifself._childrenandall(isinstance(c,HybridBlock)forcinself._children.values()):warnings.warn("All children of this Sequential layer '%s' are HybridBlocks. Consider ""using HybridSequential for the best performance."%self.prefix,stacklevel=2)super(Sequential,self).hybridize(active,**kwargs)

defadd(self,*blocks):"""Adds block on top of the stack."""forblockinblocks:self.register_child(block)defhybrid_forward(self,F,x):forblockinself._children.values():x=block(x)returnxdef__repr__(self):s='{name}(\n{modstr}\n)'modstr='\n'.join([' ({key}): {block}'.format(key=key,block=_indent(block.__repr__(),2))forkey,blockinself._children.items()])returns.format(name=self.__class__.__name__,modstr=modstr)def__getitem__(self,key):layers=list(self._children.values())[key]ifisinstance(layers,list):net=type(self)(prefix=self._prefix)withnet.name_scope():net.add(*layers)returnnetelse:returnlayersdef__len__(self):returnlen(self._children)

[docs]classDense(HybridBlock):r"""Just your regular densely-connected NN layer. `Dense` implements the operation: `output = activation(dot(input, weight) + bias)` where `activation` is the element-wise activation function passed as the `activation` argument, `weight` is a weights matrix created by the layer, and `bias` is a bias vector created by the layer (only applicable if `use_bias` is `True`). Note: the input must be a tensor with rank 2. Use `flatten` to convert it to rank 2 manually if necessary. Parameters ---------- units : int Dimensionality of the output space. activation : str Activation function to use. See help on `Activation` layer. If you don't specify anything, no activation is applied (ie. "linear" activation: `a(x) = x`). use_bias : bool, default True Whether the layer uses a bias vector. flatten: bool, default True Whether the input tensor should be flattened. If true, all but the first axis of input data are collapsed together. If false, all but the last axis of input data are kept the same, and the transformation applies on the last axis. dtype : str or np.dtype, default 'float32' Data type of output embeddings. weight_initializer : str or `Initializer` Initializer for the `kernel` weights matrix. bias_initializer: str or `Initializer` Initializer for the bias vector. in_units : int, optional Size of the input data. If not specified, initialization will be deferred to the first time `forward` is called and `in_units` will be inferred from the shape of input data. prefix : str or None See document of `Block`. params : ParameterDict or None See document of `Block`. Inputs: - **data**: if `flatten` is True, `data` should be a tensor with shape `(batch_size, x1, x2, ..., xn)`, where x1 * x2 * ... * xn is equal to `in_units`. If `flatten` is False, `data` should have shape `(x1, x2, ..., xn, in_units)`. Outputs: - **out**: if `flatten` is True, `out` will be a tensor with shape `(batch_size, units)`. If `flatten` is False, `out` will have shape `(x1, x2, ..., xn, units)`. """

[docs]classDropout(HybridBlock):"""Applies Dropout to the input. Dropout consists in randomly setting a fraction `rate` of input units to 0 at each update during training time, which helps prevent overfitting. Parameters ---------- rate : float Fraction of the input units to drop. Must be a number between 0 and 1. axes : tuple of int, default () The axes on which dropout mask is shared. If empty, regular dropout is applied. Inputs: - **data**: input tensor with arbitrary shape. Outputs: - **out**: output tensor with the same shape as `data`. References ---------- `Dropout: A Simple Way to Prevent Neural Networks from Overfitting <http://www.cs.toronto.edu/~rsalakhu/papers/srivastava14a.pdf>`_ """

[docs]classBatchNorm(HybridBlock):"""Batch normalization layer (Ioffe and Szegedy, 2014). Normalizes the input at each batch, i.e. applies a transformation that maintains the mean activation close to 0 and the activation standard deviation close to 1. Parameters ---------- axis : int, default 1 The axis that should be normalized. This is typically the channels (C) axis. For instance, after a `Conv2D` layer with `layout='NCHW'`, set `axis=1` in `BatchNorm`. If `layout='NHWC'`, then set `axis=3`. momentum: float, default 0.9 Momentum for the moving average. epsilon: float, default 1e-5 Small float added to variance to avoid dividing by zero. center: bool, default True If True, add offset of `beta` to normalized tensor. If False, `beta` is ignored. scale: bool, default True If True, multiply by `gamma`. If False, `gamma` is not used. When the next layer is linear (also e.g. `nn.relu`), this can be disabled since the scaling will be done by the next layer. use_global_stats: bool, default False If True, use global moving statistics instead of local batch-norm. This will force change batch-norm into a scale shift operator. If False, use local batch-norm. beta_initializer: str or `Initializer`, default 'zeros' Initializer for the beta weight. gamma_initializer: str or `Initializer`, default 'ones' Initializer for the gamma weight. moving_mean_initializer: str or `Initializer`, default 'zeros' Initializer for the moving mean. moving_variance_initializer: str or `Initializer`, default 'ones' Initializer for the moving variance. in_channels : int, default 0 Number of channels (feature maps) in input data. If not specified, initialization will be deferred to the first time `forward` is called and `in_channels` will be inferred from the shape of input data. Inputs: - **data**: input tensor with arbitrary shape. Outputs: - **out**: output tensor with the same shape as `data`. """

[docs]classInstanceNorm(HybridBlock):r""" Applies instance normalization to the n-dimensional input array. This operator takes an n-dimensional input array where (n>2) and normalizes the input using the following formula: .. math:: \bar{C} = \{i \mid i \neq 0, i \neq axis\} out = \frac{x - mean[data, \bar{C}]}{ \sqrt{Var[data, \bar{C}]} + \epsilon} * gamma + beta Parameters ---------- axis : int, default 1 The axis that will be excluded in the normalization process. This is typically the channels (C) axis. For instance, after a `Conv2D` layer with `layout='NCHW'`, set `axis=1` in `InstanceNorm`. If `layout='NHWC'`, then set `axis=3`. Data will be normalized along axes excluding the first axis and the axis given. epsilon: float, default 1e-5 Small float added to variance to avoid dividing by zero. center: bool, default True If True, add offset of `beta` to normalized tensor. If False, `beta` is ignored. scale: bool, default True If True, multiply by `gamma`. If False, `gamma` is not used. When the next layer is linear (also e.g. `nn.relu`), this can be disabled since the scaling will be done by the next layer. beta_initializer: str or `Initializer`, default 'zeros' Initializer for the beta weight. gamma_initializer: str or `Initializer`, default 'ones' Initializer for the gamma weight. in_channels : int, default 0 Number of channels (feature maps) in input data. If not specified, initialization will be deferred to the first time `forward` is called and `in_channels` will be inferred from the shape of input data. Inputs: - **data**: input tensor with arbitrary shape. Outputs: - **out**: output tensor with the same shape as `data`. References ---------- `Instance Normalization: The Missing Ingredient for Fast Stylization <https://arxiv.org/abs/1607.08022>`_ Examples -------- >>> # Input of shape (2,1,2) >>> x = mx.nd.array([[[ 1.1, 2.2]], ... [[ 3.3, 4.4]]]) >>> # Instance normalization is calculated with the above formula >>> layer = InstanceNorm() >>> layer.initialize(ctx=mx.cpu(0)) >>> layer(x) [[[-0.99998355 0.99998331]] [[-0.99998319 0.99998361]]] <NDArray 2x1x2 @cpu(0)> """

[docs]classLambda(Block):r"""Wraps an operator or an expression as a Block object. Parameters ---------- function : str or function Function used in lambda must be one of the following: 1) the name of an operator that is available in ndarray. For example:: block = Lambda('tanh') 2) a function that conforms to ``def function(*args)``. For example:: block = Lambda(lambda x: nd.LeakyReLU(x, slope=0.1)) Inputs: - ** *args **: one or more input data. Their shapes depend on the function. Output: - ** *outputs **: one or more output data. Their shapes depend on the function. """

[docs]def__init__(self,function,prefix=None):super(Lambda,self).__init__(prefix=prefix)ifisinstance(function,str):asserthasattr(nd,function), \
"Function name %s is not found in ndarray."%functionself._func_impl=getattr(nd,function)elifcallable(function):self._func_impl=functionelse:raiseValueError("Unrecognized function in lambda: {} of type {}".format(function,type(function)))

[docs]classHybridLambda(HybridBlock):r"""Wraps an operator or an expression as a HybridBlock object. Parameters ---------- function : str or function Function used in lambda must be one of the following: 1) The name of an operator that is available in both symbol and ndarray. For example:: block = HybridLambda('tanh') 2) A function that conforms to ``def function(F, data, *args)``. For example:: block = HybridLambda(lambda F, x: F.LeakyReLU(x, slope=0.1)) Inputs: - ** *args **: one or more input data. First argument must be symbol or ndarray. Their \ shapes depend on the function. Output: - ** *outputs **: one or more output data. Their shapes depend on the function. """

[docs]def__init__(self,function,prefix=None):super(HybridLambda,self).__init__(prefix=prefix)ifisinstance(function,str):asserthasattr(nd,function)andhasattr(sym,function), \
"Function name %s is not found in symbol/ndarray."%functionfunc_dict={sym:getattr(sym,function),nd:getattr(nd,function)}self._func=lambdaF,*args:func_dict[F](*args)self._func_name=functionelifcallable(function):self._func=functionself._func_name=function.__name__else:raiseValueError("Unrecognized function in lambda: {} of type {}".format(function,type(function)))