NDArray API

Overview

This document lists the routines of the n-dimensional array package

mxnet.ndarray NDArray API of MXNet.

A NDArray is a multidimensional container of items of the same type and size. Various methods for data manipulation and computation are provided.

>>> x = mx.nd.array([[1, 2, 3], [4, 5, 6]])
>>> type(x)
<class 'mxnet.ndarray.NDArray'>
>>> x.shape
(2, 3)
>>> y = x + mx.nd.ones(x.shape)*3
>>> print(y.asnumpy())
[[ 4.  5.  6.]
 [ 7.  8.  9.]]
>>> z = y.as_in_context(mx.gpu(0))
>>> print(z)
<NDArray 2x3 @gpu(0)>

A detailed tutorial is available at http://mxnet.io/tutorials/python/ndarray.html..

Note

mxnet.ndarray is similar to numpy.ndarray in some aspects. But the difference is not negligible. For example

  • NDArray.T does real data transpose to return new a copied array, instead of returning a view of the input array.
  • ndarray.dot performs dot between the last axis of the first input array and the first axis of the second input, while numpy.dot uses the second last axis of the input array.

In additional, NDArray supports GPU computation and various neural network layers.

Note

ndarray also provides almost same routines to symbol. Most routines between these two packages share the same C++ operator source codes. But ndarray differs to symbol in several aspects:

  • ndarray adopts imperative programming, namely sentences are executed step-by-step so that the results can be obtained immediately.
  • Most binary operators such as + and > are enabled broadcasting in default.

In the rest of this document, we first overview the methods provided by the ndarray.NDArray class, and then list other routines provided by the ndarray package.

The NDArray class

Array attributes

NDArray.shape Tuple of array dimensions.
NDArray.size Number of elements in the array.
NDArray.context Device context of the array.
NDArray.dtype Data-type of the array’s elements.

Array conversion

NDArray.copy Makes a copy of this NDArray, keeping the same context.
NDArray.copyto Copies the value of this array to another array.
NDArray.as_in_context Returns an array on the target device with the same value as this array.
NDArray.asnumpy Returns a numpy.ndarray object with value copied from this array.
NDArray.asscalar Returns a scalar whose value is copied from this array.
NDArray.astype Returns a copy of the array after casting to a specified type.

Array change shape

NDArray.T Returns a copy of the array with axes transposed.
NDArray.reshape Returns a view of this array with a new shape without altering any data.
NDArray.broadcast_to Broadcasts the input array to a new shape.

Arithmetic operations

NDArray.__add__ x.__add__(y) <=> x+y <=> mx.nd.add(x, y)
NDArray.__sub__ x.__sub__(y) <=> x-y <=> mx.nd.subtract(x, y)
NDArray.__rsub__ x.__rsub__(y) <=> y-x <=> mx.nd.subtract(y, x)
NDArray.__neg__ x.__neg__(y) <=> -x
NDArray.__mul__ x.__mul__(y) <=> x*y <=> mx.nd.multiply(x, y)
NDArray.__div__ x.__div__(y) <=> x/y <=> mx.nd.divide(x, y)
NDArray.__rdiv__ x.__rdiv__(y) <=> y/x <=> mx.nd.divide(y, x)
NDArray.__pow__ x.__pow__(y) <=> x**y <=> mx.nd.power(x,y)

In-place arithmetic operations

NDArray.__iadd__ x.__iadd__(y) <=> x+=y
NDArray.__isub__ x.__isub__(y) <=> x-=y
NDArray.__imul__ x.__imul__(y) <=> x*=y
NDArray.__idiv__ x.__rdiv__(y) <=> x/=y

Comparison operators

NDArray.__lt__ x.__lt__(y) <=> x<y <=> mx.nd.lesser(x, y)
NDArray.__le__ x.__le__(y) <=> x<=y <=> mx.nd.less_equal(x, y)
NDArray.__gt__ x.__gt__(y) <=> x>y <=> mx.nd.greater(x, y)
NDArray.__ge__ x.__ge__(y) <=> x>=y <=> mx.nd.greater_equal(x, y)
NDArray.__eq__ x.__eq__(y) <=> x==y <=> mx.nd.equal(x, y)
NDArray.__ne__ x.__ne__(y) <=> x!=y <=> mx.nd.not_equal(x, y)

Indexing

NDArray.__getitem__ x.__getitem__(i) <=> x[i]
NDArray.__setitem__ x.__setitem__(i, y) <=> x[i]=y

Lazy evaluation

NDArray.wait_to_read Waits until all previous write operations on the current array are finished.

Array creation routines

array Creates an array from any object exposing the array interface.
empty Returns a new array of given shape and type, without initializing entries.
zeros Returns a new array filled with all zeros, with the given shape and type.
ones Returns a new array filled with all ones, with the given shape and type.
full Returns a new array of given shape and type, filled with the given value val.
arange Returns evenly spaced values within a given interval.
load Load array from file.
save Save a list of arrays of a str->array dict into file.

Array manipulation routines

Changing array shape and type

cast Casts all elements of the input to the new type.
reshape Reshapes the input array into a new shape.
flatten Flattens the input array into a 2-D array by collapsing the higher dimensions.
expand_dims Insert a new axis with size 1 into the array shape

Expanding array elements

broadcast_to Broadcasts the input array to a new shape.
broadcast_axes Broadcasts the input array over particular axes.
repeat Repeat elements of an array.
tile Repeat the whole array by multiple times.
pad Pad an array.

Rearranging elements

transpose Permute the dimensions of an array.
swapaxes Interchange two axes of an array.
flip Reverse the order of elements in an array along given axis.

Joining and splitting arrays

concat Join input arrays along the given axis.
split Split an array along a particular axis into multiple sub-arrays.

Indexing routines

slice Slice a continuous region of the array.
slice_axis Slice along a given axis.
take Takes elements from an input array along the given axis.
batch_take Takes elements from a data batch.
one_hot Returns a one-hot array.
pick Picks elements from an input array according to the input indices along the given axis.

Mathematical functions

Arithmetic operations

add Returns element-wise sum of the input arrays with broadcasting.
subtract Returns element-wise difference of the input arrays with broadcasting.
negative Numerical negative, element-wise.
multiply Returns element-wise product of the input arrays with broadcasting.
divide Returns element-wise division of the input arrays with broadcasting.
dot Dot product of two arrays.
batch_dot Batchwise dot product.
add_n Add all input arguments element-wise.

Trigonometric functions

sin Computes the element-wise sine of the input.
cos Computes the element-wise cosine of the input array.
tan Computes the element-wise tangent of the input array.
arcsin Returns element-wise inverse sine of the input array.
arccos Returns element-wise inverse cosine of the input array.
arctan Returns element-wise inverse tangent of the input array.
degrees Converts each element of the input array from radians to degrees.
radians Converts each element of the input array from degrees to radians.

Hyperbolic functions

sinh Returns the hyperbolic sine of the input array, computed element-wise.
cosh Returns the hyperbolic cosine of the input array, computed element-wise.
tanh Returns the hyperbolic tangent of the input array, computed element-wise.
arcsinh Returns the element-wise inverse hyperbolic sine of the input array, computed element-wise.
arccosh Returns the element-wise inverse hyperbolic cosine of the input array, computed element-wise.
arctanh Returns the element-wise inverse hyperbolic tangent of the input array, computed element-wise.

Reduce functions

sum Compute the sum of array elements over given axes.
nansum Compute the sum of array elements over given axes treating Not a Numbers NaN as zero.
prod Compute the product of array elements over given axes.
nanprod Compute the product of array elements over given axes treating Not a Numbers NaN as one.
mean Compute the mean of array elements over given axes.
max Compute the max of array elements over given axes.
min Compute the min of array elements over given axes.
norm Flattens the input array and then computes the l2 norm.

Rounding

round Returns element-wise rounded value to the nearest integer of the input.
rint Returns element-wise rounded value to the nearest integer of the input.
fix Returns element-wise rounded value to the nearest integer towards zero of the input.
floor Returns element-wise floor of the input.
ceil Returns element-wise ceiling of the input.

Exponents and logarithms

exp Returns element-wise exponential value of the input.
expm1 Returns exp(x) - 1 computed element-wise on the input.
log Returns element-wise Natural logarithmic value of the input.
log10 Returns element-wise Base-10 logarithmic value of the input.
log2 Returns element-wise Base-2 logarithmic value of the input.
log1p Returns element-wise log(1 + x) value of the input.

Powers

power Returns result of first array elements raised to powers from second array, element-wise with broadcasting.
sqrt Returns element-wise square-root value of the input.
rsqrt Returns element-wise inverse square-root value of the input.
square Returns element-wise squared value of the input.

Logic functions

equal Returns the result of element-wise equal to (==) comparison operation with broadcasting.
not_equal Returns the result of element-wise not equal to (!=) comparison operation with broadcasting.
greater Returns the result of element-wise greater than (>) comparison operation with broadcasting.
greater_equal Returns the result of element-wise greater than or equal to (>=) comparison operation with broadcasting.
lesser Returns the result of element-wise lesser than (<) comparison operation with broadcasting.
lesser_equal Returns the result of element-wise lesser than or equal to (<=) comparison operation with broadcasting.

Random sampling

uniform Draw samples from a uniform distribution.
normal Draw random samples from a normal (Gaussian) distribution.
mxnet.random.seed Seed the random number generators in MXNet.

Sorting and searching

sort Returns a sorted copy of an input array along the given axis.
topk Returns the top k elements in an input array along the given axis.
argsort Returns the indices that would sort an input array along the given axis.
argmax Returns indices of the maximum values along an axis.
argmin Returns indices of the minimum values along an axis.

Miscellaneous

maximum Returns element-wise maximum of the input arrays with broadcasting.
minimum Returns element-wise minimum of the input arrays with broadcasting.
clip Clip (limit) the values in an array.
abs Returns element-wise absolute value of the input.
sign Returns element-wise sign of the input.
gamma Returns the gamma function (extension of the factorial function to the reals) , computed element-wise on the input array.
gammaln Returns element-wise log of the absolute value of the gamma function of the input.

Neural network

Basic

FullyConnected Apply a linear transformation: \(Y = XW^T + b\).
Convolution Compute N-D convolution on (N+2)-D input.
Activation Elementwise activation function.
BatchNorm Batch normalization.
Pooling Perform pooling on the input.
SoftmaxOutput Softmax with logit loss.
softmax Applies the softmax function.
log_softmax Compute the log softmax of the input.

More

