INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
nnabla slice assume a batch dimension existed in the shape of input data. Onnx caffe2 implementation only support one dimension for each slice, hence, we connect multiple slice node to implement slice with multiple axis
def Slice_9(self, func): """ nnabla slice assume a batch dimension existed in the shape of input data. Onnx caffe2 implementation only support one dimension for each slice, hence, we connect multiple slice node to implement slice with multiple axis """ s0 ...
Affine is decomposed as 3 steps: Reshape inputs Gemm Reshape
def Affine(self, opset, func): """ Affine is decomposed as 3 steps: Reshape inputs Gemm Reshape """ nl = [] out_a = fork_name(func.input[0]) base_axis = func.affine_param.base_axis x_shape = list(self._var_dict[func.input[0]].d...
Convert a function to a node or a group of nodes
def set_nodes(self, func): """Convert a function to a node or a group of nodes""" op_type = self.nnabla_function_type_to_onnx_optype.get(func.type) if op_type is None: raise ValueError( "function {} is currently not supported for ONNX conversion".format(func.type)) ...
Convert a given graph. Convert a given graph using the `converters` in the order of the registeration, i.e., sequentially. Args: vroot (:obj:`Variable`): NNabla Variable entry_variables (:obj:`Variable`): Entry variable from which the conversion starts.
def convert(self, vroot, entry_variables): """Convert a given graph. Convert a given graph using the `converters` in the order of the registeration, i.e., sequentially. Args: vroot (:obj:`Variable`): NNabla Variable entry_variables (:obj:`Variable`): Entry variable from...
Utility function for rescaling all pixel values of input image to fit the range of uint8. Rescaling method is min-max, which is all pixel values are normalized to [0, 1] by using img.min() and img.max() and then are scaled up by 255 times. If the argument `as_uint16` is True, output image dtype is np.uint16...
def minmax_auto_scale(img, as_uint16): """ Utility function for rescaling all pixel values of input image to fit the range of uint8. Rescaling method is min-max, which is all pixel values are normalized to [0, 1] by using img.min() and img.max() and then are scaled up by 255 times. If the argument `...
Read image from ``path``. If you specify the ``size``, the output array is resized. Default output shape is (height, width, channel) for RGB image and (height, width) for gray-scale image. Args: path (String or File Object): Input image path. grayscale (bool): If True, the img is rescaled t...
def imread(path, grayscale=False, size=None, interpolate="bilinear", channel_first=False, as_uint16=False, num_channels=-1, **kwargs): """ Read image from ``path``. If you specify the ``size``, the output array is resized. Default output shape is (height, width, channel) for RGB image and (he...
Save ``img`` to the file specified by ``path``. As default, the shape of ``img`` has to be (height, width, channel). Args: path (str): Output path. img (numpy.ndarray): Input image. All pixel values must be positive and in the range [0, 255] of int for uint8, [0, 65535] ...
def imsave(path, img, channel_first=False, as_uint16=False, auto_scale=True, **kwargs): """ Save ``img`` to the file specified by ``path``. As default, the shape of ``img`` has to be (height, width, channel). Args: path (str): Output path. img (numpy.ndarray): Input image. ...
Resize ``img`` to ``size``. As default, the shape of input image has to be (height, width, channel). Args: img (numpy.ndarray): Input image. size (tuple of int): Output shape. The order is (width, height). interpolate (str): Interpolation method. This argument is depend on t...
def imresize(img, size, interpolate="bilinear", channel_first=False, **kwargs): """ Resize ``img`` to ``size``. As default, the shape of input image has to be (height, width, channel). Args: img (numpy.ndarray): Input image. size (tuple of int): Output shape. The order is (width, height...
Monolithic update method. This method calls the following methods with the dynamic loss scaling. 1. solver.zerograd 2. feed data 3. loss.forward 4. loss.backward 5. comm.all_reduce (if it is specified) 6. solver.update
def update(self): """Monolithic update method. This method calls the following methods with the dynamic loss scaling. 1. solver.zerograd 2. feed data 3. loss.forward 4. loss.backward 5. comm.all_reduce (if it is specified) 6. solver.update """ ...
r"""Calculates the standard deviation proposed by He et al. .. math:: \sigma = \sqrt{\frac{2}{NK}} Args: inmaps (int): Map size of an input Variable, :math:`N`. outmaps (int): Map size of an output Variable, :math:`M`. kernel (:obj:`tuple` of :obj:`int`): Convolution kernel spa...
def calc_normal_std_he_forward(inmaps, outmaps, kernel=(1, 1)): r"""Calculates the standard deviation proposed by He et al. .. math:: \sigma = \sqrt{\frac{2}{NK}} Args: inmaps (int): Map size of an input Variable, :math:`N`. outmaps (int): Map size of an output Variable, :math:`M`....
r"""Calculates the standard deviation of He et al. (backward case). .. math:: \sigma = \sqrt{\frac{2}{MK}} Args: inmaps (int): Map size of an input Variable, :math:`N`. outmaps (int): Map size of an output Variable, :math:`M`. kernel (:obj:`tuple` of :obj:`int`): Convolution ke...
def calc_normal_std_he_backward(inmaps, outmaps, kernel=(1, 1)): r"""Calculates the standard deviation of He et al. (backward case). .. math:: \sigma = \sqrt{\frac{2}{MK}} Args: inmaps (int): Map size of an input Variable, :math:`N`. outmaps (int): Map size of an output Variable, :...
r"""Calculates the standard deviation proposed by Glorot et al. .. math:: \sigma = \sqrt{\frac{2}{NK + M}} Args: inmaps (int): Map size of an input Variable, :math:`N`. outmaps (int): Map size of an output Variable, :math:`M`. kernel (:obj:`tuple` of :obj:`int`): Convolution ke...
def calc_normal_std_glorot(inmaps, outmaps, kernel=(1, 1)): r"""Calculates the standard deviation proposed by Glorot et al. .. math:: \sigma = \sqrt{\frac{2}{NK + M}} Args: inmaps (int): Map size of an input Variable, :math:`N`. outmaps (int): Map size of an output Variable, :math:...
r"""Calculates the lower bound and the upper bound of the uniform distribution proposed by Glorot et al. .. math:: b &= \sqrt{\frac{6}{NK + M}}\\ a &= -b Args: inmaps (int): Map size of an input Variable, :math:`N`. outmaps (int): Map size of an output Variable, :math:`M`. ...
def calc_uniform_lim_glorot(inmaps, outmaps, kernel=(1, 1)): r"""Calculates the lower bound and the upper bound of the uniform distribution proposed by Glorot et al. .. math:: b &= \sqrt{\frac{6}{NK + M}}\\ a &= -b Args: inmaps (int): Map size of an input Variable, :math:`N`. ...
Get a unique function name. Args: function_type(str): Name of Function. Ex) Convolution, Affine functions(OrderedDict of (str, Function) Returns: str A unique function name
def _get_unique_function_name(function_type, functions): '''Get a unique function name. Args: function_type(str): Name of Function. Ex) Convolution, Affine functions(OrderedDict of (str, Function) Returns: str A unique function name ''' function_name = function_name_base = ...
Get a unique variable name. Args: vname(str): A candidate name. variable(OrderedDict of str and Variable) Returns: str A unique variable name
def _get_unique_variable_name(vname, variables): '''Get a unique variable name. Args: vname(str): A candidate name. variable(OrderedDict of str and Variable) Returns: str A unique variable name ''' count = 2 vname_base = vname while vname in variables: vname...
Args: var (~nnabla.Variable) variables (OrderedDict) names (dict): Force name table, Variable -> str params (dict): NdArray -> str prefix(str)
def _get_variable_name_or_register(var, variables, names, params, prefix): ''' Args: var (~nnabla.Variable) variables (OrderedDict) names (dict): Force name table, Variable -> str params (dict): NdArray -> str prefix(str) ''' if var not in variables.values(): ...
Save network definition, inference/training execution configurations etc. Args: filename (str): Filename to store information. The file extension is used to determine the saving file format. ``.nnp``: (Recommended) Creating a zip archive with nntxt (network definitio...
def save(filename, contents, include_params=False, variable_batch_size=True): '''Save network definition, inference/training execution configurations etc. Args: filename (str): Filename to store information. The file extension is used to determine the saving file format. ``....
Reduction along axes with sum operation. Args: x (Variable): An input variable. axis (None, int or tuple of ints): Axis or axes along which the sum is calculated. Passing the default value `None` will reduce all dimensions. keepdims (bool): Flag whether the reduced axes are kept...
def sum(x, axis=None, keepdims=False): """Reduction along axes with sum operation. Args: x (Variable): An input variable. axis (None, int or tuple of ints): Axis or axes along which the sum is calculated. Passing the default value `None` will reduce all dimensions. keepdims ...
Reduction along axes with mean operation. Args: x (Variable): An input variable. axis (None, int or tuple of ints): Axis or axes along which mean is calculated. Passing the default value `None` will reduce all dimensions. keepdims (bool): Flag whether the reduced axes are kept a...
def mean(x, axis=None, keepdims=False): """Reduction along axes with mean operation. Args: x (Variable): An input variable. axis (None, int or tuple of ints): Axis or axes along which mean is calculated. Passing the default value `None` will reduce all dimensions. keepdims (...
Reduce the input N-D array `x` along the given `axis` using the max operation. The `axis` argument may be a single integer to reduce over one axis, a tuple of integers to reduce over multiple axes, or ``None`` to reduce over all axes. If `keepdims` is ``True``, the output will keep all reduced dimension...
def max(x, axis=None, keepdims=False, with_index=False, only_index=False): """Reduce the input N-D array `x` along the given `axis` using the max operation. The `axis` argument may be a single integer to reduce over one axis, a tuple of integers to reduce over multiple axes, or ``None`` to reduce over a...
Reduce the input N-D array `x` along the given `axis` using the min operation. The `axis` argument may be a single integer to reduce over one axis, a tuple of integers to reduce over multiple axes, or ``None`` to reduce over all axes. If `keepdims` is ``True``, the output will keep all reduced dimension...
def min(x, axis=None, keepdims=False, with_index=False, only_index=False): """Reduce the input N-D array `x` along the given `axis` using the min operation. The `axis` argument may be a single integer to reduce over one axis, a tuple of integers to reduce over multiple axes, or ``None`` to reduce over a...
Reduction along axes with product operation. Args: x (Variable): An input variable. axis (None, int or tuple of ints): Axis or axes along which product is calculated. Passing the default value `None` will reduce all dimensions. keepdims (bool): Flag whether the reduced axes are ...
def prod(x, axis=None, keepdims=False): """Reduction along axes with product operation. Args: x (Variable): An input variable. axis (None, int or tuple of ints): Axis or axes along which product is calculated. Passing the default value `None` will reduce all dimensions. keep...
Reduction function with given operation. Args: x (Variable): An input. op (str): 'sum' or 'mean'. Note: This is deprecated. Use ``mean`` or ``sum`` instead.
def reduce(x, op='sum'): """Reduction function with given operation. Args: x (Variable): An input. op (str): 'sum' or 'mean'. Note: This is deprecated. Use ``mean`` or ``sum`` instead. """ import warnings warnings.warn( "Deprecated API. Use ``sum`` or ``mean`` ...
Split arrays at the specified axis. It returns a number corresponding the size of the given axis (i.e ``x.shape[axis]``) of :obj:`~nnabla.Variable` s. Args: x(~nnabla.Variable): N-D array axis(int): Axis Returns: A :obj:`tuple` of :obj:`~nnabla.Variable` s See Also: :func...
def split(x, axis=0): """ Split arrays at the specified axis. It returns a number corresponding the size of the given axis (i.e ``x.shape[axis]``) of :obj:`~nnabla.Variable` s. Args: x(~nnabla.Variable): N-D array axis(int): Axis Returns: A :obj:`tuple` of :obj:`~nnabla.Variab...
r""" Slice arrays along specified axis. This function complies with python slice wherre `slice(None, None, -1)` and `slice(-1, None, -1)` are the special case, which flips the input array and results in the output array from the end to the beginning of the input array along the corresponding dime...
def slice(ctx, x, start=None, stop=None, step=None, n_outputs=-1, outputs=None): r""" Slice arrays along specified axis. This function complies with python slice wherre `slice(None, None, -1)` and `slice(-1, None, -1)` are the special case, which flips the input array and results in the output ar...
r""" Batch normalization. .. math:: \begin{eqnarray} \mu &=& \frac{1}{M} \sum x_i \\ \sigma^2 &=& \frac{1}{M} \sum \left(x_i - \mu\right)^2 \\ \hat{x}_i &=& \frac{x_i - \mu}{\sqrt{\sigma^2 + \epsilon}} \\ y_i &=& \hat{x}_i \gamma + \beta. \end{eqnarray} ...
def batch_normalization(x, beta, gamma, mean, variance, axes=[1], decay_rate=0.9, eps=1e-05, batch_stat=True, output_stat=False, n_outputs=None): r""" Batch normalization. .. math:: \begin{eqnarray} \mu &=& \frac{1}{M} \sum x_i \\ \sigma^2 &=& \frac{1}{M} \sum \left(x_i - \mu\ri...
r""" It subtracts the mean of the elements of the input array, and normalizes it to :math:`0`. Preprocessing arrays with this function has the effect of improving accuracy in various tasks such as image classification. At training time, this function is defined as .. math:: \begin{eqnarray...
def mean_subtraction(x, mean, t, base_axis=1, update_running_mean=True): r""" It subtracts the mean of the elements of the input array, and normalizes it to :math:`0`. Preprocessing arrays with this function has the effect of improving accuracy in various tasks such as image classification. At trai...
r"""Fixed Point Quantize Args: x (Variable): An input variable. sign (bool): Indicate the signed number or the unsigned number. Default is true. n (int): Bit width used. Note that `sign` consumes one bit. :math:`n-1` is used for number representation in `signed` case. delta (floa...
def fixed_point_quantize(x, sign=True, n=8, delta=2**-4, quantize=True, ste_fine_grained=True, outputs=None): r"""Fixed Point Quantize Args: x (Variable): An input variable. sign (bool): Indicate the signed number or the unsigned number. Default is true. n (int): Bit width used. Note th...
r"""Pow2 Quantize Args: x (Variable): An input variable. sign (bool): Indicate the signed number or the unsigned number. Default is true. with_zero (bool): Indicate using zero as a quantized value. Default is true. Note that `zero` consumes one bit. n (int): Bit width used. Note tha...
def pow2_quantize(x, sign=True, with_zero=True, n=8, m=1, quantize=True, ste_fine_grained=True, outputs=None): r"""Pow2 Quantize Args: x (Variable): An input variable. sign (bool): Indicate the signed number or the unsigned number. Default is true. with_zero (bool): Indicate using zero ...
r"""Clip inputs by values. .. math:: y = \begin{cases} max & (x > max) \\ x & (otherwise) \\ min & (x < min) \end{cases}. Args: x (Variable): An input variable. min (Variable): A min variable by which `x` is clipped. Note tha...
def clip_by_value(x, min, max): r"""Clip inputs by values. .. math:: y = \begin{cases} max & (x > max) \\ x & (otherwise) \\ min & (x < min) \end{cases}. Args: x (Variable): An input variable. min (Variable): A min variab...
r""" Clip inputs by its L2 norm when the L2 norm is larger than the threshold value (defined by clip_norm). If it is less than the threshold, inputs are not modified. If it is applied, the operation is represented as .. math:: y = N \times \frac{x}{\|x\|_2}. where :math:`x` is the input, :math:`...
def clip_by_norm(x, clip_norm, axis=None): r""" Clip inputs by its L2 norm when the L2 norm is larger than the threshold value (defined by clip_norm). If it is less than the threshold, inputs are not modified. If it is applied, the operation is represented as .. math:: y = N \times \frac{x}{\|x\|...
Resize an ND array with interpolation. Scaling factors for spatial dimensions are determined by either ``scale`` or ``output_size``. ``nd = len(scale)`` or ``nd = len(output_size)`` determines the number of spatial dimensions, and the last ``nd`` dimensions of the input ``x`` are considered as...
def interpolate(x, scale=None, output_size=None, mode='linear', align_corners=None): ''' Resize an ND array with interpolation. Scaling factors for spatial dimensions are determined by either ``scale`` or ``output_size``. ``nd = len(scale)`` or ``nd = len(output_size)`` determines the number of ...
Sorts the elements of `x` along a given `axis` in ascending order by value. A negative `axis` counts from the last dimension of `x`, so the default of -1 sorts along the last dimension. If `reverse` is True, then the elements are soreted in descending order. If `with_index` is True, result is a tuple `...
def sort(x, axis=-1, reverse=False, with_index=False, only_index=False): """Sorts the elements of `x` along a given `axis` in ascending order by value. A negative `axis` counts from the last dimension of `x`, so the default of -1 sorts along the last dimension. If `reverse` is True, then the elements ar...
Forward `x` repeated the number of times given by `reps`. If `reps` is a sequence, the output has dimension of ``d = max(len(reps), x.ndim)`` and either `x` is promoted to be d-dimensional by prepending new axes or `reps` is promoted to x.ndim by prepending 1's. Args: x(~nnabla.Variable): Input...
def tile(x, reps): """Forward `x` repeated the number of times given by `reps`. If `reps` is a sequence, the output has dimension of ``d = max(len(reps), x.ndim)`` and either `x` is promoted to be d-dimensional by prepending new axes or `reps` is promoted to x.ndim by prepending 1's. Args: ...
Download a file from URL. Args: url (str): URL. output_file (str, optional): If given, the downloaded file is written to the given path. open_file (bool): If True, it returns an opened file stream of the downloaded file. allow_overwrite (bool): If True, it overwrites an existing fil...
def download(url, output_file=None, open_file=True, allow_overwrite=False): '''Download a file from URL. Args: url (str): URL. output_file (str, optional): If given, the downloaded file is written to the given path. open_file (bool): If True, it returns an opened file stream of the down...
Read image by cv2 module. Args: path (str or 'file object'): File path or object to read. grayscale (bool): size (tupple of int): (width, height). If None, output img shape depends on the files to read. channel_first (bool): This argument specifie...
def imread(path, grayscale=False, size=None, interpolate="bilinear", channel_first=False, as_uint16=False, num_channels=-1): """ Read image by cv2 module. Args: path (str or 'file object'): File path or object to read. grayscale (bool): size (tupple of int): (...
Save image by cv2 module. Args: path (str): output filename img (numpy.ndarray): Image array to save. Image shape is considered as (height, width, channel) by default. channel_first: This argument specifies the shape of img is whether (height, width, channel) or (channel, height,...
def imsave(path, img, channel_first=False, as_uint16=False, auto_scale=True): """ Save image by cv2 module. Args: path (str): output filename img (numpy.ndarray): Image array to save. Image shape is considered as (height, width, channel) by default. channel_first: This ar...
Resize image by cv2 module. Args: img (numpy.ndarray): Image array to save. Image shape is considered as (height, width, channel) for RGB or (height, width) for gray-scale by default. size (tupple of int): (width, height). channel_first: bool This argument specifies t...
def imresize(img, size, interpolate="bilinear", channel_first=False): """ Resize image by cv2 module. Args: img (numpy.ndarray): Image array to save. Image shape is considered as (height, width, channel) for RGB or (height, width) for gray-scale by default. size (tupple of int): ...
Returns a list of (name, snake_name, [argument types as c++ type])
def info_to_list(info): '''Returns a list of (name, snake_name, [argument types as c++ type])''' items = [] for name, item in info.items(): items.append((name, item['snake_name'], [ type_from_proto[v['type']]['cpp'] for v in item.get('arguments', {}).values()])) return items
Get learning rate with polymomial decay based on current iteration. Args: iter (int): current iteration (starting with 0). Returns: float: Learning rate
def get_learning_rate(self, iter): ''' Get learning rate with polymomial decay based on current iteration. Args: iter (int): current iteration (starting with 0). Returns: float: Learning rate ''' return self.init_lr * ((1.0 - iter * 1.0 / self.ma...
Get learning rate with cosine decay based on current iteration. Args: iter (int): Current iteration (starting with 0). Returns: float: Learning rate
def get_learning_rate(self, iter): ''' Get learning rate with cosine decay based on current iteration. Args: iter (int): Current iteration (starting with 0). Returns: float: Learning rate ''' return self.init_lr * ((math.cos(iter * 1.0 / (self.ma...
Get learning rate with exponential decay based on current iteration. Args: iter (int): Current iteration (starting with 0). Returns: float: Learning rate
def get_learning_rate(self, iter): ''' Get learning rate with exponential decay based on current iteration. Args: iter (int): Current iteration (starting with 0). Returns: float: Learning rate ''' return self.init_lr * (self.gamma ** (iter // se...
Get learning rate with exponential decay based on current iteration. Args: iter (int): Current iteration (starting with 0). Returns: float: Learning rate
def get_learning_rate(self, iter): ''' Get learning rate with exponential decay based on current iteration. Args: iter (int): Current iteration (starting with 0). Returns: float: Learning rate ''' lr = self.init_lr for iter_step in self.i...
Get learning rate with exponential decay based on current iteration. Args: iter (int): Current iteration (starting with 0). Returns: float: Learning rate
def get_learning_rate(self, iter): ''' Get learning rate with exponential decay based on current iteration. Args: iter (int): Current iteration (starting with 0). Returns: float: Learning rate ''' lr = self.scheduler.get_learning_rate(iter) ...
Decorator for parametric functions. The decorated function is always called under a parameter scope ``scope_name``. Also, the decorator adds an additional argument ``name`` (:obj:`str`, default is ``None``) at the end. If ``name`` is specified, the scope ``scope_name`` comes under a scope ``name``....
def parametric_function_api(scope_name=None, param_desc=None): """Decorator for parametric functions. The decorated function is always called under a parameter scope ``scope_name``. Also, the decorator adds an additional argument ``name`` (:obj:`str`, default is ``None``) at the end. If ``name`` is...
The affine layer, also known as the fully connected layer. Computes .. math:: {\\mathbf y} = {\\mathbf A} {\\mathbf x} + {\\mathbf b}. where :math:`{\\mathbf x}, {\\mathbf y}` are the inputs and outputs respectively, and :math:`{\\mathbf A}, {\\mathbf b}` are constants. Args: inp (~nn...
def affine(inp, n_outmaps, base_axis=1, w_init=None, b_init=None, fix_parameters=False, rng=None, with_bias=True, apply_w=None, apply_b=None): """ The affine layer, also known as the fully connected layer. Computes .. math:: {\\mathbf y} = {\\mathbf A} {\...
SVD affine is a low rank approximation of the affine layer. It can be seen as two consecutive affine layers with a bottleneck. It computes: .. math:: {\\mathbf y} = {\\mathbf U} {\\mathbf V} {\\mathbf x} + {\\mathbf b}. where :math:`{\\mathbf x}, {\\mathbf y}` are the inputs and outputs re...
def svd_affine(inp, n_outmaps, r, base_axis=1, uv_init=None, b_init=None, fix_parameters=False, rng=None, with_bias=True): """SVD affine is a low rank approximation of the affine layer. It can be seen as two consecutive affine layers with a bottleneck. It computes: .. math...
Binary Weight Affine, multiplier-less inner-product with a scale factor. Binary Weight Affine is the affine function, but the inner product in this function is the following, .. math:: y_j = \\frac{1}{\\|\\mathbf{w}_j\\|_{\\ell_1}} \sum_{i} sign(w_{ji}) x_i Therefore :math:`sign(w_{ji})` is ...
def binary_weight_affine(inp, n_outmaps, base_axis=1, quantize_zero_to=1.0, w_init=None, wb_init=None, b_init=None, fix_parameters=False, rng=None, with_bias=True): """Binary Weight Affine, multiplier-less inner-product with a scale factor. ...
Incremental Network Quantization Affine Layer During training, the weights are sequentially quantized to power-of-two values, which allows the training of a multiplierless network. Using `inq_iterations`, one can specify after how many forward passes half of the learnable weights are fixed and quantiz...
def inq_affine(inp, n_outmaps, base_axis=1, num_bits=4, inq_iterations=(), selection_algorithm='random', seed=-1, w_init=None, i_init=None, b_init=None, fix_parameters=False, rng=None, with_bias=True): """Incremental Network Quantization Affine Layer During training...
SVD convolution is a low rank approximation of the convolution layer. It can be seen as a depth wise convolution followed by a 1x1 convolution. The flattened kernels for the i-th input map are expressed by their low rank approximation. The kernels for the i-th input :math:`{\\mathbf W_i}` are appro...
def svd_convolution(inp, outmaps, kernel, r, pad=None, stride=None, dilation=None, uv_init=None, b_init=None, base_axis=1, fix_parameters=False, rng=None, with_bias=True): """SVD convolution is a low rank approximation of the convolution layer. It can be seen as a depth w...
CP convolution is a low rank approximation of a convolution layer. A 3D tensor containing the parameter is built by collapsing the N-D kernels into 1D, then the tensor is decomposed into three matrices. The decomposed layer can be seen as linear combinations of the input feature maps to :math:`{R}` feature maps followe...
def cpd3_convolution(inp, outmaps, kernel, r, pad=None, stride=None, dilation=None, oik_init=None, b_init=None, base_axis=1, fix_parameters=False, rng=None, with_bias=True, max_iter=500, stopping_criterion=1e-5, lambda_reg=0.0): """...
Binary Connect Convolution, multiplier-less inner-product. Binary Connect Convolution is the convolution function, except the definition of the inner product is modified. The input-output relation of this function is as follows: .. math:: y_{n, a, b} = \sum_{m} \sum_{i} \sum_{j} sign(w_{n, m,...
def binary_connect_convolution(inp, outmaps, kernel, pad=None, stride=None, dilation=None, group=1, quantize_zero_to=1.0, w_init=None, wb_init=None, b_init=None, base_axis=1, fix_parameters=False,...
Incremental Network Quantization Convolution Layer During training, the weights are sequentially quantized to power-of-two values, which allows the training of a multiplierless network. Using `inq_iterations`, one can specify after how many forward passes half of the learnable weights are fixed and qu...
def inq_convolution(inp, outmaps, kernel, pad=None, stride=None, dilation=None, group=1, num_bits=4, inq_iterations=(), selection_algorithm='random', seed=-1, w_init=None, i_init=None, b_init=None, base_axis=1, fix_parameters=False, rng=Non...
N-D Depthwise Convolution with a bias term. Reference: - F. Chollet: Chollet, Francois. "Xception: Deep Learning with Depthwise Separable Convolutions. https://arxiv.org/abs/1610.02357 Args: inp (~nnabla.Variable): N-D array. kernel (:obj:`tuple` of :obj:`int`): Convolution kernel size. F...
def depthwise_convolution(inp, kernel, pad=None, stride=None, dilation=None, multiplier=1, w_init=None, b_init=None, base_axis=1, fix_parameters=False, rng=None, with_bias=True): """ N-D Depthwise Convolution with a bias term. Reference: - F. Chollet...
Deconvolution layer. Args: inp (~nnabla.Variable): N-D array. outmaps (int): Number of deconvolution kernels (which is equal to the number of output channels). For example, to apply deconvolution on an input with 16 types of filters, specify 16. kernel (:obj:`tuple` of :obj:`int`): Convolut...
def deconvolution(inp, outmaps, kernel, pad=None, stride=None, dilation=None, group=1, w_init=None, b_init=None, base_axis=1, fix_parameters=False, rng=None, with_bias=True, apply_w=None, apply_b=None): """ Deconvolution layer. Args: ...
N-Step RNN (recurrent neural networks). N-Step RNN function implements Elman RNN with nonlineraity to input sequence. N-Step RNN function is defined as following: .. math:: h_t = \\tanh(w_{ih}x_t+b_{ih}+w_{hh}h_{(t-1)}). We use the following notations to describe the inputs and outputs below....
def rnn(x, h, w0_init=None, w_init=None, b_init=None, num_layers=1, nonlinearity='tanh', dropout=0.0, bidirectional=False, training=True, rng=None, with_bias=True, fix_parameters=False): """N-Step RNN (recurrent neural networks). N-Step RNN function implements Elman RNN with nonlineraity to input sequence. ...
Batch normalization layer. .. math:: \\begin{array}{lcl} \\mu &=& \\frac{1}{M} \\sum x_i\\\\ \\sigma^2 &=& \\frac{1}{M} \\sum \\left(x_i - \\mu\\right)^2\\\\ \\hat{x}_i &=& \\frac{x_i - \\mu}{\\sqrt{\\sigma^2 + \\epsilon }}\\\\ y_i &= & \\hat{x}_i \\gamma + \\beta. ...
def batch_normalization(inp, axes=[1], decay_rate=0.9, eps=1e-5, batch_stat=True, output_stat=False, fix_parameters=False, param_init=None): """ Batch normalization layer. .. math:: \\begin{array}{lcl} \\mu &=& \\frac{1}{M} \\sum x_i\\\\ ...
Mean subtraction layer. It subtracts the mean of the elements of the input array, and normalizes it to :math:`0`. Preprocessing arrays with this function has the effect of improving accuracy in various tasks such as image classification. At training time, this function is defined as .. math:: ...
def mean_subtraction(inp, base_axis=1, update_running_mean=True, fix_parameters=False): """ Mean subtraction layer. It subtracts the mean of the elements of the input array, and normalizes it to :math:`0`. Preprocessing arrays with this function has the effect of improving accuracy in various tasks...
Embed. Embed slices a matrix/tensor with indexing array/tensor. Weights are initialized with :obj:`nnabla.initializer.UniformInitializer` within the range of :math:`-\\sqrt{3}` and :math:`\\sqrt{3}`. Args: x(~nnabla.Variable): [Integer] Indices with shape :math:`(I_0, ..., I_N)` n_inputs : num...
def embed(inp, n_inputs, n_features, initializer=None, fix_parameters=False, apply_w=None): """ Embed. Embed slices a matrix/tensor with indexing array/tensor. Weights are initialized with :obj:`nnabla.initializer.UniformInitializer` within the range of :math:`-\\sqrt{3}` and :math:`\\sqrt{3}`. ...
Parametrized Rectified Linear Unit function defined as .. math:: y_i = \max(0, x_i) + w_i \min(0, -x_i) where negative slope :math:`w` is learned and can vary across channels (an axis specified with base_axis). Weights are initialized with :math:`-1`. Args: x(~nnabla.Variable): N-D ar...
def prelu(inp, base_axis=1, shared=True, fix_parameters=False): """ Parametrized Rectified Linear Unit function defined as .. math:: y_i = \max(0, x_i) + w_i \min(0, -x_i) where negative slope :math:`w` is learned and can vary across channels (an axis specified with base_axis). Weights are...
Fixed-Point Quantized Affine. Fixed-Point Quantized Affine is the affine function, except the definition of the inner product is modified. The input-output relation of this function is as follows: .. math:: y_j = \sum_{i} Q(w_{ji}) x_i, where :math:`Q(w_{ji})` is the fixed-point quantiza...
def fixed_point_quantized_affine(inp, n_outmaps, base_axis=1, w_init=None, b_init=None, fix_parameters=False, rng=None, with_bias=True, quantize_w=True, sign_w=True, n_w=8, delta_w=2**-4, ...
Fixed-Point Quantized Convolution. Fixed-Point Quantized Convolution is the convolution function, except the definition of the inner product is modified. The input-output relation of this function is as follows: .. math:: y_{n, a, b} = \sum_{m} \sum_{i} \sum_{j} Q(w_{n, m, i, j}) x_{m, a + i,...
def fixed_point_quantized_convolution(inp, outmaps, kernel, pad=None, stride=None, dilation=None, group=1, w_init=None, b_init=None, base_axis=1, fix_parameters=False, rng=None, with_bias=True, ...
Pow2 Quantized Affine. Pow2 Quantized Affine is the affine function, except the definition of the inner product is modified. The input-output relation of this function is as follows: .. math:: y_j = \sum_{i} Q(w_{ji}) x_i, where :math:`Q(w_{ji})` is the power-of-2 quantization function. ...
def pow2_quantized_affine(inp, n_outmaps, base_axis=1, w_init=None, b_init=None, fix_parameters=False, rng=None, with_bias=True, quantize_w=True, sign_w=True, with_zero_w=False, n_w=8, m_w=2, ste_fine_grained_w=True,...
Pow2 Quantized Convolution. Pow2 Quantized Convolution is the convolution function, except the definition of the inner product is modified. The input-output relation of this function is as follows: .. math:: y_{n, a, b} = \sum_{m} \sum_{i} \sum_{j} Q(w_{n, m, i, j}) x_{m, a + i, b + j}, ...
def pow2_quantized_convolution(inp, outmaps, kernel, pad=None, stride=None, dilation=None, group=1, w_init=None, b_init=None, base_axis=1, fix_parameters=False, rng=None, with_bias=True, quantize_...
Pruned Affine. Pruned Affine is the affine function, except the definition of the inner product is modified. The input-output relation of this function is as follows: .. math:: y_j = \sum_{i} Q(w_{ji}) x_i, where :math:`Q(w_{ji})` is the pruning function, i.e., `F.prune`. .. note:...
def pruned_affine(inp, n_outmaps, base_axis=1, w_init=None, b_init=None, fix_parameters=False, rng=None, with_bias=True, prune_w=True, rate_w=0.9, prune_b=True, rate_b=0.9): """Pruned Affine. Pruned Affine is the affine function, exce...
Pruned Convolution. Pruned Convolution is the convolution function, except the definition of the inner product is modified. The input-output relation of this function is as follows: .. math:: y_{n, a, b} = \sum_{m} \sum_{i} \sum_{j} Q(w_{n, m, i, j}) x_{m, a + i, b + j}, where :math:`Q...
def pruned_convolution(inp, outmaps, kernel, pad=None, stride=None, dilation=None, group=1, w_init=None, b_init=None, base_axis=1, fix_parameters=False, rng=None, with_bias=True, prune_w=True, rate_w=0.9, prune_b=True, rate_b=0....
Long Short-Term Memory. Long Short-Term Memory, or LSTM, is a building block for recurrent neural networks (RNN) layers. LSTM unit consists of a cell and input, output, forget gates whose functions are defined as following: .. math:: f_t&&=\\sigma(W_fx_t+U_fh_{t-1}+b_f) \\\\ i_t&&=\\sigma(...
def lstm_cell(x, h, c, state_size, w_init=None, b_init=None, fix_parameters=False): """Long Short-Term Memory. Long Short-Term Memory, or LSTM, is a building block for recurrent neural networks (RNN) layers. LSTM unit consists of a cell and input, output, forget gates whose functions are defined as followi...
Spectral Normalization. .. math:: W_{sn} = \\frac{W}{\\sigma(W)}. where :math:`W` is the input matrix, and the :math:`\\sigma(W)` is the spectral norm of :math:`W`. The spectral norm is approximately computed by the power iteration. References: Takeru Miyato, Toshiki Kataoka, Masanori K...
def spectral_norm(w, dim=0, itr=1, eps=1e-12, test=False, u_init=None, fix_parameters=True): """Spectral Normalization. .. math:: W_{sn} = \\frac{W}{\\sigma(W)}. where :math:`W` is the input matrix, and the :math:`\\sigma(W)` is the spectral norm of :math:`W`. The spectral norm is approximately c...
Resets states h and c to zero.
def reset_state(self): """ Resets states h and c to zero. """ self.h.data.zero() self.c.data.zero()
Create input :obj:`nnabla.Variable` from :obj:`Inspec`. Args: inspecs (:obj:`list` of :obj:`Inspec`): A list of ``Inspec``. Returns: :obj:`list` of :obj:`nnabla.Variable`: Input variables.
def create_inputs(inspecs): """Create input :obj:`nnabla.Variable` from :obj:`Inspec`. Args: inspecs (:obj:`list` of :obj:`Inspec`): A list of ``Inspec``. Returns: :obj:`list` of :obj:`nnabla.Variable`: Input variables. """ ret = [] for i in inspecs: v = nn.Variable(i....
Calculate lap time. Returns: float: Lap time. The duration from the previous call of ``lap()`` or initialization at first call. float: Total time. The duration from initialization.
def lap(self): """Calculate lap time. Returns: float: Lap time. The duration from the previous call of ``lap()`` or initialization at first call. float: Total time. The duration from initialization. """ now = time.time() lap_time = now -...
Write a single function benchmark. Args: fb (FunctionBenchmark): FunctionBenchmark class instance. Before passing to this, you should call ``fb.benchmark()``.
def write(self, fb): """Write a single function benchmark. Args: fb (FunctionBenchmark): FunctionBenchmark class instance. Before passing to this, you should call ``fb.benchmark()``. """ print('[{}.{}]'.format(fb.module, fb.func.__name__), file=self.file) ...
Create a function instance and execute setup. Args: delete (bool): Delete buffered variables.
def _setup(self, delete=True): """Create a function instance and execute setup. Args: delete (bool): Delete buffered variables. """ if delete: self.clear() with nn.context_scope(self.ctx): outputs = self.func( *(self.inputs_f ...
Benchmark setup execution.
def benchmark_setup(self): """Benchmark setup execution. """ def f(): self._setup() self.mod_ext.synchronize(**self.ext_kwargs) f() # Ignore first self.setup_stat = self._calc_benchmark_stat(f)
Benchmark forward execution.
def benchmark_forward(self): """Benchmark forward execution. """ self._setup() def f(): self._forward() self.mod_ext.synchronize(**self.ext_kwargs) f() # Ignore first self.forward_stat = self._calc_benchmark_stat(f)
Benchmark backward execution. Note: If backward execution throws any exception, this benchmark system considers the error is because the function doesn't support backward operation, then set the benchmark ``None``.
def benchmark_backward(self): """Benchmark backward execution. Note: If backward execution throws any exception, this benchmark system considers the error is because the function doesn't support backward operation, then set the benchmark ``None``. ...
CPU Context.
def context(type_config='float', **kw): """CPU Context.""" backends = ['cpu:float'] if type_config == 'half': backends = ['cpu:half', 'cpu:float'] elif type_config == 'float': pass else: raise ValueError("Unknown data type config is given %s" % type_config) return nn.Cont...
Get the context of the specified extension. All extension's module must provide `context(**kw)` function. Args: extension_name (str) : Module path relative to `nnabla_ext`. kw (dict) : Additional keyword arguments for context function in a extension module. Returns: :class:`nnabla...
def extension_context(extension_name='cpu', **kw): """Get the context of the specified extension. All extension's module must provide `context(**kw)` function. Args: extension_name (str) : Module path relative to `nnabla_ext`. kw (dict) : Additional keyword arguments for context function i...
This function is used to revise buffer size, use byte as its unit, instead of data item. This is only used for nnb, not for csrc. When settings contains user customized data type, not pure FLOAT32, it affects the memory consumption.
def revise_buffer_size(info, settings): ''' This function is used to revise buffer size, use byte as its unit, instead of data item. This is only used for nnb, not for csrc. When settings contains user customized data type, not pure FLOAT32, it affects the memory consumption. ''' size_ma...
Returns category names of 1000 ImageNet classes.
def category_names(self): ''' Returns category names of 1000 ImageNet classes. ''' if hasattr(self, '_category_names'): return self._category_names with open(os.path.join(os.path.dirname(__file__), 'category_names.txt'), 'r') as fd: self._category_names = ...
Args: rel_name: relative path to where donwloaded nnp is saved. rel_url: relative url path to where nnp is downloaded from.
def _load_nnp(self, rel_name, rel_url): ''' Args: rel_name: relative path to where donwloaded nnp is saved. rel_url: relative url path to where nnp is downloaded from. ''' from nnabla.utils.download import download path_nnp = os.path.join(...
Write result to the file. The output file is specified by ``file``.
def write(self): """ Write result to the file. The output file is specified by ``file``. """ writer = csv.writer(self.file) for f, b in zip(self.gb.result["forward"], self.gb.result["backward"]): f = f._asdict() b = b._asdict() if not ...
Convert an array with shape of (B, C, H, W) into a tiled image. Args: data (~numpy.ndarray): An array with shape of (B, C, H, W). padsize (int): Each tile has padding with this size. padval (float): Padding pixels are filled with this value. Returns: tile_image (~numpy.ndarray)...
def tile_images(data, padsize=1, padval=0): """ Convert an array with shape of (B, C, H, W) into a tiled image. Args: data (~numpy.ndarray): An array with shape of (B, C, H, W). padsize (int): Each tile has padding with this size. padval (float): Padding pixels are filled with this ...
Plot series data from MonitorSeries output text file. Args: filename (str): Path to *.series.txt file produced by :obj:`~nnabla.MonitorSeries` class. plot_kwags (dict, optional): Keyward arguments passed to :function:`matplotlib.pyplot.plot`. Note: matplotlib package is req...
def plot_series(filename, plot_kwargs=None): '''Plot series data from MonitorSeries output text file. Args: filename (str): Path to *.series.txt file produced by :obj:`~nnabla.MonitorSeries` class. plot_kwags (dict, optional): Keyward arguments passed to :function:`matplotlib.pyplot...
Plot series data from MonitorTimeElapsed output text file. Args: filename (str): Path to *.series.txt file produced by :obj:`~nnabla.MonitorSeries` class. elapsed (bool): If ``True``, it plots the total elapsed time. unit (str): Time unit chosen from ``'s'``, ``'m'``, ``'h'``, o...
def plot_time_elapsed(filename, elapsed=False, unit='s', plot_kwargs=None): '''Plot series data from MonitorTimeElapsed output text file. Args: filename (str): Path to *.series.txt file produced by :obj:`~nnabla.MonitorSeries` class. elapsed (bool): If ``True``, it plots the total elapsed time....
Add a value to the series. Args: index (int): Index. value (float): Value.
def add(self, index, value): """Add a value to the series. Args: index (int): Index. value (float): Value. """ self.buf.append(value) if (index - self.flush_at) < self.interval: return value = np.mean(self.buf) if self.verbose...
Calculate time elapsed from the point previously called this method or this object is created to this is called. Args: index (int): Index to be displayed, and be used to take intervals.
def add(self, index): """Calculate time elapsed from the point previously called this method or this object is created to this is called. Args: index (int): Index to be displayed, and be used to take intervals. """ if (index - self.flush_at) < self.interval: ...
Add a minibatch of images to the monitor. Args: index (int): Index. var (:obj:`~nnabla.Variable`, :obj:`~nnabla.NdArray`, or :obj:`~numpy.ndarray`): A minibatch of images with ``(N, ..., C, H, W)`` format. If C == 2, blue channel is appended with ones. If...
def add(self, index, var): """Add a minibatch of images to the monitor. Args: index (int): Index. var (:obj:`~nnabla.Variable`, :obj:`~nnabla.NdArray`, or :obj:`~numpy.ndarray`): A minibatch of images with ``(N, ..., C, H, W)`` format. If C == 2, ...
Store cache data into file. Data will be stored as hdf5 format, placed at config.. Cache file name format is "cache_START_END.h5"
def _save_cache_to_file(self): ''' Store cache data into file. Data will be stored as hdf5 format, placed at config.. Cache file name format is "cache_START_END.h5" ''' if self._cache_dir is None: raise DataSourceWithFileCacheError( 'Use this ...
Solve CPD Args: X (numpy.ndarray): Target tensor of CPD. rank (int): Rank of the approximate tensor. max_iter (int): Max iteration of the ALS. stopping_criterion (float): Threshold for stopping the ALS. If the value is negative, the convergence ch...
def solve(self, X, rank, max_iter=500, stopping_criterion=1e-5, lambda_reg=0.0, dtype=np.float32, rng=None): """Solve CPD Args: X (numpy.ndarray): Target tensor of CPD. rank (int): Rank of the approximate tensor. max_iter (int): Max iteration of the ALS...
data_iterator Helper method to use :py:class:`DataSource <nnabla.utils.data_source.DataSource>`. You can use :py:class:`DataIterator <nnabla.utils.data_iterator.DataIterator>` with your own :py:class:`DataSource <nnabla.utils.data_source.DataSource>` for easy implementation of data sources. For exampl...
def data_iterator(data_source, batch_size, rng=None, with_memory_cache=True, with_file_cache=False, cache_dir=None, epoch_begin_callbacks=[], epoch_end_callbacks=[]): '''data_iterator He...
A generator that ``yield`` s minibatch data as a tuple, as defined in ``load_func`` . It can unlimitedly yield minibatches at your request, queried from the provided data. Args: load_func (function): Takes a single argument `i`, an index of an example in your dataset to be loaded, and retur...
def data_iterator_simple(load_func, num_examples, batch_size, shuffle=False, rng=None, with_memory_cache=True, with_file_cache=True, cache_dir=No...
data_iterator_csv_dataset Get data directly from a dataset provided as a CSV file. You can read files located on the local file system, http(s) servers or Amazon AWS S3 storage. For example, .. code-block:: python batch = data_iterator_csv_dataset('CSV_FILE.csv', batch_size, shuffle=True) ...
def data_iterator_csv_dataset(uri, batch_size, shuffle=False, rng=None, normalize=True, with_memory_cache=True, with_file_cache=True, ...
data_iterator_cache Get data from the cache directory. Cache files are read from the local file system. For example, .. code-block:: python batch = data_iterator_cache('CACHE_DIR', batch_size, shuffle=True) Args: uri (str): Location of directory with cache files. batch_s...
def data_iterator_cache(uri, batch_size, shuffle=False, rng=None, normalize=True, with_memory_cache=True, epoch_begin_callbacks=[], epoch_end_callbacks=...
data_iterator_concat_datasets Get data from multiple datasets. For example, .. code-block:: python batch = data_iterator_concat_datasets([DataSource0, DataSource1, ...], batch_size) Args: data_source_list (list of DataSource): list of datasets. batch_size (int): Size of data ...
def data_iterator_concat_datasets(data_source_list, batch_size, shuffle=False, rng=None, with_memory_cache=True, with_file_cache=False, ...
next It generates tuple of data. For example, if :py:meth:`self._variables == ('x', 'y')` This method returns :py:meth:` ( [[X] * batch_size], [[Y] * batch_size] )` Returns: tuple: tuple of data for mini-batch in numpy.ndarray.
def next(self): '''next It generates tuple of data. For example, if :py:meth:`self._variables == ('x', 'y')` This method returns :py:meth:` ( [[X] * batch_size], [[Y] * batch_size] )` Returns: tuple: tuple of data for mini-batch in numpy.ndarray. ''...
Slices the data iterator so that newly generated data iterator has access to limited portion of the original data. Args: rng (numpy.random.RandomState): Random generator for Initializer. num_of_slices(int): Total number of slices to be made. Muts be used together with `slice_pos`. ...
def slice(self, rng, num_of_slices=None, slice_pos=None, slice_start=None, slice_end=None, cache_dir=None): ''' Slices the data iterator so that newly generated data iterator has access to limited portion of the original data. Args: rng (numpy.random.Rand...
All functions are replaced with the same `new` function. Args: vroot (:obj:`Variable`): NNabla Variable entry_variables (:obj:`Variable`): Entry variable from which the conversion starts.
def convert(self, vroot, entry_variables): """ All functions are replaced with the same `new` function. Args: vroot (:obj:`Variable`): NNabla Variable entry_variables (:obj:`Variable`): Entry variable from which the conversion starts. """ self.graph_info ...
Context for dynamic graph execution mode. Args: auto (bool): Whether forward computation is executed during a computation graph construction. Returns: bool
def auto_forward(auto=True): """ Context for dynamic graph execution mode. Args: auto (bool): Whether forward computation is executed during a computation graph construction. Returns: bool """ global __auto_forward_state prev = __auto_forward_state __auto_forward_s...
Decorating a function that is profiled with a Python profiler such as :class:`cProfile.Profile`. **Note**: ``function`` doesn't refer to :obj:`~nnabla.function.Function`. A Python function. Args: fn (function): A function that is profiled. If None is specified (default), it ...
def profile(fn=None, condition=None, profile_class=cProfile.Profile, print_freq=0, sort_keys=None, print_restrictions=None): '''Decorating a function that is profiled with a Python profiler such as :class:`cProfile.Profile`. **Note**: ``function`` doesn't refer to :obj:`~nnabla.function.Function`. A Py...