Correlation Apply correlation to inputs
Deconvolution Apply deconvolution to input then add a bias.
RNN Apply a recurrent layer to input.
Embedding Maps integer indices to vector representations (embeddings).
LeakyReLU Leaky ReLu activation
InstanceNorm An operator taking in a n-dimensional input tensor (n > 2), and normalizing the input by subtracting the mean and variance calculated over the spatial dimensions.
L2Normalization Set the l2 norm of each instance to a constant.
LRN Apply convolution to input then add a bias.
ROIPooling Performs region of interest(ROI) pooling on the input array.
SoftmaxActivation Apply softmax activation to input.
Dropout Apply dropout to input.
BilinearSampler Apply bilinear sampling to input feature map, which is the key of “[NIPS2015] Spatial Transformer Networks” output[batch, channel, y_dst, x_dst] = G(data[batch, channel, y_src, x_src) x_dst, y_dst enumerate all spatial locations in output x_src = grid[batch, 0, y_dst, x_dst] y_src = grid[batch, 1, y_dst, x_dst] G() denotes the bilinear interpolation kernel The out-boundary points will be padded as zeros.
GridGenerator generate sampling grid for bilinear sampling.
UpSampling Perform nearest neighboor/bilinear up sampling to inputs
SpatialTransformer Apply spatial transformer to input feature map.
LinearRegressionOutput LinearRegressionOutput computes and optimizes for squared loss.
LogisticRegressionOutput LogisticRegressionOutput applies a logistic function to the input.
MAERegressionOutput MAERegressionOutput function computes mean absolute error.
SVMOutput Computes support vector machine based transformation of the input.
softmax_cross_entropy Calculate cross_entropy(data, one_hot(label))
smooth_l1 Calculate Smooth L1 Loss(lhs, scalar)
IdentityAttachKLSparseReg Apply a sparse regularization to the output a sigmoid activation function.
MakeLoss Get output from a symbol and pass 1 gradient back.
BlockGrad Get output from a symbol and pass 0 gradient back
Custom Custom operator implemented in frontend.

API Reference

NDArray API of MXNet.

mxnet.ndarray.waitall()

Wait for all async operations to finish in MXNet.

This function is used for benchmarking only.

class mxnet.ndarray.NDArray(handle, writable=True)

An array object representing a multidimensional, homogeneous array of fixed-size items.

reshape(shape)

Returns a view of this array with a new shape without altering any data.

Parameters:shape (tuple of int) – The new shape should not change the array size, namely np.prod(new_shape) should be equal to np.prod(self.shape). One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions.
Returns:An array with desired shape that shares data with this array.
Return type:NDArray

Examples

>>> x = mx.nd.arange(0,6).reshape((2,3))
>>> x.asnumpy()
array([[ 0.,  1.,  2.],
       [ 3.,  4.,  5.]], dtype=float32)
>>> y = x.reshape((3,2))
>>> y.asnumpy()
array([[ 0.,  1.],
       [ 2.,  3.],
       [ 4.,  5.]], dtype=float32)
>>> y = x.reshape((3,-1))
>>> y.asnumpy()
array([[ 0.,  1.],
       [ 2.,  3.],
       [ 4.,  5.]], dtype=float32)
>>> y[:] = -1
>>> x.asnumpy()
array([[-1., -1., -1.],
       [-1., -1., -1.]], dtype=float32)
broadcast_to(shape)

Broadcasts the input array to a new shape.

Broadcasting is only allowed on axes with size 1. The new shape cannot change the number of dimensions. For example, you could broadcast from shape (2, 1) to (2, 3), but not from shape (2, 3) to (2, 3, 3).

Parameters:shape (tuple of int) – The shape of the desired array.
Returns:A NDArray with the desired shape that is not sharing data with this array, even if the new shape is the same as self.shape.
Return type:NDArray

Examples

>>> x = mx.nd.arange(0,3).reshape((1,3,1))
>>> x.asnumpy()
array([[[ 0.],
        [ 1.],
        [ 2.]]], dtype=float32)
>>> y = x.broadcast_to((2,3,3))
>>> y.asnumpy()
array([[[ 0.,  0.,  0.],
        [ 1.,  1.,  1.],
        [ 2.,  2.,  2.]],

       [[ 0.,  0.,  0.],
        [ 1.,  1.,  1.],
        [ 2.,  2.,  2.]]], dtype=float32)
wait_to_read()

Waits until all previous write operations on the current array are finished.

This method guarantees that all previous write operations that pushed into the backend engine for execution are actually finished.

Examples

>>> import time
>>> tic = time.time()
>>> a = mx.nd.ones((1000,1000))
>>> b = mx.nd.dot(a, a)
>>> print(time.time() - tic) 
0.003854036331176758
>>> b.wait_to_read()
>>> print(time.time() - tic) 
0.0893700122833252
ndim

Returns the number of dimensions of this array

Examples

>>> x = mx.nd.array([1, 2, 3, 4])
>>> x.ndim
1
>>> x = mx.nd.array([[1, 2],
                     [3, 4]])
>>> x.ndim
2
shape

Tuple of array dimensions.

Examples

>>> x = mx.nd.array([1, 2, 3, 4])
>>> x.shape
(4L,)
>>> y = mx.nd.zeros((2, 3, 4))
>>> y.shape
(2L, 3L, 4L)
size

Number of elements in the array.

Equivalent to the product of the array’s dimensions.

Examples

>>> import numpy as np
>>> x = mx.nd.zeros((3, 5, 2))
>>> x.size
30
>>> np.prod(x.shape)
30
context

Device context of the array.

Examples

>>> x = mx.nd.array([1, 2, 3, 4])
>>> x.context
cpu(0)
>>> type(x.context)
<class 'mxnet.context.Context'>
>>> y = mx.nd.zeros((2,3), mx.gpu(0))
>>> y.context
gpu(0)
dtype

Data-type of the array’s elements.

Returns:This NDArray’s data type.
Return type:numpy.dtype

Examples

>>> x = mx.nd.zeros((2,3))
>>> x.dtype
<type 'numpy.float32'>
>>> y = mx.nd.zeros((2,3), dtype='int32')
>>> y.dtype
<type 'numpy.int32'>
T

Returns a copy of the array with axes transposed.

Equivalent to mx.nd.transpose(self) except that self is returned if self.ndim < 2.

Unlike numpy.ndarray.T, this function returns a copy rather than a view of the array unless self.ndim < 2.

Examples

>>> x = mx.nd.arange(0,6).reshape((2,3))
>>> x.asnumpy()
array([[ 0.,  1.,  2.],
       [ 3.,  4.,  5.]], dtype=float32)
>>> x.T.asnumpy()
array([[ 0.,  3.],
       [ 1.,  4.],
       [ 2.,  5.]], dtype=float32)
asnumpy()

Returns a numpy.ndarray object with value copied from this array.

Examples

>>> x = mx.nd.ones((2,3))
>>> y = x.asnumpy()
>>> type(y)
<type 'numpy.ndarray'>
>>> y
array([[ 1.,  1.,  1.],
       [ 1.,  1.,  1.]], dtype=float32)
>>> z = mx.nd.ones((2,3), dtype='int32')
>>> z.asnumpy()
array([[1, 1, 1],
       [1, 1, 1]], dtype=int32)
asscalar()

Returns a scalar whose value is copied from this array.

This function is equivalent to self.asnumpy()[0]. This NDArray must have shape (1,).

Examples

>>> x = mx.nd.ones((1,), dtype='int32')
>>> x.asscalar()
1
>>> type(x.asscalar())
<type 'numpy.int32'>
astype(dtype)

Returns a copy of the array after casting to a specified type.

Parameters:dtype (numpy.dtype or str) – The type of the returned array.

Examples

>>> x = mx.nd.zeros((2,3), dtype='float32')
>>> y = x.astype('int32')
>>> y.dtype
<type 'numpy.int32'>
copyto(other)

Copies the value of this array to another array.

If other is a NDArray object, then other.shape and self.shape should be the same. This function copies the value from self to other.

If other is a context, a new NDArray will be first created on the target context, and the value of self is copied.

Parameters:other (NDArray or Context) – The destination array or context.
Returns:The copied array. If other is an NDArray, then the return value and other will point to the same NDArray.
Return type:NDArray

Examples

>>> x = mx.nd.ones((2,3))
>>> y = mx.nd.zeros((2,3), mx.gpu(0))
>>> z = x.copyto(y)
>>> z is y
True
>>> y.asnumpy()
array([[ 1.,  1.,  1.],
       [ 1.,  1.,  1.]], dtype=float32)
>>> y.copyto(mx.gpu(0))
<NDArray 2x3 @gpu(0)>
copy()

Makes a copy of this NDArray, keeping the same context.

Returns:The copied array
Return type:NDArray

Examples

>>> x = mx.nd.ones((2,3))
>>> y = x.copy()
>>> y.asnumpy()
array([[ 1.,  1.,  1.],
       [ 1.,  1.,  1.]], dtype=float32)
as_in_context(context)

Returns an array on the target device with the same value as this array.

If the target context is the same as self.context, then self is returned. Otherwise, a copy is made.

Parameters:context (Context) – The target context.
Returns:The target array.
Return type:NDArray

Examples

>>> x = mx.nd.ones((2,3))
>>> y = x.as_in_context(mx.cpu())
>>> y is x
True
>>> z = x.as_in_context(mx.gpu(0))
>>> z is x
False
mxnet.ndarray.onehot_encode(indices, out)

One-hot encoding indices into matrix out.

Note

onehot_encode is deprecated. Use one_hot instead.

mxnet.ndarray.empty(shape, ctx=None, dtype=<Mock name='mock.float32' id='47404882836560'>)

Returns a new array of given shape and type, without initializing entries.

Parameters:
  • shape (int or tuple of int) – The shape of the empty array.
  • ctx (Context, optional) – An optional device context (default is the current default context).
  • dtype (str or numpy.dtype, optional) – An optional value type (default is float32).
Returns:

A created array.

Return type:

NDArray

Examples

>>> mx.nd.empty(1)
<NDArray 1 @cpu(0)>
>>> mx.nd.empty((1,2), mx.gpu(0))
<NDArray 1x2 @gpu(0)>
>>> mx.nd.empty((1,2), mx.gpu(0), 'float16')
<NDArray 1x2 @gpu(0)>
mxnet.ndarray.zeros(shape, ctx=None, dtype=<Mock name='mock.float32' id='47404882836560'>)

Returns a new array filled with all zeros, with the given shape and type.

Parameters:
  • shape (int or tuple of int) – The shape of the empty array.
  • ctx (Context, optional) – An optional device context (default is the current default context).
  • dtype (str or numpy.dtype, optional) – An optional value type (default is float32).
Returns:

A created array

Return type:

NDArray

Examples

>>> mx.nd.zeros(1).asnumpy()
array([ 0.], dtype=float32)
>>> mx.nd.zeros((1,2), mx.gpu(0))
<NDArray 1x2 @gpu(0)>
>>> mx.nd.zeros((1,2), mx.gpu(0), 'float16').asnumpy()
array([[ 0.,  0.]], dtype=float16)
mxnet.ndarray.ones(shape, ctx=None, dtype=<Mock name='mock.float32' id='47404882836560'>)

Returns a new array filled with all ones, with the given shape and type.

Parameters:
  • shape (int or tuple of int or list of int) – The shape of the empty array.
  • ctx (Context, optional) – An optional device context. Defaults to the current default context (mxnet.Context.default_ctx).
  • dtype (str or numpy.dtype, optional) – An optional value type (default is float32).
Returns:

A new array of the specified shape filled with all ones.

Return type:

NDArray

Examples

>>> mx.nd.ones(1).asnumpy()
array([ 1.], dtype=float32)
>>> mx.nd.ones((1,2), mx.gpu(0))
<NDArray 1x2 @gpu(0)>
>>> mx.nd.ones((1,2), dtype='float16').asnumpy()
array([[ 1.,  1.]], dtype=float16)
mxnet.ndarray.full(shape, val, ctx=None, dtype=<Mock name='mock.float32' id='47404882836560'>)

Returns a new array of given shape and type, filled with the given value val.

Parameters:
  • shape (int or tuple of int) – The shape of the new array.
  • val (scalar) – Fill value.
  • ctx (Context, optional) – Device context (default is the current default context).
  • dtype (str or numpy.dtype, optional) – The data type of the returned NDArray. The default datatype is float32.
Returns:

NDArray filled with val, with the given shape, ctx, and dtype.

Return type:

NDArray

Examples

>>> mx.nd.full(1, 2.0).asnumpy()
array([ 2.], dtype=float32)
>>> mx.nd.full((1, 2), 2.0, mx.gpu(0))
<NDArray 1x2 @gpu(0)>
>>> mx.nd.full((1, 2), 2.0, dtype='float16').asnumpy()
array([[ 2.,  2.]], dtype=float16)
mxnet.ndarray.array(source_array, ctx=None, dtype=None)

Creates an array from any object exposing the array interface.

Parameters:
  • source_array (array_like) – An object exposing the array interface, an object whose __array__ method returns an array, or any (nested) sequence.
  • ctx (Context, optional) – Device context (default is the current default context).
  • dtype (str or numpy.dtype, optional) – The data type of the output array. The default dtype is source_array.dtype if source_array is an NDArray, float32 otherwise.
Returns:

An NDArray with the same contents as the source_array.

Return type:

NDArray

Examples

>>> import numpy as np
>>> mx.nd.array([1, 2, 3])
<NDArray 3 @cpu(0)>
>>> mx.nd.array([[1, 2], [3, 4]])
<NDArray 2x2 @cpu(0)>
>>> mx.nd.array(np.zeros((3, 2)))
<NDArray 3x2 @cpu(0)>
>>> mx.nd.array(np.zeros((3, 2)), mx.gpu(0))
<NDArray 3x2 @gpu(0)>
mxnet.ndarray.moveaxis(tensor, source, destination)

Moves the source axis into the destination position while leaving the other axes in their original order

Parameters:
  • tensor (mx.nd.array) – The array which axes should be reordered
  • source (int) – Original position of the axes to move.
  • destination (int) – Destination position for each of the original axes.
Returns:

result – Array with moved axes.

Return type:

mx.nd.array

Examples

>>> X = mx.nd.array([[1, 2, 3],
                     [4, 5, 6]])
>>> mx.nd.moveaxis(X, 0, 1).shape
(3, 2)
mxnet.ndarray.arange(start, stop=None, step=1.0, repeat=1, ctx=None, dtype=<Mock name='mock.float32' id='47404882836560'>)

Returns evenly spaced values within a given interval.

Values are generated within the half-open interval [start, stop). In other words, the interval includes start but excludes stop. The function is similar to the built-in Python function range and to numpy.arange, but returns an NDArray.

Parameters:
  • start (float, optional) – Start of interval. The default start value is 0.
  • stop (float) – End of interval.
  • step (float, optional) – Spacing between values. The default step size is 1.
  • repeat (int, optional) – Number of times to repeat each element. The default repeat count is 1.
  • ctx (Context, optional) – Device context. Default context is the current default context.
  • dtype (str or numpy.dtype, optional) – The data type of the NDArray. The default datatype is np.float32.
Returns:

NDArray of evenly spaced values in the specified range.

Return type:

NDArray

Examples

>>> mx.nd.arange(3).asnumpy()
array([ 0.,  1.,  2.], dtype=float32)
>>> mx.nd.arange(2, 6).asnumpy()
array([ 2.,  3.,  4.,  5.], dtype=float32)
>>> mx.nd.arange(2, 6, step=2).asnumpy()
array([ 2.,  4.], dtype=float32)
>>> mx.nd.arange(2, 6, step=1.5, repeat=2).asnumpy()
array([ 2. ,  2. ,  3.5,  3.5,  5. ,  5. ], dtype=float32)
>>> mx.nd.arange(2, 6, step=2, repeat=3, dtype='int32').asnumpy()
array([2, 2, 2, 4, 4, 4], dtype=int32)
mxnet.ndarray.add(lhs, rhs)

Returns element-wise sum of the input arrays with broadcasting.

Equivalent to lhs + rhs, mx.nd.broadcast_add(lhs, rhs) and mx.nd.broadcast_plus(lhs, rhs).

Note

If the corresponding dimensions of two arrays have the same size or one of them has size 1, then the arrays are broadcastable to a common shape.

Parameters:
  • lhs (scalar or array) – First array to be added.
  • rhs (scalar or array) – Second array to be added. If lhs.shape != rhs.shape, they must be broadcastable to a common shape.
Returns:

The element-wise sum of the input arrays.

Return type:

NDArray

Examples

>>> x = mx.nd.ones((2,3))
>>> y = mx.nd.arange(2).reshape((2,1))
>>> z = mx.nd.arange(2).reshape((1,2))
>>> x.asnumpy()
array([[ 1.,  1.,  1.],
       [ 1.,  1.,  1.]], dtype=float32)
>>> y.asnumpy()
array([[ 0.],
      [ 1.]], dtype=float32)
>>> z.asnumpy()
array([[ 0.,  1.]], dtype=float32)
>>> (x+2).asnumpy()
array([[ 3.,  3.,  3.],
       [ 3.,  3.,  3.]], dtype=float32)
>>> (x+y).asnumpy()
array([[ 1.,  1.,  1.],
       [ 2.,  2.,  2.]], dtype=float32)
>>> mx.nd.add(x,y).asnumpy()
array([[ 1.,  1.,  1.],
       [ 2.,  2.,  2.]], dtype=float32)
>>> (z + y).asnumpy()
array([[ 0.,  1.],
       [ 1.,  2.]], dtype=float32)
mxnet.ndarray.subtract(lhs, rhs)

Returns element-wise difference of the input arrays with broadcasting.

Equivalent to lhs - rhs, mx.nd.broadcast_sub(lhs, rhs) and mx.nd.broadcast_minus(lhs, rhs).

Note

If the corresponding dimensions of two arrays have the same size or one of them has size 1, then the arrays are broadcastable to a common shape.

Parameters:
  • lhs (scalar or array) – First array to be subtracted.
  • rhs (scalar or array) – Second array to be subtracted. If lhs.shape != rhs.shape, they must be broadcastable to a common shape.
Returns:

The element-wise difference of the input arrays.

Return type:

NDArray

Examples

>>> x = mx.nd.ones((2,3))
>>> y = mx.nd.arange(2).reshape((2,1))
>>> z = mx.nd.arange(2).reshape((1,2))
>>> x.asnumpy()
array([[ 1.,  1.,  1.],
       [ 1.,  1.,  1.]], dtype=float32)
>>> y.asnumpy()
array([[ 0.],
      [ 1.]], dtype=float32)
>>> z.asnumpy()
array([[ 0.,  1.]], dtype=float32)
>>> (x-2).asnumpy()
array([[-1., -1., -1.],
       [-1., -1., -1.]], dtype=float32)
>>> (x-y).asnumpy()
array([[ 1.,  1.,  1.],
       [ 0.,  0.,  0.]], dtype=float32)
>>> mx.nd.subtract(x,y).asnumpy()
array([[ 1.,  1.,  1.],
       [ 0.,  0.,  0.]], dtype=float32)
>>> (z-y).asnumpy()
array([[ 0.,  1.],
       [-1.,  0.]], dtype=float32)
mxnet.ndarray.multiply(lhs, rhs)

Returns element-wise product of the input arrays with broadcasting.

Equivalent to lhs * rhs and mx.nd.broadcast_mul(lhs, rhs).

Note

If the corresponding dimensions of two arrays have the same size or one of them has size 1, then the arrays are broadcastable to a common shape.

Parameters:
  • lhs (scalar or array) – First array to be multiplied.
  • rhs (scalar or array) – Second array to be multiplied. If lhs.shape != rhs.shape, they must be broadcastable to a common shape.
Returns:

The element-wise multiplication of the input arrays.

Return type:

NDArray

Examples

>>> x = mx.nd.ones((2,3))
>>> y = mx.nd.arange(2).reshape((2,1))
>>> z = mx.nd.arange(2).reshape((1,2))
>>> x.asnumpy()
array([[ 1.,  1.,  1.],
       [ 1.,  1.,  1.]], dtype=float32)
>>> y.asnumpy()
array([[ 0.],
      [ 1.]], dtype=float32)
>>> z.asnumpy()
array([[ 0.,  1.]], dtype=float32)
>>> (x*2).asnumpy()
array([[ 2.,  2.,  2.],
       [ 2.,  2.,  2.]], dtype=float32)
>>> (x*y).asnumpy()
array([[ 0.,  0.,  0.],
       [ 1.,  1.,  1.]], dtype=float32)
>>> mx.nd.multiply(x, y).asnumpy()
array([[ 0.,  0.,  0.],
       [ 1.,  1.,  1.]], dtype=float32)
>>> (z*y).asnumpy()
array([[ 0.,  0.],
       [ 0.,  1.]], dtype=float32)
mxnet.ndarray.divide(lhs, rhs)

Returns element-wise division of the input arrays with broadcasting.

Equivalent to lhs / rhs and mx.nd.broadcast_div(lhs, rhs).

Note

If the corresponding dimensions of two arrays have the same size or one of them has size 1, then the arrays are broadcastable to a common shape.

Parameters:
  • lhs (scalar or array) – First array in division.
  • rhs (scalar or array) – Second array in division. The arrays to be divided. If lhs.shape != rhs.shape, they must be broadcastable to a common shape.
Returns:

The element-wise division of the input arrays.

Return type:

NDArray

Examples

>>> x = mx.nd.ones((2,3))*6
>>> y = mx.nd.ones((2,1))*2
>>> x.asnumpy()
array([[ 6.,  6.,  6.],
       [ 6.,  6.,  6.]], dtype=float32)
>>> y.asnumpy()
array([[ 2.],
       [ 2.]], dtype=float32)
>>> x/2
<NDArray 2x3 @cpu(0)>
>>> (x/3).asnumpy()
array([[ 2.,  2.,  2.],
       [ 2.,  2.,  2.]], dtype=float32)
>>> (x/y).asnumpy()
array([[ 3.,  3.,  3.],
       [ 3.,  3.,  3.]], dtype=float32)
>>> mx.nd.divide(x,y).asnumpy()
array([[ 3.,  3.,  3.],
       [ 3.,  3.,  3.]], dtype=float32)
mxnet.ndarray.power(base, exp)

Returns result of first array elements raised to powers from second array, element-wise with broadcasting.

Equivalent to base ** exp and mx.nd.broadcast_power(lhs, rhs).

Note

If the corresponding dimensions of two arrays have the same size or one of them has size 1, then the arrays are broadcastable to a common shape.

Parameters:
  • base (scalar or NDArray) – The base array
  • exp (scalar or NDArray) – The exponent array. If base.shape != exp.shape, they must be broadcastable to a common shape.
Returns:

The bases in x raised to the exponents in y.

Return type:

NDArray

Examples

>>> x = mx.nd.ones((2,3))*2
>>> y = mx.nd.arange(1,3).reshape((2,1))
>>> z = mx.nd.arange(1,3).reshape((2,1))
>>> x.asnumpy()
array([[ 2.,  2.,  2.],
       [ 2.,  2.,  2.]], dtype=float32)
>>> y.asnumpy()
array([[ 1.],
       [ 2.]], dtype=float32)
>>> z.asnumpy()
array([[ 1.],
       [ 2.]], dtype=float32)
>>> (x**2).asnumpy()
array([[ 4.,  4.,  4.],
       [ 4.,  4.,  4.]], dtype=float32)
>>> (x**y).asnumpy()
array([[ 2.,  2.,  2.],
       [ 4.,  4.,  4.]], dtype=float32)
>>> mx.nd.power(x,y).asnumpy()
array([[ 2.,  2.,  2.],
       [ 4.,  4.,  4.]], dtype=float32)
>>> (z**y).asnumpy()
array([[ 1.],
       [ 4.]], dtype=float32)
mxnet.ndarray.maximum(lhs, rhs)

Returns element-wise maximum of the input arrays with broadcasting.

Equivalent to mx.nd.broadcast_maximum(lhs, rhs).

Note

If the corresponding dimensions of two arrays have the same size or one of them has size 1, then the arrays are broadcastable to a common shape.

Parameters:
  • lhs (scalar or array) – First array to be compared.
  • rhs (scalar or array) – Second array to be compared. If lhs.shape != rhs.shape, they must be broadcastable to a common shape.
Returns:

The element-wise maximum of the input arrays.

Return type:

NDArray

Examples

>>> x = mx.nd.ones((2,3))
>>> y = mx.nd.arange(2).reshape((2,1))
>>> z = mx.nd.arange(2).reshape((1,2))
>>> x.asnumpy()
array([[ 1.,  1.,  1.],
       [ 1.,  1.,  1.]], dtype=float32)
>>> y.asnumpy()
array([[ 0.],
      [ 1.]], dtype=float32)
>>> z.asnumpy()
array([[ 0.,  1.]], dtype=float32)
>>> mx.nd.maximum(x, 2).asnumpy()
array([[ 2.,  2.,  2.],
       [ 2.,  2.,  2.]], dtype=float32)
>>> mx.nd.maximum(x, y).asnumpy()
array([[ 1.,  1.,  1.],
       [ 1.,  1.,  1.]], dtype=float32)
>>> mx.nd.maximum(y, z).asnumpy()
array([[ 0.,  1.],
       [ 1.,  1.]], dtype=float32)
mxnet.ndarray.minimum(lhs, rhs)

Returns element-wise minimum of the input arrays with broadcasting.

Equivalent to mx.nd.broadcast_minimum(lhs, rhs).

Note

If the corresponding dimensions of two arrays have the same size or one of them has size 1, then the arrays are broadcastable to a common shape.

Parameters:
  • lhs (scalar or array) – First array to be compared.
  • rhs (scalar or array) – Second array to be compared. If lhs.shape != rhs.shape, they must be broadcastable to a common shape.
Returns:

The element-wise minimum of the input arrays.

Return type:

NDArray

Examples

>>> x = mx.nd.ones((2,3))
>>> y = mx.nd.arange(2).reshape((2,1))
>>> z = mx.nd.arange(2).reshape((1,2))
>>> x.asnumpy()
array([[ 1.,  1.,  1.],
       [ 1.,  1.,  1.]], dtype=float32)
>>> y.asnumpy()
array([[ 0.],
      [ 1.]], dtype=float32)
>>> z.asnumpy()
array([[ 0.,  1.]], dtype=float32)
>>> mx.nd.minimum(x, 2).asnumpy()
array([[ 1.,  1.,  1.],
       [ 1.,  1.,  1.]], dtype=float32)
>>> mx.nd.minimum(x, y).asnumpy()
array([[ 0.,  0.,  0.],
       [ 1.,  1.,  1.]], dtype=float32)
>>> mx.nd.minimum(z, y).asnumpy()
array([[ 0.,  0.],
       [ 0.,  1.]], dtype=float32)
mxnet.ndarray.equal(lhs, rhs)

Returns the result of element-wise equal to (==) comparison operation with broadcasting.

For each element in input arrays, return 1(true) if corresponding elements are same, otherwise return 0(false).

Equivalent to lhs == rhs and mx.nd.broadcast_equal(lhs, rhs).

Note

If the corresponding dimensions of two arrays have the same size or one of them has size 1, then the arrays are broadcastable to a common shape.

Parameters:
  • lhs (scalar or array) – First array to be compared.
  • rhs (scalar or array) – Second array to be compared. If lhs.shape != rhs.shape, they must be broadcastable to a common shape.
Returns:

Output array of boolean values.

Return type:

NDArray

Examples

>>> x = mx.nd.ones((2,3))
>>> y = mx.nd.arange(2).reshape((2,1))
>>> z = mx.nd.arange(2).reshape((1,2))
>>> x.asnumpy()
array([[ 1.,  1.,  1.],
       [ 1.,  1.,  1.]], dtype=float32)
>>> y.asnumpy()
array([[ 0.],
       [ 1.]], dtype=float32)
>>> z.asnumpy()
array([[ 0.,  1.]], dtype=float32)
>>> (x == 1).asnumpy()
array([[ 1.,  1.,  1.],
       [ 1.,  1.,  1.]], dtype=float32)
>>> (x == y).asnumpy()
array([[ 0.,  0.,  0.],
       [ 1.,  1.,  1.]], dtype=float32)
>>> mx.nd.equal(x,y).asnumpy()
array([[ 0.,  0.,  0.],
       [ 1.,  1.,  1.]], dtype=float32)
>>> (z == y).asnumpy()
array([[ 1.,  0.],
       [ 0.,  1.]], dtype=float32)
mxnet.ndarray.not_equal(lhs, rhs)

Returns the result of element-wise not equal to (!=) comparison operation with broadcasting.

For each element in input arrays, return 1(true) if corresponding elements are different, otherwise return 0(false).

Equivalent to lhs != rhs and mx.nd.broadcast_not_equal(lhs, rhs).

Note

If the corresponding dimensions of two arrays have the same size or one of them has size 1, then the arrays are broadcastable to a common shape.

Parameters:
  • lhs (scalar or array) – First array to be compared.
  • rhs (scalar or array) – Second array to be compared. If lhs.shape != rhs.shape, they must be broadcastable to a common shape.
Returns:

Output array of boolean values.

Return type:

NDArray

Examples

>>> x = mx.nd.ones((2,3))
>>> y = mx.nd.arange(2).reshape((2,1))
>>> z = mx.nd.arange(2).reshape((1,2))
>>> x.asnumpy()
array([[ 1.,  1.,  1.],
       [ 1.,  1.,  1.]], dtype=float32)
>>> y.asnumpy()
array([[ 0.],
       [ 1.]], dtype=float32)
>>> z.asnumpy()
array([[ 0.,  1.]], dtype=float32)
>>> (z == y).asnumpy()
array([[ 1.,  0.],
       [ 0.,  1.]], dtype=float32)
>>> (x != 1).asnumpy()
array([[ 0.,  0.,  0.],
       [ 0.,  0.,  0.]], dtype=float32)
>>> (x != y).asnumpy()
array([[ 1.,  1.,  1.],
       [ 0.,  0.,  0.]], dtype=float32)
>>> mx.nd.not_equal(x, y).asnumpy()
array([[ 1.,  1.,  1.],
       [ 0.,  0.,  0.]], dtype=float32)
>>> (z != y).asnumpy()
array([[ 0.,  1.],
       [ 1.,  0.]], dtype=float32)
mxnet.ndarray.greater(lhs, rhs)

Returns the result of element-wise greater than (>) comparison operation with broadcasting.

For each element in input arrays, return 1(true) if lhs elements are greater than rhs, otherwise return 0(false).

Equivalent to lhs > rhs and mx.nd.broadcast_greater(lhs, rhs).

Note

If the corresponding dimensions of two arrays have the same size or one of them has size 1, then the arrays are broadcastable to a common shape.

Parameters:
  • lhs (scalar or array) – First array to be compared.
  • rhs (scalar or array) – Second array to be compared. If lhs.shape != rhs.shape, they must be broadcastable to a common shape.
Returns:

Output array of boolean values.

Return type:

NDArray

Examples

>>> x = mx.nd.ones((2,3))
>>> y = mx.nd.arange(2).reshape((2,1))
>>> z = mx.nd.arange(2).reshape((1,2))
>>> x.asnumpy()
array([[ 1.,  1.,  1.],
       [ 1.,  1.,  1.]], dtype=float32)
>>> y.asnumpy()
array([[ 0.],
       [ 1.]], dtype=float32)
>>> z.asnumpy()
array([[ 0.,  1.]], dtype=float32)
>>> (x > 1).asnumpy()
array([[ 0.,  0.,  0.],
       [ 0.,  0.,  0.]], dtype=float32)
>>> (x > y).asnumpy()
array([[ 1.,  1.,  1.],
       [ 0.,  0.,  0.]], dtype=float32)
>>> mx.nd.greater(x, y).asnumpy()
array([[ 1.,  1.,  1.],
       [ 0.,  0.,  0.]], dtype=float32)
>>> (z > y).asnumpy()
array([[ 0.,  1.],
       [ 0.,  0.]], dtype=float32)
mxnet.ndarray.greater_equal(lhs, rhs)

Returns the result of element-wise greater than or equal to (>=) comparison operation with broadcasting.

For each element in input arrays, return 1(true) if lhs elements are greater than equal to rhs, otherwise return 0(false).

Equivalent to lhs >= rhs and mx.nd.broadcast_greater_equal(lhs, rhs).

Note

If the corresponding dimensions of two arrays have the same size or one of them has size 1, then the arrays are broadcastable to a common shape.

Parameters:
  • lhs (scalar or array) – First array to be compared.
  • rhs (scalar or array) – Second array to be compared. If lhs.shape != rhs.shape, they must be broadcastable to a common shape.
Returns:

Output array of boolean values.

Return type:

NDArray

Examples

>>> x = mx.nd.ones((2,3))
>>> y = mx.nd.arange(2).reshape((2,1))
>>> z = mx.nd.arange(2).reshape((1,2))
>>> x.asnumpy()
array([[ 1.,  1.,  1.],
       [ 1.,  1.,  1.]], dtype=float32)
>>> y.asnumpy()
array([[ 0.],
       [ 1.]], dtype=float32)
>>> z.asnumpy()
array([[ 0.,  1.]], dtype=float32)
>>> (x >= 1).asnumpy()
array([[ 1.,  1.,  1.],
       [ 1.,  1.,  1.]], dtype=float32)
>>> (x >= y).asnumpy()
array([[ 1.,  1.,  1.],
       [ 1.,  1.,  1.]], dtype=float32)
>>> mx.nd.greater_equal(x, y).asnumpy()
array([[ 1.,  1.,  1.],
       [ 1.,  1.,  1.]], dtype=float32)
>>> (z >= y).asnumpy()
array([[ 1.,  1.],
       [ 0.,  1.]], dtype=float32)
mxnet.ndarray.lesser(lhs, rhs)

Returns the result of element-wise lesser than (<) comparison operation with broadcasting.

For each element in input arrays, return 1(true) if lhs elements are less than rhs, otherwise return 0(false).

Equivalent to lhs < rhs and mx.nd.broadcast_lesser(lhs, rhs).

Note

If the corresponding dimensions of two arrays have the same size or one of them has size 1, then the arrays are broadcastable to a common shape.

Parameters:
  • lhs (scalar or array) – First array to be compared.
  • rhs (scalar or array) – Second array to be compared. If lhs.shape != rhs.shape, they must be broadcastable to a common shape.
Returns:

Output array of boolean values.

Return type:

NDArray

Examples

>>> x = mx.nd.ones((2,3))
>>> y = mx.nd.arange(2).reshape((2,1))
>>> z = mx.nd.arange(2).reshape((1,2))
>>> x.asnumpy()
array([[ 1.,  1.,  1.],
       [ 1.,  1.,  1.]], dtype=float32)
>>> y.asnumpy()
array([[ 0.],
       [ 1.]], dtype=float32)
>>> z.asnumpy()
array([[ 0.,  1.]], dtype=float32)
>>> (x < 1).asnumpy()
array([[ 0.,  0.,  0.],
       [ 0.,  0.,  0.]], dtype=float32)
>>> (x < y).asnumpy()
array([[ 0.,  0.,  0.],
       [ 0.,  0.,  0.]], dtype=float32)
>>> mx.nd.lesser(x, y).asnumpy()
array([[ 0.,  0.,  0.],
       [ 0.,  0.,  0.]], dtype=float32)
>>> (z < y).asnumpy()
array([[ 0.,  0.],
       [ 1.,  0.]], dtype=float32)
mxnet.ndarray.lesser_equal(lhs, rhs)

Returns the result of element-wise lesser than or equal to (<=) comparison operation with broadcasting.

For each element in input arrays, return 1(true) if lhs elements are lesser than equal to rhs, otherwise return 0(false).

Equivalent to lhs <= rhs and mx.nd.broadcast_lesser_equal(lhs, rhs).

Note

If the corresponding dimensions of two arrays have the same size or one of them has size 1, then the arrays are broadcastable to a common shape.

Parameters:
  • lhs (scalar or array) – First array to be compared.
  • rhs (scalar or array) – Second array to be compared. If lhs.shape != rhs.shape, they must be broadcastable to a common shape.
Returns:

Output array of boolean values.

Return type:

NDArray

Examples

>>> x = mx.nd.ones((2,3))
>>> y = mx.nd.arange(2).reshape((2,1))
>>> z = mx.nd.arange(2).reshape((1,2))
>>> x.asnumpy()
array([[ 1.,  1.,  1.],
       [ 1.,  1.,  1.]], dtype=float32)
>>> y.asnumpy()
array([[ 0.],
       [ 1.]], dtype=float32)
>>> z.asnumpy()
array([[ 0.,  1.]], dtype=float32)
>>> (x <= 1).asnumpy()
array([[ 1.,  1.,  1.],
       [ 1.,  1.,  1.]], dtype=float32)
>>> (x <= y).asnumpy()
array([[ 0.,  0.,  0.],
       [ 1.,  1.,  1.]], dtype=float32)
>>> mx.nd.lesser_equal(x, y).asnumpy()
array([[ 0.,  0.,  0.],
       [ 1.,  1.,  1.]], dtype=float32)
>>> (z <= y).asnumpy()
array([[ 1.,  0.],
       [ 1.,  1.]], dtype=float32)
mxnet.ndarray.true_divide(lhs, rhs)

This function is similar to divide().

mxnet.ndarray.negative(arr)

Numerical negative, element-wise.

Equals -arr

Parameters:arr (NDArray) – The input array
Returns:-arr
Return type:NDArray

Examples

>>> x = mx.nd.ones((2,3))
>>> (-x).asnumpy()
array([[-1., -1., -1.],
       [-1., -1., -1.]], dtype=float32)
mxnet.ndarray.load(fname)

Load array from file.

See more details in save.

Parameters:fname (str) – The filename.
Returns:Loaded data.
Return type:list of NDArray or dict of str to NDArray
mxnet.ndarray.save(fname, data)

Save a list of arrays of a str->array dict into file.

Examples of filenames:

  • /path/to/file
  • s3://my-bucket/path/to/file (if compiled with AWS S3 supports)
  • hdfs://path/to/file (if compiled with HDFS supports)
Parameters:
  • fname (str) – The filename.
  • data (list of NDArray` or dict of str to ``NDArray) – The data for saving.

Examples

>>> x = mx.nd.zeros((2,3))
>>> y = mx.nd.ones((1,4))
>>> mx.nd.save('my_list', [x,y])
>>> mx.nd.save('my_dict', {'x':x, 'y':y})
>>> mx.nd.load('my_list')
[<NDArray 2x3 @cpu(0)>, <NDArray 1x4 @cpu(0)>]
>>> mx.nd.load('my_dict')
{'y': <NDArray 1x4 @cpu(0)>, 'x': <NDArray 2x3 @cpu(0)>}
mxnet.ndarray.concatenate(arrays, axis=0, always_copy=True)

DEPRECATED, use concat instead

Parameters:
  • arrays (list of NDArray) – Arrays to be concatenate. They must have identical shape except the first dimension. They also must have the same data type.
  • axis (int) – The axis along which to concatenate.
  • always_copy (bool) – Default True. When not True, if the arrays only contain one NDArray, that element will be returned directly, avoid copying.
Returns:

An NDArray that lives on the same context as arrays[0].context.

Return type:

NDArray

mxnet.ndarray.imdecode(str_img, clip_rect=(0, 0, 0, 0), out=None, index=0, channels=3, mean=None)

DEPRECATED, use mx.img instead

Parameters:
  • str_img (str) – Binary image data
  • clip_rect (iterable of 4 int) – Clip decoded image to rectangle (x0, y0, x1, y1).
  • out (NDArray) – Output buffer. Can be 3 dimensional (c, h, w) or 4 dimensional (n, c, h, w).
  • index (int) – Output decoded image to i-th slice of 4 dimensional buffer.
  • channels (int) – Number of channels to output. Decode to grey scale when channels = 1.
  • mean (NDArray) – Subtract mean from decode image before outputing.
mxnet.ndarray.Activation(data=None, act_type=_Null, out=None, **kwargs)

Elementwise activation function. The activation operations are applied elementwisely to each array elements. The following types are supported:

  • relu: Rectified Linear Unit, y = max(x, 0)
  • sigmoid: y = 1 / (1 + exp(-x))
  • tanh: Hyperbolic tangent, y = (exp(x) - exp(-x)) / (exp(x) + exp(-x))
  • softrelu: Soft ReLU, or SoftPlus, y = log(1 + exp(x))

Defined in src/operator/activation.cc:L76

Parameters:
  • data (NDArray) – Input data to activation function.
  • act_type ({'relu', 'sigmoid', 'softrelu', 'tanh'}, required) – Activation function to be applied.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.BatchNorm(data=None, gamma=None, beta=None, eps=_Null, momentum=_Null, fix_gamma=_Null, use_global_stats=_Null, output_mean_var=_Null, out=None, **kwargs)

Batch normalization.

Normalizes a data batch by mean and variance, and applies a scale gamma as well as offset beta.

Assume the input has more than one dimension and we normalize along axis 1. We first compute the mean and variance along this axis:

\[\begin{split}data\_mean[i] = mean(data[:,i,:,...]) \\ data\_var[i] = var(data[:,i,:,...])\end{split}\]

Then compute the normalized output, which has the same shape as input, as following:

\[out[:,i,:,...] = \frac{data[:,i,:,...] - data\_mean[i]}{\sqrt{data\_var[i]+\epsilon}} * gamma[i] + beta[i]\]

Both mean and var returns a scalar by treating the input as a vector.

Assume the input has size k on axis 1, then both gamma and beta have shape (k,). If output_mean_var is set to be true, then outputs both data_mean and data_var as well, which are needed for the backward pass.

Besides the inputs and the outputs, this operator accepts two auxiliary states, moving_mean and moving_var, which are k-length vectors. They are global statistics for the whole dataset, which are updated by:

moving_mean = moving_mean * momentum + data_mean * (1 - momentum)
moving_var = moving_var * momentum + data_var * (1 - momentum)

If use_global_stats is set to be true, then moving_mean and moving_var are used instead of data_mean and data_var to compute the output. It is often used during inference.

Both gamma and beta are learnable parameters. But if fix_gamma is true, then set gamma to 1 and its gradient to 0.

Defined in src/operator/batch_norm.cc:L79

Parameters:
  • data (NDArray) – Input data to batch normalization
  • gamma (NDArray) – gamma array
  • beta (NDArray) – beta array
  • eps (float, optional, default=0.001) – Epsilon to prevent div 0. Must be bigger than CUDNN_BN_MIN_EPSILON defined in cudnn.h when using cudnn (usually 1e-5)
  • momentum (float, optional, default=0.9) – Momentum for moving average
  • fix_gamma (boolean, optional, default=True) – Fix gamma while training
  • use_global_stats (boolean, optional, default=False) – Whether use global moving statistics instead of local batch-norm. This will force change batch-norm into a scale shift operator.
  • output_mean_var (boolean, optional, default=False) – Output All,normal mean and var
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.BilinearSampler(data=None, grid=None, out=None, **kwargs)
Apply bilinear sampling to input feature map, which is the key of “[NIPS2015] Spatial Transformer Networks”
output[batch, channel, y_dst, x_dst] = G(data[batch, channel, y_src, x_src) x_dst, y_dst enumerate all spatial locations in output x_src = grid[batch, 0, y_dst, x_dst] y_src = grid[batch, 1, y_dst, x_dst] G() denotes the bilinear interpolation kernel

The out-boundary points will be padded as zeros. (The boundary is defined to be [-1, 1]) The shape of output will be (data.shape[0], data.shape[1], grid.shape[2], grid.shape[3]) The operator assumes that grid has been nomalized. If you want to design a CustomOp to manipulate grid, please refer to GridGeneratorOp.

Parameters:
  • data (NDArray) – Input data to the BilinearsamplerOp.
  • grid (NDArray) – Input grid to the BilinearsamplerOp.grid has two channels: x_src, y_src
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.BlockGrad(data=None, out=None, **kwargs)

Get output from a symbol and pass 0 gradient back

From:src/operator/tensor/elemwise_unary_op.cc:32

Parameters:
  • data (NDArray) – The input
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.Cast(data=None, dtype=_Null, out=None, **kwargs)

Casts all elements of the input to the new type.

Note

Cast is deprecated. Use cast instead.

Example:

cast([0.9, 1.3], dtype='int32') = [0, 1]
cast([1e20, 11.1], dtype='float16') = [inf, 11.09375]
cast([300, 11.1, 10.9, -1, -3], dtype='uint8') = [44, 11, 10, 255, 253]

Defined in src/operator/tensor/elemwise_unary_op.cc:L86

Parameters:
  • data (NDArray) – The input.
  • dtype ({'float16', 'float32', 'float64', 'int32', 'uint8'}, required) – Output data type.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.Concat(*data, **kwargs)

Join input arrays along the given axis.

Note

Concat is deprecated. Use concat instead.

The dimensions of the input arrays should be the same except the axis along
which they will concatenated.

The dimension of the output array along the concatenated axis will be equal to the sum of the corresponding dimensions of the input arrays.

Example:

x = [[1,1],[2,2]]
y = [[3,3],[4,4],[5,5]]
z = [[6,6], [7,7],[8,8]]

concat(x,y,z,dim=0) = [[ 1.,  1.],
                       [ 2.,  2.],
                       [ 3.,  3.],
                       [ 4.,  4.],
                       [ 5.,  5.],
                       [ 6.,  6.],
                       [ 7.,  7.],
                       [ 8.,  8.]]

Note that you cannot concat x,y,z along dimension 1 since dimension
0 is not the same for all the input arrays.

concat(y,z,dim=1) = [[ 3.,  3.,  6.,  6.],
                      [ 4.,  4.,  7.,  7.],
                      [ 5.,  5.,  8.,  8.]]

Defined in src/operator/concat.cc:L80

Parameters:
  • data (NDArray[]) – List of arrays to concatenate
  • dim (int, optional, default='1') – the dimension to be concated.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.Convolution(data=None, weight=None, bias=None, kernel=_Null, stride=_Null, dilate=_Null, pad=_Null, num_filter=_Null, num_group=_Null, workspace=_Null, no_bias=_Null, cudnn_tune=_Null, cudnn_off=_Null, layout=_Null, out=None, **kwargs)

Compute N-D convolution on (N+2)-D input.

In the 2-D convolution, given input data with shape (batch_size, channel, height, width), the output is computed by

\[out[n,i,:,:] = bias[i] + \sum_{j=0}^{num\_filter} data[n,j,:,:] \star weight[i,j,:,:]\]

where \(\star\) is the 2-D cross-correlation operator.

For general 2-D convolution, the shapes are

  • data: (batch_size, channel, height, width)
  • weight: (num_filter, channel, kernel[0], kernel[1])
  • bias: (num_filter,)
  • out: (batch_size, num_filter, out_height, out_width).

Define:

f(x,k,p,s,d) = floor((x+2*p-d*(k-1)-1)/s)+1

then we have:

out_height=f(height, kernel[0], pad[0], stride[0], dilate[0])
out_width=f(width, kernel[1], pad[1], stride[1], dilate[1])

If no_bias is set to be true, then the bias term is ignored.

The default data layout is NCHW, namely (batch_size, channle, height, width). We can choose other layouts such as NHWC.

If num_group is larger than 1, denoted by g, then split the input data evenly into g parts along the channel axis, and also evenly split weight along the first dimension. Next compute the convolution on the i-th part of the data with the i-th weight part. The output is obtained by concating all the g results.

1-D convolution does not have height dimension but only width in space.

  • data: (batch_size, channel, width)
  • weight: (num_filter, channel, kernel[0])
  • bias: (num_filter,)
  • out: (batch_size, num_filter, out_width).

3-D convolution adds an additional depth dimension besides height and width. The shapes are

  • data: (batch_size, channel, depth, height, width)
  • weight: (num_filter, channel, kernel[0], kernel[1], kernel[2])
  • bias: (num_filter,)
  • out: (batch_size, num_filter, out_depth, out_height, out_width).

Both weight and bias are learnable parameters.

There are other options to tune the performance.

  • cudnn_tune: enable this option leads to higher startup time but may give faster speed. Options are
    • off: no tuning
    • limited_workspace:run test and pick the fastest algorithm that doesn’t exceed workspace limit.
    • fastest: pick the fastest algorithm and ignore workspace limit.
    • None (default): the behavior is determined by environment variable MXNET_CUDNN_AUTOTUNE_DEFAULT. 0 for off, 1 for limited workspace (default), 2 for fastest.
  • workspace: A large number leads to more (GPU) memory usage but may improve the performance.

Defined in src/operator/convolution.cc:L154

Parameters:
  • data (NDArray) – Input data to the ConvolutionOp.
  • weight (NDArray) – Weight matrix.
  • bias (NDArray) – Bias parameter.
  • kernel (Shape(tuple), required) – convolution kernel size: (h, w) or (d, h, w)
  • stride (Shape(tuple), optional, default=()) – convolution stride: (h, w) or (d, h, w)
  • dilate (Shape(tuple), optional, default=()) – convolution dilate: (h, w) or (d, h, w)
  • pad (Shape(tuple), optional, default=()) – pad for convolution: (h, w) or (d, h, w)
  • num_filter (int (non-negative), required) – convolution filter(channel) number
  • num_group (int (non-negative), optional, default=1) – Number of group partitions.
  • workspace (long (non-negative), optional, default=1024) – Maximum temperal workspace allowed for convolution (MB).
  • no_bias (boolean, optional, default=False) – Whether to disable bias parameter.
  • cudnn_tune ({None, 'fastest', 'limited_workspace', 'off'},optional, default='None') – Whether to pick convolution algo by running performance test.
  • cudnn_off (boolean, optional, default=False) – Turn off cudnn for this layer.
  • layout ({None, 'NCDHW', 'NCHW', 'NCW', 'NDHWC', 'NHWC'},optional, default='None') – Set layout for input, output and weight. Empty for default layout: NCW for 1d, NCHW for 2d and NCDHW for 3d.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.Convolution_v1(data=None, weight=None, bias=None, kernel=_Null, stride=_Null, dilate=_Null, pad=_Null, num_filter=_Null, num_group=_Null, workspace=_Null, no_bias=_Null, cudnn_tune=_Null, cudnn_off=_Null, layout=_Null, out=None, **kwargs)

This operator is DEPRECATED. Apply convolution to input then add a bias.

Parameters:
  • data (NDArray) – Input data to the ConvolutionV1Op.
  • weight (NDArray) – Weight matrix.
  • bias (NDArray) – Bias parameter.
  • kernel (Shape(tuple), required) – convolution kernel size: (h, w) or (d, h, w)
  • stride (Shape(tuple), optional, default=()) – convolution stride: (h, w) or (d, h, w)
  • dilate (Shape(tuple), optional, default=()) – convolution dilate: (h, w) or (d, h, w)
  • pad (Shape(tuple), optional, default=()) – pad for convolution: (h, w) or (d, h, w)
  • num_filter (int (non-negative), required) – convolution filter(channel) number
  • num_group (int (non-negative), optional, default=1) – Number of group partitions. Equivalent to slicing input into num_group partitions, apply convolution on each, then concatenate the results
  • workspace (long (non-negative), optional, default=1024) – Maximum tmp workspace allowed for convolution (MB).
  • no_bias (boolean, optional, default=False) – Whether to disable bias parameter.
  • cudnn_tune ({None, 'fastest', 'limited_workspace', 'off'},optional, default='None') – Whether to pick convolution algo by running performance test. Leads to higher startup time but may give faster speed. Options are: ‘off’: no tuning ‘limited_workspace’: run test and pick the fastest algorithm that doesn’t exceed workspace limit. ‘fastest’: pick the fastest algorithm and ignore workspace limit. If set to None (default), behavior is determined by environment variable MXNET_CUDNN_AUTOTUNE_DEFAULT: 0 for off, 1 for limited workspace (default), 2 for fastest.
  • cudnn_off (boolean, optional, default=False) – Turn off cudnn for this layer.
  • layout ({None, 'NCDHW', 'NCHW', 'NDHWC', 'NHWC'},optional, default='None') – Set layout for input, output and weight. Empty for default layout: NCHW for 2d and NCDHW for 3d.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.Correlation(data1=None, data2=None, kernel_size=_Null, max_displacement=_Null, stride1=_Null, stride2=_Null, pad_size=_Null, is_multiply=_Null, out=None, **kwargs)

Apply correlation to inputs

Parameters:
  • data1 (NDArray) – Input data1 to the correlation.
  • data2 (NDArray) – Input data2 to the correlation.
  • kernel_size (int (non-negative), optional, default=1) – kernel size for Correlation must be an odd number
  • max_displacement (int (non-negative), optional, default=1) – Max displacement of Correlation
  • stride1 (int (non-negative), optional, default=1) – stride1 quantize data1 globally
  • stride2 (int (non-negative), optional, default=1) – stride2 quantize data2 within the neighborhood centered around data1
  • pad_size (int (non-negative), optional, default=0) – pad for Correlation
  • is_multiply (boolean, optional, default=True) – operation type is either multiplication or subduction
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.Crop(*data, **kwargs)

Note

Crop is deprecated. Use slice instead.

Crop the 2nd and 3rd dim of input data, with the corresponding size of h_w or with width and height of the second input symbol, i.e., with one input, we need h_w to specify the crop height and width, otherwise the second input symbol’s size will be used

Defined in src/operator/crop.cc:L31

Parameters:
  • data (Symbol or Symbol[]) – Tensor or List of Tensors, the second input will be used as crop_like shape reference
  • offset (Shape(tuple), optional, default=(0,0)) – crop offset coordinate: (y, x)
  • h_w (Shape(tuple), optional, default=(0,0)) – crop height and width: (h, w)
  • center_crop (boolean, optional, default=False) – If set to true, then it will use be the center_crop,or it will crop using the shape of crop_like
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.Custom(op_type=_Null, out=None, **kwargs)

Custom operator implemented in frontend.

Parameters:
  • op_type (string) – Type of custom operator. Must be registered first.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.Deconvolution(data=None, weight=None, bias=None, kernel=_Null, stride=_Null, dilate=_Null, pad=_Null, adj=_Null, target_shape=_Null, num_filter=_Null, num_group=_Null, workspace=_Null, no_bias=_Null, cudnn_tune=_Null, cudnn_off=_Null, layout=_Null, out=None, **kwargs)

Apply deconvolution to input then add a bias.

Parameters:
  • data (NDArray) – Input data to the DeconvolutionOp.
  • weight (NDArray) – Weight matrix.
  • bias (NDArray) – Bias parameter.
  • kernel (Shape(tuple), required) – deconvolution kernel size: (h, w) or (d, h, w)
  • stride (Shape(tuple), optional, default=()) – deconvolution stride: (h, w) or (d, h, w)
  • dilate (Shape(tuple), optional, default=()) – deconvolution dilate: (h, w) or (d, h, w)
  • pad (Shape(tuple), optional, default=()) – pad for deconvolution: (h, w) or (d, h, w). A good number is : (kernel-1)/2. If target_shape is set, pad will be ignored and computed accordingly
  • adj (Shape(tuple), optional, default=()) – adjustment for output shape: (h, w) or (d, h, w). If target_shape is set, ad will be ignored and computed accordingly
  • target_shape (Shape(tuple), optional, default=()) – output shape with target shape : (h, w) or (d, h, w)
  • num_filter (int (non-negative), required) – deconvolution filter(channel) number
  • num_group (int (non-negative), optional, default=1) – number of groups partition
  • workspace (long (non-negative), optional, default=512) – Maximum temporal workspace allowed for deconvolution (MB).
  • no_bias (boolean, optional, default=True) – Whether to disable bias parameter.
  • cudnn_tune ({None, 'fastest', 'limited_workspace', 'off'},optional, default='None') – Whether to pick convolution algo by running performance test.
  • cudnn_off (boolean, optional, default=False) – Turn off cudnn for this layer.
  • layout ({None, 'NCDHW', 'NCHW', 'NCW', 'NDHWC', 'NHWC'},optional, default='None') – Set layout for input, output and weight. Empty for default layout: NCW for 1d, NCHW for 2d and NCDHW for 3d.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.Dropout(data=None, p=_Null, out=None, **kwargs)

Apply dropout to input. During training, each element of the input is randomly set to zero with probability p. And then the whole tensor is rescaled by 1/(1-p) to keep the expectation the same as before applying dropout. During the test time, this behaves as an identity map.

Parameters:
  • data (NDArray) – Input data to dropout.
  • p (float, optional, default=0.5) – Fraction of the input that gets dropped out at training time
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.ElementWiseSum(*args, **kwargs)

Add all input arguments element-wise.

\[add\_n(a_1, a_2, ..., a_n) = a_1 + a_2 + ... + a_n\]

add_n is potentially more efficient than calling add by n times.

Defined in src/operator/tensor/elemwise_sum.cc:L63

Parameters:
  • args (NDArray[]) – Positional input arguments
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.Embedding(data=None, weight=None, input_dim=_Null, output_dim=_Null, dtype=_Null, out=None, **kwargs)

Maps integer indices to vector representations (embeddings).

This operator maps words to real-valued vectors in a high-dimensional space, called word embeddings. These embeddings can capture semantic and syntactic properties of the words. For example, it has been noted that in the learned embedding spaces, similar words tend to be close to each other and dissimilar words far apart.

For an input array of shape (d1, ..., dK), the shape of an output array is (d1, ..., dK, output_dim). All the input values should be integers in the range [0, input_dim).

If the input_dim is ip0 and output_dim is op0, then shape of the embedding weight matrix must be (ip0, op0).

By default, if any index mentioned is too large, it is replaced by the index that addresses the last vector in an embedding matrix.

Examples:

input_dim = 4
output_dim = 5

// Each row in weight matrix y represents a word. So, y = (w0,w1,w2,w3)
y = [[  0.,   1.,   2.,   3.,   4.],
     [  5.,   6.,   7.,   8.,   9.],
     [ 10.,  11.,  12.,  13.,  14.],
     [ 15.,  16.,  17.,  18.,  19.]]

// Input array x represents n-grams(2-gram). So, x = [(w1,w3), (w0,w2)]
x = [[ 1.,  3.],
     [ 0.,  2.]]

// Mapped input x to its vector representation y.
Embedding(x, y, 4, 5) = [[[  5.,   6.,   7.,   8.,   9.],
                          [ 15.,  16.,  17.,  18.,  19.]],

                         [[  0.,   1.,   2.,   3.,   4.],
                          [ 10.,  11.,  12.,  13.,  14.]]]

Defined in src/operator/tensor/indexing_op.cc:L55

Parameters:
  • data (NDArray) – The input array to the embedding operator.
  • weight (NDArray) – The embedding weight matrix.
  • input_dim (int, required) – Vocabulary size of the input indices.
  • output_dim (int, required) – Dimension of the embedding vectors.
  • dtype ({'float16', 'float32', 'float64', 'int32', 'uint8'},optional, default='float32') – Data type of weight.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.Flatten(data=None, out=None, **kwargs)

Flattens the input array into a 2-D array by collapsing the higher dimensions.

Note

Flatten is deprecated. Use flatten instead.

For an input array with shape (d1, d2, ..., dk), flatten operation reshapes the input array into an output array of shape (d1, d2*...*dk).

Example:

x = [[
    [1,2,3],
    [4,5,6],
    [7,8,9]
],
[    [1,2,3],
    [4,5,6],
    [7,8,9]
]],

flatten(x) = [[ 1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9.],
   [ 1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9.]]

Defined in src/operator/tensor/matrix_op.cc:L127

Parameters:
  • data (NDArray) – Input array.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.FullyConnected(data=None, weight=None, bias=None, num_hidden=_Null, no_bias=_Null, out=None, **kwargs)

Apply a linear transformation: \(Y = XW^T + b\).

Shapes:

  • data: (batch_size, input_dim)
  • weight: (num_hidden, input_dim)
  • bias: (num_hidden,)
  • out: (batch_size, num_hidden)

The learnable parameters include both weight and bias.

If no_bias is set to be true, then the bias term is ignored.

Defined in src/operator/fully_connected.cc:L74

Parameters:
  • data (NDArray) – Input data.
  • weight (NDArray) – Weight matrix.
  • bias (NDArray) – Bias parameter.
  • num_hidden (int, required) – Number of hidden nodes of the output.
  • no_bias (boolean, optional, default=False) – Whether to disable bias parameter.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.GridGenerator(data=None, transform_type=_Null, target_shape=_Null, out=None, **kwargs)

generate sampling grid for bilinear sampling.

Parameters:
  • data (NDArray) – Input data to the GridGeneratorOp.
  • transform_type ({'affine', 'warp'}, required) – transformation type if transformation type is affine, data is affine matrix : (batch, 6) if transformation type is warp, data is optical flow : (batch, 2, h, w)
  • target_shape (Shape(tuple), optional, default=(0,0)) – if transformation type is affine, the operator need a target_shape : (H, W) if transofrmation type is warp, the operator will ignore target_shape
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.IdentityAttachKLSparseReg(data=None, sparseness_target=_Null, penalty=_Null, momentum=_Null, out=None, **kwargs)

Apply a sparse regularization to the output a sigmoid activation function.

Parameters:
  • data (NDArray) – Input data.
  • sparseness_target (float, optional, default=0.1) – The sparseness target
  • penalty (float, optional, default=0.001) – The tradeoff parameter for the sparseness penalty
  • momentum (float, optional, default=0.9) – The momentum for running average
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.InstanceNorm(data=None, gamma=None, beta=None, eps=_Null, out=None, **kwargs)

An operator taking in a n-dimensional input tensor (n > 2), and normalizing the input by subtracting the mean and variance calculated over the spatial dimensions. This is an implemention of the operator described in “Instance Normalization: The Missing Ingredient for Fast Stylization”, D. Ulyanov, A. Vedaldi, V. Lempitsky, 2016 (arXiv:1607.08022v2). This layer is similar to batch normalization, with two differences: first, the normalization is carried out per example (‘instance’), not over a batch. Second, the same normalization is applied both at test and train time. This operation is also known as ‘contrast normalization’.

Parameters:
  • data (NDArray) – A n-dimensional tensor (n > 2) of the form [batch, channel, spatial_dim1, spatial_dim2, ...].
  • gamma (NDArray) – A vector of length ‘channel’, which multiplies the normalized input.
  • beta (NDArray) – A vector of length ‘channel’, which is added to the product of the normalized input and the weight.
  • eps (float, optional, default=0.001) – Epsilon to prevent division by 0.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.L2Normalization(data=None, eps=_Null, mode=_Null, out=None, **kwargs)

Set the l2 norm of each instance to a constant.

Parameters:
  • data (NDArray) – Input data to the L2NormalizationOp.
  • eps (float, optional, default=1e-10) – Epsilon to prevent div 0
  • mode ({'channel', 'instance', 'spatial'},optional, default='instance') – Normalization Mode. If set to instance, this operator will compute a norm for each instance in the batch; this is the default mode. If set to channel, this operator will compute a cross channel norm at each position of each instance. If set to spatial, this operator will compute a norm for each channel.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.LRN(data=None, alpha=_Null, beta=_Null, knorm=_Null, nsize=_Null, out=None, **kwargs)

Apply convolution to input then add a bias.

Parameters:
  • data (NDArray) – Input data to the ConvolutionOp.
  • alpha (float, optional, default=0.0001) – value of the alpha variance scaling parameter in the normalization formula
  • beta (float, optional, default=0.75) – value of the beta power parameter in the normalization formula
  • knorm (float, optional, default=2) – value of the k parameter in normalization formula
  • nsize (int (non-negative), required) – normalization window width in elements.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.LeakyReLU(data=None, act_type=_Null, slope=_Null, lower_bound=_Null, upper_bound=_Null, out=None, **kwargs)

Leaky ReLu activation

The following types are supported:

  • elu: y = x > 0 ? x : slop * (exp(x)-1)
  • leaky: y = x > 0 ? x : slope * x
  • prelu: same as leaky but the slope is learnable.
  • rrelu: same as leaky but the slope is uniformly randomly chosen from [lower_bound, upper_bound) for training, while fixed to be (lower_bound+upper_bound)/2 for inference.

Defined in src/operator/leaky_relu.cc:L36

Parameters:
  • data (NDArray) – Input data to activation function.
  • act_type ({'elu', 'leaky', 'prelu', 'rrelu'},optional, default='leaky') – Activation function to be applied.
  • slope (float, optional, default=0.25) – Init slope for the activation. (For leaky and elu only)
  • lower_bound (float, optional, default=0.125) – Lower bound of random slope. (For rrelu only)
  • upper_bound (float, optional, default=0.334) – Upper bound of random slope. (For rrelu only)
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.LinearRegressionOutput(data=None, label=None, grad_scale=_Null, out=None, **kwargs)

LinearRegressionOutput computes and optimizes for squared loss.

Note

Use the LinearRegressionOutput as the final output layer of a net.

By default, gradients of this loss function are scaled by factor 1/n, where n is the number of training examples. The parameter grad_scale can be used to change this scale to grad_scale/n.

Defined in src/operator/regression_output.cc:L45

Parameters:
  • data (NDArray) – Input data to the function.
  • label (NDArray) – Input label to the function.
  • grad_scale (float, optional, default=1) – Scale the gradient by a float factor
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.LogisticRegressionOutput(data=None, label=None, grad_scale=_Null, out=None, **kwargs)

LogisticRegressionOutput applies a logistic function to the input.

The logistic function, also known as the sigmoid function, is computed as \(\frac{1}{1+exp(-x)}\).

Commonly, the sigmoid is used to squash the real-valued output of a linear model :math:wTx+b into the [0,1] range so that it can be interpreted as a probability. It is suitable for binary classification or probability prediction tasks.

Note

Use the LogisticRegressionOutput as the final output layer of a net.

By default, gradients of this loss function are scaled by factor 1/n, where n is the number of training examples. The parameter grad_scale can be used to change this scale to grad_scale/n.

Defined in src/operator/regression_output.cc:L87

Parameters:
  • data (NDArray) – Input data to the function.
  • label (NDArray) – Input label to the function.
  • grad_scale (float, optional, default=1) – Scale the gradient by a float factor
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.MAERegressionOutput(data=None, label=None, grad_scale=_Null, out=None, **kwargs)

MAERegressionOutput function computes mean absolute error.

MAE is a risk metric corresponding to the expected value of the absolute error.

If \(\hat{y}_i\) is the predicted value of the i-th sample, and \(y_i\) is the corresponding target value, then the mean absolute error (MAE) estimated over \(n\) samples is defined as

\(\text{MAE}(y, \hat{y} ) = \frac{1}{n} \sum_{i=0}^{n-1} \left| y_i - \hat{y}_i \right|\)

Note

Use the MAERegressionOutput as the final output layer of a net.

By default, gradients of this loss function are scaled by factor 1/n, where n is the number of training examples. The parameter grad_scale can be used to change this scale to grad_scale/n.

Defined in src/operator/regression_output.cc:L66

Parameters:
  • data (NDArray) – Input data to the function.
  • label (NDArray) – Input label to the function.
  • grad_scale (float, optional, default=1) – Scale the gradient by a float factor
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.MakeLoss(data=None, grad_scale=_Null, valid_thresh=_Null, normalization=_Null, out=None, **kwargs)

Get output from a symbol and pass 1 gradient back. This is used as a terminal loss if unary and binary operator are used to composite a loss with no declaration of backward dependency

Parameters:
  • data (NDArray) – Input data.
  • grad_scale (float, optional, default=1) – gradient scale as a supplement to unary and binary operators
  • valid_thresh (float, optional, default=0) – regard element valid when x > valid_thresh, this is used only in valid normalization mode.
  • normalization ({'batch', 'null', 'valid'},optional, default='null') – If set to null, op will not normalize on output gradient.If set to batch, op will normalize gradient by divide batch size.If set to valid, op will normalize gradient by divide # sample marked as valid
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.Pad(data=None, mode=_Null, pad_width=_Null, constant_value=_Null, out=None, **kwargs)

Pad an array.

Only supports 4-D and 5-D input array.

Defined in src/operator/pad.cc:L407

Parameters:
  • data (NDArray) – An n-dimensional input tensor.
  • mode ({'constant', 'edge'}, required) – Padding type to use. “constant” pads all values with a constant value, the value of which can be specified with the constant_value option. “edge” uses the boundary values of the array as padding.
  • pad_width (Shape(tuple), required) – A tuple of padding widths of length 2*r, where r is the rank of the input tensor, specifying number of values padded to the edges of each axis. (before_1, after_1, ... , before_N, after_N) unique pad widths for each axis. Equivalent to pad_width in numpy.pad, but flattened.
  • constant_value (double, optional, default=0) – This option is only used when mode is “constant”. This value will be used as the padding value. Defaults to 0 if not specified.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.Pooling(data=None, global_pool=_Null, cudnn_off=_Null, kernel=_Null, pool_type=_Null, pooling_convention=_Null, stride=_Null, pad=_Null, out=None, **kwargs)

Perform pooling on the input.

The shapes for 1-D pooling are

  • data: (batch_size, channel, width),
  • out: (batch_size, num_filter, out_width).

The shapes for 2-D pooling are

  • data: (batch_size, channel, height, width)

  • out: (batch_size, num_filter, out_height, out_width), with:

    out_height = f(height, kernel[0], pad[0], stride[0])
    out_width = f(width, kernel[1], pad[1], stride[1])
    

The defintion of f depends on pooling_convention, which has two options:

  • valid (default):

    f(x, k, p, s) = floor(x+2*p-k)/s+1
    
  • full, which is compatible with Caffe:

    f(x, k, p, s) = ceil(x+2*p-k)/s+1
    

But global_pool is set to be true, then do a global pooling, namely reset kernel=(height, width).

Three pooling options are supported by pool_type:

  • avg: average pooling
  • max: max pooling
  • sum: sum pooling

For 3-D pooling, an additional depth dimension is added before height. Namely the input data will have shape (batch_size, channel, depth, height, width).

Defined in src/operator/pooling.cc:L121

Parameters:
  • data (NDArray) – Input data to the pooling operator.
  • global_pool (boolean, optional, default=False) – Ignore kernel size, do global pooling based on current input feature map.
  • cudnn_off (boolean, optional, default=False) – Turn off cudnn pooling and use MXNet pooling operator.
  • kernel (Shape(tuple), required) – pooling kernel size: (y, x) or (d, y, x)
  • pool_type ({'avg', 'max', 'sum'}, required) – Pooling type to be applied.
  • pooling_convention ({'full', 'valid'},optional, default='valid') – Pooling convention to be applied.
  • stride (Shape(tuple), optional, default=()) – stride: for pooling (y, x) or (d, y, x)
  • pad (Shape(tuple), optional, default=()) – pad for pooling: (y, x) or (d, y, x)
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.Pooling_v1(data=None, global_pool=_Null, kernel=_Null, pool_type=_Null, pooling_convention=_Null, stride=_Null, pad=_Null, out=None, **kwargs)

This operator is DEPRECATED. Perform pooling on the input.

The shapes for 2-D pooling is

  • data: (batch_size, channel, height, width)

  • out: (batch_size, num_filter, out_height, out_width), with:

    out_height = f(height, kernel[0], pad[0], stride[0])
    out_width = f(width, kernel[1], pad[1], stride[1])
    

The defintion of f depends on pooling_convention, which has two options:

  • valid (default):

    f(x, k, p, s) = floor(x+2*p-k)/s+1
    
  • full, which is compatible with Caffe:

    f(x, k, p, s) = ceil(x+2*p-k)/s+1
    

But global_pool is set to be true, then do a global pooling, namely reset kernel=(height, width).

Three pooling options are supported by pool_type:

  • avg: average pooling
  • max: max pooling
  • sum: sum pooling

1-D pooling is special case of 2-D pooling with weight=1 and kernel[1]=1.

For 3-D pooling, an additional depth dimension is added before height. Namely the input data will have shape (batch_size, channel, depth, height, width).

Defined in src/operator/pooling_v1.cc:L85

Parameters:
  • data (NDArray) – Input data to the pooling operator.
  • global_pool (boolean, optional, default=False) – Ignore kernel size, do global pooling based on current input feature map.
  • kernel (Shape(tuple), required) – pooling kernel size: (y, x) or (d, y, x)
  • pool_type ({'avg', 'max', 'sum'}, required) – Pooling type to be applied.
  • pooling_convention ({'full', 'valid'},optional, default='valid') – Pooling convention to be applied.
  • stride (Shape(tuple), optional, default=()) – stride: for pooling (y, x) or (d, y, x)
  • pad (Shape(tuple), optional, default=()) – pad for pooling: (y, x) or (d, y, x)
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.RNN(data=None, parameters=None, state=None, state_cell=None, state_size=_Null, num_layers=_Null, bidirectional=_Null, mode=_Null, p=_Null, state_outputs=_Null, out=None, **kwargs)

Apply a recurrent layer to input.

Parameters:
  • data (NDArray) – Input data to RNN
  • parameters (NDArray) – Vector of all RNN trainable parameters concatenated
  • state (NDArray) – initial hidden state of the RNN
  • state_cell (NDArray) – initial cell state for LSTM networks (only for LSTM)
  • state_size (int (non-negative), required) – size of the state for each layer
  • num_layers (int (non-negative), required) – number of stacked layers
  • bidirectional (boolean, optional, default=False) – whether to use bidirectional recurrent layers
  • mode ({'gru', 'lstm', 'rnn_relu', 'rnn_tanh'}, required) – the type of RNN to compute
  • p (float, optional, default=0) – Dropout probability, fraction of the input that gets dropped out at training time
  • state_outputs (boolean, optional, default=False) – Whether to have the states as symbol outputs.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.ROIPooling(data=None, rois=None, pooled_size=_Null, spatial_scale=_Null, out=None, **kwargs)

Performs region of interest(ROI) pooling on the input array.

ROI pooling is a variant of a max pooling layer, in which the output size is fixed and region of interest is a parameter. Its purpose is to perform max pooling on the inputs of non-uniform sizes to obtain fixed-size feature maps. ROI pooling is a neural-net layer mostly used in training a Fast R-CNN network for object detection.

This operator takes a 4D feature map as an input array and region proposals as rois, then it pools over sub-regions of input and produces a fixed-sized output array regardless of the ROI size.

To crop the feature map accordingly, you can resize the bounding box coordinates by changing the parameters rois and spatial_scale.

The cropped feature maps are pooled by standard max pooling operation to a fixed size output indicated by a pooled_size parameter. batch_size will change to the number of region bounding boxes after ROIPooling.

The size of each region of interest doesn’t have to be perfectly divisible by the number of pooling sections(pooled_size).

Example:

x = [[[[  0.,   1.,   2.,   3.,   4.,   5.],
       [  6.,   7.,   8.,   9.,  10.,  11.],
       [ 12.,  13.,  14.,  15.,  16.,  17.],
       [ 18.,  19.,  20.,  21.,  22.,  23.],
       [ 24.,  25.,  26.,  27.,  28.,  29.],
       [ 30.,  31.,  32.,  33.,  34.,  35.],
       [ 36.,  37.,  38.,  39.,  40.,  41.],
       [ 42.,  43.,  44.,  45.,  46.,  47.]]]]

// region of interest i.e. bounding box coordinates.
y = [[0,0,0,4,4]]

// returns array of shape (2,2) according to the given roi with max pooling.
ROIPooling(x, y, (2,2), 1.0) = [[[[ 14.,  16.],
                                  [ 26.,  28.]]]]

// region of interest is changed due to the change in `spacial_scale` parameter.
ROIPooling(x, y, (2,2), 0.7) = [[[[  7.,   9.],
                                  [ 19.,  21.]]]]

Defined in src/operator/roi_pooling.cc:L273

Parameters:
  • data (NDArray) – The input array to the pooling operator, a 4D Feature maps
  • rois (NDArray) – Bounding box coordinates, a 2D array of [[batch_index, x1, y1, x2, y2]], where (x1, y1) and (x2, y2) are top left and bottom right corners of designated region of interest. batch_index indicates the index of corresponding image in the input array
  • pooled_size (Shape(tuple), required) – ROI pooling output shape (h,w)
  • spatial_scale (float, required) – Ratio of input feature map height (or w) to raw image height (or w). Equals the reciprocal of total stride in convolutional layers
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.Reshape(data=None, shape=_Null, reverse=_Null, target_shape=_Null, keep_highest=_Null, out=None, **kwargs)

Reshapes the input array into a new shape.

Note

Reshape is deprecated, use reshape

Given an array and a shape, this function returns a copy of the array in the new shape. The shape is a tuple of integers such as (2,3,4).The size of the new shape should be same as the size of the input array.

Example:

reshape([1,2,3,4], shape=(2,2)) = [[1,2], [3,4]]

Some dimensions of the shape can take special values from the set {0, -1, -2, -3, -4}. The significance of each is explained below:

  • 0 copy this dimension from the input to the output shape.

    Example:

    - input shape = (2,3,4), shape = (4,0,2), output shape = (4,3,2)
    - input shape = (2,3,4), shape = (2,0,0), output shape = (2,3,4)
    
  • -1 infers the dimension of the output shape by using the remainder of the input dimensions keeping the size of the new array same as that of the input array. At most one dimension of shape can be -1.

    Example:

    - input shape = (2,3,4), shape = (6,1,-1), output shape = (6,1,4)
    - input shape = (2,3,4), shape = (3,-1,8), output shape = (3,1,8)
    - input shape = (2,3,4), shape=(-1,), output shape = (24,)
    
  • -2 copy all/remainder of the input dimensions to the output shape.

    Example:

    - input shape = (2,3,4), shape = (-2,), output shape = (2,3,4)
    - input shape = (2,3,4), shape = (2,-2), output shape = (2,3,4)
    - input shape = (2,3,4), shape = (-2,1,1), output shape = (2,3,4,1,1)
    
  • -3 use the product of two consecutive dimensions of the input shape as the output dimension.

    Example:

    - input shape = (2,3,4), shape = (-3,4), output shape = (6,4)
    - input shape = (2,3,4,5), shape = (-3,-3), output shape = (6,20)
    - input shape = (2,3,4), shape = (0,-3), output shape = (2,12)
    - input shape = (2,3,4), shape = (-3,-2), output shape = (6,4)
    
  • -4 split one dimension of the input into two dimensions passed subsequent to -4 in shape (can contain -1).

    Example:

    - input shape = (2,3,4), shape = (-4,1,2,-2), output shape =(1,2,3,4)
    - input shape = (2,3,4), shape = (2,-4,-1,3,-2), output shape = (2,1,3,4)
    

If the argument reverse is set to 1, then the special values are inferred from right to left.

Example:

- without reverse=1, for input shape = (10,5,4), shape = (-1,0), output shape would be (40,5)
- with reverse=1, output shape will be (50,4).

Defined in src/operator/tensor/matrix_op.cc:L87

Parameters:
  • data (NDArray) – Input data to reshape.
  • shape (Shape(tuple), optional, default=()) – The target shape
  • reverse (boolean, optional, default=False) – If true then the special values are inferred from right to left
  • target_shape (Shape(tuple), optional, default=(0,0)) – (Deprecated! Use shape instead.) Target new shape. One and only one dim can be 0, in which case it will be inferred from the rest of dims
  • keep_highest (boolean, optional, default=False) – (Deprecated! Use shape instead.) Whether keep the highest dim unchanged.If set to true, then the first dim in target_shape is ignored,and always fixed as input
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

Examples

Reshapes the input array into a new shape.

>>> x = mx.nd.array([1, 2, 3, 4])
>>> y = mx.nd.reshape(x,shape=(2, 2))
>>> x.shape
(4L,)
>>> y.shape
(2L, 2L)
>>> y.asnumpy()
array([[ 1.,  2.],
   [ 3.,  4.]], dtype=float32)

You can use 0 to copy a particular dimension from the input to the output shape and ‘-1’ to infer the dimensions of the output.

>>> x = mx.nd.ones((2, 3, 4))
>>> x.shape
(2L, 3L, 4L)
>>> y = mx.nd.reshape(x, shape=(4, 0, -1))
>>> y.shape
(4L, 3L, 2L)
mxnet.ndarray.SVMOutput(data=None, label=None, margin=_Null, regularization_coefficient=_Null, use_linear=_Null, out=None, **kwargs)

Computes support vector machine based transformation of the input.

This tutorial demonstrates using SVM as output layer for classification instead of softmax: https://github.com/dmlc/mxnet/tree/master/example/svm_mnist.

Parameters:
  • data (NDArray) – Input data for SVM transformation.
  • label (NDArray) – Class label for the input data.
  • margin (float, optional, default=1) – The loss function penalizes outputs that lie outside this margin. Default margin is 1.
  • regularization_coefficient (float, optional, default=1) – Regularization parameter for the SVM. This balances the tradeoff between coefficient size and error.
  • use_linear (boolean, optional, default=False) – Whether to use L1-SVM objective. L2-SVM objective is used by default.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.SequenceLast(data=None, sequence_length=None, use_sequence_length=_Null, out=None, **kwargs)

Takes the last element of a sequence.

This function takes an n-dimensional input array of the form [max_sequence_length, batch_size, other_feature_dims] and returns a (n-1)-dimensional array of the form [batch_size, other_feature_dims].

Parameter sequence_length is used to handle variable-length sequences. sequence_length should be an input array of positive ints of dimension [batch_size]. To use this parameter, set use_sequence_length to True, otherwise each example in the batch is assumed to have the max sequence length.

Note

Alternatively, you can also use take operator.

Example:

x = [[[  1.,   2.,   3.],
      [  4.,   5.,   6.],
      [  7.,   8.,   9.]],

     [[ 10.,   11.,   12.],
      [ 13.,   14.,   15.],
      [ 16.,   17.,   18.]],

     [[  19.,   20.,   21.],
      [  22.,   23.,   24.],
      [  25.,   26.,   27.]]]

// returns last sequence when sequence_length parameter is not used
SequenceLast(x) = [[  19.,   20.,   21.],
                   [  22.,   23.,   24.],
                   [  25.,   26.,   27.]]

// sequence_length y is used
SequenceLast(x, y=[1,1,1], use_sequence_length=True) =
         [[  1.,   2.,   3.],
          [  4.,   5.,   6.],
          [  7.,   8.,   9.]]

// sequence_length y is used
SequenceLast(x, y=[1,2,3], use_sequence_length=True) =
         [[  1.,    2.,   3.],
          [  13.,  14.,  15.],
          [  25.,  26.,  27.]]

Defined in src/operator/sequence_last.cc:L77

Parameters:
  • data (NDArray) – n-dimensional input array of the form [max_sequence_length, batch_size, other_feature_dims] where n>2
  • sequence_length (NDArray) – vector of sequence lengths of the form [batch_size]
  • use_sequence_length (boolean, optional, default=False) – If set to true, this layer takes in an extra input parameter sequence_length to specify variable length sequence
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.SequenceMask(data=None, sequence_length=None, use_sequence_length=_Null, value=_Null, out=None, **kwargs)

Sets all elements outside the sequence to a constant value.

This function takes an n-dimensional input array of the form [max_sequence_length, batch_size, other_feature_dims] and returns an array of the same shape.

Parameter sequence_length is used to handle variable-length sequences. sequence_length should be an input array of positive ints of dimension [batch_size]. To use this parameter, set use_sequence_length to True, otherwise each example in the batch is assumed to have the max sequence length and this operator works as the identity operator.

Example:

x = [[[  1.,   2.,   3.],
      [  4.,   5.,   6.]],

     [[  7.,   8.,   9.],
      [ 10.,  11.,  12.]],

     [[ 13.,  14.,   15.],
      [ 16.,  17.,   18.]]]

// Batch 1
B1 = [[  1.,   2.,   3.],
      [  7.,   8.,   9.],
      [ 13.,  14.,  15.]]

// Batch 2
B2 = [[  4.,   5.,   6.],
      [ 10.,  11.,  12.],
      [ 16.,  17.,  18.]]

// works as identity operator when sequence_length parameter is not used
SequenceMask(x) = [[[  1.,   2.,   3.],
                    [  4.,   5.,   6.]],

                   [[  7.,   8.,   9.],
                    [ 10.,  11.,  12.]],

                   [[ 13.,  14.,   15.],
                    [ 16.,  17.,   18.]]]

// sequence_length [1,1] means 1 of each batch will be kept
// and other rows are masked with default mask value = 0
SequenceMask(x, y=[1,1], use_sequence_length=True) =
             [[[  1.,   2.,   3.],
               [  4.,   5.,   6.]],

              [[  0.,   0.,   0.],
               [  0.,   0.,   0.]],

              [[  0.,   0.,   0.],
               [  0.,   0.,   0.]]]

// sequence_length [2,3] means 2 of batch B1 and 3 of batch B2 will be kept
// and other rows are masked with value = 1
SequenceMask(x, y=[2,3], use_sequence_length=True, value=1) =
             [[[  1.,   2.,   3.],
               [  4.,   5.,   6.]],

              [[  7.,   8.,   9.],
               [  10.,  11.,  12.]],

              [[   1.,   1.,   1.],
               [  16.,  17.,  18.]]]

Defined in src/operator/sequence_mask.cc:L112

Parameters:
  • data (NDArray) – n-dimensional input array of the form [max_sequence_length, batch_size, other_feature_dims] where n>2
  • sequence_length (NDArray) – vector of sequence lengths of the form [batch_size]
  • use_sequence_length (boolean, optional, default=False) – If set to true, this layer takes in an extra input parameter sequence_length to specify variable length sequence
  • value (float, optional, default=0) – The value to be used as a mask.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.SequenceReverse(data=None, sequence_length=None, use_sequence_length=_Null, out=None, **kwargs)

Reverses the elements of each sequence.

This function takes an n-dimensional input array of the form [max_sequence_length, batch_size, other_feature_dims] and returns an array of the same shape.

Parameter sequence_length is used to handle variable-length sequences. sequence_length should be an input array of positive ints of dimension [batch_size]. To use this parameter, set use_sequence_length to True, otherwise each example in the batch is assumed to have the max sequence length.

Example:

x = [[[  1.,   2.,   3.],
      [  4.,   5.,   6.]],

     [[  7.,   8.,   9.],
      [ 10.,  11.,  12.]],

     [[ 13.,  14.,   15.],
      [ 16.,  17.,   18.]]]

// Batch 1
B1 = [[  1.,   2.,   3.],
      [  7.,   8.,   9.],
      [ 13.,  14.,  15.]]

// Batch 2
B2 = [[  4.,   5.,   6.],
      [ 10.,  11.,  12.],
      [ 16.,  17.,  18.]]

// returns reverse sequence when sequence_length parameter is not used
SequenceReverse(x) = [[[ 13.,  14.,   15.],
                       [ 16.,  17.,   18.]],

                      [[  7.,   8.,   9.],
                       [ 10.,  11.,  12.]],

                      [[  1.,   2.,   3.],
                       [  4.,   5.,   6.]]]

// sequence_length [2,2] means 2 rows of
// both batch B1 and B2 will be reversed.
SequenceReverse(x, y=[2,2], use_sequence_length=True) =
                  [[[  7.,   8.,   9.],
                    [ 10.,  11.,  12.]],

                   [[  1.,   2.,   3.],
                    [  4.,   5.,   6.]],

                   [[ 13.,  14.,   15.],
                    [ 16.,  17.,   18.]]]

// sequence_length [2,3] means 2 of batch B2 and 3 of batch B3
// will be reversed.
SequenceReverse(x, y=[2,3], use_sequence_length=True) =
                 [[[  7.,   8.,   9.],
                   [ 16.,  17.,  18.]],

                  [[  1.,   2.,   3.],
                   [ 10.,  11.,  12.]],

                  [[ 13.,  14,   15.],
                   [  4.,   5.,   6.]]]

Defined in src/operator/sequence_reverse.cc:L98

Parameters:
  • data (NDArray) – n-dimensional input array of the form [max_sequence_length, batch_size, other dims] where n>2
  • sequence_length (NDArray) – vector of sequence lengths of the form [batch_size]
  • use_sequence_length (boolean, optional, default=False) – If set to true, this layer takes in an extra input parameter sequence_length to specify variable length sequence
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.SliceChannel(data=None, num_outputs=_Null, axis=_Null, squeeze_axis=_Null, out=None, **kwargs)

Split an array along a particular axis into multiple sub-arrays.

Assume the input array has shape (d_0, ..., d_n) and we slice it into m (num_outputs=m) subarrays along axis k, then we will obtain a list of m arrays with each of which has shape (d_0, ..., d_k/m, ..., d_n).

For example:

x = [[1, 2],
     [3, 4],
     [5, 6],
     [7, 8]]  // 4x2 array

y = split(x, axis=0, num_outputs=4) // a list of 4 arrays
y[0] = [[ 1.,  2.]]  // 1x2 array

z = split(x, axis=0, num_outputs=2) // a list of 2 arrays
z[0] = [[ 1.,  2.],
        [ 3.,  4.]]

When setting optional argument squeeze_axis=1, then the k-dimension will be removed from the shape if it becomes 1:

y = split(x, axis=0, num_outputs=4, squeeze_axis=1)
y[0] = [ 1.,  2.]  // (2,) vector

Defined in src/operator/slice_channel.cc:L56

Parameters:
  • data (NDArray) – Source input
  • num_outputs (int, required) – Number of outputs to be sliced.
  • axis (int, optional, default='1') – Dimension along which to slice.
  • squeeze_axis (boolean, optional, default=False) – If true, the dimension will be squeezed. Also, input.shape[axis] must be the same as num_outputs when squeeze_axis is turned on.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.Softmax(data=None, grad_scale=_Null, ignore_label=_Null, multi_output=_Null, use_ignore=_Null, preserve_shape=_Null, normalization=_Null, out_grad=_Null, out=None, **kwargs)

Perform a softmax transformation on input. Please use SoftmaxOutput.. note:: Softmax` is deprecated. Use softmax

Parameters:
  • data (NDArray) – Input data to softmax.
  • grad_scale (float, optional, default=1) – Scale the gradient by a float factor
  • ignore_label (float, optional, default=-1) – the labels with value equals to ignore_label will be ignored during backward (only works if use_ignore is set to be true).
  • multi_output (boolean, optional, default=False) – If set to true, softmax will applied on axis 1
  • use_ignore (boolean, optional, default=False) – If set to true, the ignore_label value will not contribute to the backward gradient
  • preserve_shape (boolean, optional, default=False) – If true, softmax will applied on the last axis
  • normalization ({'batch', 'null', 'valid'},optional, default='null') – Normalize the gradient
  • out_grad (boolean, optional, default=False) – Apply weighting from output gradient
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.SoftmaxActivation(data=None, mode=_Null, out=None, **kwargs)

Apply softmax activation to input. This is intended for internal layers. For output (loss layer) please use SoftmaxOutput. If mode=instance, this operator will compute a softmax for each instance in the batch; this is the default mode. If mode=channel, this operator will compute a num_channel-class softmax at each position of each instance; this can be used for fully convolutional network, image segmentation, etc.

Parameters:
  • data (NDArray) – Input data to activation function.
  • mode ({'channel', 'instance'},optional, default='instance') – Softmax Mode. If set to instance, this operator will compute a softmax for each instance in the batch; this is the default mode. If set to channel, this operator will compute a num_channel-class softmax at each position of each instance; this can be used for fully convolutional network, image segmentation, etc.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.SoftmaxOutput(data=None, label=None, grad_scale=_Null, ignore_label=_Null, multi_output=_Null, use_ignore=_Null, preserve_shape=_Null, normalization=_Null, out_grad=_Null, out=None, **kwargs)

Softmax with logit loss.

In the forward pass, the softmax output is returned. Assume the input data has shape (n,k), then the output will have the same shape as the input, which is computed by

\[out[i,:] = softmax(data[i,:])\]

for \(i=0,...,n-1\), where

\[softmax(x) = \left[..., \frac{exp(x[j])}{exp(x[0])+...+exp(x[k-1])}, ...\right]\]

For general N-D input array with shape \((d_1, ..., d_n)\). Denoted by the size \(s=d_1d_2...d_n\). The way to compute softmax various:

  • preserve_shape is false (default). Reshape input into a 2-D array with shape \((d_1, s/d_1)\) beforing computing the softmax, and then reshaped back to the original shape.

  • preserve_shape is true. For all \(i_1, ..., i_{n-1}\), compute

    \[out[i_1, ..., i_{n-1}, :] = softmax(data[i_1, ..., i_{n-1},:])\]
  • multi_output is true. For all \(i_1, ..., i_{n-1}\), compute

    \[out[i_1, :, ..., i_{n-1}] = softmax(data[i_1, :, ..., i_{n-1}])\]

In the backward pass, the logit loss, also called cross-entroy loss, is added. The provided label can be a (N-1)-D label index array or a N-D label probability array.

Examples with a particular label can be ignored during backward by specifying ignore_label (also need use_ignore to be true).

A scale can be applied to the gradient by grad_scale, which is often used in mutli-loss object function in which we can given each loss different weight. It also supports various ways to normalize the gradient by normalization:

  • null: do nothing
  • batch: divide by batch size (number of examples)
  • valid: divide by the number of examples which are not ignored.

Defined in src/operator/softmax_output.cc:L77

Parameters:
  • data (NDArray) – Input data.
  • label (NDArray) – Ground truth label.
  • grad_scale (float, optional, default=1) – Scale the gradient by a float factor
  • ignore_label (float, optional, default=-1) – the labels with value equals to ignore_label will be ignored during backward (only works if use_ignore is set to be true).
  • multi_output (boolean, optional, default=False) – If set to true, softmax will applied on axis 1
  • use_ignore (boolean, optional, default=False) – If set to true, the ignore_label value will not contribute to the backward gradient
  • preserve_shape (boolean, optional, default=False) – If true, softmax will applied on the last axis
  • normalization ({'batch', 'null', 'valid'},optional, default='null') – Normalize the gradient
  • out_grad (boolean, optional, default=False) – Apply weighting from output gradient
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.SpatialTransformer(data=None, loc=None, target_shape=_Null, transform_type=_Null, sampler_type=_Null, out=None, **kwargs)

Apply spatial transformer to input feature map.

Parameters:
  • data (NDArray) – Input data to the SpatialTransformerOp.
  • loc (NDArray) – localisation net, the output dim should be 6 when transform_type is affine. You shold initialize the weight and bias with identity tranform.
  • target_shape (Shape(tuple), optional, default=(0,0)) – output shape(h, w) of spatial transformer: (y, x)
  • transform_type ({'affine'}, required) – transformation type
  • sampler_type ({'bilinear'}, required) – sampling type
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.SwapAxis(data=None, dim1=_Null, dim2=_Null, out=None, **kwargs)

Interchange two axes of an array.

Examples:

 x = [[1, 2, 3]])
 swapaxes(x, 0, 1) = [[ 1],
                      [ 2],
                      [ 3]]

 x = [[[ 0, 1],
       [ 2, 3]],
      [[ 4, 5],
       [ 6, 7]]]  // (2,2,2) array

swapaxes(x, 0, 2) = [[[ 0, 4],
                      [ 2, 6]],
                     [[ 1, 5],
                      [ 3, 7]]]

Defined in src/operator/swapaxis.cc:L55

Parameters:
  • data (NDArray) – Input array.
  • dim1 (int (non-negative), optional, default=0) – the first axis to be swapped.
  • dim2 (int (non-negative), optional, default=0) – the second axis to be swapped.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.UpSampling(*data, **kwargs)

Perform nearest neighboor/bilinear up sampling to inputs

Parameters:
  • data (NDArray[]) – Array of tensors to upsample
  • scale (int (non-negative), required) – Up sampling scale
  • num_filter (int (non-negative), optional, default=0) – Input filter. Only used by bilinear sample_type.
  • sample_type ({'bilinear', 'nearest'}, required) – upsampling method
  • multi_input_mode ({'concat', 'sum'},optional, default='concat') – How to handle multiple input. concat means concatenate upsampled images along the channel dimension. sum means add all images together, only available for nearest neighbor upsampling.
  • workspace (long (non-negative), optional, default=512) – Tmp workspace for deconvolution (MB)
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.abs(data=None, out=None, **kwargs)

Returns element-wise absolute value of the input.

Example:

abs([-2, 0, 3]) = [2, 0, 3]

Defined in src/operator/tensor/elemwise_unary_op.cc:L117

Parameters:
  • data (NDArray) – The input
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.adam_update(weight=None, grad=None, mean=None, var=None, lr=_Null, beta1=_Null, beta2=_Null, epsilon=_Null, wd=_Null, rescale_grad=_Null, clip_gradient=_Null, out=None, **kwargs)

Update function for Adam optimizer. Adam is seen as a generalization of AdaGrad.

Adam update consists of the following steps, where g represents gradient and m, v are 1st and 2nd order moment estimates (mean and variance).

\[\begin{split}g_t = \nabla J(W_{t-1})\\ m_t = \beta_1 m_{t-1} + (1 - \beta_1) g_t\\ v_t = \beta_2 v_{t-1} + (1 - \beta_2) g_t^2\\ W_t = W_{t-1} - \alpha \frac{ m_t }{ \sqrt{ v_t } + \epsilon }\end{split}\]

It updates the weights using:

m = beta1*m + (1-beta1)*grad
v = beta2*v + (1-beta2)*(grad**2)
w += - learning_rate * m / (sqrt(v) + epsilon)

Defined in src/operator/optimizer_op.cc:L91

Parameters:
  • weight (NDArray) – Weight
  • grad (NDArray) – Gradient
  • mean (NDArray) – Moving mean
  • var (NDArray) – Moving variance
  • lr (float, required) – Learning rate
  • beta1 (float, optional, default=0.9) – The decay rate for the 1st moment estimates.
  • beta2 (float, optional, default=0.999) – The decay rate for the 2nd moment estimates.
  • epsilon (float, optional, default=1e-08) – A small constant for numerical stability.
  • wd (float, optional, default=0) – Weight decay augments the objective function with a regularization term that penalizes large weights. The penalty scales with the square of the magnitude of each weight.
  • rescale_grad (float, optional, default=1) – Rescale gradient to grad = rescale_grad*grad.
  • clip_gradient (float, optional, default=-1) – Clip gradient to the range of [-clip_gradient, clip_gradient] If clip_gradient <= 0, gradient clipping is turned off. grad = max(min(grad, clip_gradient), -clip_gradient).
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.add_n(*args, **kwargs)

Add all input arguments element-wise.

\[add\_n(a_1, a_2, ..., a_n) = a_1 + a_2 + ... + a_n\]

add_n is potentially more efficient than calling add by n times.

Defined in src/operator/tensor/elemwise_sum.cc:L63

Parameters:
  • args (NDArray[]) – Positional input arguments
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.arccos(data=None, out=None, **kwargs)

Returns element-wise inverse cosine of the input array.

The input should be in range [-1, 1]. The output is in the closed interval \([0, \pi]\)

\[arccos([-1, -.707, 0, .707, 1]) = [\pi, 3\pi/4, \pi/2, \pi/4, 0]\]

Defined in src/operator/tensor/elemwise_unary_op.cc:L404

Parameters:
  • data (NDArray) – The input
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.arccosh(data=None, out=None, **kwargs)

Returns the element-wise inverse hyperbolic cosine of the input array, computed element-wise.

Defined in src/operator/tensor/elemwise_unary_op.cc:L510

Parameters:
  • data (NDArray) – The input
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.arcsin(data=None, out=None, **kwargs)

Returns element-wise inverse sine of the input array.

The input should be in the range [-1, 1]. The output is in the closed interval of [\(-\pi/2\), \(\pi/2\)].

\[arcsin([-1, -.707, 0, .707, 1]) = [-\pi/2, -\pi/4, 0, \pi/4, \pi/2]\]

Defined in src/operator/tensor/elemwise_unary_op.cc:L387

Parameters:
  • data (NDArray) – The input
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.arcsinh(data=None, out=None, **kwargs)

Returns the element-wise inverse hyperbolic sine of the input array, computed element-wise.

Defined in src/operator/tensor/elemwise_unary_op.cc:L500

Parameters:
  • data (NDArray) – The input
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.arctan(data=None, out=None, **kwargs)

Returns element-wise inverse tangent of the input array.

The output is in the closed interval \([-\pi/2, \pi/2]\)

\[arctan([-1, 0, 1]) = [-\pi/4, 0, \pi/4]\]

Defined in src/operator/tensor/elemwise_unary_op.cc:L420

Parameters:
  • data (NDArray) – The input
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.arctanh(data=None, out=None, **kwargs)

Returns the element-wise inverse hyperbolic tangent of the input array, computed element-wise.

Defined in src/operator/tensor/elemwise_unary_op.cc:L520

Parameters:
  • data (NDArray) – The input
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.argmax(data=None, axis=_Null, keepdims=_Null, out=None, **kwargs)

Returns indices of the maximum values along an axis.

In the case of multiple occurrences of maximum values, the indices corresponding to the first occurrence are returned.

Examples:

x = [[ 0.,  1.,  2.],
     [ 3.,  4.,  5.]]

// argmax along axis 0
argmax(x, axis=0) = [ 1.,  1.,  1.]

// argmax along axis 1
argmax(x, axis=1) = [ 2.,  2.]

// argmax along axis 1 keeping same dims as an input array
argmax(x, axis=1, keepdims=True) = [[ 2.],
                                    [ 2.]]

Defined in src/operator/tensor/broadcast_reduce_op_index.cc:L31

Parameters:
  • data (NDArray) – The input
  • axis (int or None, optional, default='None') – The axis along which to perform the reduction. Negative values means indexing from right to left. Requires axis to be set as int, because global reduction is not supported yet.
  • keepdims (boolean, optional, default=False) – If this is set to True, the reduced axis is left in the result as dimension with size one.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.argmax_channel(data=None, out=None, **kwargs)

Returns argmax indices of each channel from the input array.

The result will be an NDArray of shape (num_channel,).

In case of multiple occurrences of the maximum values, the indices corresponding to the first occurrence are returned.

Examples:

x = [[ 0.,  1.,  2.],
     [ 3.,  4.,  5.]]

argmax_channel(x) = [ 2.,  2.]

Defined in src/operator/tensor/broadcast_reduce_op_index.cc:L76

Parameters:
  • data (NDArray) – The input array
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.argmin(data=None, axis=_Null, keepdims=_Null, out=None, **kwargs)

Returns indices of the minimum values along an axis.

In the case of multiple occurrences of minimum values, the indices corresponding to the first occurrence are returned.

Examples:

x = [[ 0.,  1.,  2.],
     [ 3.,  4.,  5.]]

// argmin along axis 0
argmin(x, axis=0) = [ 0.,  0.,  0.]

// argmin along axis 1
argmin(x, axis=1) = [ 0.,  0.]

// argmin along axis 1 keeping same dims as an input array
argmin(x, axis=1, keepdims=True) = [[ 0.],
                                    [ 0.]]

Defined in src/operator/tensor/broadcast_reduce_op_index.cc:L56

Parameters:
  • data (NDArray) – The input
  • axis (int or None, optional, default='None') – The axis along which to perform the reduction. Negative values means indexing from right to left. Requires axis to be set as int, because global reduction is not supported yet.
  • keepdims (boolean, optional, default=False) – If this is set to True, the reduced axis is left in the result as dimension with size one.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.argsort(data=None, axis=_Null, is_ascend=_Null, out=None, **kwargs)

Returns the indices that would sort an input array along the given axis.

This function performs sorting along the given axis and returns an array of indices having same shape as an input array that index data in sorted order.

Examples:

x = [[ 0.3,  0.2,  0.4],
     [ 0.1,  0.3,  0.2]]

// sort along axis -1
argsort(x) = [[ 1.,  0.,  2.],
              [ 0.,  2.,  1.]]

// sort along axis 0
argsort(x, axis=0) = [[ 1.,  0.,  1.]
                      [ 0.,  1.,  0.]]

// flatten and then sort
argsort(x) = [ 3.,  1.,  5.,  0.,  4.,  2.]

Defined in src/operator/tensor/ordering_op.cc:L157

Parameters:
  • data (NDArray) – The input array
  • axis (int or None, optional, default='-1') – Axis along which to sort the input tensor. If not given, the flattened array is used. Default is -1.
  • is_ascend (boolean, optional, default=True) – Whether to sort in ascending or descending order.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.batch_dot(lhs=None, rhs=None, transpose_a=_Null, transpose_b=_Null, out=None, **kwargs)

Batchwise dot product.

batch_dot is used to compute dot product of x and y when x and y are data in batch, namely 3D arrays in shape of (batch_size, :, :).

For example, given x with shape (batch_size, n, m) and y with shape (batch_size, m, k), the result array will have shape (batch_size, n, k), which is computed by:

batch_dot(x,y)[i,:,:] = dot(x[i,:,:], y[i,:,:])

Defined in src/operator/tensor/matrix_op.cc:L393

Parameters:
  • lhs (NDArray) – The first input
  • rhs (NDArray) – The second input
  • transpose_a (boolean, optional, default=False) – If true then transpose the first input before dot.
  • transpose_b (boolean, optional, default=False) – If true then transpose the second input before dot.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.batch_take(a=None, indices=None, out=None, **kwargs)

Takes elements from a data batch.

Note

batch_take is deprecated. Use pick instead.

Given an input array of shape (d0, d1) and indices of shape (i0,), the result will be an output array of shape (i0,) with:

output[i] = input[i, indices[i]]

Examples:

x = [[ 1.,  2.],
     [ 3.,  4.],
     [ 5.,  6.]]

// takes elements with specified indices
batch_take(x, [0,1,0]) = [ 1.  4.  5.]

Defined in src/operator/tensor/indexing_op.cc:L172

Parameters:
  • a (NDArray) – The input array
  • indices (NDArray) – The index array
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.broadcast_add(lhs=None, rhs=None, out=None, **kwargs)

Returns element-wise sum of the input arrays with broadcasting.

broadcast_plus is an alias to the function broadcast_add.

Example:

x = [[ 1.,  1.,  1.],
     [ 1.,  1.,  1.]]

y = [[ 0.],
     [ 1.]]

broadcast_add(x, y) = [[ 1.,  1.,  1.],
                       [ 2.,  2.,  2.]]

broadcast_plus(x, y) = [[ 1.,  1.,  1.],
                        [ 2.,  2.,  2.]]

Defined in src/operator/tensor/elemwise_binary_broadcast_op_basic.cc:L32

Parameters:
  • lhs (NDArray) – First input to the function
  • rhs (NDArray) – Second input to the function
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.broadcast_axes(data=None, axis=_Null, size=_Null, out=None, **kwargs)

Broadcasts the input array over particular axes.

Broadcasting is allowed on axes with size 1, such as from (2,1,3,1) to (2,8,3,9). Elements will be duplicated on the broadcasted axes.

Example:

// given x of shape (1,2,1)
x = [[[ 1.],
      [ 2.]]]

// broadcast x on on axis 2
broadcast_axis(x, axis=2, size=3) = [[[ 1.,  1.,  1.],
                                      [ 2.,  2.,  2.]]]
// broadcast x on on axes 0 and 2
broadcast_axis(x, axis=(0,2), size=(2,3)) = [[[ 1.,  1.,  1.],
                                              [ 2.,  2.,  2.]],
                                             [[ 1.,  1.,  1.],
                                              [ 2.,  2.,  2.]]]

Defined in src/operator/tensor/broadcast_reduce_op_value.cc:L121

Parameters:
  • data (NDArray) – The input
  • axis (Shape(tuple), optional, default=()) – The axes to perform the broadcasting.
  • size (Shape(tuple), optional, default=()) – Target sizes of the broadcasting axes.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.broadcast_axis(data=None, axis=_Null, size=_Null, out=None, **kwargs)

Broadcasts the input array over particular axes.

Broadcasting is allowed on axes with size 1, such as from (2,1,3,1) to (2,8,3,9). Elements will be duplicated on the broadcasted axes.

Example:

// given x of shape (1,2,1)
x = [[[ 1.],
      [ 2.]]]

// broadcast x on on axis 2
broadcast_axis(x, axis=2, size=3) = [[[ 1.,  1.,  1.],
                                      [ 2.,  2.,  2.]]]
// broadcast x on on axes 0 and 2
broadcast_axis(x, axis=(0,2), size=(2,3)) = [[[ 1.,  1.,  1.],
                                              [ 2.,  2.,  2.]],
                                             [[ 1.,  1.,  1.],
                                              [ 2.,  2.,  2.]]]

Defined in src/operator/tensor/broadcast_reduce_op_value.cc:L121

Parameters:
  • data (NDArray) – The input
  • axis (Shape(tuple), optional, default=()) – The axes to perform the broadcasting.
  • size (Shape(tuple), optional, default=()) – Target sizes of the broadcasting axes.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.broadcast_div(lhs=None, rhs=None, out=None, **kwargs)

Returns element-wise division of the input arrays with broadcasting.

Example:

x = [[ 6.,  6.,  6.],
     [ 6.,  6.,  6.]]

y = [[ 2.],
     [ 3.]]

broadcast_div(x, y) = [[ 3.,  3.,  3.],
                       [ 2.,  2.,  2.]]

Defined in src/operator/tensor/elemwise_binary_broadcast_op_basic.cc:L137

Parameters:
  • lhs (NDArray) – First input to the function
  • rhs (NDArray) – Second input to the function
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.broadcast_equal(lhs=None, rhs=None, out=None, **kwargs)

Returns the result of element-wise equal to (==) comparison operation with broadcasting.

Example:

x = [[ 1.,  1.,  1.],
     [ 1.,  1.,  1.]]

y = [[ 0.],
     [ 1.]]

broadcast_equal(x, y) = [[ 0.,  0.,  0.],
                         [ 1.,  1.,  1.]]

Defined in src/operator/tensor/elemwise_binary_broadcast_op_logic.cc:L27

Parameters:
  • lhs (NDArray) – First input to the function
  • rhs (NDArray) – Second input to the function
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.broadcast_greater(lhs=None, rhs=None, out=None, **kwargs)

Returns the result of element-wise greater than (>) comparison operation with broadcasting.

Example:

x = [[ 1.,  1.,  1.],
     [ 1.,  1.,  1.]]

y = [[ 0.],
     [ 1.]]

broadcast_greater(x, y) = [[ 1.,  1.,  1.],
                           [ 0.,  0.,  0.]]

Defined in src/operator/tensor/elemwise_binary_broadcast_op_logic.cc:L63

Parameters:
  • lhs (NDArray) – First input to the function
  • rhs (NDArray) – Second input to the function
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.broadcast_greater_equal(lhs=None, rhs=None, out=None, **kwargs)

Returns the result of element-wise greater than or equal to (>=) comparison operation with broadcasting.

Example:

x = [[ 1.,  1.,  1.],
     [ 1.,  1.,  1.]]

y = [[ 0.],
     [ 1.]]

broadcast_greater_equal(x, y) = [[ 1.,  1.,  1.],
                                 [ 1.,  1.,  1.]]

Defined in src/operator/tensor/elemwise_binary_broadcast_op_logic.cc:L81

Parameters:
  • lhs (NDArray) – First input to the function
  • rhs (NDArray) – Second input to the function
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.broadcast_hypot(lhs=None, rhs=None, out=None, **kwargs)

Returns the hypotenuse of a right angled triangle, given its “legs” with broadcasting.

It is equivalent to doing \(sqrt(x_1^2 + x_2^2)\).

Example:

x = [[ 3.,  3.,  3.]]

y = [[ 4.],
     [ 4.]]

broadcast_hypot(x, y) = [[ 5.,  5.,  5.],
                         [ 5.,  5.,  5.]]

z = [[ 0.],
     [ 4.]]

broadcast_hypot(x, z) = [[ 3.,  3.,  3.],
                         [ 5.,  5.,  5.]]

Defined in src/operator/tensor/elemwise_binary_broadcast_op_extended.cc:L137

Parameters:
  • lhs (NDArray) – First input to the function
  • rhs (NDArray) – Second input to the function
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.broadcast_lesser(lhs=None, rhs=None, out=None, **kwargs)

Returns the result of element-wise lesser than (<) comparison operation with broadcasting.

Example:

x = [[ 1.,  1.,  1.],
     [ 1.,  1.,  1.]]

y = [[ 0.],
     [ 1.]]

broadcast_lesser(x, y) = [[ 0.,  0.,  0.],
                          [ 0.,  0.,  0.]]

Defined in src/operator/tensor/elemwise_binary_broadcast_op_logic.cc:L99

Parameters:
  • lhs (NDArray) – First input to the function
  • rhs (NDArray) – Second input to the function
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.broadcast_lesser_equal(lhs=None, rhs=None, out=None, **kwargs)

Returns the result of element-wise lesser than or equal to (<=) comparison operation with broadcasting.

Example:

x = [[ 1.,  1.,  1.],
     [ 1.,  1.,  1.]]

y = [[ 0.],
     [ 1.]]

broadcast_lesser_equal(x, y) = [[ 0.,  0.,  0.],
                                [ 1.,  1.,  1.]]

Defined in src/operator/tensor/elemwise_binary_broadcast_op_logic.cc:L117

Parameters:
  • lhs (NDArray) – First input to the function
  • rhs (NDArray) – Second input to the function
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.broadcast_maximum(lhs=None, rhs=None, out=None, **kwargs)

Returns element-wise maximum of the input arrays with broadcasting.

This function compares two input arrays and returns a new array having the element-wise maxima.

Example:

x = [[ 1.,  1.,  1.],
     [ 1.,  1.,  1.]]

y = [[ 0.],
     [ 1.]]

broadcast_maximum(x, y) = [[ 1.,  1.,  1.],
                           [ 1.,  1.,  1.]]

Defined in src/operator/tensor/elemwise_binary_broadcast_op_extended.cc:L61

Parameters:
  • lhs (NDArray) – First input to the function
  • rhs (NDArray) – Second input to the function
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.broadcast_minimum(lhs=None, rhs=None, out=None, **kwargs)

Returns element-wise minimum of the input arrays with broadcasting.

This function compares two input arrays and returns a new array having the element-wise minima.

Example:

x = [[ 1.,  1.,  1.],
     [ 1.,  1.,  1.]]

y = [[ 0.],
     [ 1.]]

broadcast_maximum(x, y) = [[ 0.,  0.,  0.],
                           [ 1.,  1.,  1.]]

Defined in src/operator/tensor/elemwise_binary_broadcast_op_extended.cc:L96

Parameters:
  • lhs (NDArray) – First input to the function
  • rhs (NDArray) – Second input to the function
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.broadcast_minus(lhs=None, rhs=None, out=None, **kwargs)

Returns element-wise difference of the input arrays with broadcasting.

broadcast_minus is an alias to the function broadcast_sub.

Example:

x = [[ 1.,  1.,  1.],
     [ 1.,  1.,  1.]]

y = [[ 0.],
     [ 1.]]

broadcast_sub(x, y) = [[ 1.,  1.,  1.],
                       [ 0.,  0.,  0.]]

broadcast_minus(x, y) = [[ 1.,  1.,  1.],
                         [ 0.,  0.,  0.]]

Defined in src/operator/tensor/elemwise_binary_broadcast_op_basic.cc:L71

Parameters:
  • lhs (NDArray) – First input to the function
  • rhs (NDArray) – Second input to the function
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.broadcast_mul(lhs=None, rhs=None, out=None, **kwargs)

Returns element-wise product of the input arrays with broadcasting.

Example:

x = [[ 1.,  1.,  1.],
     [ 1.,  1.,  1.]]

y = [[ 0.],
     [ 1.]]

broadcast_mul(x, y) = [[ 0.,  0.,  0.],
                       [ 1.,  1.,  1.]]

Defined in src/operator/tensor/elemwise_binary_broadcast_op_basic.cc:L104

Parameters:
  • lhs (NDArray) – First input to the function
  • rhs (NDArray) – Second input to the function
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.broadcast_not_equal(lhs=None, rhs=None, out=None, **kwargs)

Returns the result of element-wise not equal to (!=) comparison operation with broadcasting.

Example:

x = [[ 1.,  1.,  1.],
     [ 1.,  1.,  1.]]

y = [[ 0.],
     [ 1.]]

broadcast_not_equal(x, y) = [[ 1.,  1.,  1.],
                             [ 0.,  0.,  0.]]

Defined in src/operator/tensor/elemwise_binary_broadcast_op_logic.cc:L45

Parameters:
  • lhs (NDArray) – First input to the function
  • rhs (NDArray) – Second input to the function
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.broadcast_plus(lhs=None, rhs=None, out=None, **kwargs)

Returns element-wise sum of the input arrays with broadcasting.

broadcast_plus is an alias to the function broadcast_add.

Example:

x = [[ 1.,  1.,  1.],
     [ 1.,  1.,  1.]]

y = [[ 0.],
     [ 1.]]

broadcast_add(x, y) = [[ 1.,  1.,  1.],
                       [ 2.,  2.,  2.]]

broadcast_plus(x, y) = [[ 1.,  1.,  1.],
                        [ 2.,  2.,  2.]]

Defined in src/operator/tensor/elemwise_binary_broadcast_op_basic.cc:L32

Parameters:
  • lhs (NDArray) – First input to the function
  • rhs (NDArray) – Second input to the function
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.broadcast_power(lhs=None, rhs=None, out=None, **kwargs)

Returns result of first array elements raised to powers from second array, element-wise with broadcasting.

Example:

x = [[ 1.,  1.,  1.],
     [ 1.,  1.,  1.]]

y = [[ 0.],
     [ 1.]]

broadcast_power(x, y) = [[ 2.,  2.,  2.],
                         [ 4.,  4.,  4.]]

Defined in src/operator/tensor/elemwise_binary_broadcast_op_extended.cc:L26

Parameters:
  • lhs (NDArray) – First input to the function
  • rhs (NDArray) – Second input to the function
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.broadcast_sub(lhs=None, rhs=None, out=None, **kwargs)

Returns element-wise difference of the input arrays with broadcasting.

broadcast_minus is an alias to the function broadcast_sub.

Example:

x = [[ 1.,  1.,  1.],
     [ 1.,  1.,  1.]]

y = [[ 0.],
     [ 1.]]

broadcast_sub(x, y) = [[ 1.,  1.,  1.],
                       [ 0.,  0.,  0.]]

broadcast_minus(x, y) = [[ 1.,  1.,  1.],
                         [ 0.,  0.,  0.]]

Defined in src/operator/tensor/elemwise_binary_broadcast_op_basic.cc:L71

Parameters:
  • lhs (NDArray) – First input to the function
  • rhs (NDArray) – Second input to the function
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.broadcast_to(data=None, shape=_Null, out=None, **kwargs)

Broadcasts the input array to a new shape.

Broadcasting is a mechanism that allows NDArrays to perform arithmetic operations with arrays of different shapes efficiently without creating multiple copies of arrays. Also see, Broadcasting for more explanation.

Broadcasting is allowed on axes with size 1, such as from (2,1,3,1) to (2,8,3,9). Elements will be duplicated on the broadcasted axes.

For example:

broadcast_to([[1,2,3]], shape=(2,3)) = [[ 1.,  2.,  3.],
                                        [ 1.,  2.,  3.]])

The dimension which you do not want to change can also be kept as 0 which means copy the original value. So with shape=(2,0), we will obtain the same result as in the above example.

Defined in src/operator/tensor/broadcast_reduce_op_value.cc:L145

Parameters:
  • data (NDArray) – The input
  • shape (Shape(tuple), optional, default=()) – The shape of the desired array. We can set the dim to zero if it’s same as the original. E.g A = broadcast_to(B, shape=(10, 0, 0)) has the same meaning as A = broadcast_axis(B, axis=0, size=10).
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.cast(data=None, dtype=_Null, out=None, **kwargs)

Casts all elements of the input to the new type.

Note

Cast is deprecated. Use cast instead.

Example:

cast([0.9, 1.3], dtype='int32') = [0, 1]
cast([1e20, 11.1], dtype='float16') = [inf, 11.09375]
cast([300, 11.1, 10.9, -1, -3], dtype='uint8') = [44, 11, 10, 255, 253]

Defined in src/operator/tensor/elemwise_unary_op.cc:L86

Parameters:
  • data (NDArray) – The input.
  • dtype ({'float16', 'float32', 'float64', 'int32', 'uint8'}, required) – Output data type.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.ceil(data=None, out=None, **kwargs)

Returns element-wise ceiling of the input.

Example:

ceil([-2.1, -1.9, 1.5, 1.9, 2.1]) = [-2., -1.,  2.,  2.,  3.]

Defined in src/operator/tensor/elemwise_unary_op.cc:L174

Parameters:
  • data (NDArray) – The input
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.choose_element_0index(lhs=None, rhs=None, out=None, **kwargs)

Choose one element from each line(row for python, column for R/Julia) in lhs according to index indicated by rhs. This function assume rhs uses 0-based index.

Parameters:
  • lhs (NDArray) – Left operand to the function.
  • rhs (NDArray) – Right operand to the function.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.clip(data=None, a_min=_Null, a_max=_Null, out=None, **kwargs)

Clip (limit) the values in an array.

Given an interval, values outside the interval are clipped to the interval edges. Clipping x between a_min and a_x would be:

clip(x, a_min, a_max) = max(min(x, a_max), a_min))

Example:

x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

clip(x,1,8) = [ 1.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  8.]

Defined in src/operator/tensor/matrix_op.cc:L438

Parameters:
  • data (NDArray) – Input array.
  • a_min (float, required) – Minimum value
  • a_max (float, required) – Maximum value
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.concat(*data, **kwargs)

Join input arrays along the given axis.

Note

Concat is deprecated. Use concat instead.

The dimensions of the input arrays should be the same except the axis along
which they will concatenated.

The dimension of the output array along the concatenated axis will be equal to the sum of the corresponding dimensions of the input arrays.

Example:

x = [[1,1],[2,2]]
y = [[3,3],[4,4],[5,5]]
z = [[6,6], [7,7],[8,8]]

concat(x,y,z,dim=0) = [[ 1.,  1.],
                       [ 2.,  2.],
                       [ 3.,  3.],
                       [ 4.,  4.],
                       [ 5.,  5.],
                       [ 6.,  6.],
                       [ 7.,  7.],
                       [ 8.,  8.]]

Note that you cannot concat x,y,z along dimension 1 since dimension
0 is not the same for all the input arrays.

concat(y,z,dim=1) = [[ 3.,  3.,  6.,  6.],
                      [ 4.,  4.,  7.,  7.],
                      [ 5.,  5.,  8.,  8.]]

Defined in src/operator/concat.cc:L80

Parameters:
  • data (NDArray[]) – List of arrays to concatenate
  • dim (int, optional, default='1') – the dimension to be concated.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.cos(data=None, out=None, **kwargs)

Computes the element-wise cosine of the input array.

The input should be in radians (\(2\pi\) rad equals 360 degrees).

\[cos([0, \pi/4, \pi/2]) = [1, 0.707, 0]\]

Defined in src/operator/tensor/elemwise_unary_op.cc:L354

Parameters:
  • data (NDArray) – The input
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.cosh(data=None, out=None, **kwargs)

Returns the hyperbolic cosine of the input array, computed element-wise.

\[cosh(x) = 0.5\times(exp(x) + exp(-x))\]

Defined in src/operator/tensor/elemwise_unary_op.cc:L476

Parameters:
  • data (NDArray) – The input
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.crop(data=None, begin=_Null, end=_Null, out=None, **kwargs)

Slice a continuous region of the array.

Note

crop is deprecated. Use slice instead.

This function returns a sliced continous region of the array between the indices given by begin and end.

For an input array of n dimensions, slice operation with begin=(b_0, b_1...b_n-1) indices and end=(e_1, e_2, ... e_n) indices will result in an array with the shape (e_1-b_0, ..., e_n-b_n-1).

The resulting array’s k-th dimension contains elements
from the k-th dimension of the input array with the open range [b_k, e_k).

Example:

x = [[  1.,   2.,   3.,   4.],
     [  5.,   6.,   7.,   8.],
     [  9.,  10.,  11.,  12.]]

slice(x, begin=(0,1), end=(2,4)) = [[ 2.,  3.,  4.],
                                   [ 6.,  7.,  8.]]

Defined in src/operator/tensor/matrix_op.cc:L244

Parameters:
  • data (NDArray) – Source input
  • begin (Shape(tuple), required) – starting indices for the slice operation, supports negative indices.
  • end (Shape(tuple), required) – ending indices for the slice operation, supports negative indices.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.degrees(data=None, out=None, **kwargs)

Converts each element of the input array from radians to degrees.

\[degrees([0, \pi/2, \pi, 3\pi/2, 2\pi]) = [0, 90, 180, 270, 360]\]

Defined in src/operator/tensor/elemwise_unary_op.cc:L434

Parameters:
  • data (NDArray) – The input
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.dot(lhs=None, rhs=None, transpose_a=_Null, transpose_b=_Null, out=None, **kwargs)

Dot product of two arrays.

dot‘s behavior depends on the input array dimensions:

  • 1-D arrays: inner product of vectors

  • 2-D arrays: matrix multiplication

  • N-D arrays: a sum product over the last axis of the first input and the first axis of the second input

    For example, given 3-D x with shape (n,m,k) and y with shape (k,r,s), the result array will have shape (n,m,r,s). It is computed by:

    dot(x,y)[i,j,a,b] = sum(x[i,j,:]*y[:,a,b])
    

Defined in src/operator/tensor/matrix_op.cc:L357

Parameters:
  • lhs (NDArray) – The first input
  • rhs (NDArray) – The second input
  • transpose_a (boolean, optional, default=False) – If true then transpose the first input before dot.
  • transpose_b (boolean, optional, default=False) – If true then transpose the second input before dot.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.elemwise_add(lhs=None, rhs=None, out=None, **kwargs)
Parameters:
  • lhs (NDArray) – first input
  • rhs (NDArray) – second input
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.exp(data=None, out=None, **kwargs)

Returns element-wise exponential value of the input.

\[exp(x) = e^x \approx 2.718^x\]

Example:

exp([0, 1, 2]) = [inf, 1, 0.707]

Defined in src/operator/tensor/elemwise_unary_op.cc:L265

Parameters:
  • data (NDArray) – The input
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.expand_dims(data=None, axis=_Null, out=None, **kwargs)

Insert a new axis with size 1 into the array shape

For example, given x with shape (2,3,4), then expand_dims(x, axis=1) will return a new array with shape (2,1,3,4).

Defined in src/operator/tensor/matrix_op.cc:L204

Parameters:
  • data (NDArray) – Source input
  • axis (int (non-negative), required) – Position (amongst axes) where new axis is to be inserted.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.expm1(data=None, out=None, **kwargs)

Returns exp(x) - 1 computed element-wise on the input.

This function provides greater precision than exp(x) - 1 for small values of x.

Defined in src/operator/tensor/elemwise_unary_op.cc:L338

Parameters:
  • data (NDArray) – The input
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.fill_element_0index(lhs=None, mhs=None, rhs=None, out=None, **kwargs)

Fill one element of each line(row for python, column for R/Julia) in lhs according to index indicated by rhs and values indicated by mhs. This function assume rhs uses 0-based index.

Parameters:
  • lhs (NDArray) – Left operand to the function.
  • mhs (NDArray) – Middle operand to the function.
  • rhs (NDArray) – Right operand to the function.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.fix(data=None, out=None, **kwargs)

Returns element-wise rounded value to the nearest integer towards zero of the input.

Example:

fix([-2.1, -1.9, 1.9, 2.1]) = [-2., -1.,  1., 2.]

Defined in src/operator/tensor/elemwise_unary_op.cc:L196

Parameters:
  • data (NDArray) – The input
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.flatten(data=None, out=None, **kwargs)

Flattens the input array into a 2-D array by collapsing the higher dimensions.

Note

Flatten is deprecated. Use flatten instead.

For an input array with shape (d1, d2, ..., dk), flatten operation reshapes the input array into an output array of shape (d1, d2*...*dk).

Example:

x = [[
    [1,2,3],
    [4,5,6],
    [7,8,9]
],
[    [1,2,3],
    [4,5,6],
    [7,8,9]
]],

flatten(x) = [[ 1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9.],
   [ 1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9.]]

Defined in src/operator/tensor/matrix_op.cc:L127

Parameters:
  • data (NDArray) – Input array.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.flip(data=None, axis=_Null, out=None, **kwargs)

Reverse the order of elements in an array along given axis. The shape of the array is preserved.

Note: reverse and flip are equivalent. We use reverse in the following examples.

Examples:

x = [[ 0.,  1.,  2.,  3.,  4.],
     [ 5.,  6.,  7.,  8.,  9.]]

reverse(x, axis=0) = [[ 5.,  6.,  7.,  8.,  9.],
                      [ 0.,  1.,  2.,  3.,  4.]]

reverse(x, axis=1) = [[ 4.,  3.,  2.,  1.,  0.],
                      [ 9.,  8.,  7.,  6.,  5.]]

Defined in src/operator/tensor/matrix_op.cc:L575

Parameters:
  • data (NDArray) – Input data array
  • axis (Shape(tuple), required) – The axis which to reverse elements.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.floor(data=None, out=None, **kwargs)

Returns element-wise floor of the input.

Example:

floor([-2.1, -1.9, 1.5, 1.9, 2.1]) = [-3., -2.,  1.,  1.,  2.]

Defined in src/operator/tensor/elemwise_unary_op.cc:L185

Parameters:
  • data (NDArray) – The input
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.gamma(data=None, out=None, **kwargs)

Returns the gamma function (extension of the factorial function to the reals) , computed element-wise on the input array.

From:src/operator/tensor/elemwise_unary_op.cc:530

Parameters:
  • data (NDArray) – The input
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.gammaln(data=None, out=None, **kwargs)

Returns element-wise log of the absolute value of the gamma function of the input.

From:src/operator/tensor/elemwise_unary_op.cc:540

Parameters:
  • data (NDArray) – The input
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.identity(data=None, out=None, **kwargs)

Returns a copy of the input.

From:src/operator/tensor/elemwise_unary_op.cc:15

Parameters:
  • data (NDArray) – The input
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.log(data=None, out=None, **kwargs)

Returns element-wise Natural logarithmic value of the input.

The natural logarithm is logarithm in base e, so that log(exp(x)) = x

Defined in src/operator/tensor/elemwise_unary_op.cc:L275

Parameters:
  • data (NDArray) – The input
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.log10(data=None, out=None, **kwargs)

Returns element-wise Base-10 logarithmic value of the input.

10**log10(x) = x

Defined in src/operator/tensor/elemwise_unary_op.cc:L285

Parameters:
  • data (NDArray) – The input
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.log1p(data=None, out=None, **kwargs)

Returns element-wise log(1 + x) value of the input.

This function is more accurate than log(1 + x) for small x so that \(1+x\approx 1\)

Defined in src/operator/tensor/elemwise_unary_op.cc:L325

Parameters:
  • data (NDArray) – The input
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.log2(data=None, out=None, **kwargs)

Returns element-wise Base-2 logarithmic value of the input.

2**log2(x) = x

Defined in src/operator/tensor/elemwise_unary_op.cc:L295

Parameters:
  • data (NDArray) – The input
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.log_softmax(data=None, axis=_Null, out=None, **kwargs)

Compute the log softmax of the input. This is equivalent to computing softmax followed by log.

Examples:

>>> x = mx.nd.array([1, 2, .1])
>>> mx.nd.log_softmax(x).asnumpy()
array([-1.41702998, -0.41702995, -2.31702995], dtype=float32)

>>> x = mx.nd.array( [[1, 2, .1],[.1, 2, 1]] )
>>> mx.nd.log_softmax(x, axis=0).asnumpy()
array([[-0.34115392, -0.69314718, -1.24115396],
       [-1.24115396, -0.69314718, -0.34115392]], dtype=float32)
Parameters:
  • data (NDArray) – The input
  • axis (int, optional, default='-1') – The axis along which to compute softmax.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.make_loss(data=None, out=None, **kwargs)

Get output from a symbol and pass 1 gradient back. This is used as a terminal loss if unary and binary operator are used to composite a loss with no declaration of backward dependency

From:src/operator/tensor/elemwise_unary_op.cc:40

Parameters:
  • data (NDArray) – The input
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.max(data=None, axis=_Null, keepdims=_Null, out=None, **kwargs)

Compute the max of array elements over given axes.

Defined in src/operator/tensor/broadcast_reduce_op_value.cc:L82

Parameters:
  • data (NDArray) – The input
  • axis (Shape(tuple), optional, default=()) – The axis or axes along which to perform the reduction. The default, axis=(), will compute over all elements into a scalar array with shape (1,).
  • axis is int, a reduction is performed on a particular axis. (If) –
  • axis is a tuple of ints, a reduction is performed on all the axes specified in the tuple. (If) –
  • keepdims (boolean, optional, default=False) – If this is set to True, the reduced axes are left in the result as dimension with size one.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.max_axis(data=None, axis=_Null, keepdims=_Null, out=None, **kwargs)

Compute the max of array elements over given axes.

Defined in src/operator/tensor/broadcast_reduce_op_value.cc:L82

Parameters:
  • data (NDArray) – The input
  • axis (Shape(tuple), optional, default=()) – The axis or axes along which to perform the reduction. The default, axis=(), will compute over all elements into a scalar array with shape (1,).
  • axis is int, a reduction is performed on a particular axis. (If) –
  • axis is a tuple of ints, a reduction is performed on all the axes specified in the tuple. (If) –
  • keepdims (boolean, optional, default=False) – If this is set to True, the reduced axes are left in the result as dimension with size one.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.mean(data=None, axis=_Null, keepdims=_Null, out=None, **kwargs)

Compute the mean of array elements over given axes.

Defined in src/operator/tensor/broadcast_reduce_op_value.cc:L41

Parameters:
  • data (NDArray) – The input
  • axis (Shape(tuple), optional, default=()) – The axis or axes along which to perform the reduction. The default, axis=(), will compute over all elements into a scalar array with shape (1,).
  • axis is int, a reduction is performed on a particular axis. (If) –
  • axis is a tuple of ints, a reduction is performed on all the axes specified in the tuple. (If) –
  • keepdims (boolean, optional, default=False) – If this is set to True, the reduced axes are left in the result as dimension with size one.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.min(data=None, axis=_Null, keepdims=_Null, out=None, **kwargs)

Compute the min of array elements over given axes.

Defined in src/operator/tensor/broadcast_reduce_op_value.cc:L92

Parameters:
  • data (NDArray) – The input
  • axis (Shape(tuple), optional, default=()) – The axis or axes along which to perform the reduction. The default, axis=(), will compute over all elements into a scalar array with shape (1,).
  • axis is int, a reduction is performed on a particular axis. (If) –
  • axis is a tuple of ints, a reduction is performed on all the axes specified in the tuple. (If) –
  • keepdims (boolean, optional, default=False) – If this is set to True, the reduced axes are left in the result as dimension with size one.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.min_axis(data=None, axis=_Null, keepdims=_Null, out=None, **kwargs)

Compute the min of array elements over given axes.

Defined in src/operator/tensor/broadcast_reduce_op_value.cc:L92

Parameters:
  • data (NDArray) – The input
  • axis (Shape(tuple), optional, default=()) – The axis or axes along which to perform the reduction. The default, axis=(), will compute over all elements into a scalar array with shape (1,).
  • axis is int, a reduction is performed on a particular axis. (If) –
  • axis is a tuple of ints, a reduction is performed on all the axes specified in the tuple. (If) –
  • keepdims (boolean, optional, default=False) – If this is set to True, the reduced axes are left in the result as dimension with size one.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.nanprod(data=None, axis=_Null, keepdims=_Null, out=None, **kwargs)

Compute the product of array elements over given axes treating Not a Numbers NaN as one.

Defined in src/operator/tensor/broadcast_reduce_op_value.cc:L72

Parameters:
  • data (NDArray) – The input
  • axis (Shape(tuple), optional, default=()) – The axis or axes along which to perform the reduction. The default, axis=(), will compute over all elements into a scalar array with shape (1,).
  • axis is int, a reduction is performed on a particular axis. (If) –
  • axis is a tuple of ints, a reduction is performed on all the axes specified in the tuple. (If) –
  • keepdims (boolean, optional, default=False) – If this is set to True, the reduced axes are left in the result as dimension with size one.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.nansum(data=None, axis=_Null, keepdims=_Null, out=None, **kwargs)

Compute the sum of array elements over given axes treating Not a Numbers NaN as zero.

Defined in src/operator/tensor/broadcast_reduce_op_value.cc:L61

Parameters:
  • data (NDArray) – The input
  • axis (Shape(tuple), optional, default=()) – The axis or axes along which to perform the reduction. The default, axis=(), will compute over all elements into a scalar array with shape (1,).
  • axis is int, a reduction is performed on a particular axis. (If) –
  • axis is a tuple of ints, a reduction is performed on all the axes specified in the tuple. (If) –
  • keepdims (boolean, optional, default=False) – If this is set to True, the reduced axes are left in the result as dimension with size one.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.norm(data=None, out=None, **kwargs)

Flattens the input array and then computes the l2 norm.

Examples:

x = [[1, 2],
     [3, 4]]

norm(x) = [5.47722578]

Defined in src/operator/tensor/broadcast_reduce_op_value.cc:L167

Parameters:
  • data (NDArray) – Source input
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.normal(loc=_Null, scale=_Null, shape=_Null, ctx=_Null, dtype=_Null, out=None, **kwargs)

Draw random samples from a normal (Gaussian) distribution.

Examples:

normal(loc=0, scale=1, shape=(2,2)) = [[ 1.89171135, -1.16881478],
                                       [-1.23474145,  1.55807114]]

Defined in src/operator/tensor/sample_op.cc:L54

Parameters:
  • loc (float, optional, default=0) – Mean of the distribution.
  • scale (float, optional, default=1) – Standard deviation of the distribution.
  • shape (Shape(tuple), optional, default=()) – The shape of the output
  • ctx (string, optional, default='') – Context of output, in format [cpu|gpu|cpu_pinned](n).Only used for imperative calls.
  • dtype ({'None', 'float16', 'float32', 'float64'},optional, default='None') – DType of the output. If output given, set to type of output.If output not given and type not defined (dtype=None), set to float32.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.one_hot(indices=None, depth=_Null, on_value=_Null, off_value=_Null, dtype=_Null, out=None, **kwargs)

Returns a one-hot array.

The locations represented by indices take value on_value, while all other locations take value off_value.

one_hot operation with indices of shape (i0, i1) and depth of d would result

in an output array of shape (i0, i1, d) with:

output[i,j,:] = off_value
output[i,j,indices[i,j]] = on_value

Examples:

one_hot([1,0,2,0], 3) = [[ 0.  1.  0.]
                         [ 1.  0.  0.]
                         [ 0.  0.  1.]
                         [ 1.  0.  0.]]

one_hot([1,0,2,0], 3, on_value=8, off_value=1,
        dtype='int32') = [[1 8 1]
                          [8 1 1]
                          [1 1 8]
                          [8 1 1]]

one_hot([[1,0],[1,0],[2,0]], 3) = [[[ 0.  1.  0.]
                                    [ 1.  0.  0.]]

                                   [[ 0.  1.  0.]
                                    [ 1.  0.  0.]]

                                   [[ 0.  0.  1.]
                                    [ 1.  0.  0.]]]

Defined in src/operator/tensor/indexing_op.cc:L218

Parameters:
  • indices (NDArray) – array of locations where to set on_value
  • depth (int, required) – Depth of the one hot dimension.
  • on_value (double, optional, default=1) – The value assigned to the locations represented by indices.
  • off_value (double, optional, default=0) – The value assigned to the locations not represented by indices.
  • dtype ({'float16', 'float32', 'float64', 'int32', 'uint8'},optional, default='float32') – DType of the output
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.ones_like(data=None, out=None, **kwargs)

Return an array of ones with the same shape and type as the input array.

From:src/operator/tensor/init_op.cc:59

Parameters:
  • data (NDArray) – The input
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.pad(data=None, mode=_Null, pad_width=_Null, constant_value=_Null, out=None, **kwargs)

Pad an array.

Only supports 4-D and 5-D input array.

Defined in src/operator/pad.cc:L407

Parameters:
  • data (NDArray) – An n-dimensional input tensor.
  • mode ({'constant', 'edge'}, required) – Padding type to use. “constant” pads all values with a constant value, the value of which can be specified with the constant_value option. “edge” uses the boundary values of the array as padding.
  • pad_width (Shape(tuple), required) – A tuple of padding widths of length 2*r, where r is the rank of the input tensor, specifying number of values padded to the edges of each axis. (before_1, after_1, ... , before_N, after_N) unique pad widths for each axis. Equivalent to pad_width in numpy.pad, but flattened.
  • constant_value (double, optional, default=0) – This option is only used when mode is “constant”. This value will be used as the padding value. Defaults to 0 if not specified.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.pick(data=None, index=None, axis=_Null, keepdims=_Null, out=None, **kwargs)

Picks elements from an input array according to the input indices along the given axis.

Given an input array of shape (d0, d1) and indices of shape (i0,), the result will be an output array of shape (i0,) with:

output[i] = input[i, indices[i]]

By default, if any index mentioned is too large, it is replaced by the index that addresses the last element along an axis.

This function supports n-dimensional input and (n-1)-dimensional indices arrays.

Examples:

x = [[ 1.,  2.],
     [ 3.,  4.],
     [ 5.,  6.]]

// picks elements with specified indices along axis 0
pick(x, y=[0,1], 0) = [ 1.,  4.]

// picks elements with specified indices along axis 1
pick(x, y=[0,1,0], 1) = [ 1.,  4.,  5.]

y = [[ 1.],
     [ 0.],
     [ 2.]]

// picks elements with specified indices along axis 1 and dims are maintained
pick(x,y, 1, keepdims=True) = [[ 2.],
                               [ 3.],
                               [ 6.]]

Defined in src/operator/tensor/broadcast_reduce_op_index.cc:L124

Parameters:
  • data (NDArray) – The input array
  • index (NDArray) – The index array
  • axis (int or None, optional, default='None') – The axis along which to perform the reduction. Negative values means indexing from right to left. Requires axis to be set as int, because global reduction is not supported yet.
  • keepdims (boolean, optional, default=False) – If this is set to True, the reduced axis is left in the result as dimension with size one.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.prod(data=None, axis=_Null, keepdims=_Null, out=None, **kwargs)

Compute the product of array elements over given axes.

Defined in src/operator/tensor/broadcast_reduce_op_value.cc:L50

Parameters:
  • data (NDArray) – The input
  • axis (Shape(tuple), optional, default=()) – The axis or axes along which to perform the reduction. The default, axis=(), will compute over all elements into a scalar array with shape (1,).
  • axis is int, a reduction is performed on a particular axis. (If) –
  • axis is a tuple of ints, a reduction is performed on all the axes specified in the tuple. (If) –
  • keepdims (boolean, optional, default=False) – If this is set to True, the reduced axes are left in the result as dimension with size one.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.radians(data=None, out=None, **kwargs)

Converts each element of the input array from degrees to radians.

\[radians([0, 90, 180, 270, 360]) = [0, \pi/2, \pi, 3\pi/2, 2\pi]\]

Defined in src/operator/tensor/elemwise_unary_op.cc:L448

Parameters:
  • data (NDArray) – The input
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.random_exponential(lam=_Null, shape=_Null, ctx=_Null, dtype=_Null, out=None, **kwargs)

Sample an exponential distribution

Parameters:
  • lam (float, optional, default=1) – lambda parameter (rate) of the exponential distribution.
  • shape (Shape(tuple), optional, default=()) – The shape of the output
  • ctx (string, optional, default='') – Context of output, in format [cpu|gpu|cpu_pinned](n).Only used for imperative calls.
  • dtype ({'None', 'float16', 'float32', 'float64'},optional, default='None') – DType of the output. If output given, set to type of output.If output not given and type not defined (dtype=None), set to float32.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.random_gamma(alpha=_Null, beta=_Null, shape=_Null, ctx=_Null, dtype=_Null, out=None, **kwargs)

Sample a gamma distribution

Parameters:
  • alpha (float, optional, default=1) – alpha parameter (shape parameter) of the gamma distribution.
  • beta (float, optional, default=1) – beta parameter (scale parameter) of the gamma distribution.
  • shape (Shape(tuple), optional, default=()) – The shape of the output
  • ctx (string, optional, default='') – Context of output, in format [cpu|gpu|cpu_pinned](n).Only used for imperative calls.
  • dtype ({'None', 'float16', 'float32', 'float64'},optional, default='None') – DType of the output. If output given, set to type of output.If output not given and type not defined (dtype=None), set to float32.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.random_generalized_negative_binomial(mu=_Null, alpha=_Null, shape=_Null, ctx=_Null, dtype=_Null, out=None, **kwargs)

Sample a generalized negative binomial distribution

Parameters:
  • mu (float, optional, default=1) – mean of the negative binomial distribution.
  • alpha (float, optional, default=1) – alpha parameter of the negative binomial distribution.
  • shape (Shape(tuple), optional, default=()) – The shape of the output
  • ctx (string, optional, default='') – Context of output, in format [cpu|gpu|cpu_pinned](n).Only used for imperative calls.
  • dtype ({'None', 'float16', 'float32', 'float64'},optional, default='None') – DType of the output. If output given, set to type of output.If output not given and type not defined (dtype=None), set to float32.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.random_negative_binomial(k=_Null, p=_Null, shape=_Null, ctx=_Null, dtype=_Null, out=None, **kwargs)

Sample a negative binomial distribution

Parameters:
  • k (int, optional, default='1') – limit of unsuccessful tries.
  • p (float, optional, default=1) – success probability.
  • shape (Shape(tuple), optional, default=()) – The shape of the output
  • ctx (string, optional, default='') – Context of output, in format [cpu|gpu|cpu_pinned](n).Only used for imperative calls.
  • dtype ({'None', 'float16', 'float32', 'float64'},optional, default='None') – DType of the output. If output given, set to type of output.If output not given and type not defined (dtype=None), set to float32.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.random_normal(loc=_Null, scale=_Null, shape=_Null, ctx=_Null, dtype=_Null, out=None, **kwargs)

Draw random samples from a normal (Gaussian) distribution.

Examples:

normal(loc=0, scale=1, shape=(2,2)) = [[ 1.89171135, -1.16881478],
                                       [-1.23474145,  1.55807114]]

Defined in src/operator/tensor/sample_op.cc:L54

Parameters:
  • loc (float, optional, default=0) – Mean of the distribution.
  • scale (float, optional, default=1) – Standard deviation of the distribution.
  • shape (Shape(tuple), optional, default=()) – The shape of the output
  • ctx (string, optional, default='') – Context of output, in format [cpu|gpu|cpu_pinned](n).Only used for imperative calls.
  • dtype ({'None', 'float16', 'float32', 'float64'},optional, default='None') – DType of the output. If output given, set to type of output.If output not given and type not defined (dtype=None), set to float32.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.random_poisson(lam=_Null, shape=_Null, ctx=_Null, dtype=_Null, out=None, **kwargs)

Sample a Poisson distribution

Parameters:
  • lam (float, optional, default=1) – lambda parameter (rate) of the Poisson distribution.
  • shape (Shape(tuple), optional, default=()) – The shape of the output
  • ctx (string, optional, default='') – Context of output, in format [cpu|gpu|cpu_pinned](n).Only used for imperative calls.
  • dtype ({'None', 'float16', 'float32', 'float64'},optional, default='None') – DType of the output. If output given, set to type of output.If output not given and type not defined (dtype=None), set to float32.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.random_uniform(low=_Null, high=_Null, shape=_Null, ctx=_Null, dtype=_Null, out=None, **kwargs)

Draw samples from a uniform distribution.

Samples are uniformly distributed over the half-open interval [low, high) (includes low, but excludes high):

nd.uniform(low=0, high=1, shape=(2,2)) = [[ 0.60276335,  0.85794562],
                                          [ 0.54488319,  0.84725171]]

Defined in src/operator/tensor/sample_op.cc:L41

Parameters:
  • low (float, optional, default=0) – The lower bound of distribution
  • high (float, optional, default=1) – The upper bound of distribution
  • shape (Shape(tuple), optional, default=()) – The shape of the output
  • ctx (string, optional, default='') – Context of output, in format [cpu|gpu|cpu_pinned](n).Only used for imperative calls.
  • dtype ({'None', 'float16', 'float32', 'float64'},optional, default='None') – DType of the output. If output given, set to type of output.If output not given and type not defined (dtype=None), set to float32.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.repeat(data=None, repeats=_Null, axis=_Null, out=None, **kwargs)

Repeat elements of an array.

By default, repeat flattens the input array into 1-D and then repeats the elements:

x = [[ 1, 2],
     [ 3, 4]]

repeat(x, repeats=2) = [ 1.,  1.,  2.,  2.,  3.,  3.,  4.,  4.]

The parameter axis specifies the axis along which to perform repeat:

repeat(x, repeats=2, axis=1) = [[ 1.,  1.,  2.,  2.],
                                [ 3.,  3.,  4.,  4.]]

repeat(x, repeats=2, axis=0) = [[ 1.,  2.],
                                [ 1.,  2.],
                                [ 3.,  4.],
                                [ 3.,  4.]]

repeat(x, repeats=2, axis=-1) = [[ 1.,  1.,  2.,  2.],
                                 [ 3.,  3.,  4.,  4.]]

Defined in src/operator/tensor/matrix_op.cc:L480

Parameters:
  • data (NDArray) – Input data array
  • repeats (int, required) – The number of repetitions for each element.
  • axis (int or None, optional, default='None') – The axis along which to repeat values. The negative numbers are interpreted counting from the backward. By default, use the flattened input array, and return a flat output array.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.reshape(data=None, shape=_Null, reverse=_Null, target_shape=_Null, keep_highest=_Null, out=None, **kwargs)

Reshapes the input array into a new shape.

Note

Reshape is deprecated, use reshape

Given an array and a shape, this function returns a copy of the array in the new shape. The shape is a tuple of integers such as (2,3,4).The size of the new shape should be same as the size of the input array.

Example:

reshape([1,2,3,4], shape=(2,2)) = [[1,2], [3,4]]

Some dimensions of the shape can take special values from the set {0, -1, -2, -3, -4}. The significance of each is explained below:

  • 0 copy this dimension from the input to the output shape.

    Example:

    - input shape = (2,3,4), shape = (4,0,2), output shape = (4,3,2)
    - input shape = (2,3,4), shape = (2,0,0), output shape = (2,3,4)
    
  • -1 infers the dimension of the output shape by using the remainder of the input dimensions keeping the size of the new array same as that of the input array. At most one dimension of shape can be -1.

    Example:

    - input shape = (2,3,4), shape = (6,1,-1), output shape = (6,1,4)
    - input shape = (2,3,4), shape = (3,-1,8), output shape = (3,1,8)
    - input shape = (2,3,4), shape=(-1,), output shape = (24,)
    
  • -2 copy all/remainder of the input dimensions to the output shape.

    Example:

    - input shape = (2,3,4), shape = (-2,), output shape = (2,3,4)
    - input shape = (2,3,4), shape = (2,-2), output shape = (2,3,4)
    - input shape = (2,3,4), shape = (-2,1,1), output shape = (2,3,4,1,1)
    
  • -3 use the product of two consecutive dimensions of the input shape as the output dimension.

    Example:

    - input shape = (2,3,4), shape = (-3,4), output shape = (6,4)
    - input shape = (2,3,4,5), shape = (-3,-3), output shape = (6,20)
    - input shape = (2,3,4), shape = (0,-3), output shape = (2,12)
    - input shape = (2,3,4), shape = (-3,-2), output shape = (6,4)
    
  • -4 split one dimension of the input into two dimensions passed subsequent to -4 in shape (can contain -1).

    Example:

    - input shape = (2,3,4), shape = (-4,1,2,-2), output shape =(1,2,3,4)
    - input shape = (2,3,4), shape = (2,-4,-1,3,-2), output shape = (2,1,3,4)
    

If the argument reverse is set to 1, then the special values are inferred from right to left.

Example:

- without reverse=1, for input shape = (10,5,4), shape = (-1,0), output shape would be (40,5)
- with reverse=1, output shape will be (50,4).

Defined in src/operator/tensor/matrix_op.cc:L87

Parameters:
  • data (NDArray) – Input data to reshape.
  • shape (Shape(tuple), optional, default=()) – The target shape
  • reverse (boolean, optional, default=False) – If true then the special values are inferred from right to left
  • target_shape (Shape(tuple), optional, default=(0,0)) – (Deprecated! Use shape instead.) Target new shape. One and only one dim can be 0, in which case it will be inferred from the rest of dims
  • keep_highest (boolean, optional, default=False) – (Deprecated! Use shape instead.) Whether keep the highest dim unchanged.If set to true, then the first dim in target_shape is ignored,and always fixed as input
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.reverse(data=None, axis=_Null, out=None, **kwargs)

Reverse the order of elements in an array along given axis. The shape of the array is preserved.

Note: reverse and flip are equivalent. We use reverse in the following examples.

Examples:

x = [[ 0.,  1.,  2.,  3.,  4.],
     [ 5.,  6.,  7.,  8.,  9.]]

reverse(x, axis=0) = [[ 5.,  6.,  7.,  8.,  9.],
                      [ 0.,  1.,  2.,  3.,  4.]]

reverse(x, axis=1) = [[ 4.,  3.,  2.,  1.,  0.],
                      [ 9.,  8.,  7.,  6.,  5.]]

Defined in src/operator/tensor/matrix_op.cc:L575

Parameters:
  • data (NDArray) – Input data array
  • axis (Shape(tuple), required) – The axis which to reverse elements.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.rint(data=None, out=None, **kwargs)

Returns element-wise rounded value to the nearest integer of the input.

Note

  • For input n.5 rint returns n while round returns n+1.
  • For input -n.5 both rint and round returns -n-1.

Example:

rint([-1.5, 1.5, -1.9, 1.9, 2.1]) = [-2.,  1., -2.,  2.,  2.]

Defined in src/operator/tensor/elemwise_unary_op.cc:L163

Parameters:
  • data (NDArray) – The input
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.rmsprop_update(weight=None, grad=None, n=None, lr=_Null, gamma1=_Null, epsilon=_Null, wd=_Null, rescale_grad=_Null, clip_gradient=_Null, clip_weights=_Null, out=None, **kwargs)

Update function for RMSProp optimizer. The RMSProp code follows the version in http://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf Tieleman & Hinton, 2012.

Defined in src/operator/optimizer_op.cc:L111

Parameters:
  • weight (NDArray) – Weight
  • grad (NDArray) – Gradient
  • n (NDArray) – n
  • lr (float, required) – Learning rate
  • gamma1 (float, optional, default=0.95) – The dacay rate of momentum estimates.
  • epsilon (float, optional, default=1e-08) – A small constant for numerical stability.
  • wd (float, optional, default=0) – Weight decay augments the objective function with a regularization term that penalizes large weights. The penalty scales with the square of the magnitude of each weight.
  • rescale_grad (float, optional, default=1) – Rescale gradient to grad = rescale_grad*grad.
  • clip_gradient (float, optional, default=-1) – Clip gradient to the range of [-clip_gradient, clip_gradient] If clip_gradient <= 0, gradient clipping is turned off. grad = max(min(grad, clip_gradient), -clip_gradient).
  • clip_weights (float, optional, default=-1) – Clip weights to the range of [-clip_weights, clip_weights] If clip_weights <= 0, weight clipping is turned off. weights = max(min(weights, clip_weights), -clip_weights).
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.rmspropalex_update(weight=None, grad=None, n=None, g=None, delta=None, lr=_Null, gamma1=_Null, gamma2=_Null, epsilon=_Null, wd=_Null, rescale_grad=_Null, clip_gradient=_Null, clip_weights=_Null, out=None, **kwargs)

Update function for RMSPropAlex optimizer. The RMSPropAlex code follows the version in http://arxiv.org/pdf/1308.0850v5.pdf Eq(38) - Eq(45) by Alex Graves, 2013.

Defined in src/operator/optimizer_op.cc:L130

Parameters:
  • weight (NDArray) – Weight
  • grad (NDArray) – Gradient
  • n (NDArray) – n
  • g (NDArray) – g
  • delta (NDArray) – delta
  • lr (float, required) – Learning rate
  • gamma1 (float, optional, default=0.95) – Decay rate.
  • gamma2 (float, optional, default=0.9) – Decay rate.
  • epsilon (float, optional, default=1e-08) – A small constant for numerical stability.
  • wd (float, optional, default=0) – Weight decay augments the objective function with a regularization term that penalizes large weights. The penalty scales with the square of the magnitude of each weight.
  • rescale_grad (float, optional, default=1) – Rescale gradient to grad = rescale_grad*grad.
  • clip_gradient (float, optional, default=-1) – Clip gradient to the range of [-clip_gradient, clip_gradient] If clip_gradient <= 0, gradient clipping is turned off. grad = max(min(grad, clip_gradient), -clip_gradient).
  • clip_weights (float, optional, default=-1) – Clip weights to the range of [-clip_weights, clip_weights] If clip_weights <= 0, weight clipping is turned off. weights = max(min(weights, clip_weights), -clip_weights).
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.round(data=None, out=None, **kwargs)

Returns element-wise rounded value to the nearest integer of the input.

Example:

round([-1.5, 1.5, -1.9, 1.9, 2.1]) = [-2.,  2., -2.,  2.,  2.]

Defined in src/operator/tensor/elemwise_unary_op.cc:L147

Parameters:
  • data (NDArray) – The input
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.rsqrt(data=None, out=None, **kwargs)

Returns element-wise inverse square-root value of the input.

\[rsqrt(x) = 1/\sqrt{x}\]

Example:

rsqrt([4,9,16]) = [0.5, 0.33333334, 0.25]

Defined in src/operator/tensor/elemwise_unary_op.cc:L246

Parameters:
  • data (NDArray) – The input
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.sample_exponential(lam=None, shape=_Null, dtype=_Null, out=None, **kwargs)

Multi-sampling from exponential distributions with parameters lambda. The parameters of the distributions are provided as input tensor(s). Let “[s]” be the shape of the input tensor(s), “n” be the dimension of [s], “[t]” be the shape specified as the parameter of the operator, and “m” be the dimension of [t]. Then the output will be a (n+m)-dimensional tensor with shape [s]x[t]. For any valid n-dimensional index “i” with respect to the input tensor(s), output[i] will be an m-dimensional tensor that holds randomly drawn samples from the distribution which is parameterized by the input values at index i. If the shape parameter of the operator is not set, then one sample will be drawn per distribution and the output tensor has the same dimensions as the input tensor(s).

From:src/operator/tensor/multisample_op.cc:172

Parameters:
  • shape (Shape(tuple), optional, default=()) – Shape to be sampled from each random distribution.
  • dtype ({'None', 'float16', 'float32', 'float64'},optional, default='None') – DType of the output. If output given, set to type of output.If output not given and type not defined (dtype=None), set to float32.
  • lam (NDArray) –
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.sample_gamma(alpha=None, beta=None, shape=_Null, dtype=_Null, out=None, **kwargs)

Multi-sampling from gamma distributions with parameters alpha and beta. The parameters of the distributions are provided as input tensor(s). Let “[s]” be the shape of the input tensor(s), “n” be the dimension of [s], “[t]” be the shape specified as the parameter of the operator, and “m” be the dimension of [t]. Then the output will be a (n+m)-dimensional tensor with shape [s]x[t]. For any valid n-dimensional index “i” with respect to the input tensor(s), output[i] will be an m-dimensional tensor that holds randomly drawn samples from the distribution which is parameterized by the input values at index i. If the shape parameter of the operator is not set, then one sample will be drawn per distribution and the output tensor has the same dimensions as the input tensor(s).

From:src/operator/tensor/multisample_op.cc:170

Parameters:
  • shape (Shape(tuple), optional, default=()) – Shape to be sampled from each random distribution.
  • dtype ({'None', 'float16', 'float32', 'float64'},optional, default='None') – DType of the output. If output given, set to type of output.If output not given and type not defined (dtype=None), set to float32.
  • alpha (NDArray) –
  • beta (NDArray) –
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.sample_generalized_negative_binomial(mu=None, alpha=None, shape=_Null, dtype=_Null, out=None, **kwargs)

Multi-sampling from generalized negative binomial distributions with parameters mu (mean) and alpha (over dispersion). The parameters of the distributions are provided as input tensor(s). Let “[s]” be the shape of the input tensor(s), “n” be the dimension of [s], “[t]” be the shape specified as the parameter of the operator, and “m” be the dimension of [t]. Then the output will be a (n+m)-dimensional tensor with shape [s]x[t]. For any valid n-dimensional index “i” with respect to the input tensor(s), output[i] will be an m-dimensional tensor that holds randomly drawn samples from the distribution which is parameterized by the input values at index i. If the shape parameter of the operator is not set, then one sample will be drawn per distribution and the output tensor has the same dimensions as the input tensor(s).

From:src/operator/tensor/multisample_op.cc:180

Parameters:
  • shape (Shape(tuple), optional, default=()) – Shape to be sampled from each random distribution.
  • dtype ({'None', 'float16', 'float32', 'float64'},optional, default='None') – DType of the output. If output given, set to type of output.If output not given and type not defined (dtype=None), set to float32.
  • mu (NDArray) –
  • alpha (NDArray) –
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.sample_negative_binomial(k=None, p=None, shape=_Null, dtype=_Null, out=None, **kwargs)

Multi-sampling from negative binomial distributions with parameters k (failure limit) and p (failure probability). The parameters of the distributions are provided as input tensor(s). Let “[s]” be the shape of the input tensor(s), “n” be the dimension of [s], “[t]” be the shape specified as the parameter of the operator, and “m” be the dimension of [t]. Then the output will be a (n+m)-dimensional tensor with shape [s]x[t]. For any valid n-dimensional index “i” with respect to the input tensor(s), output[i] will be an m-dimensional tensor that holds randomly drawn samples from the distribution which is parameterized by the input values at index i. If the shape parameter of the operator is not set, then one sample will be drawn per distribution and the output tensor has the same dimensions as the input tensor(s).

From:src/operator/tensor/multisample_op.cc:176

Parameters:
  • shape (Shape(tuple), optional, default=()) – Shape to be sampled from each random distribution.
  • dtype ({'None', 'float16', 'float32', 'float64'},optional, default='None') – DType of the output. If output given, set to type of output.If output not given and type not defined (dtype=None), set to float32.
  • k (NDArray) –
  • p (NDArray) –
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.sample_normal(mu=None, sigma=None, shape=_Null, dtype=_Null, out=None, **kwargs)

Multi-sampling from normal distributions with parameters mu and sigma. The parameters of the distributions are provided as input tensor(s). Let “[s]” be the shape of the input tensor(s), “n” be the dimension of [s], “[t]” be the shape specified as the parameter of the operator, and “m” be the dimension of [t]. Then the output will be a (n+m)-dimensional tensor with shape [s]x[t]. For any valid n-dimensional index “i” with respect to the input tensor(s), output[i] will be an m-dimensional tensor that holds randomly drawn samples from the distribution which is parameterized by the input values at index i. If the shape parameter of the operator is not set, then one sample will be drawn per distribution and the output tensor has the same dimensions as the input tensor(s).

From:src/operator/tensor/multisample_op.cc:168

Parameters:
  • shape (Shape(tuple), optional, default=()) – Shape to be sampled from each random distribution.
  • dtype ({'None', 'float16', 'float32', 'float64'},optional, default='None') – DType of the output. If output given, set to type of output.If output not given and type not defined (dtype=None), set to float32.
  • mu (NDArray) –
  • sigma (NDArray) –
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.sample_poisson(lam=None, shape=_Null, dtype=_Null, out=None, **kwargs)

Multi-sampling from Poisson distributions with parameters lambda. The parameters of the distributions are provided as input tensor(s). Let “[s]” be the shape of the input tensor(s), “n” be the dimension of [s], “[t]” be the shape specified as the parameter of the operator, and “m” be the dimension of [t]. Then the output will be a (n+m)-dimensional tensor with shape [s]x[t]. For any valid n-dimensional index “i” with respect to the input tensor(s), output[i] will be an m-dimensional tensor that holds randomly drawn samples from the distribution which is parameterized by the input values at index i. If the shape parameter of the operator is not set, then one sample will be drawn per distribution and the output tensor has the same dimensions as the input tensor(s).

From:src/operator/tensor/multisample_op.cc:174

Parameters:
  • shape (Shape(tuple), optional, default=()) – Shape to be sampled from each random distribution.
  • dtype ({'None', 'float16', 'float32', 'float64'},optional, default='None') – DType of the output. If output given, set to type of output.If output not given and type not defined (dtype=None), set to float32.
  • lam (NDArray) –
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.sample_uniform(low=None, high=None, shape=_Null, dtype=_Null, out=None, **kwargs)

Multi-sampling from uniform distributions on the interval [low,high). The parameters of the distributions are provided as input tensor(s). Let “[s]” be the shape of the input tensor(s), “n” be the dimension of [s], “[t]” be the shape specified as the parameter of the operator, and “m” be the dimension of [t]. Then the output will be a (n+m)-dimensional tensor with shape [s]x[t]. For any valid n-dimensional index “i” with respect to the input tensor(s), output[i] will be an m-dimensional tensor that holds randomly drawn samples from the distribution which is parameterized by the input values at index i. If the shape parameter of the operator is not set, then one sample will be drawn per distribution and the output tensor has the same dimensions as the input tensor(s).

From:src/operator/tensor/multisample_op.cc:166

Parameters:
  • shape (Shape(tuple), optional, default=()) – Shape to be sampled from each random distribution.
  • dtype ({'None', 'float16', 'float32', 'float64'},optional, default='None') – DType of the output. If output given, set to type of output.If output not given and type not defined (dtype=None), set to float32.
  • low (NDArray) –
  • high (NDArray) –
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.sgd_mom_update(weight=None, grad=None, mom=None, lr=_Null, momentum=_Null, wd=_Null, rescale_grad=_Null, clip_gradient=_Null, out=None, **kwargs)

Momentum update function for Stochastic Gradient Descent (SDG) optimizer.

Momentum update has better convergence rates on neural networks. Mathematically it looks like below:

\[\begin{split}v_1 = \alpha * \nabla J(W_0)\\ v_t = \gamma v_{t-1} - \alpha * \nabla J(W_{t-1})\\ W_t = W_{t-1} + v_t\end{split}\]

It updates the weights using:

v = momentum * v - learning_rate * gradient
weight += v

Where the parameter momentum is the decay rate of momentum estimates at each epoch.

Defined in src/operator/optimizer_op.cc:L55

Parameters:
  • weight (NDArray) – Weight
  • grad (NDArray) – Gradient
  • mom (NDArray) – Momentum
  • lr (float, required) – Learning rate
  • momentum (float, optional, default=0) – The decay rate of momentum estimates at each epoch.
  • wd (float, optional, default=0) – Weight decay augments the objective function with a regularization term that penalizes large weights. The penalty scales with the square of the magnitude of each weight.
  • rescale_grad (float, optional, default=1) – Rescale gradient to grad = rescale_grad*grad.
  • clip_gradient (float, optional, default=-1) – Clip gradient to the range of [-clip_gradient, clip_gradient] If clip_gradient <= 0, gradient clipping is turned off. grad = max(min(grad, clip_gradient), -clip_gradient).
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.sgd_update(weight=None, grad=None, lr=_Null, wd=_Null, rescale_grad=_Null, clip_gradient=_Null, out=None, **kwargs)

Update function for Stochastic Gradient Descent (SDG) optimizer.

It updates the weights using:

weight = weight - learning_rate * gradient

Defined in src/operator/optimizer_op.cc:L25

Parameters:
  • weight (NDArray) – Weight
  • grad (NDArray) – Gradient
  • lr (float, required) – Learning rate
  • wd (float, optional, default=0) – Weight decay augments the objective function with a regularization term that penalizes large weights. The penalty scales with the square of the magnitude of each weight.
  • rescale_grad (float, optional, default=1) – Rescale gradient to grad = rescale_grad*grad.
  • clip_gradient (float, optional, default=-1) – Clip gradient to the range of [-clip_gradient, clip_gradient] If clip_gradient <= 0, gradient clipping is turned off. grad = max(min(grad, clip_gradient), -clip_gradient).
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.sign(data=None, out=None, **kwargs)

Returns element-wise sign of the input.

Example:

sign([-2, 0, 3]) = [-1, 0, 1]

Defined in src/operator/tensor/elemwise_unary_op.cc:L132

Parameters:
  • data (NDArray) – The input
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.sin(data=None, out=None, **kwargs)

Computes the element-wise sine of the input.

The input should be in radians (\(2\pi\) rad equals 360 degrees).

\[sin([0, \pi/4, \pi/2]) = [0, 0.707, 1]\]

Defined in src/operator/tensor/elemwise_unary_op.cc:L311

Parameters:
  • data (NDArray) – The input
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.sinh(data=None, out=None, **kwargs)

Returns the hyperbolic sine of the input array, computed element-wise.

\[sinh(x) = 0.5\times(exp(x) - exp(-x))\]

Defined in src/operator/tensor/elemwise_unary_op.cc:L462

Parameters:
  • data (NDArray) – The input
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.slice(data=None, begin=_Null, end=_Null, out=None, **kwargs)

Slice a continuous region of the array.

Note

crop is deprecated. Use slice instead.

This function returns a sliced continous region of the array between the indices given by begin and end.

For an input array of n dimensions, slice operation with begin=(b_0, b_1...b_n-1) indices and end=(e_1, e_2, ... e_n) indices will result in an array with the shape (e_1-b_0, ..., e_n-b_n-1).

The resulting array’s k-th dimension contains elements
from the k-th dimension of the input array with the open range [b_k, e_k).

Example:

x = [[  1.,   2.,   3.,   4.],
     [  5.,   6.,   7.,   8.],
     [  9.,  10.,  11.,  12.]]

slice(x, begin=(0,1), end=(2,4)) = [[ 2.,  3.,  4.],
                                   [ 6.,  7.,  8.]]

Defined in src/operator/tensor/matrix_op.cc:L244

Parameters:
  • data (NDArray) – Source input
  • begin (Shape(tuple), required) – starting indices for the slice operation, supports negative indices.
  • end (Shape(tuple), required) – ending indices for the slice operation, supports negative indices.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.slice_axis(data=None, axis=_Null, begin=_Null, end=_Null, out=None, **kwargs)

Slice along a given axis.

Returns an array slice along a given axis starting from the begin index
to the end index.

Examples:

x = [[  1.,   2.,   3.,   4.],
     [  5.,   6.,   7.,   8.],
     [  9.,  10.,  11.,  12.]]

slice_axis(x, axis=0, begin=1, end=3) = [[  5.,   6.,   7.,   8.],
                                         [  9.,  10.,  11.,  12.]]

slice_axis(x, axis=1, begin=0, end=2) = [[  1.,   2.],
                                         [  5.,   6.],
                                         [  9.,  10.]]

slice_axis(x, axis=1, begin=-3, end=-1) = [[  2.,   3.],
                                           [  6.,   7.],
                                           [ 10.,  11.]]

Defined in src/operator/tensor/matrix_op.cc:L324

Parameters:
  • data (NDArray) – Source input
  • axis (int, required) – Axis along which to be sliced, supports negative indexes.
  • begin (int, required) – The beginning index along the axis to be sliced, supports negative indexes.
  • end (int or None, required) – The ending index along the axis to be sliced, supports negative indexes.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.smooth_l1(data=None, scalar=_Null, out=None, **kwargs)

Calculate Smooth L1 Loss(lhs, scalar)

From:src/operator/tensor/elemwise_binary_scalar_op_extended.cc:63

Parameters:
  • data (NDArray) – source input
  • scalar (float) – scalar input
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.softmax(data=None, axis=_Null, out=None, **kwargs)
Applies the softmax function. The resulting array contains
elements in the range (0,1) and the elements along the given axis sum up to 1.
\[softmax(\mathbf{z})_j = \frac{e^{z_j}}{\sum_{k=1}^K e^{z_k}}\]

for \(j = 1, ..., K\)

Example:

x = [[ 1.  1.  1.]
     [ 1.  1.  1.]]

softmax(x,axis=0) = [[ 0.5  0.5  0.5]
                     [ 0.5  0.5  0.5]]

softmax(x,axis=1) = [[ 0.33333334,  0.33333334,  0.33333334],
                     [ 0.33333334,  0.33333334,  0.33333334]]

Defined in src/operator/nn/softmax.cc:L34

Parameters:
  • data (NDArray) – The input
  • axis (int, optional, default='-1') – The axis along which to compute softmax.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.softmax_cross_entropy(data=None, label=None, out=None, **kwargs)

Calculate cross_entropy(data, one_hot(label))

From:src/operator/loss_binary_op.cc:12

Parameters:
  • data (NDArray) – Input data
  • label (NDArray) – Input label
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.sort(data=None, axis=_Null, is_ascend=_Null, out=None, **kwargs)

Returns a sorted copy of an input array along the given axis.

Examples:

x = [[ 1, 4],
     [ 3, 1]]

// sorts along the last axis
sort(x) = [[ 1.,  4.],
           [ 1.,  3.]]

// flattens and then sorts
sort(x) = [ 1.,  1.,  3.,  4.]

// sorts along the first axis
sort(x, axis=0) = [[ 1.,  1.],
                   [ 3.,  4.]]

// in a descend order
sort(x, is_ascend=0) = [[ 4.,  1.],
                        [ 3.,  1.]]

Defined in src/operator/tensor/ordering_op.cc:L107

Parameters:
  • data (NDArray) – The input array
  • axis (int or None, optional, default='-1') – Axis along which to choose sort the input tensor. If not given, the flattened array is used. Default is -1.
  • is_ascend (boolean, optional, default=True) – Whether to sort in ascending or descending order.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.split(data=None, num_outputs=_Null, axis=_Null, squeeze_axis=_Null, out=None, **kwargs)

Split an array along a particular axis into multiple sub-arrays.

Assume the input array has shape (d_0, ..., d_n) and we slice it into m (num_outputs=m) subarrays along axis k, then we will obtain a list of m arrays with each of which has shape (d_0, ..., d_k/m, ..., d_n).

For example:

x = [[1, 2],
     [3, 4],
     [5, 6],
     [7, 8]]  // 4x2 array

y = split(x, axis=0, num_outputs=4) // a list of 4 arrays
y[0] = [[ 1.,  2.]]  // 1x2 array

z = split(x, axis=0, num_outputs=2) // a list of 2 arrays
z[0] = [[ 1.,  2.],
        [ 3.,  4.]]

When setting optional argument squeeze_axis=1, then the k-dimension will be removed from the shape if it becomes 1:

y = split(x, axis=0, num_outputs=4, squeeze_axis=1)
y[0] = [ 1.,  2.]  // (2,) vector

Defined in src/operator/slice_channel.cc:L56

Parameters:
  • data (NDArray) – Source input
  • num_outputs (int, required) – Number of outputs to be sliced.
  • axis (int, optional, default='1') – Dimension along which to slice.
  • squeeze_axis (boolean, optional, default=False) – If true, the dimension will be squeezed. Also, input.shape[axis] must be the same as num_outputs when squeeze_axis is turned on.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.sqrt(data=None, out=None, **kwargs)

Returns element-wise square-root value of the input.

\[\textrm{sqrt}(x) = \sqrt{x}\]

Example:

sqrt([4, 9, 16]) = [2, 3, 4]

Defined in src/operator/tensor/elemwise_unary_op.cc:L228

Parameters:
  • data (NDArray) – The input
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.square(data=None, out=None, **kwargs)

Returns element-wise squared value of the input.

\[square(x) = x^2\]

Example:

square([2, 3, 4]) = [3, 9, 16]

Defined in src/operator/tensor/elemwise_unary_op.cc:L210

Parameters:
  • data (NDArray) – The input
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.stop_gradient(data=None, out=None, **kwargs)

Get output from a symbol and pass 0 gradient back

From:src/operator/tensor/elemwise_unary_op.cc:32

Parameters:
  • data (NDArray) – The input
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.sum(data=None, axis=_Null, keepdims=_Null, out=None, **kwargs)

Compute the sum of array elements over given axes.

Defined in src/operator/tensor/broadcast_reduce_op_value.cc:L32

Parameters:
  • data (NDArray) – The input
  • axis (Shape(tuple), optional, default=()) – The axis or axes along which to perform the reduction. The default, axis=(), will compute over all elements into a scalar array with shape (1,).
  • axis is int, a reduction is performed on a particular axis. (If) –
  • axis is a tuple of ints, a reduction is performed on all the axes specified in the tuple. (If) –
  • keepdims (boolean, optional, default=False) – If this is set to True, the reduced axes are left in the result as dimension with size one.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.sum_axis(data=None, axis=_Null, keepdims=_Null, out=None, **kwargs)

Compute the sum of array elements over given axes.

Defined in src/operator/tensor/broadcast_reduce_op_value.cc:L32

Parameters:
  • data (NDArray) – The input
  • axis (Shape(tuple), optional, default=()) – The axis or axes along which to perform the reduction. The default, axis=(), will compute over all elements into a scalar array with shape (1,).
  • axis is int, a reduction is performed on a particular axis. (If) –
  • axis is a tuple of ints, a reduction is performed on all the axes specified in the tuple. (If) –
  • keepdims (boolean, optional, default=False) – If this is set to True, the reduced axes are left in the result as dimension with size one.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.swapaxes(data=None, dim1=_Null, dim2=_Null, out=None, **kwargs)

Interchange two axes of an array.

Examples:

 x = [[1, 2, 3]])
 swapaxes(x, 0, 1) = [[ 1],
                      [ 2],
                      [ 3]]

 x = [[[ 0, 1],
       [ 2, 3]],
      [[ 4, 5],
       [ 6, 7]]]  // (2,2,2) array

swapaxes(x, 0, 2) = [[[ 0, 4],
                      [ 2, 6]],
                     [[ 1, 5],
                      [ 3, 7]]]

Defined in src/operator/swapaxis.cc:L55

Parameters:
  • data (NDArray) – Input array.
  • dim1 (int (non-negative), optional, default=0) – the first axis to be swapped.
  • dim2 (int (non-negative), optional, default=0) – the second axis to be swapped.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.take(a=None, indices=None, axis=_Null, mode=_Null, out=None, **kwargs)

Takes elements from an input array along the given axis.

This function slices the input array along a particular axis with the provided indices.

Given an input array with shape (d0, d1, d2) and indices with shape (i0, i1), the output will have shape (i0, i1, d1, d2), computed by:

output[i,j,:,:] = input[indices[i,j],:,:]

Note

  • axis- Only slicing along axis 0 is supported for now.
  • mode- Only clip mode is supported for now.

Examples:

x = [[ 1.,  2.],
     [ 3.,  4.],
     [ 5.,  6.]]

// takes elements with specified indices along axis 0
take(x, [[0,1],[1,2]]) = [[[ 1.,  2.],
                           [ 3.,  4.]],

                          [[ 3.,  4.],
                           [ 5.,  6.]]]

Defined in src/operator/tensor/indexing_op.cc:L117

Parameters:
  • a (NDArray) – The input array.
  • indices (NDArray) – The indices of the values to be extracted.
  • axis (int, optional, default='0') – The axis of input array to be taken.
  • mode ({'clip', 'raise', 'wrap'},optional, default='clip') – Specify how out-of-bound indices bahave. “clip” means clip to the range. So, if all indices mentioned are too large, they are replaced by the index that addresses the last element along an axis. “wrap” means to wrap around. “raise” means to raise an error.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.tan(data=None, out=None, **kwargs)

Computes the element-wise tangent of the input array.

The input should be in radians (\(2\pi\) rad equals 360 degrees).

\[tan([0, \pi/4, \pi/2]) = [0, 1, -inf]\]

Defined in src/operator/tensor/elemwise_unary_op.cc:L370

Parameters:
  • data (NDArray) – The input
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.tanh(data=None, out=None, **kwargs)

Returns the hyperbolic tangent of the input array, computed element-wise.

\[tanh(x) = sinh(x) / cosh(x)\]

Defined in src/operator/tensor/elemwise_unary_op.cc:L490

Parameters:
  • data (NDArray) – The input
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.tile(data=None, reps=_Null, out=None, **kwargs)

Repeat the whole array by multiple times.

If reps has length d, and input array has dimension of n. There are there cases:

  • n=d. Repeat i-th dimension of the input by reps[i] times:

    x = [[1, 2],
         [3, 4]]
    
    tile(x, reps=(2,3)) = [[ 1.,  2.,  1.,  2.,  1.,  2.],
                           [ 3.,  4.,  3.,  4.,  3.,  4.],
                           [ 1.,  2.,  1.,  2.,  1.,  2.],
                           [ 3.,  4.,  3.,  4.,  3.,  4.]]
    
  • n>d. reps is promoted to length n by pre-pending 1’s to it. Thus for an input shape (2,3), repos=(2,) is treated as (1,2):

    tile(x, reps=(2,)) = [[ 1.,  2.,  1.,  2.],
                          [ 3.,  4.,  3.,  4.]]
    
  • n<d. The input is promoted to be d-dimensional by prepending new axes. So a shape (2,2) array is promoted to (1,2,2) for 3-D replication:

    tile(x, reps=(2,2,3)) = [[[ 1.,  2.,  1.,  2.,  1.,  2.],
                              [ 3.,  4.,  3.,  4.,  3.,  4.],
                              [ 1.,  2.,  1.,  2.,  1.,  2.],
                              [ 3.,  4.,  3.,  4.,  3.,  4.]],
    
                             [[ 1.,  2.,  1.,  2.,  1.,  2.],
                              [ 3.,  4.,  3.,  4.,  3.,  4.],
                              [ 1.,  2.,  1.,  2.,  1.,  2.],
                              [ 3.,  4.,  3.,  4.,  3.,  4.]]]
    

Defined in src/operator/tensor/matrix_op.cc:L537

Parameters:
  • data (NDArray) – Input data array
  • reps (Shape(tuple), required) – The number of times for repeating the tensor a. If reps has length d, the result will have dimension of max(d, a.ndim); If a.ndim < d, a is promoted to be d-dimensional by prepending new axes. If a.ndim > d, reps is promoted to a.ndim by pre-pending 1’s to it.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.topk(data=None, axis=_Null, k=_Null, ret_typ=_Null, is_ascend=_Null, out=None, **kwargs)

Returns the top k elements in an input array along the given axis.

Examples:

x = [[ 0.3,  0.2,  0.4],
     [ 0.1,  0.3,  0.2]]

// returns an index of the largest element on last axis
topk(x) = [[ 2.],
           [ 1.]]

// returns the value of top-2 largest elements on last axis
topk(x, ret_typ='value', k=2) = [[ 0.4,  0.3],
                                 [ 0.3,  0.2]]

// returns the value of top-2 smallest elements on last axis
topk(x, ret_typ='value', k=2, is_ascend=1) = [[ 0.2 ,  0.3],
                                             [ 0.1 ,  0.2]]

// returns the value of top-2 largest elements on axis 0
topk(x, axis=0, ret_typ='value', k=2) = [[ 0.3,  0.3,  0.4],
                                         [ 0.1,  0.2,  0.2]]

// flattens and then returns list of both values and indices
topk(x, ret_typ='both', k=2) = [[[ 0.4,  0.3], [ 0.3,  0.2]] ,  [[ 2.,  0.], [ 1.,  2.]]]

Defined in src/operator/tensor/ordering_op.cc:L44

Parameters:
  • data (NDArray) – The input array
  • axis (int or None, optional, default='-1') – Axis along which to choose the top k indices. If not given, the flattened array is used. Default is -1.
  • k (int, optional, default='1') – Number of top elements to select, should be always smaller than or equal to the element number in the given axis. A global sort is performed if set k < 1.
  • ret_typ ({'both', 'indices', 'mask', 'value'},optional, default='indices') – The return type. “value” means to return the top k values, “indices” means to return the indices of the top k values, “mask” means to return a mask array containing 0 and 1. 1 means the top k values. “both” means to return a list of both values and indices of top k elements.
  • is_ascend (boolean, optional, default=False) – Whether to choose k largest or k smallest elements. Top K largest elements will be chosen if set to false.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.transpose(data=None, axes=_Null, out=None, **kwargs)

Permute the dimensions of an array.

Examples:

x = [[ 1, 2],
     [ 3, 4]]

transpose(x) = [[ 1.,  3.],
                [ 2.,  4.]]

x = [[[ 1.,  2.],
      [ 3.,  4.]],

     [[ 5.,  6.],
      [ 7.,  8.]]]

transpose(x) = [[[ 1.,  5.],
                 [ 3.,  7.]],

                [[ 2.,  6.],
                 [ 4.,  8.]]]

transpose(x, axes=(1,0,2)) = [[[ 1.,  2.],
                               [ 5.,  6.]],

                              [[ 3.,  4.],
                               [ 7.,  8.]]]

Defined in src/operator/tensor/matrix_op.cc:L168

Parameters:
  • data (NDArray) – Source input
  • axes (Shape(tuple), optional, default=()) – Target axis order. By default the axes will be inverted.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.uniform(low=_Null, high=_Null, shape=_Null, ctx=_Null, dtype=_Null, out=None, **kwargs)

Draw samples from a uniform distribution.

Samples are uniformly distributed over the half-open interval [low, high) (includes low, but excludes high):

nd.uniform(low=0, high=1, shape=(2,2)) = [[ 0.60276335,  0.85794562],
                                          [ 0.54488319,  0.84725171]]

Defined in src/operator/tensor/sample_op.cc:L41

Parameters:
  • low (float, optional, default=0) – The lower bound of distribution
  • high (float, optional, default=1) – The upper bound of distribution
  • shape (Shape(tuple), optional, default=()) – The shape of the output
  • ctx (string, optional, default='') – Context of output, in format [cpu|gpu|cpu_pinned](n).Only used for imperative calls.
  • dtype ({'None', 'float16', 'float32', 'float64'},optional, default='None') – DType of the output. If output given, set to type of output.If output not given and type not defined (dtype=None), set to float32.
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.where(condition=None, x=None, y=None, out=None, **kwargs)

Given three ndarrays, condition, x, and y, return an ndarray with the elements from x or y, depending on the elements from condition are true or false. x and y must have the same shape. If condition has the same shape as x, each element in the output array is from x if the corresponding element in the condition is true, and from y if false. If condtion does not have the same shape as x, it must be a 1D array whose size is the same as x’s first dimension size. Each row of the output array is from x’s row if the corresponding element from condition is true, and from y’s row if false.

From:src/operator/tensor/control_flow_op.cc:21

Parameters:
  • condition (NDArray) – condition array
  • x (NDArray) –
  • y (NDArray) –
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

mxnet.ndarray.zeros_like(data=None, out=None, **kwargs)

Return an array of zeros with the same shape and type as the input array.

From:src/operator/tensor/init_op.cc:47

Parameters:
  • data (NDArray) – The input
  • out (NDArray, optional) – The output NDArray to hold the result.
Returns:

out – The output of this function.

Return type:

NDArray or list of NDArrays

Random number interface of MXNet.

mxnet.random.seed(seed_state)

Seed the random number generators in MXNet.

This seed will affect behavior of functions in this module. It also affects the results from executors that contain random numbers such as dropout operators.

Parameters:seed_state (int) – The random number seed to set to all devices.

Notes

The random number generator of MXNet is, by default, device-specific. This means that if you set the same seed, the random number sequence generated from GPU0 can be different from CPU.