mxnet.numpy.multiarray

numpy ndarray and util functions.

Functions

wrap_mxnp_np_ufunc(func)

A convenience decorator for wrapping for python overload-able ops to provide type casting for mixed use of mx_np and onp inputs.

wrap_mxnp_np_ufunc_inplace(func)

A convenience decorator for in-place binary ops (__iadd__, __imul__, etc.).

mxnet.numpy.multiarray.abs(x, out=None, **kwargs)

Calculate the absolute value element-wise.

Parameters:
  • x (ndarray or scalar) – Input array.

  • out (ndarray or None, optional) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned.

Returns:

absolute – An ndarray containing the absolute value of each element in x. This is a scalar if x is a scalar.

Return type:

ndarray

Examples

>>> x = np.array([-1.2, 1.2])
>>> np.abs(x)
array([1.2, 1.2])
mxnet.numpy.multiarray.absolute(x, out=None, **kwargs)

Calculate the absolute value element-wise. np.abs is a shorthand for this function.

Parameters:
  • x (ndarray) – Input array.

  • out (ndarray, optional) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.

Returns:

absolute – An ndarray containing the absolute value of each element in x.

Return type:

ndarray

Examples

>>> x = np.array([-1.2, 1.2])
>>> np.absolute(x)
array([ 1.2,  1.2])
mxnet.numpy.multiarray.acos(x, out=None, **kwargs)

Trigonometric inverse cosine, element-wise. The inverse of cos so that, if y = cos(x), then x = acos(y).

>>>np.acos is np.arccos True

Parameters:
  • x (ndarray) – x-coordinate on the unit circle. For real arguments, the domain is [-1, 1].

  • out (ndarray, optional) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.

Returns:

angle – The angle of the ray intersecting the unit circle at the given x-coordinate in radians [0, pi]. This is a scalar if x is a scalar.

Return type:

ndarray

Notes

acos is a alias for arccos. It is a standard API in https://data-apis.org/array-api/latest/API_specification/generated/signatures.elementwise_functions.acos.html instead of an official NumPy operator.

acos is a multivalued function: for each x there are infinitely many numbers z such that cos(z) = x. The convention is to return the angle z whose real part lies in [0, pi]. For real-valued input data types, acos always returns real output. For each value that cannot be expressed as a real number or infinity, it yields nan and sets the invalid floating point error flag. The inverse cos is also known as acos or cos^-1.

Examples

>>> np.acos([1, -1])
array([ 0.        ,  3.14159265])
mxnet.numpy.multiarray.acosh(x, out=None, **kwargs)

Inverse hyperbolic cosine, element-wise.

>>>np.acosh is np.arccosh True

Parameters:
  • x (ndarray or scalar) – Input array.

  • out (ndarray or None, optional) – A location into which the result is stored.

Returns:

  • acosh (ndarray) – Array of the same shape as x. This is a scalar if x is a scalar.

  • .. note::acosh is a alias for arccosh. It is a standard API in https://data-apis.org/array-api/latest/API_specification/generated/signatures.elementwise_functions.acosh.html instead of an official NumPy operator.

    acosh is a multivalued function: for each x there are infinitely many numbers z such that cosh(z) = x.

    For real-valued input data types, acosh always returns real output. For each value that cannot be expressed as a real number or infinity, it yields nan and sets the invalid floating point error flag.

    This function differs from the original numpy.arccosh in the following aspects:

    • Do not support where, a parameter in numpy which indicates where to calculate.

    • Do not support complex-valued input.

    • Cannot cast type automatically. Dtype of out must be same as the expected one.

    • Cannot broadcast automatically. Shape of out must be same as the expected one.

    • If x is plain python numeric, the result won’t be stored in out.

Examples

>>> a = np.array([3.2, 5.0])
>>> np.acosh(a)
array([1.8309381, 2.2924316])
>>> np.acosh(1)
0.0
mxnet.numpy.multiarray.add(x1, x2, out=None, **kwargs)

Add arguments element-wise.

Parameters:
  • x1 (ndarrays or scalar values) – The arrays to be added. If x1.shape != x2.shape, they must be broadcastable to a common shape (which may be the shape of one or the other).

  • x2 (ndarrays or scalar values) – The arrays to be added. If x1.shape != x2.shape, they must be broadcastable to a common shape (which may be the shape of one or the other).

  • out (ndarray) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned.

Returns:

  • The sum of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars.

  • .. note:: – This operator now supports automatic type promotion. The resulting type will be determined according to the following rules: * If both inputs are of floating number types, the output is the more precise type. * If only one of the inputs is floating number type, the result is that type. * If both inputs are of integer types (including boolean), not supported yet.

Examples

>>> np.add(1.0, 4.0)
5.0
>>>
>>> x1 = np.arange(9.0).reshape((3, 3))
>>> x2 = np.arange(3.0)
>>> np.add(x1, x2)
array([[ 0.,  2.,  4.],
       [ 3.,  5.,  7.],
       [ 6.,  8., 10.]])
mxnet.numpy.multiarray.all(a, axis=None, out=None, keepdims=False)

Test whether all array elements along a given axis evaluate to True.

Parameters:
  • a (ndarray) – Input array or object that can be converted to an array.

  • axis (None or int or tuple of ints, optional) – Axis or axes along which a logical AND reduction is performed. The default (axis = None) is to perform a logical AND over all the dimensions of the input array.

  • keepdims (bool, optional) – If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

  • out (ndarray, optional) – Alternate output array in which to place the result. It must have the same shape as the expected output and its type is preserved

Returns:

  • all (ndarray, bool) – A new boolean or array is returned unless out is specified, in which case a reference to out is returned.

  • Examples

  • ———

  • >>> np.all([[True,False],[True,True]])

  • False

  • >>> np.all([[True,False],[True,True]], axis=0)

  • array([ True, False])

  • >>> np.all([-1, 4, 5])

  • True

  • >>> np.all([1.0, np.nan])

  • True

  • >>> o=np.array(False)

  • >>> z=np.all([-1, 4, 5], out=o)

  • >>> id(z), id(o), z

  • (28293632, 28293632, array(True)) # may vary

mxnet.numpy.multiarray.allclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False)

Returns True if two arrays are element-wise equal within a tolerance.

The tolerance values are positive, typically very small numbers. The relative difference (rtol * abs(b)) and the absolute difference atol are added together to compare against the absolute difference between a and b.

NaNs are treated as equal if they are in the same place and if equal_nan=True. Infs are treated as equal if they are in the same place and of the same sign in both arrays.

Parameters:
  • a (array_like) – Input arrays to compare.

  • b (array_like) – Input arrays to compare.

  • rtol (float) – The relative tolerance parameter (see Notes).

  • atol (float) – The absolute tolerance parameter (see Notes).

  • equal_nan (bool) –

    Whether to compare NaN’s as equal. If True, NaN’s in a will be considered equal to NaN’s in b in the output array.

    Added in version 1.10.0.

Returns:

allclose – Returns True if the two arrays are equal within the given tolerance; False otherwise.

Return type:

bool

See also

isclose, all, any, equal

Notes

If the following equation is element-wise True, then allclose returns True.

absolute(a - b) <= (atol + rtol * absolute(b))

The above equation is not symmetric in a and b, so that allclose(a, b) might be different from allclose(b, a) in some rare cases.

The comparison of a and b uses standard broadcasting, which means that a and b need not have the same shape in order for allclose(a, b) to evaluate to True. The same is true for equal but not array_equal.

allclose is not defined for non-numeric data types. bool is considered a numeric data-type for this purpose.

Examples

>>> np.allclose([1e10,1e-7], [1.00001e10,1e-8])
False
>>> np.allclose([1e10,1e-8], [1.00001e10,1e-9])
True
>>> np.allclose([1e10,1e-8], [1.0001e10,1e-9])
False
>>> np.allclose([1.0, np.nan], [1.0, np.nan])
False
>>> np.allclose([1.0, np.nan], [1.0, np.nan], equal_nan=True)
True
mxnet.numpy.multiarray.amax(a, axis=None, out=None, keepdims=False)

Return the maximum of an array or maximum along an axis.

Parameters:
  • a (ndarray) – Input data.

  • axis (int, optional) – Axis along which to operate. By default, flattened input is used.

  • out (ndarray, optional) – Alternative output array in which to place the result. Must be of the same shape and buffer length as the expected output. See doc.ufuncs (Section “Output arguments”) for more details.

  • keepdims (bool, optional) – If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original arr.

Returns:

max – Maximum of a. If axis is None, the result is an array of dimension 1. If axis is given, the result is an array of dimension a.ndim - 1.

Return type:

ndarray

See also

min

The minimum value of an array along a given axis, ignoring any nan.

maximum

Element-wise maximum of two arrays, ignoring any nan.

argmax

Return the indices of the maximum values.

Notes

NaN in the orginal numpy is denoted as nan and will be ignored.

Don’t use max for element-wise comparison of 2 arrays; when a.shape[0] is 2, maximum(a[0], a[1]) is faster than max(a, axis=0).

Examples

>>> a = np.arange(4).reshape((2,2))
>>> a
array([[0., 1.],
    [2., 3.]])
>>> np.max(a)            # Maximum of the flattened array
array(3.)
>>> np.max(a, axis=0)    # Maxima along the first axis
array([2., 3.])
>>> np.max(a, axis=1)    # Maxima along the second axis
array([1., 3.])
>>> b = np.arange(5, dtype=np.float32)
>>> b[2] = np.nan
>>> np.max(b)
array(4.)
mxnet.numpy.multiarray.amin(a, axis=None, out=None, keepdims=False)

Return the minimum of an array or minimum along an axis.

Parameters:
  • a (ndarray) – Input data.

  • axis (int, optional) – Axis along which to operate. By default, flattened input is used.

  • out (ndarray, optional) – Alternative output array in which to place the result. Must be of the same shape and buffer length as the expected output. See doc.ufuncs (Section “Output arguments”) for more details.

  • keepdims (bool, optional) – If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original arr.

Returns:

min – Minimum of a. If axis is None, the result is an array of dimension 1. If axis is given, the result is an array of dimension a.ndim - 1.

Return type:

ndarray

See also

max

The maximum value of an array along a given axis, ignoring any nan.

minimum

Element-wise minimum of two arrays, ignoring any nan.

Notes

NaN in the orginal numpy is denoted as nan and will be ignored.

Don’t use min for element-wise comparison of 2 arrays; when a.shape[0] is 2, minimum(a[0], a[1]) is faster than min(a, axis=0).

Examples

>>> a = np.arange(4).reshape((2,2))
>>> a
array([[0., 1.],
    [2., 3.]])
>>> np.min(a)           # Minimum of the flattened array
array(0.)
>>> np.min(a, axis=0)   # Minima along the first axis
array([0., 1.])
>>> np.min(a, axis=1)   # Minima along the second axis
array([0., 2.])
>>> b = np.arange(5, dtype=np.float32)
>>> b[2] = np.nan
>>> np.min(b)
array(0.) # nan will be ignored
mxnet.numpy.multiarray.any(a, axis=None, out=None, keepdims=False)

Test whether any array element along a given axis evaluates to True. Returns single boolean unless axis is not None

Parameters:
  • a (ndarray) – Input array or object that can be converted to an array.

  • axis (None or int or tuple of ints, optional) – Axis or axes along which a logical AND reduction is performed. The default (axis = None) is to perform a logical AND over all the dimensions of the input array.

  • keepdims (bool, optional) – If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

  • out (ndarray, optional) – Alternate output array in which to place the result. It must have the same shape as the expected output and its type is preserved

Returns:

  • any (bool or ndarray) – A new boolean or ndarray is returned unless out is specified, in which case a reference to out is returned.

  • Examples

  • ———

  • >>> np.any([[True, False], [True, True]])

  • True

  • >>> np.any([[True, False], [False, False]], axis=0)

  • array([ True, False])

  • >>> np.any([-1, 0, 5])

  • True

  • >>> np.any(np.nan)

  • True

  • >>> o=np.array(False)

  • >>> z=np.any([-1, 4, 5], out=o)

  • >>> z, o

  • (array(True), array(True))

  • >>> # Check now that z is a reference to o

  • >>> z is o

  • True

  • >>> id(z), id(o) # identity of z and o # doctest (+SKIP)

  • (191614240, 191614240)

mxnet.numpy.multiarray.append(arr, values, axis=None)

Append values to the end of an array.

Parameters:
  • arr (ndarray) – Values are appended to a copy of this array.

  • values (ndarray) – These values are appended to a copy of arr. It must be of the correct shape (the same shape as arr, excluding axis). If axis is not specified, values can be any shape and will be flattened before use.

  • axis (int, optional) – The axis along which values are appended. If axis is not given, both arr and values are flattened before use.

Returns:

append – A copy of arr with values appended to axis. Note that append does not occur in-place: a new array is allocated and filled. If axis is None, out is a flattened array.

Return type:

ndarray

Examples

>>> np.append(np.array([1, 2, 3]), np.array([[4, 5, 6],[7, 8, 9]]))
array([1., 2., 3., 4., 5., 6., 7., 8., 9.])

When axis is specified, values must have the correct shape.

>>> np.append(np.array([[1, 2, 3], [4, 5, 6]]), np.array([[7, 8, 9]]), axis=0)
array([[1., 2., 3.],
       [4., 5., 6.],
       [7., 8., 9.]])
mxnet.numpy.multiarray.apply_along_axis(func1d, axis, arr, *args, **kwargs)

Apply a function to 1-D slices along the given axis.

Execute func1d(a, *args, **kwargs) where func1d operates on 1-D arrays and a is a 1-D slice of arr along axis.

This is equivalent to (but faster than) the following use of ndindex and s_, which sets each of ii, jj, and kk to a tuple of indices:

Ni, Nk = a.shape[:axis], a.shape[axis+1:]
for ii in ndindex(Ni):
    for kk in ndindex(Nk):
        f = func1d(arr[ii + s_[:,] + kk])
        Nj = f.shape
        for jj in ndindex(Nj):
            out[ii + jj + kk] = f[jj]

Equivalently, eliminating the inner loop, this can be expressed as:

Ni, Nk = a.shape[:axis], a.shape[axis+1:]
for ii in ndindex(Ni):
    for kk in ndindex(Nk):
        out[ii + s_[...,] + kk] = func1d(arr[ii + s_[:,] + kk])
Parameters:
  • func1d (function (M,) -> (Nj...)) – This function should accept 1-D arrays. It is applied to 1-D slices of arr along the specified axis.

  • axis (integer) – Axis along which arr is sliced.

  • arr (ndarray (Ni..., M, Nk...)) – Input array.

  • args (any) – Additional arguments to func1d.

  • kwargs (any) –

    Additional named arguments to func1d.

    Added in version 1.9.0.

Returns:

out – The output array. The shape of out is identical to the shape of arr, except along the axis dimension. This axis is removed, and replaced with new dimensions equal to the shape of the return value of func1d. So if func1d returns a scalar out will have one fewer dimensions than arr.

Return type:

ndarray (Ni…, Nj…, Nk…)

See also

apply_over_axes

Apply a function repeatedly over multiple axes.

Examples

>>> def my_func(a):
...     """Average first and last element of a 1-D array"""
...     return (a[0] + a[-1]) * 0.5
>>> b = np.array([[1,2,3], [4,5,6], [7,8,9]])
>>> np.apply_along_axis(my_func, 0, b)
array([4., 5., 6.])
>>> np.apply_along_axis(my_func, 1, b)
array([2.,  5.,  8.])

For a function that returns a 1D array, the number of dimensions in outarr is the same as arr.

>>> b = np.array([[8,1,7], [4,3,9], [5,2,6]])
>>> np.apply_along_axis(sorted, 1, b)
array([[1, 7, 8],
       [3, 4, 9],
       [2, 5, 6]])

For a function that returns a higher dimensional array, those dimensions are inserted in place of the axis dimension.

>>> b = np.array([[1,2,3], [4,5,6], [7,8,9]])
>>> np.apply_along_axis(np.diag, -1, b)
array([[[1, 0, 0],
        [0, 2, 0],
        [0, 0, 3]],
       [[4, 0, 0],
        [0, 5, 0],
        [0, 0, 6]],
       [[7, 0, 0],
        [0, 8, 0],
        [0, 0, 9]]])
mxnet.numpy.multiarray.apply_over_axes(func, a, axes)

Apply a function repeatedly over multiple axes.

func is called as res = func(a, axis), where axis is the first element of axes. The result res of the function call must have either the same dimensions as a or one less dimension. If res has one less dimension than a, a dimension is inserted before axis. The call to func is then repeated for each axis in axes, with res as the first argument.

Parameters:
  • func (function) – This function must take two arguments, func(a, axis).

  • a (array_like) – Input array.

  • axes (array_like) – Axes over which func is applied; the elements must be integers.

Returns:

apply_over_axis – The output array. The number of dimensions is the same as a, but the shape can be different. This depends on whether func changes the shape of its output with respect to its input.

Return type:

ndarray

See also

apply_along_axis

Apply a function to 1-D slices of an array along the given axis.

Notes

This function is equivalent to tuple axis arguments to reorderable ufuncs with keepdims=True. Tuple axis arguments to ufuncs have been available since version 1.7.0.

Examples

>>> a = np.arange(24).reshape(2,3,4)
>>> a
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]],
       [[12, 13, 14, 15],
        [16, 17, 18, 19],
        [20, 21, 22, 23]]])

Sum over axes 0 and 2. The result has same number of dimensions as the original array:

>>> np.apply_over_axes(np.sum, a, [0,2])
array([[[ 60],
        [ 92],
        [124]]])

Tuple axis arguments to ufuncs are equivalent:

>>> np.sum(a, axis=(0,2), keepdims=True)
array([[[ 60],
        [ 92],
        [124]]])
mxnet.numpy.multiarray.arange(start, stop=None, step=1, dtype=None, device=None)

Return evenly spaced values within a given interval.

Values are generated within the half-open interval [start, stop) (in other words, the interval including start but excluding stop). For integer arguments the function is equivalent to the Python built-in range function, but returns an ndarray rather than a list.

Parameters:
  • start (number, optional) – Start of interval. The interval includes this value. The default start value is 0.

  • stop (number) – End of interval. The interval does not include this value, except in some cases where step is not an integer and floating point round-off affects the length of out.

  • step (number, optional) – Spacing between values. For any output out, this is the distance between two adjacent values, out[i+1] - out[i]. The default step size is 1. If step is specified as a position argument, start must also be given.

  • dtype (dtype) – The type of the output array. Default dtype can be set to be consistent with offical numpy by npx.set_np(dtype=True). * When npx.is_np_default_dtype() returns False, default dtype is float32; * When npx.is_np_default_dtype() returns True, default dtype is int64.

  • device (device context, optional) – Device context on which the memory is allocated. Default is mxnet.device.current_device().

Returns:

arange – Array of evenly spaced values.

For floating point arguments, the length of the result is ceil((stop - start)/step). Because of floating point overflow, this rule may result in the last element of out being greater than stop.

Return type:

ndarray

Examples

>>> np.arange(3)
array([0., 1., 2.])
>>> np.arange(3.0)
array([0., 1., 2.])
>>> np.arange(3,7)
array([3., 4., 5., 6.])
>>> np.arange(3,7,2)
array([3., 5.])
>>> np.arange(3).dtype
dtype('float32')
>>> npx.set_np(dtype=True)
>>> np.arange(3).dtype
dtype('int64')
mxnet.numpy.multiarray.arccos(x, out=None, **kwargs)

Trigonometric inverse cosine, element-wise. The inverse of cos so that, if y = cos(x), then x = acos(y).

>>>np.acos is np.arccos True

Parameters:
  • x (ndarray) – x-coordinate on the unit circle. For real arguments, the domain is [-1, 1].

  • out (ndarray, optional) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.

Returns:

angle – The angle of the ray intersecting the unit circle at the given x-coordinate in radians [0, pi]. This is a scalar if x is a scalar.

Return type:

ndarray

Notes

acos is a alias for arccos. It is a standard API in https://data-apis.org/array-api/latest/API_specification/generated/signatures.elementwise_functions.acos.html instead of an official NumPy operator.

acos is a multivalued function: for each x there are infinitely many numbers z such that cos(z) = x. The convention is to return the angle z whose real part lies in [0, pi]. For real-valued input data types, acos always returns real output. For each value that cannot be expressed as a real number or infinity, it yields nan and sets the invalid floating point error flag. The inverse cos is also known as acos or cos^-1.

Examples

>>> np.acos([1, -1])
array([ 0.        ,  3.14159265])
mxnet.numpy.multiarray.arccosh(x, out=None, **kwargs)

Inverse hyperbolic cosine, element-wise.

>>>np.acosh is np.arccosh True

Parameters:
  • x (ndarray or scalar) – Input array.

  • out (ndarray or None, optional) – A location into which the result is stored.

Returns:

  • acosh (ndarray) – Array of the same shape as x. This is a scalar if x is a scalar.

  • .. note::acosh is a alias for arccosh. It is a standard API in https://data-apis.org/array-api/latest/API_specification/generated/signatures.elementwise_functions.acosh.html instead of an official NumPy operator.

    acosh is a multivalued function: for each x there are infinitely many numbers z such that cosh(z) = x.

    For real-valued input data types, acosh always returns real output. For each value that cannot be expressed as a real number or infinity, it yields nan and sets the invalid floating point error flag.

    This function differs from the original numpy.arccosh in the following aspects:

    • Do not support where, a parameter in numpy which indicates where to calculate.

    • Do not support complex-valued input.

    • Cannot cast type automatically. Dtype of out must be same as the expected one.

    • Cannot broadcast automatically. Shape of out must be same as the expected one.

    • If x is plain python numeric, the result won’t be stored in out.

Examples

>>> a = np.array([3.2, 5.0])
>>> np.acosh(a)
array([1.8309381, 2.2924316])
>>> np.acosh(1)
0.0
mxnet.numpy.multiarray.arcsin(x, out=None, **kwargs)

Inverse sine, element-wise.

>>>np.asin is np.asin True

Parameters:
  • x (ndarray or scalar) – y-coordinate on the unit circle.

  • out (ndarray or None, optional) – A location into which the result is stored. If provided, it must have the same shape as the input. If not provided or None, a freshly-allocated array is returned.

Returns:

angle – Output array is same shape and type as x. This is a scalar if x is a scalar. The inverse sine of each element in x, in radians and in the closed interval [-pi/2, pi/2].

Return type:

ndarray or scalar

Examples

>>> np.asin(1)     # pi/2
1.5707963267948966
>>> np.asin(-1)    # -pi/2
-1.5707963267948966
>>> np.asin(0)
0.0

Note

asin is a alias for arcsin. It is a standard API in https://data-apis.org/array-api/latest/API_specification/generated/signatures.elementwise_functions.asin.html instead of an official NumPy operator.

asin is a multivalued function: for each x there are infinitely many numbers z such that \(sin(z) = x\). The convention is to return the angle z whose real part lies in [-pi/2, pi/2]. For real-valued input data types, asin always returns real output. For each value that cannot be expressed as a real number or infinity, it yields nan and sets the invalid floating point error flag. The inverse sine is also known as asin or sin^{-1}. The output ndarray has the same ctx as the input ndarray. This function differs from the original numpy.arcsin in the following aspects:

  • Only support ndarray or scalar now.

  • where argument is not supported.

  • Complex input is not supported.

References

Abramowitz, M. and Stegun, I. A., Handbook of Mathematical Functions, 10th printing, New York: Dover, 1964, pp. 79ff. http://www.math.sfu.ca/~cbm/aands/

mxnet.numpy.multiarray.arcsinh(x, out=None, **kwargs)

Inverse hyperbolic cosine, element-wise.

>>>np.asinh is np.arcsinh True

Parameters:
  • x (ndarray or scalar) – Input array.

  • out (ndarray or None, optional) – A location into which the result is stored.

Returns:

  • asinh (ndarray) – Array of the same shape as x. This is a scalar if x is a scalar.

  • .. note::asinh is a alias for arcsinh. It is a standard API in https://data-apis.org/array-api/latest/API_specification/generated/signatures.elementwise_functions.asinh.html instead of an official NumPy operator.

    asinh is a multivalued function: for each x there are infinitely many numbers z such that sinh(z) = x.

    For real-valued input data types, asinh always returns real output. For each value that cannot be expressed as a real number or infinity, it yields nan and sets the invalid floating point error flag.

    This function differs from the original numpy.arcsinh in the following aspects:

    • Do not support where, a parameter in numpy which indicates where to calculate.

    • Do not support complex-valued input.

    • Cannot cast type automatically. DType of out must be same as the expected one.

    • Cannot broadcast automatically. Shape of out must be same as the expected one.

    • If x is plain python numeric, the result won’t be stored in out.

Examples

>>> a = np.array([3.2, 5.0])
>>> np.asinh(a)
array([1.8309381, 2.2924316])
>>> np.asinh(1)
0.0
mxnet.numpy.multiarray.arctan(x, out=None, **kwargs)

Trigonometric inverse tangent, element-wise. The inverse of tan, so that if y = tan(x) then x = atan(y).

>>>np.atan is np.arctan True

Parameters:
  • x (ndarray or scalar) – Input values.

  • out (ndarray or None, optional) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned.

Returns:

out – Out has the same shape as x. It lies is in [-pi/2, pi/2] (atan(+/-inf) returns +/-pi/2). This is a scalar if x is a scalar.

Return type:

ndarray or scalar

Notes

atan is a alias for arctan. It is a standard API in https://data-apis.org/array-api/latest/API_specification/generated/signatures.elementwise_functions.atan.html instead of an official NumPy operator.

atan is a multi-valued function: for each x there are infinitely many numbers z such that tan(z) = x. The convention is to return the angle z whose real part lies in [-pi/2, pi/2]. For real-valued input data types, atan always returns real output. For each value that cannot be expressed as a real number or infinity, it yields nan and sets the invalid floating point error flag. For complex-valued input, we do not have support for them yet. The inverse tangent is also known as atan or tan^{-1}.

Examples

>>> x = np.array([0, 1])
>>> np.atan(x)
array([0.       , 0.7853982])
>>> np.pi/4
0.7853981633974483
mxnet.numpy.multiarray.arctan2(x1, x2, out=None, **kwargs)

Element-wise arc tangent of x1/x2 choosing the quadrant correctly.

The quadrant (i.e., branch) is chosen so that atan2(x1, x2) is the signed angle in radians between the ray ending at the origin and passing through the point (1,0), and the ray ending at the origin and passing through the point (x2, x1). (Note the role reversal: the “y-coordinate” is the first function parameter, the “x-coordinate” is the second.) By IEEE convention, this function is defined for x2 = +/-0 and for either or both of x1 and x2 = +/-inf (see Notes for specific values).

This function is not defined for complex-valued arguments; for the so-called argument of complex values, use angle.

>>>np.atan2 is np.arctan2 True

Parameters:
  • x1 (ndarray or scalar) – y-coordinates.

  • x2 (ndarray or scalar) – x-coordinates. x2 must be broadcastable to match the shape of x1 or vice versa.

  • out (ndarray or None, optional) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned.

Returns:

  • out (ndarray or scalar) – Array of angles in radians, in the range [-pi, pi]. This is a scalar if x1 and x2 are scalars.

  • .. notes::atan2 is a alias for arctan2. It is a standard API in https://data-apis.org/array-api/latest/API_specification/generated/signatures.elementwise_functions.atan2.html instead of an official NumPy operator.

    atan2 is identical to the atan2 function of the underlying C library. The following special values are defined in the C standard: [1]_

    +========+========+==================+ | x1 | x2 | atan2(x1,x2) | +========+========+==================+ | +/- 0 | +0 | +/- 0 | +========+========+==================+ | +/- 0 | -0 | +/- pi | +========+========+==================+ | > 0 | +/-inf | +0 / +pi | +========+========+==================+ | < 0 | +/-inf | -0 / -pi | +========+========+==================+ | +/-inf | +inf | +/- (pi/4) | +========+========+==================+ | +/-inf | -inf | +/- (3*pi/4) | +========+========+==================+

    Note that +0 and -0 are distinct floating point numbers, as are +inf and -inf.

    This function differs from the original numpy.arange in the following aspects:

    • Only support float16, float32 and float64.

References

Examples

Consider four points in different quadrants:

>>> x = np.array([-1, +1, +1, -1])
>>> y = np.array([-1, -1, +1, +1])
>>> np.atan2(y, x) * 180 / np.pi
array([-135.,  -45.,   45.,  135.])

Note the order of the parameters. atan2 is defined also when x2 = 0 and at several other special points, obtaining values in the range [-pi, pi]:

>>> x = np.array([1, -1])
>>> y = np.array([0, 0])
>>> np.atan2(x, y)
array([ 1.5707964, -1.5707964])
mxnet.numpy.multiarray.arctanh(x, out=None, **kwargs)

Inverse hyperbolic tangent, element-wise.

>>>np.atanh is np.arctanh True

Parameters:
  • x (ndarray or scalar) – Input array.

  • out (ndarray or None, optional) – A location into which the result is stored.

Returns:

  • atanh (ndarray) – Array of the same shape as x. This is a scalar if x is a scalar.

  • .. note::atanh is a alias for arctanh. It is a standard API in https://data-apis.org/array-api/latest/API_specification/generated/signatures.elementwise_functions.atanh.html instead of an official NumPy operator.

    atanh is a multivalued function: for each x there are infinitely many numbers z such that tanh(z) = x.

    For real-valued input data types, atanh always returns real output. For each value that cannot be expressed as a real number or infinity, it yields nan and sets the invalid floating point error flag.

    This function differs from the original numpy.arctanh in the following aspects:

    • Do not support where, a parameter in numpy which indicates where to calculate.

    • Do not support complex-valued input.

    • Cannot cast type automatically. Dtype of out must be same as the expected one.

    • Cannot broadcast automatically. Shape of out must be same as the expected one.

    • If x is plain python numeric, the result won’t be stored in out.

Examples

>>> a = np.array([0.0, -0.5])
>>> np.atanh(a)
array([0., -0.54930615])
>>> np.atanh(1)
0.0
mxnet.numpy.multiarray.argmax(a, axis=None, out=None, keepdims=False)

Returns the indices of the maximum values along an axis.

Parameters:
  • a (ndarray) – Input array. Only support ndarrays of dtype float16, float32, and float64.

  • axis (int, optional) – By default, the index is into the flattened array, otherwise along the specified axis.

  • out (ndarray or None, optional) – If provided, the result will be inserted into this array. It should be of the appropriate shape and dtype.

  • keepdims (bool) – If True, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array. Otherwise, if False, the reduced axes (dimensions) must not be included in the result. Default: False .

Returns:

  • index_array (ndarray of indices whose dtype is same as the input ndarray.) – Array of indices into the array. It has the same shape as a.shape with the dimension along axis removed.

  • .. note::keepdims param is part of request in data-api-standard <https://data-apis.org/array-api/latest/API_specification/generated/signatures.searching_functions.argmax.html>`_, which is not the parameter in official NumPy

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

    This function differs from the original numpy.argmax in the following aspects:

    • Input type does not support Python native iterables(list, tuple, …).

    • out param: cannot perform auto broadcasting. out ndarray’s shape must be the same as the expected output.

    • out param: cannot perform auto type cast. out ndarray’s dtype must be the same as the expected output.

    • out param does not support scalar input case.

Examples

>>> a = np.arange(6).reshape(2,3) + 10
>>> a
array([[10., 11., 12.],
       [13., 14., 15.]])
>>> np.argmax(a)
array(5.)
>>> np.argmax(a, axis=0)
array([1., 1., 1.])
>>> np.argmax(a, axis=1)
array([2., 2.])
>>> b = np.arange(6)
>>> b[1] = 5
>>> b
array([0., 5., 2., 3., 4., 5.])
>>> np.argmax(b)  # Only the first occurrence is returned.
array(1.)

Specify out ndarray:

>>> a = np.arange(6).reshape(2,3) + 10
>>> b = np.zeros((2,))
>>> np.argmax(a, axis=1, out=b)
array([2., 2.])
>>> b
array([2., 2.])
mxnet.numpy.multiarray.argmin(a, axis=None, out=None, keepdims=False)

Returns the indices of the minimum values along an axis.

Parameters:
  • a (ndarray) – Input array. Only support ndarrays of dtype float16, float32, and float64.

  • axis (int, optional) – By default, the index is into the flattened array, otherwise along the specified axis.

  • out (ndarray or None, optional) – If provided, the result will be inserted into this array. It should be of the appropriate shape and dtype.

  • keepdims (bool) – If True, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array. Otherwise, if False, the reduced axes (dimensions) must not be included in the result. Default: False .

Returns:

  • index_array (ndarray of indices whose dtype is same as the input ndarray.) – Array of indices into the array. It has the same shape as a.shape with the dimension along axis removed.

  • .. note::keepdims param is part of request in data-api-standard <https://data-apis.org/array-api/latest/API_specification/generated/signatures.searching_functions.argmin.html>`_, which is not the parameter in official NumPy

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

    This function differs from the original numpy.argmin in the following aspects:

    • Input type does not support Python native iterables(list, tuple, …).

    • out param: cannot perform auto broadcasting. out ndarray’s shape must be the same as the expected output.

    • out param: cannot perform auto type cast. out ndarray’s dtype must be the same as the expected output.

    • out param does not support scalar input case.

Examples

>>> a = np.arange(6).reshape(2,3) + 10
>>> a
array([[10., 11., 12.],
       [13., 14., 15.]])
>>> np.argmin(a)
array(0.)
>>> np.argmin(a, axis=0)
array([0., 0., 0.])
>>> np.argmin(a, axis=1)
array([0., 0.])
>>> b = np.arange(6)
>>> b[2] = 0
>>> b
array([0., 1., 0., 3., 4., 5.])
>>> np.argmax(b)  # Only the first occurrence is returned.
array(0.)

Specify out ndarray:

>>> a = np.arange(6).reshape(2,3) + 10
>>> b = np.zeros((2,))
>>> np.argmin(a, axis=1, out=b)
array([0., 0.])
>>> b
array([0., 0.])
mxnet.numpy.multiarray.argpartition(a, kth, axis=-1, kind='introselect', order=None)

Perform an indirect partition along the given axis using the algorithm specified by the kind keyword. It returns an array of indices of the same shape as a that index data along the given axis in partitioned order.

Added in version 1.8.0.

Parameters:
  • a (array_like) – Array to sort.

  • kth (int or sequence of ints) –

    Element index to partition by. The k-th element will be in its final sorted position and all smaller elements will be moved before it and all larger elements behind it. The order of all elements in the partitions is undefined. If provided with a sequence of k-th it will partition all of them into their sorted position at once.

    Deprecated since version 1.22.0: Passing booleans as index is deprecated.

  • axis (int or None, optional) – Axis along which to sort. The default is -1 (the last axis). If None, the flattened array is used.

  • kind ({'introselect'}, optional) – Selection algorithm. Default is ‘introselect’

  • order (str or list of str, optional) – When a is an array with fields defined, this argument specifies which fields to compare first, second, etc. A single field can be specified as a string, and not all fields need be specified, but unspecified fields will still be used, in the order in which they come up in the dtype, to break ties.

Returns:

index_array – Array of indices that partition a along the specified axis. If a is one-dimensional, a[index_array] yields a partitioned a. More generally, np.take_along_axis(a, index_array, axis=axis) always yields the partitioned a, irrespective of dimensionality.

Return type:

ndarray, int

See also

partition

Describes partition algorithms used.

ndarray.partition

Inplace partition.

argsort

Full indirect sort.

take_along_axis

Apply index_array from argpartition to an array as if by calling partition.

Notes

See partition for notes on the different selection algorithms.

Examples

One dimensional array:

>>> x = np.array([3, 4, 2, 1])
>>> x[np.argpartition(x, 3)]
array([2, 1, 3, 4])
>>> x[np.argpartition(x, (1, 3))]
array([1, 2, 3, 4])
>>> x = [3, 4, 2, 1]
>>> np.array(x)[np.argpartition(x, 3)]
array([2, 1, 3, 4])

Multi-dimensional array:

>>> x = np.array([[3, 4, 2], [1, 3, 1]])
>>> index_array = np.argpartition(x, kth=1, axis=-1)
>>> np.take_along_axis(x, index_array, axis=-1)  # same as np.partition(x, kth=1)
array([[2, 3, 4],
       [1, 1, 3]])
mxnet.numpy.multiarray.argsort(a, axis=-1, descending=False, stable=True)

Returns the indices that sort an array x along a specified axis.

Notes

argsort is a standard API in https://data-apis.org/array-api/latest/API_specification/generated/signatures.sorting_functions.argsort.html instead of an official NumPy operator.

Parameters:
  • a (ndarray) – Array to sort.

  • axis (int or None, optional) – Axis along which to sort. The default is -1 (the last axis). If None, the flattened array is used.

  • descending (bool, optional) – sort order. If True, the returned indices sort x in descending order (by value). If False, the returned indices sort x in ascending order (by value).Default: False.

  • stable (bool, optional) – sort stability. If True, the returned indices must maintain the relative order of x values which compare as equal. If False, the returned indices may or may not maintain the relative order of x values which compare as equal. Default: True.

Returns:

index_array – Array of indices that sort a along the specified axis. If a is one-dimensional, a[index_array] yields a sorted a. More generally, np.take_along_axis(a, index_array, axis=axis) always yields the sorted a, irrespective of dimensionality.

Return type:

ndarray, int

Notes

This operator does not support different sorting algorithms.

Examples

One dimensional array:

>>> x = np.array([3, 1, 2])
>>> np.argsort(x)
array([1, 2, 0])

Two-dimensional array:

>>> x = np.array([[0, 3], [2, 2]])
>>> x
array([[0, 3],
       [2, 2]])
>>> ind = np.argsort(x, axis=0)  # sorts along first axis (down)
>>> ind
array([[0, 1],
       [1, 0]])
>>> np.take_along_axis(x, ind, axis=0)  # same as np.sort(x, axis=0)
array([[0, 2],
       [2, 3]])
>>> ind = np.argsort(x, axis=1)  # sorts along last axis (across)
>>> ind
array([[0, 1],
       [0, 1]])
>>> np.take_along_axis(x, ind, axis=1)  # same as np.sort(x, axis=1)
array([[0, 3],
       [2, 2]])

Indices of the sorted elements of a N-dimensional array:

>>> ind = np.unravel_index(np.argsort(x, axis=None), x.shape)
>>> ind
(array([0, 1, 1, 0]), array([0, 0, 1, 1]))
>>> x[ind]  # same as np.sort(x, axis=None)
array([0, 2, 2, 3])
mxnet.numpy.multiarray.argwhere(a)

Find the indices of array elements that are non-zero, grouped by element.

Parameters:

a (array_like) – Input data.

Returns:

index_array – Indices of elements that are non-zero. Indices are grouped by element. This array will have shape (N, a.ndim) where N is the number of non-zero items.

Return type:

(N, a.ndim) ndarray

See also

where, nonzero

Notes

np.argwhere(a) is almost the same as np.transpose(np.nonzero(a)), but produces a result of the correct shape for a 0D array.

The output of argwhere is not suitable for indexing arrays. For this purpose use nonzero(a) instead.

Examples

>>> x = np.arange(6).reshape(2,3)
>>> x
array([[0, 1, 2],
       [3, 4, 5]])
>>> np.argwhere(x>1)
array([[0, 2],
       [1, 0],
       [1, 1],
       [1, 2]])
mxnet.numpy.multiarray.around(x, decimals=0, out=None)

Evenly round to the given number of decimals.

Parameters:
  • x (ndarray or scalar) – Input data.

  • decimals (int, optional) – Number of decimal places to round to (default: 0). If decimals is negative, it specifies the number of positions to the left of the decimal point.

  • out (ndarray, optional) – Alternative output array in which to place the result. It must have the same shape and type as the expected output.

Returns:

  • rounded_array (ndarray or scalar) – An array of the same type as x, containing the rounded values. A reference to the result is returned.

  • .. note:: – For values exactly halfway between rounded decimal values, NumPy rounds to the nearest even value. Thus 1.5 and 2.5 round to 2.0, -0.5 and 0.5 round to 0.0, etc.

    This function differs from the original numpy.prod in the following aspects:

    • Cannot cast type automatically. Dtype of out must be same as the expected one.

    • Cannot support complex-valued number.

Examples

>>> np.around([0.37, 1.64])
array([ 0.,  2.])
>>> np.around([0.37, 1.64], decimals=1)
array([ 0.4,  1.6])
>>> np.around([.5, 1.5, 2.5, 3.5, 4.5]) # rounds to nearest even value
array([ 0.,  2.,  2.,  4.,  4.])
>>> np.around([1, 2, 3, 11], decimals=1) # ndarray of ints is returned
array([ 1,  2,  3, 11])
>>> np.around([1, 2, 3, 11], decimals=-1)
array([ 0,  0,  0, 10])
mxnet.numpy.multiarray.array(object, dtype=None, device=None)

Create an array.

Parameters:
  • object (array_like or numpy.ndarray or mxnet.numpy.ndarray) – An array, any object exposing the array interface, an object whose __array__ method returns an array, or any (nested) sequence.

  • dtype (data-type, optional) –

    The desired data-type for the array. The default dtype is object.dtype if object is an ndarray, float32 otherwise. Default dtype can be set to be consistent with offical numpy by npx.set_np(dtype=True).

    • When npx.is_np_default_dtype() returns False, default dtype is float32;

    • When npx.is_np_default_dtype() returns True, default dtype is float64.

  • device (Device, optional) – Device context on which the memory is allocated. Default is mxnet.device.current_device().

Returns:

out – An array object satisfying the specified requirements.

Return type:

ndarray

Examples

>>> np.array([1, 2, 3])
array([1., 2., 3.])
>>> np.array([[1, 2], [3, 4]])
array([[1., 2.],
       [3., 4.]])
>>> np.array([[1, 0], [0, 1]], dtype=bool)
array([[ True, False],
       [False,  True]])
>>> np.array([1, 2, 3]).dtype
dtype('float32')
>>> npx.set_np(dtype=True)
>>> np.array([1, 2, 3]).dtype
dtype('float64')
mxnet.numpy.multiarray.array_equal(a1, a2, equal_nan=False)

True if two arrays have the same shape and elements, False otherwise.

Parameters:
  • a1 (array_like) – Input arrays.

  • a2 (array_like) – Input arrays.

  • equal_nan (bool) –

    Whether to compare NaN’s as equal. If the dtype of a1 and a2 is complex, values will be considered equal if either the real or the imaginary component of a given value is nan.

    Added in version 1.19.0.

Returns:

b – Returns True if the arrays are equal.

Return type:

bool

See also

allclose

Returns True if two arrays are element-wise equal within a tolerance.

array_equiv

Returns True if input arrays are shape consistent and all elements equal.

Examples

>>> np.array_equal([1, 2], [1, 2])
True
>>> np.array_equal(np.array([1, 2]), np.array([1, 2]))
True
>>> np.array_equal([1, 2], [1, 2, 3])
False
>>> np.array_equal([1, 2], [1, 4])
False
>>> a = np.array([1, np.nan])
>>> np.array_equal(a, a)
False
>>> np.array_equal(a, a, equal_nan=True)
True

When equal_nan is True, complex values with nan components are considered equal if either the real or the imaginary components are nan.

>>> a = np.array([1 + 1j])
>>> b = a.copy()
>>> a.real = np.nan
>>> b.imag = np.nan
>>> np.array_equal(a, b, equal_nan=True)
True
mxnet.numpy.multiarray.array_equiv(a1, a2)

Returns True if input arrays are shape consistent and all elements equal.

Shape consistent means they are either the same shape, or one input array can be broadcasted to create the same shape as the other one.

Parameters:
  • a1 (array_like) – Input arrays.

  • a2 (array_like) – Input arrays.

Returns:

out – True if equivalent, False otherwise.

Return type:

bool

Examples

>>> np.array_equiv([1, 2], [1, 2])
True
>>> np.array_equiv([1, 2], [1, 3])
False

Showing the shape equivalence:

>>> np.array_equiv([1, 2], [[1, 2], [1, 2]])
True
>>> np.array_equiv([1, 2], [[1, 2, 1, 2], [1, 2, 1, 2]])
False
>>> np.array_equiv([1, 2], [[1, 2], [1, 3]])
False
mxnet.numpy.multiarray.array_split(ary, indices_or_sections, axis=0)

Split an array into multiple sub-arrays.

If indices_or_sections is an integer, N, the array will be divided into N equal arrays along axis. If such a split is not possible, an array of length l that should be split into n sections, it returns l % n sub-arrays of size l//n + 1 and the rest of size l//n.

If indices_or_sections is a 1-D array of sorted integers, the entries indicate where along axis the array is split. For example, [2, 3] would, for axis=0, result in * ary[:2] * ary[2:3] * ary[3:]

If an index exceeds the dimension of the array along axis, an empty sub-array is returned correspondingly.

Parameters:
  • ary (ndarray) – Array to be divided into sub-arrays.

  • indices_or_sections (int or 1-D Python tuple, list or set.) – Param used to determine the number and size of the subarray.

  • axis (int, optional) – The axis along which to split, default is 0.

Returns:

sub-arrays – A list of sub-arrays.

Return type:

list of ndarrays

Examples

>>> x = np.arange(9.0)
>>> np.array_split(x, 3)
[array([0., 1., 2.]), array([3., 4., 5.]), array([6., 7., 8.])]
>>> np.array_split(x, [3, 5, 6, 8])
[array([0., 1., 2.]), array([3., 4.]), array([5.]), array([6., 7.]), array([])]
>>> x = np.arange(8.0)
>>> np.array_split(x, 3)
[array([0.,  1.,  2.]), array([3.,  4.,  5.]), array([6.,  7.])]
>>> x = np.arange(7.0)
>>> np.array_split(x, 3)
[array([0.,  1.,  2.]), array([3.,  4.]), array([5.,  6.])]
mxnet.numpy.multiarray.asarray(obj, dtype=None, device=None, copy=None)

Convert the input to an array.

Parameters:
  • obj (<array>, bool, int, float, NestedSequence[ bool | int | float ]) – Object to be converted to an array. Can be a Python scalar, a (possibly nested) sequence of Python scalars, or an object supporting DLPack or the Python buffer protocol.

  • dtype (dtype, Optional) – output array data type. Default: None .

  • device (Device, optional) – Device context on which the memory is allocated. Default is mxnet.device.current_device().

  • copy (bool, Optional) –

    Whether or not to make a copy of the input. If True, always copies. If False, never copies for input which supports DLPack or the buffer protocol, and raises ValueError in case that would be necessary. If None, reuses existing memory buffer if possible, copies otherwise. Default: None .

    An array containing the data from obj.

Examples

>>> np.asarray([1, 2, 3])
array([1., 2., 3.])
>>> np.asarray([[1, 2], [3, 4]], dtype=np.int32)
array([[1, 2],
       [3, 4]], dtype=int32)
>>> np.asarray([1.2], device=mx.gpu())
array([1.2], device=gpu(0))
mxnet.numpy.multiarray.asin(x, out=None, **kwargs)

Inverse sine, element-wise.

>>>np.asin is np.asin True

Parameters:
  • x (ndarray or scalar) – y-coordinate on the unit circle.

  • out (ndarray or None, optional) – A location into which the result is stored. If provided, it must have the same shape as the input. If not provided or None, a freshly-allocated array is returned.

Returns:

angle – Output array is same shape and type as x. This is a scalar if x is a scalar. The inverse sine of each element in x, in radians and in the closed interval [-pi/2, pi/2].

Return type:

ndarray or scalar

Examples

>>> np.asin(1)     # pi/2
1.5707963267948966
>>> np.asin(-1)    # -pi/2
-1.5707963267948966
>>> np.asin(0)
0.0

Note

asin is a alias for arcsin. It is a standard API in https://data-apis.org/array-api/latest/API_specification/generated/signatures.elementwise_functions.asin.html instead of an official NumPy operator.

asin is a multivalued function: for each x there are infinitely many numbers z such that \(sin(z) = x\). The convention is to return the angle z whose real part lies in [-pi/2, pi/2]. For real-valued input data types, asin always returns real output. For each value that cannot be expressed as a real number or infinity, it yields nan and sets the invalid floating point error flag. The inverse sine is also known as asin or sin^{-1}. The output ndarray has the same ctx as the input ndarray. This function differs from the original numpy.arcsin in the following aspects:

  • Only support ndarray or scalar now.

  • where argument is not supported.

  • Complex input is not supported.

References

Abramowitz, M. and Stegun, I. A., Handbook of Mathematical Functions, 10th printing, New York: Dover, 1964, pp. 79ff. http://www.math.sfu.ca/~cbm/aands/

mxnet.numpy.multiarray.asinh(x, out=None, **kwargs)

Inverse hyperbolic cosine, element-wise.

>>>np.asinh is np.arcsinh True

Parameters:
  • x (ndarray or scalar) – Input array.

  • out (ndarray or None, optional) – A location into which the result is stored.

Returns:

  • asinh (ndarray) – Array of the same shape as x. This is a scalar if x is a scalar.

  • .. note::asinh is a alias for arcsinh. It is a standard API in https://data-apis.org/array-api/latest/API_specification/generated/signatures.elementwise_functions.asinh.html instead of an official NumPy operator.

    asinh is a multivalued function: for each x there are infinitely many numbers z such that sinh(z) = x.

    For real-valued input data types, asinh always returns real output. For each value that cannot be expressed as a real number or infinity, it yields nan and sets the invalid floating point error flag.

    This function differs from the original numpy.arcsinh in the following aspects:

    • Do not support where, a parameter in numpy which indicates where to calculate.

    • Do not support complex-valued input.

    • Cannot cast type automatically. DType of out must be same as the expected one.

    • Cannot broadcast automatically. Shape of out must be same as the expected one.

    • If x is plain python numeric, the result won’t be stored in out.

Examples

>>> a = np.array([3.2, 5.0])
>>> np.asinh(a)
array([1.8309381, 2.2924316])
>>> np.asinh(1)
0.0
mxnet.numpy.multiarray.atan(x, out=None, **kwargs)

Trigonometric inverse tangent, element-wise. The inverse of tan, so that if y = tan(x) then x = atan(y).

>>>np.atan is np.arctan True

Parameters:
  • x (ndarray or scalar) – Input values.

  • out (ndarray or None, optional) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned.

Returns:

out – Out has the same shape as x. It lies is in [-pi/2, pi/2] (atan(+/-inf) returns +/-pi/2). This is a scalar if x is a scalar.

Return type:

ndarray or scalar

Notes

atan is a alias for arctan. It is a standard API in https://data-apis.org/array-api/latest/API_specification/generated/signatures.elementwise_functions.atan.html instead of an official NumPy operator.

atan is a multi-valued function: for each x there are infinitely many numbers z such that tan(z) = x. The convention is to return the angle z whose real part lies in [-pi/2, pi/2]. For real-valued input data types, atan always returns real output. For each value that cannot be expressed as a real number or infinity, it yields nan and sets the invalid floating point error flag. For complex-valued input, we do not have support for them yet. The inverse tangent is also known as atan or tan^{-1}.

Examples

>>> x = np.array([0, 1])
>>> np.atan(x)
array([0.       , 0.7853982])
>>> np.pi/4
0.7853981633974483
mxnet.numpy.multiarray.atan2(x1, x2, out=None, **kwargs)

Element-wise arc tangent of x1/x2 choosing the quadrant correctly.

The quadrant (i.e., branch) is chosen so that atan2(x1, x2) is the signed angle in radians between the ray ending at the origin and passing through the point (1,0), and the ray ending at the origin and passing through the point (x2, x1). (Note the role reversal: the “y-coordinate” is the first function parameter, the “x-coordinate” is the second.) By IEEE convention, this function is defined for x2 = +/-0 and for either or both of x1 and x2 = +/-inf (see Notes for specific values).

This function is not defined for complex-valued arguments; for the so-called argument of complex values, use angle.

>>>np.atan2 is np.arctan2 True

Parameters:
  • x1 (ndarray or scalar) – y-coordinates.

  • x2 (ndarray or scalar) – x-coordinates. x2 must be broadcastable to match the shape of x1 or vice versa.

  • out (ndarray or None, optional) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned.

Returns:

  • out (ndarray or scalar) – Array of angles in radians, in the range [-pi, pi]. This is a scalar if x1 and x2 are scalars.

  • .. notes::atan2 is a alias for arctan2. It is a standard API in https://data-apis.org/array-api/latest/API_specification/generated/signatures.elementwise_functions.atan2.html instead of an official NumPy operator.

    atan2 is identical to the atan2 function of the underlying C library. The following special values are defined in the C standard: [1]_

    +========+========+==================+ | x1 | x2 | atan2(x1,x2) | +========+========+==================+ | +/- 0 | +0 | +/- 0 | +========+========+==================+ | +/- 0 | -0 | +/- pi | +========+========+==================+ | > 0 | +/-inf | +0 / +pi | +========+========+==================+ | < 0 | +/-inf | -0 / -pi | +========+========+==================+ | +/-inf | +inf | +/- (pi/4) | +========+========+==================+ | +/-inf | -inf | +/- (3*pi/4) | +========+========+==================+

    Note that +0 and -0 are distinct floating point numbers, as are +inf and -inf.

    This function differs from the original numpy.arange in the following aspects:

    • Only support float16, float32 and float64.

References

Examples

Consider four points in different quadrants:

>>> x = np.array([-1, +1, +1, -1])
>>> y = np.array([-1, -1, +1, +1])
>>> np.atan2(y, x) * 180 / np.pi
array([-135.,  -45.,   45.,  135.])

Note the order of the parameters. atan2 is defined also when x2 = 0 and at several other special points, obtaining values in the range [-pi, pi]:

>>> x = np.array([1, -1])
>>> y = np.array([0, 0])
>>> np.atan2(x, y)
array([ 1.5707964, -1.5707964])
mxnet.numpy.multiarray.atanh(x, out=None, **kwargs)

Inverse hyperbolic tangent, element-wise.

>>>np.atanh is np.arctanh True

Parameters:
  • x (ndarray or scalar) – Input array.

  • out (ndarray or None, optional) – A location into which the result is stored.

Returns:

  • atanh (ndarray) – Array of the same shape as x. This is a scalar if x is a scalar.

  • .. note::atanh is a alias for arctanh. It is a standard API in https://data-apis.org/array-api/latest/API_specification/generated/signatures.elementwise_functions.atanh.html instead of an official NumPy operator.

    atanh is a multivalued function: for each x there are infinitely many numbers z such that tanh(z) = x.

    For real-valued input data types, atanh always returns real output. For each value that cannot be expressed as a real number or infinity, it yields nan and sets the invalid floating point error flag.

    This function differs from the original numpy.arctanh in the following aspects:

    • Do not support where, a parameter in numpy which indicates where to calculate.

    • Do not support complex-valued input.

    • Cannot cast type automatically. Dtype of out must be same as the expected one.

    • Cannot broadcast automatically. Shape of out must be same as the expected one.

    • If x is plain python numeric, the result won’t be stored in out.

Examples

>>> a = np.array([0.0, -0.5])
>>> np.atanh(a)
array([0., -0.54930615])
>>> np.atanh(1)
0.0
mxnet.numpy.multiarray.atleast_1d(*arys)

Convert inputs to arrays with at least one dimension.

Scalar inputs are converted to 1-dimensional arrays, whilst higher-dimensional inputs are preserved.

Parameters:
  • arys1 (ndarray) – One or more input arrays.

  • arys2 (ndarray) – One or more input arrays.

  • ... (ndarray) – One or more input arrays.

Returns:

ret – An array, or list of arrays, each with a.ndim >= 1. Copies are made only if necessary.

Return type:

ndarray

Examples

>>> np.atleast_1d(1.0)
array([1.])
>>> x = np.arange(9.0).reshape(3,3)
>>> np.atleast_1d(x)
array([[0., 1., 2.],
       [3., 4., 5.],
       [6., 7., 8.]])
>>> np.atleast_1d(np.array(1), np.array([3, 4]))
[array([1.]), array([3., 4.])]
mxnet.numpy.multiarray.atleast_2d(*arys)

Convert inputs to arrays with at least two dimensions.

Parameters:
  • arys1 (ndarray) – One or more input arrays.

  • arys2 (ndarray) – One or more input arrays.

  • ... (ndarray) – One or more input arrays.

Returns:

ret – An array, or list of arrays, each with a.ndim >= 2. Copies are made only if necessary.

Return type:

ndarray

Examples

>>> np.atleast_2d(3.0)
array([[3.]])
>>> x = np.arange(3.0)
>>> np.atleast_2d(x)
array([[0., 1., 2.]])
>>> np.atleast_2d(np.array(1), np.array([1, 2]), np.array([[1, 2]]))
[array([[1.]]), array([[1., 2.]]), array([[1., 2.]])]
mxnet.numpy.multiarray.atleast_3d(*arys)

Convert inputs to arrays with at least three dimension.

Parameters:
  • arys1 (ndarray) – One or more input arrays.

  • arys2 (ndarray) – One or more input arrays.

  • ... (ndarray) – One or more input arrays.

Returns:

ret – An array, or list of arrays, each with a.ndim >= 3. For example, a 1-D array of shape (N,) becomes a view of shape (1, N, 1), and a 2-D array of shape (M, N) becomes a view of shape (M, N, 1).

Return type:

ndarray

Examples

>>> np.atleast_3d(3.0)
array([[[3.]]])
>>> x = np.arange(3.0)
>>> np.atleast_3d(x).shape
(1, 3, 1)
>>> x = np.arange(12.0).reshape(4,3)
>>> np.atleast_3d(x).shape
(4, 3, 1)
>>> for arr in np.atleast_3d(np.array([1, 2]), np.array([[1, 2]]), np.array([[[1, 2]]])):
...     print(arr, arr.shape)
...
[[[1.]
  [2.]]] (1, 2, 1)
[[[1.]
  [2.]]] (1, 2, 1)
[[[1. 2.]]] (1, 1, 2)
mxnet.numpy.multiarray.average(a, axis=None, weights=None, returned=False, out=None)

Compute the weighted average along the specified axis.

Parameters:
  • a (ndarray) – Array containing data to be averaged.

  • axis (None or int or tuple of ints, optional) – Axis or axes along which to average a. The default, axis=None, will average over all of the elements of the input array. If axis is negative it counts from the last to the first axis. New in version 1.7.0. If axis is a tuple of ints, averaging is performed on all of the axes specified in the tuple instead of a single axis or all the axes as before.

  • weights (ndarray, optional) – An array of weights associated with the values in a, must be the same dtype with a. Each value in a contributes to the average according to its associated weight. The weights array can either be 1-D (in which case its length must be the size of a along the given axis) or of the same shape as a. If weights=None, then all data in a are assumed to have a weight equal to one. The 1-D calculation is: avg = sum(a * weights) / sum(weights) The only constraint on weights is that sum(weights) must not be 0.

  • returned (bool, optional) – Default is False. If True, the tuple (average, sum_of_weights) is returned, otherwise only the average is returned. If weights=None, sum_of_weights is equivalent to the number of elements over which the average is taken.

  • out (ndarray, optional) – If provided, the calculation is done into this array.

Returns:

retval, [sum_of_weights] – Return the average along the specified axis. When returned is True, return a tuple with the average as the first element and the sum of the weights as the second element. sum_of_weights is of the same type as retval. If a is integral, the result dtype will be current default dtype, When npx.is_np_default_dtype() returns False, default dtype is float32, When npx.is_np_default_dtype() returns True, default dtype is float64; otherwise it will be the same as dtype of a.

Return type:

ndarray

Raises:
  • MXNetError

  • * When all weights along axis sum to zero.

  • * When the length of 1D weights is not the same as the shape of a along axis.

  • * When given 1D weights, the axis is not specified or is not int.

  • * When the shape of weights and a differ, but weights are not 1D.

Note

This function differs from the original numpy.average <https://numpy.org/devdocs/reference/generated/numpy.average.html>`_ in the following way(s):

  • Does not guarantee the same behavior with numpy when given float16 dtype and overflow happens

  • Does not support complex dtype

  • The dtypes of a and weights must be the same

  • Integral a results in float32 or float64 returned dtype:

    • When npx.is_np_default_dtype() returns False, default dtype is float32,

    • When npx.is_np_default_dtype() returns True, default dtype is float64;

Examples

>>> data = np.arange(1, 5)
>>> data
array([1., 2., 3., 4.])
>>> np.average(data)
array(2.5)
>>> np.average(np.arange(1, 11), weights=np.arange(10, 0, -1))
array(4.)
>>> data = np.arange(6).reshape((3,2))
>>> data
array([[0., 1.],
       [2., 3.],
       [4., 5.]])
>>> weights = np.array([0.25, 0.75])
array([0.25, 0.75])
>>> np.average(data, axis=1, weights=weights)
array([0.75, 2.75, 4.75])
mxnet.numpy.multiarray.bincount(x, weights=None, minlength=0)

Count number of occurrences of each value in array of non-negative ints.

Parameters:
  • x (ndarray) – input array, 1 dimension, nonnegative ints.

  • weights (ndarray) – input weigths same shape as x. (Optional)

  • minlength (int) – A minimum number of bins for the output. (Optional)

Returns:

out – the result of binning the input array. The length of out is equal to amax(x)+1.

Return type:

ndarray

Raises:
  • Value Error – If the input is not 1-dimensional, or contains elements with negative values, or if minlength is negative

  • TypeError – If the type of the input is float or complex.

Examples

>>> np.bincount(np.arange(5))
array([1, 1, 1, 1, 1])
>>> np.bincount(np.array([0, 1, 1, 3, 2, 1, 7]))
array([1, 3, 1, 1, 0, 0, 0, 1])
>>> x = np.array([0, 1, 1, 3, 2, 1, 7, 23])
>>> np.bincount(x).size == np.amax(x)+1
True
>>> np.bincount(np.arange(5, dtype=float))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: array cannot be safely cast to required type
>>> w = np.array([0.3, 0.5, 0.2, 0.7, 1., -0.6]) # weights
>>> x = np.array([0, 1, 1, 2, 2, 2])
>>> np.bincount(x,  weights=w)
array([ 0.3,  0.7,  1.1])
mxnet.numpy.multiarray.bitwise_and(x1, x2, out=None, **kwargs)

Compute the bit-wise XOR of two arrays element-wise.

Parameters:
  • x1 (ndarray or scalar) – Only integer and boolean types are handled. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • x2 (ndarray or scalar) – Only integer and boolean types are handled. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • out (ndarray, optional) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned.

Returns:

out – Result.

Return type:

ndarray

Examples

>>> np.bitwise_and(13, 17)
1
>>> np.bitwise_and(14, 13)
12
>>> np.bitwise_and(np.array([14,3], dtype='int32'), 13)
array([26,  5], dtype=int32)
>>> np.bitwise_and(np.array([11,7], dtype='int32'), np.array([4,25], dtype='int32'))
array([0, 1], dtype=int32)
>>> np.bitwise_and(np.array([2,5,255], dtype='int32'), np.array([3,14,16], dtype='int32'))
array([ 2,  4, 16], dtype=int32)
>>> np.bitwise_and(np.array([True, True], dtype='bool'), np.array([False, True], dtype='bool'))
array([False,  True])
mxnet.numpy.multiarray.bitwise_invert(x, out=None, **kwargs)

Compute bit-wise inversion, or bit-wise NOT, element-wise. Computes the bit-wise NOT of the underlying binary representation of the integers in the input arrays. This ufunc implements the C/Python operator ~.

Parameters:
  • x (array_like) – Only integer and boolean types are handled.

  • out (ndarray, None, or tuple of ndarray and None, optional) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.

Returns:

out – Result. This is a scalar if x is a scalar.

Return type:

ndarray or scalar

See also

bitwise_and, bitwise_or, bitwise_xor, logical_not

binary_repr

Return the binary representation of the input number as a string.

Examples

We’ve seen that 13 is represented by 00001101. The invert or bit-wise NOT of 13 is then:

>>> x = np.bitwise_invert(np.array(13, dtype=np.uint8))
>>> x
242
>>> np.binary_repr(x, width=8)
'11110010'

Notes

bitwise_not is an alias for invert:

>>> np.bitwise_not is np.invert
True
mxnet.numpy.multiarray.bitwise_left_shift(x1, x2, out=None)

Shift the bits of and integer to the left. Bits are shifted to the left by appending x2 0s at the right of x1. Since the internal representation of numbers is in binary format, this operation is equivalent to x1 * 2**x2

Parameters:
  • x1 (ndarray or scalar) – Input values.

  • x2 (ndarray or scalar) – Number of zeros to append to x1. Has to be non-negative. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • out (ndarray, optional) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned.

Returns:

out – Result.

Return type:

ndarray

Examples

>>> np.binary_repr(5)
'101'
>>> np.left_shift(5, 2)
20
>>> np.binary_repr(20)
'10100'
mxnet.numpy.multiarray.bitwise_not(x, out=None, **kwargs)

Compute bit-wise inversion, or bit-wise NOT, element-wise. Computes the bit-wise NOT of the underlying binary representation of the integers in the input arrays. This ufunc implements the C/Python operator ~.

Parameters:
  • x (array_like) – Only integer and boolean types are handled.

  • out (ndarray, None, or tuple of ndarray and None, optional) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.

Returns:

out – Result. This is a scalar if x is a scalar.

Return type:

ndarray or scalar

See also

bitwise_and, bitwise_or, bitwise_xor, logical_not

binary_repr

Return the binary representation of the input number as a string.

Examples

We’ve seen that 13 is represented by 00001101. The invert or bit-wise NOT of 13 is then:

>>> x = np.invert(np.array(13, dtype=np.uint8))
>>> x
242
>>> np.binary_repr(x, width=8)
'11110010'

Notes

bitwise_not is an alias for invert:

>>> np.bitwise_not is np.invert
True
mxnet.numpy.multiarray.bitwise_or(x1, x2, out=None, **kwargs)

Compute the bit-wise OR of two arrays element-wise.

Parameters:
  • x1 (ndarray or scalar) – Only integer and boolean types are handled. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • x2 (ndarray or scalar) – Only integer and boolean types are handled. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • out (ndarray, optional) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned.

Returns:

out – Result.

Return type:

ndarray

Examples

>>> np.bitwise_or(13, 17)
29
>>> np.bitwise_or(31, 5)
31
>>> np.bitwise_or(np.array([31,3], dtype=np.int32), 5)
array([31,  7])
>>> np.bitwise_or(np.array([31,3], dtype='int32'), np.array([5,6], dtype='int32'))
array([31,  7])
>>> np.bitwise_or(np.array([True, True], dtype='bool'), np.array([False, True], dtype='bool'))
array([ True, True])
mxnet.numpy.multiarray.bitwise_right_shift(x1, x2, out=None)

Shift the bits of and integer to the right. Bits are shifted to the right by x2. Because the internal representation of numbers is in binary format, this operation is equivalent to x1 / 2**x2

Parameters:
  • x1 (ndarray or scalar) – Input values.

  • x1 – Number of bits to remove at the right of x1. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • out (ndarray, optional) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned.

Returns:

out – Result.

Return type:

ndarray

Examples

>>> np.binary_repr(10)
'1010'
>>> np.right_shift(10, 1)
5
>>> np.binary_repr(5)
'101'
>>> np.right_shift(10, np.array([1,2,3]))
array([5, 2, 1])
mxnet.numpy.multiarray.bitwise_xor(x1, x2, out=None, **kwargs)

Compute the bit-wise XOR of two arrays element-wise.

Parameters:
  • x1 (ndarray or scalar) – Only integer and boolean types are handled. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • x2 (ndarray or scalar) – Only integer and boolean types are handled. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • out (ndarray, optional) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned.

Returns:

out – Result.

Return type:

ndarray

Examples

>>> np.bitwise_xor(13, 17)
28
>>> np.bitwise_xor(31, 5)
26
>>> np.bitwise_xor(np.array([31,3], dtype=np.int32), 5)
array([26,  6], dtype=int32)
>>> np.bitwise_xor(np.array([31,3], dtype='int32'), np.array([5,6], dtype='int32'))
array([26,  5], dtype=int32)
>>> np.bitwise_xor(np.array([True, True], dtype='bool'), np.array([False, True], dtype='bool'))
array([ True, False])
mxnet.numpy.multiarray.blackman(M, dtype=None, device=None)

Return the Blackman window.

The Blackman window is a taper formed by using the first three terms of a summation of cosines. It was designed to have close to the minimal leakage possible. It is close to optimal, only slightly worse than a Kaiser window.

Parameters:
  • M (int) – Number of points in the output window. If zero or less, an empty array is returned.

  • device (Device, optional) – Device context on which the memory is allocated. Default is mxnet.device.current_device().

Returns:

out – The window, with the maximum value normalized to one (the value one appears only if the number of samples is odd). When npx.is_np_default_dtype() returns False, default dtype is float32; When npx.is_np_default_dtype() returns True, default dtype is float64. Note that you need select numpy.float32 or float64 in this operator.

Return type:

ndarray

See also

hamming, hanning

Notes

The Blackman window is defined as

\[w(n) = 0.42 - 0.5 \cos(2\pi n/{M-1}) + 0.08 \cos(4\pi n/{M-1})\]

Most references to the Blackman window come from the signal processing literature, where it is used as one of many windowing functions for smoothing values. It is also known as an apodization (which means “removing the foot”, i.e. smoothing discontinuities at the beginning and end of the sampled signal) or tapering function. It is known as a “near optimal” tapering function, almost as good (by some measures) as the kaiser window.

References

Blackman, R.B. and Tukey, J.W., (1958) The measurement of power spectra, Dover Publications, New York.

Oppenheim, A.V., and R.W. Schafer. Discrete-Time Signal Processing. Upper Saddle River, NJ: Prentice-Hall, 1999, pp. 468-471.

Examples

>>> np.blackman(12)
array([-1.4901161e-08,  3.2606423e-02,  1.5990365e-01,  4.1439798e-01,
        7.3604530e-01,  9.6704686e-01,  9.6704674e-01,  7.3604506e-01,
        4.1439781e-01,  1.5990359e-01,  3.2606363e-02, -1.4901161e-08])

Plot the window and its frequency response:

>>> import matplotlib.pyplot as plt
>>> window = np.blackman(51)
>>> plt.plot(window.asnumpy())
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.title("blackman window")
Text(0.5, 1.0, 'blackman window')
>>> plt.ylabel("Amplitude")
Text(0, 0.5, 'Amplitude')
>>> plt.xlabel("Sample")
Text(0.5, 0, 'Sample')
>>> plt.show()
mxnet.numpy.multiarray.broadcast_to(array, shape)

Broadcast an array to a new shape.

Parameters:
  • array (ndarray or scalar) – The array to broadcast.

  • shape (tuple) – The shape of the desired array.

Returns:

broadcast – A readonly view on the original array with the given shape. It is typically not contiguous. Furthermore, more than one element of a broadcasted array may refer to a single memory location.

Return type:

array

Raises:

MXNetError – If the array is not compatible with the new shape according to NumPy’s broadcasting rules.

mxnet.numpy.multiarray.cbrt(x, out=None, **kwargs)

Return the cube-root of an array, element-wise.

Parameters:
  • x (ndarray) – The values whose cube-roots are required.

  • out (ndarray, optional) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.

Returns:

y – An array of the same shape as x, containing the cube cube-root of each element in x. If out was provided, y is a reference to it. This is a scalar if x is a scalar.

Return type:

ndarray

Examples

>>> np.cbrt([1,8,27])
array([ 1.,  2.,  3.])
mxnet.numpy.multiarray.ceil(x, out=None, **kwargs)

Return the ceiling of the input, element-wise. The ceil of the ndarray x is the smallest integer i, such that i >= x. It is often denoted as \(\lceil x \rceil\).

Parameters:
  • x (ndarray or scalar) – Input array.

  • out (ndarray or None) – A location into which the result is stored. If provided, it must have a shape that the inputs fill into. If not provided or None, a freshly-allocated array is returned. The dtype of the output and input must be the same.

Returns:

y – The ceiling of each element in x, with float dtype. This is a scalar if x is a scalar.

Return type:

ndarray or scalar

Examples

>>> a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0])
>>> np.ceil(a)
array([-1., -1., -0.,  1.,  2.,  2.,  2.])
>>> # if you use parameter out, x and out must be ndarray.
>>> a = np.array(1)
>>> np.ceil(np.array(3.5), a)
array(4.)
>>> a
array(4.)
mxnet.numpy.multiarray.choose(a, choices, out=None, mode='raise')

Construct an array from an index array and a list of arrays to choose from.

First of all, if confused or uncertain, definitely look at the Examples - in its full generality, this function is less simple than it might seem from the following code description (below ndi = numpy.lib.index_tricks):

np.choose(a,c) == np.array([c[a[I]][I] for I in ndi.ndindex(a.shape)]).

But this omits some subtleties. Here is a fully general summary:

Given an “index” array (a) of integers and a sequence of n arrays (choices), a and each choice array are first broadcast, as necessary, to arrays of a common shape; calling these Ba and Bchoices[i], i = 0,…,n-1 we have that, necessarily, Ba.shape == Bchoices[i].shape for each i. Then, a new array with shape Ba.shape is created as follows:

  • if mode='raise' (the default), then, first of all, each element of a (and thus Ba) must be in the range [0, n-1]; now, suppose that i (in that range) is the value at the (j0, j1, ..., jm) position in Ba - then the value at the same position in the new array is the value in Bchoices[i] at that same position;

  • if mode='wrap', values in a (and thus Ba) may be any (signed) integer; modular arithmetic is used to map integers outside the range [0, n-1] back into that range; and then the new array is constructed as above;

  • if mode='clip', values in a (and thus Ba) may be any (signed) integer; negative integers are mapped to 0; values greater than n-1 are mapped to n-1; and then the new array is constructed as above.

Parameters:
  • a (int array) – This array must contain integers in [0, n-1], where n is the number of choices, unless mode=wrap or mode=clip, in which cases any integers are permissible.

  • choices (sequence of arrays) – Choice arrays. a and all of the choices must be broadcastable to the same shape. If choices is itself an array (not recommended), then its outermost dimension (i.e., the one corresponding to choices.shape[0]) is taken as defining the “sequence”.

  • out (array, optional) – If provided, the result will be inserted into this array. It should be of the appropriate shape and dtype. Note that out is always buffered if mode='raise'; use other modes for better performance.

  • mode ({'raise' (default), 'wrap', 'clip'}, optional) –

    Specifies how indices outside [0, n-1] will be treated:

    • ’raise’ : an exception is raised

    • ’wrap’ : value becomes value mod n

    • ’clip’ : values < 0 are mapped to 0, values > n-1 are mapped to n-1

Returns:

merged_array – The merged result.

Return type:

array

Raises:

ValueError – shape mismatch: If a and each choice array are not all broadcastable to the same shape.

See also

ndarray.choose

equivalent method

numpy.take_along_axis

Preferable if choices is an array

Notes

To reduce the chance of misinterpretation, even though the following “abuse” is nominally supported, choices should neither be, nor be thought of as, a single array, i.e., the outermost sequence-like container should be either a list or a tuple.

Examples

>>> choices = [[0, 1, 2, 3], [10, 11, 12, 13],
...   [20, 21, 22, 23], [30, 31, 32, 33]]
>>> np.choose([2, 3, 1, 0], choices
... # the first element of the result will be the first element of the
... # third (2+1) "array" in choices, namely, 20; the second element
... # will be the second element of the fourth (3+1) choice array, i.e.,
... # 31, etc.
... )
array([20, 31, 12,  3])
>>> np.choose([2, 4, 1, 0], choices, mode='clip') # 4 goes to 3 (4-1)
array([20, 31, 12,  3])
>>> # because there are 4 choice arrays
>>> np.choose([2, 4, 1, 0], choices, mode='wrap') # 4 goes to (4 mod 4)
array([20,  1, 12,  3])
>>> # i.e., 0

A couple examples illustrating how choose broadcasts:

>>> a = [[1, 0, 1], [0, 1, 0], [1, 0, 1]]
>>> choices = [-10, 10]
>>> np.choose(a, choices)
array([[ 10, -10,  10],
       [-10,  10, -10],
       [ 10, -10,  10]])
>>> # With thanks to Anne Archibald
>>> a = np.array([0, 1]).reshape((2,1,1))
>>> c1 = np.array([1, 2, 3]).reshape((1,3,1))
>>> c2 = np.array([-1, -2, -3, -4, -5]).reshape((1,1,5))
>>> np.choose(a, (c1, c2)) # result is 2x3x5, res[0,:,:]=c1, res[1,:,:]=c2
array([[[ 1,  1,  1,  1,  1],
        [ 2,  2,  2,  2,  2],
        [ 3,  3,  3,  3,  3]],
       [[-1, -2, -3, -4, -5],
        [-1, -2, -3, -4, -5],
        [-1, -2, -3, -4, -5]]])
mxnet.numpy.multiarray.clip(a, a_min, a_max, out=None)

Clip (limit) the values in an array. Given an interval, values outside the interval are clipped to the interval edges. For example, if an interval of [0, 1] is specified, values smaller than 0 become 0, and values larger than 1 become 1.

Parameters:
  • a (ndarray) – Array containing elements to clip.

  • a_min (scalar or None) – Minimum value. If None, clipping is not performed on lower interval edge. Not more than one of a_min and a_max may be None.

  • a_max (scalar or None) – Maximum value. If None, clipping is not performed on upper interval edge. Not more than one of a_min and a_max may be None.

  • out (ndarray, optional) – The results will be placed in this array. It may be the input array for in-place clipping. out must be of the right shape to hold the output. Its type is preserved.

Returns:

clipped_array – An array with the elements of a, but where values < a_min are replaced with a_min, and those > a_max with a_max.

Return type:

ndarray

Notes

array_like a_min and a_max are not supported.

Examples

>>> a = np.arange(10)
>>> np.clip(a, 1, 8)
array([1., 1., 2., 3., 4., 5., 6., 7., 8., 8.])
>>> a
array([0., 1., 2., 3., 4., 5., 6., 7., 8., 9.])
>>> np.clip(a, 3, 6, out=a)
array([3., 3., 3., 3., 4., 5., 6., 6., 6., 6.])
mxnet.numpy.multiarray.column_stack(tup)

Stack 1-D arrays as columns into a 2-D array.

Take a sequence of 1-D arrays and stack them as columns to make a single 2-D array. 2-D arrays are stacked as-is, just like with hstack. 1-D arrays are turned into 2-D columns first.

Parameters:

tup (sequence of 1-D or 2-D arrays.) – Arrays to stack. All of them must have the same first dimension.

Returns:

stacked – The array formed by stacking the given arrays.

Return type:

2-D array

Examples

>>> a = np.array((1,2,3))
>>> b = np.array((2,3,4))
>>> np.column_stack((a,b))
array([[1., 2.],
       [2., 3.],
       [3., 4.]])
mxnet.numpy.multiarray.compress(condition, a, axis=None, out=None)

Return selected slices of an array along given axis.

When working along a given axis, a slice along that axis is returned in output for each index where condition evaluates to True. When working on a 1-D array, compress is equivalent to extract.

Parameters:
  • condition (1-D array of bools) – Array that selects which entries to return. If len(condition) is less than the size of a along the given axis, then output is truncated to the length of the condition array.

  • a (array_like) – Array from which to extract a part.

  • axis (int, optional) – Axis along which to take slices. If None (default), work on the flattened array.

  • out (ndarray, optional) – Output array. Its type is preserved and it must be of the right shape to hold the output.

Returns:

compressed_array – A copy of a without the slices along axis for which condition is false.

Return type:

ndarray

See also

take, choose, diag, diagonal, select

ndarray.compress

Equivalent method in ndarray

extract

Equivalent method when working on 1-D arrays

Output type determination

Examples

>>> a = np.array([[1, 2], [3, 4], [5, 6]])
>>> a
array([[1, 2],
       [3, 4],
       [5, 6]])
>>> np.compress([0, 1], a, axis=0)
array([[3, 4]])
>>> np.compress([False, True, True], a, axis=0)
array([[3, 4],
       [5, 6]])
>>> np.compress([False, True], a, axis=1)
array([[2],
       [4],
       [6]])

Working on the flattened array does not return slices along an axis but selects elements.

>>> np.compress([False, True], a)
array([2])
mxnet.numpy.multiarray.concat(seq, axis=0, out=None)

Join a sequence of arrays along an existing axis.

Parameters:
  • a1 (sequence of array_like) – The arrays must have the same shape, except in the dimension corresponding to axis (the first, by default).

  • a2 (sequence of array_like) – The arrays must have the same shape, except in the dimension corresponding to axis (the first, by default).

  • ... (sequence of array_like) – The arrays must have the same shape, except in the dimension corresponding to axis (the first, by default).

  • axis (int, optional) – The axis along which the arrays will be joined. If axis is None, arrays are flattened before use. Default is 0.

  • out (ndarray, optional) – If provided, the destination to place the result. The shape must be correct, matching that of what concatenate would have returned if no out argument were specified.

Returns:

res – The concatenated array.

Return type:

ndarray

Note

concate is a alias for concatante. It is a standard API in https://data-apis.org/array-api/latest/API_specification/manipulation_functions.html#concat-arrays-axis-0 instead of an official NumPy operator.

See also

split

Split array into a list of multiple sub-arrays of equal size.

hsplit

Split array into multiple sub-arrays horizontally (column wise)

vsplit

Split array into multiple sub-arrays vertically (row wise)

dsplit

Split array into multiple sub-arrays along the 3rd axis (depth).

stack

Stack a sequence of arrays along a new axis.

hstack

Stack arrays in sequence horizontally (column wise)

vstack

Stack arrays in sequence vertically (row wise)

dstack

Stack arrays in sequence depth wise (along third dimension)

Examples

>>> a = np.array([[1, 2], [3, 4]])
>>> b = np.array([[5, 6]])
>>> np.concat((a, b), axis=0)
array([[1., 2.],
       [3., 4.],
       [5., 6.]])
>>> np.concat((a, b.T), axis=1)
array([[1., 2., 5.],
       [3., 4., 6.]])
>>> np.concat((a, b), axis=None)
array([1., 2., 3., 4., 5., 6.])
mxnet.numpy.multiarray.concatenate(seq, axis=0, out=None)

Join a sequence of arrays along an existing axis.

Parameters:
  • a1 (sequence of array_like) – The arrays must have the same shape, except in the dimension corresponding to axis (the first, by default).

  • a2 (sequence of array_like) – The arrays must have the same shape, except in the dimension corresponding to axis (the first, by default).

  • ... (sequence of array_like) – The arrays must have the same shape, except in the dimension corresponding to axis (the first, by default).

  • axis (int, optional) – The axis along which the arrays will be joined. If axis is None, arrays are flattened before use. Default is 0.

  • out (ndarray, optional) – If provided, the destination to place the result. The shape must be correct, matching that of what concatenate would have returned if no out argument were specified.

Returns:

res – The concatenated array.

Return type:

ndarray

See also

split

Split array into a list of multiple sub-arrays of equal size.

hsplit

Split array into multiple sub-arrays horizontally (column wise)

vsplit

Split array into multiple sub-arrays vertically (row wise)

dsplit

Split array into multiple sub-arrays along the 3rd axis (depth).

stack

Stack a sequence of arrays along a new axis.

hstack

Stack arrays in sequence horizontally (column wise)

vstack

Stack arrays in sequence vertically (row wise)

dstack

Stack arrays in sequence depth wise (along third dimension)

Examples

>>> a = np.array([[1, 2], [3, 4]])
>>> b = np.array([[5, 6]])
>>> np.concatenate((a, b), axis=0)
array([[1., 2.],
       [3., 4.],
       [5., 6.]])
>>> np.concatenate((a, b.T), axis=1)
array([[1., 2., 5.],
       [3., 4., 6.]])
>>> np.concatenate((a, b), axis=None)
array([1., 2., 3., 4., 5., 6.])
mxnet.numpy.multiarray.copy(a, out=None)

Return an array copy of the given object.

Parameters:

a (_Symbol) – Input array.

Returns:

  • arr (_Symbol) – Array interpretation of a.

  • —–

Examples

>>> x = np.array([1, 2, 3])
>>> y = x
>>> z = np.copy(x)
>>> x[0] = 10
>>> x[0] == y[0]
    True
>>> x[0] == z[0]
    False
mxnet.numpy.multiarray.copysign(x1, x2, out=None, **kwargs)

Change the sign of x1 to that of x2, element-wise.

If x2 is a scalar, its sign will be copied to all elements of x1.

Parameters:
  • x1 (ndarray or scalar) – Values to change the sign of.

  • x2 (ndarray or scalar) – The sign of x2 is copied to x1.

  • out (ndarray or None, optional) – A location into which the result is stored. It must be of the right shape and right type to hold the output. If not provided or None,a freshly-allocated array is returned.

Returns:

  • out (ndarray or scalar) – The values of x1 with the sign of x2. This is a scalar if both x1 and x2 are scalars.

  • .. note:: – This function differs from the original numpy.copysign in the following aspects:

    • where param is not supported.

Examples

>>> np.copysign(1.3, -1)
-1.3
>>> 1/np.copysign(0, 1)
inf
>>> 1/np.copysign(0, -1)
-inf
>>> a = np.array([-1, 0, 1])
>>> np.copysign(a, -1.1)
array([-1., -0., -1.])
>>> np.copysign(a, np.arange(3)-1)
array([-1.,  0.,  1.])
mxnet.numpy.multiarray.corrcoef(x, y=None, rowvar=True, bias=<no value>, ddof=<no value>, *, dtype=None)

Return Pearson product-moment correlation coefficients.

Please refer to the documentation for cov for more detail. The relationship between the correlation coefficient matrix, R, and the covariance matrix, C, is

\[R_{ij} = \frac{ C_{ij} } { \sqrt{ C_{ii} C_{jj} } }\]

The values of R are between -1 and 1, inclusive.

Parameters:
  • x (array_like) – A 1-D or 2-D array containing multiple variables and observations. Each row of x represents a variable, and each column a single observation of all those variables. Also see rowvar below.

  • y (array_like, optional) – An additional set of variables and observations. y has the same shape as x.

  • rowvar (bool, optional) – If rowvar is True (default), then each row represents a variable, with observations in the columns. Otherwise, the relationship is transposed: each column represents a variable, while the rows contain observations.

  • bias (_NoValue, optional) –

    Has no effect, do not use.

    Deprecated since version 1.10.0.

  • ddof (_NoValue, optional) –

    Has no effect, do not use.

    Deprecated since version 1.10.0.

  • dtype (data-type, optional) –

    Data-type of the result. By default, the return data-type will have at least numpy.float64 precision.

    Added in version 1.20.

Returns:

R – The correlation coefficient matrix of the variables.

Return type:

ndarray

See also

cov

Covariance matrix

Notes

Due to floating point rounding the resulting array may not be Hermitian, the diagonal elements may not be 1, and the elements may not satisfy the inequality abs(a) <= 1. The real and imaginary parts are clipped to the interval [-1, 1] in an attempt to improve on that situation but is not much help in the complex case.

This function accepts but discards arguments bias and ddof. This is for backwards compatibility with previous versions of this function. These arguments had no effect on the return values of the function and can be safely ignored in this and previous versions of numpy.

Examples

In this example we generate two random arrays, xarr and yarr, and compute the row-wise and column-wise Pearson correlation coefficients, R. Since rowvar is true by default, we first find the row-wise Pearson correlation coefficients between the variables of xarr.

>>> import numpy as np
>>> rng = np.random.default_rng(seed=42)
>>> xarr = rng.random((3, 3))
>>> xarr
array([[0.77395605, 0.43887844, 0.85859792],
       [0.69736803, 0.09417735, 0.97562235],
       [0.7611397 , 0.78606431, 0.12811363]])
>>> R1 = np.corrcoef(xarr)
>>> R1
array([[ 1.        ,  0.99256089, -0.68080986],
       [ 0.99256089,  1.        , -0.76492172],
       [-0.68080986, -0.76492172,  1.        ]])

If we add another set of variables and observations yarr, we can compute the row-wise Pearson correlation coefficients between the variables in xarr and yarr.

>>> yarr = rng.random((3, 3))
>>> yarr
array([[0.45038594, 0.37079802, 0.92676499],
       [0.64386512, 0.82276161, 0.4434142 ],
       [0.22723872, 0.55458479, 0.06381726]])
>>> R2 = np.corrcoef(xarr, yarr)
>>> R2
array([[ 1.        ,  0.99256089, -0.68080986,  0.75008178, -0.934284  ,
        -0.99004057],
       [ 0.99256089,  1.        , -0.76492172,  0.82502011, -0.97074098,
        -0.99981569],
       [-0.68080986, -0.76492172,  1.        , -0.99507202,  0.89721355,
         0.77714685],
       [ 0.75008178,  0.82502011, -0.99507202,  1.        , -0.93657855,
        -0.83571711],
       [-0.934284  , -0.97074098,  0.89721355, -0.93657855,  1.        ,
         0.97517215],
       [-0.99004057, -0.99981569,  0.77714685, -0.83571711,  0.97517215,
         1.        ]])

Finally if we use the option rowvar=False, the columns are now being treated as the variables and we will find the column-wise Pearson correlation coefficients between variables in xarr and yarr.

>>> R3 = np.corrcoef(xarr, yarr, rowvar=False)
>>> R3
array([[ 1.        ,  0.77598074, -0.47458546, -0.75078643, -0.9665554 ,
         0.22423734],
       [ 0.77598074,  1.        , -0.92346708, -0.99923895, -0.58826587,
        -0.44069024],
       [-0.47458546, -0.92346708,  1.        ,  0.93773029,  0.23297648,
         0.75137473],
       [-0.75078643, -0.99923895,  0.93773029,  1.        ,  0.55627469,
         0.47536961],
       [-0.9665554 , -0.58826587,  0.23297648,  0.55627469,  1.        ,
        -0.46666491],
       [ 0.22423734, -0.44069024,  0.75137473,  0.47536961, -0.46666491,
         1.        ]])
mxnet.numpy.multiarray.correlate(a, v, mode='valid')

Cross-correlation of two 1-dimensional sequences.

This function computes the correlation as generally defined in signal processing texts:

\[c_k = \sum_n a_{n+k} \cdot \overline{v}_n\]

with a and v sequences being zero-padded where necessary and \(\overline x\) denoting complex conjugation.

Parameters:
  • a (array_like) – Input sequences.

  • v (array_like) – Input sequences.

  • mode ({'valid', 'same', 'full'}, optional) – Refer to the convolve docstring. Note that the default is ‘valid’, unlike convolve, which uses ‘full’.

  • old_behavior (bool) – old_behavior was removed in NumPy 1.10. If you need the old behavior, use multiarray.correlate.

Returns:

out – Discrete cross-correlation of a and v.

Return type:

ndarray

See also

convolve

Discrete, linear convolution of two one-dimensional sequences.

multiarray.correlate

Old, no conjugate, version of correlate.

scipy.signal.correlate

uses FFT which has superior performance on large arrays.

Notes

The definition of correlation above is not unique and sometimes correlation may be defined differently. Another common definition is:

\[c'_k = \sum_n a_{n} \cdot \overline{v_{n+k}}\]

which is related to \(c_k\) by \(c'_k = c_{-k}\).

numpy.correlate may perform slowly in large arrays (i.e. n = 1e5) because it does not use the FFT to compute the convolution; in that case, scipy.signal.correlate might be preferable.

Examples

>>> np.correlate([1, 2, 3], [0, 1, 0.5])
array([3.5])
>>> np.correlate([1, 2, 3], [0, 1, 0.5], "same")
array([2. ,  3.5,  3. ])
>>> np.correlate([1, 2, 3], [0, 1, 0.5], "full")
array([0.5,  2. ,  3.5,  3. ,  0. ])

Using complex sequences:

>>> np.correlate([1+1j, 2, 3-1j], [0, 1, 0.5j], 'full')
array([ 0.5-0.5j,  1.0+0.j ,  1.5-1.5j,  3.0-1.j ,  0.0+0.j ])

Note that you get the time reversed, complex conjugated result (\(\overline{c_{-k}}\)) when the two input sequences a and v change places:

>>> np.correlate([0, 1, 0.5j], [1+1j, 2, 3-1j], 'full')
array([ 0.0+0.j ,  3.0+1.j ,  1.5+1.5j,  1.0+0.j ,  0.5+0.5j])
mxnet.numpy.multiarray.cos(x, out=None, **kwargs)

Cosine, element-wise.

Parameters:
  • x (ndarray or scalar) – Angle, in radians (\(2 \pi\) rad equals 360 degrees).

  • out (ndarray or None) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. The dtype of the output is the same as that of the input if the input is an ndarray.

Returns:

y – The corresponding cosine values. This is a scalar if x is a scalar.

Return type:

ndarray or scalar

Notes

This function only supports input type of float.

Examples

>>> np.cos(np.array([0, np.pi/2, np.pi]))
array([ 1.000000e+00, -4.371139e-08, -1.000000e+00])
>>> # Example of providing the optional output parameter
>>> out1 = np.array([0], dtype='f')
>>> out2 = np.cos(np.array([0.1]), out1)
>>> out2 is out1
True
mxnet.numpy.multiarray.cosh(x, out=None, **kwargs)

Hyperbolic cosine, element-wise. Equivalent to 1/2 * (np.exp(x) + np.exp(-x)) and np.cos(1j*x).

Parameters:
  • x (ndarray or scalar) – Input array or scalar.

  • out (ndarray or None) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. The dtype of the output is the same as that of the input if the input is an ndarray.

Returns:

y – The corresponding hyperbolic cosine values. This is a scalar if x is a scalar.

Return type:

ndarray or scalar

Notes

This function only supports input type of float.

Examples

>>> np.cosh(0)
1.0
mxnet.numpy.multiarray.count_nonzero(a, axis=None, *, keepdims=False)

Counts the number of non-zero values in the array a.

The word “non-zero” is in reference to the Python 2.x built-in method __nonzero__() (renamed __bool__() in Python 3.x) of Python objects that tests an object’s “truthfulness”. For example, any number is considered truthful if it is nonzero, whereas any string is considered truthful if it is not the empty string. Thus, this function (recursively) counts how many elements in a (and in sub-arrays thereof) have their __nonzero__() or __bool__() method evaluated to True.

Parameters:
  • a (array_like) – The array for which to count non-zeros.

  • axis (int or tuple, optional) –

    Axis or tuple of axes along which to count non-zeros. Default is None, meaning that non-zeros will be counted along a flattened version of a.

    Added in version 1.12.0.

  • keepdims (bool, optional) –

    If this is set to True, the axes that are counted are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

    Added in version 1.19.0.

Returns:

count – Number of non-zero values in the array along a given axis. Otherwise, the total number of non-zero values in the array is returned.

Return type:

int or array of int

See also

nonzero

Return the coordinates of all the non-zero values.

Examples

>>> np.count_nonzero(np.eye(4))
4
>>> a = np.array([[0, 1, 7, 0],
...               [3, 0, 2, 19]])
>>> np.count_nonzero(a)
5
>>> np.count_nonzero(a, axis=0)
array([1, 1, 2, 1])
>>> np.count_nonzero(a, axis=1)
array([2, 3])
>>> np.count_nonzero(a, axis=1, keepdims=True)
array([[2],
       [3]])
mxnet.numpy.multiarray.cov(m, y=None, rowvar=True, bias=False, ddof=None, fweights=None, aweights=None, *, dtype=None)

Estimate a covariance matrix, given data and weights.

Covariance indicates the level to which two variables vary together. If we examine N-dimensional samples, \(X = [x_1, x_2, ... x_N]^T\), then the covariance matrix element \(C_{ij}\) is the covariance of \(x_i\) and \(x_j\). The element \(C_{ii}\) is the variance of \(x_i\).

See the notes for an outline of the algorithm.

Parameters:
  • m (array_like) – A 1-D or 2-D array containing multiple variables and observations. Each row of m represents a variable, and each column a single observation of all those variables. Also see rowvar below.

  • y (array_like, optional) – An additional set of variables and observations. y has the same form as that of m.

  • rowvar (bool, optional) – If rowvar is True (default), then each row represents a variable, with observations in the columns. Otherwise, the relationship is transposed: each column represents a variable, while the rows contain observations.

  • bias (bool, optional) – Default normalization (False) is by (N - 1), where N is the number of observations given (unbiased estimate). If bias is True, then normalization is by N. These values can be overridden by using the keyword ddof in numpy versions >= 1.5.

  • ddof (int, optional) –

    If not None the default value implied by bias is overridden. Note that ddof=1 will return the unbiased estimate, even if both fweights and aweights are specified, and ddof=0 will return the simple average. See the notes for the details. The default value is None.

    Added in version 1.5.

  • fweights (array_like, int, optional) –

    1-D array of integer frequency weights; the number of times each observation vector should be repeated.

    Added in version 1.10.

  • aweights (array_like, optional) –

    1-D array of observation vector weights. These relative weights are typically large for observations considered “important” and smaller for observations considered less “important”. If ddof=0 the array of weights can be used to assign probabilities to observation vectors.

    Added in version 1.10.

  • dtype (data-type, optional) –

    Data-type of the result. By default, the return data-type will have at least numpy.float64 precision.

    Added in version 1.20.

Returns:

out – The covariance matrix of the variables.

Return type:

ndarray

See also

corrcoef

Normalized covariance matrix

Notes

Assume that the observations are in the columns of the observation array m and let f = fweights and a = aweights for brevity. The steps to compute the weighted covariance are as follows:

>>> m = np.arange(10, dtype=np.float64)
>>> f = np.arange(10) * 2
>>> a = np.arange(10) ** 2.
>>> ddof = 1
>>> w = f * a
>>> v1 = np.sum(w)
>>> v2 = np.sum(w * a)
>>> m -= np.sum(m * w, axis=None, keepdims=True) / v1
>>> cov = np.dot(m * w, m.T) * v1 / (v1**2 - ddof * v2)

Note that when a == 1, the normalization factor v1 / (v1**2 - ddof * v2) goes over to 1 / (np.sum(f) - ddof) as it should.

Examples

Consider two variables, \(x_0\) and \(x_1\), which correlate perfectly, but in opposite directions:

>>> x = np.array([[0, 2], [1, 1], [2, 0]]).T
>>> x
array([[0, 1, 2],
       [2, 1, 0]])

Note how \(x_0\) increases while \(x_1\) decreases. The covariance matrix shows this clearly:

>>> np.cov(x)
array([[ 1., -1.],
       [-1.,  1.]])

Note that element \(C_{0,1}\), which shows the correlation between \(x_0\) and \(x_1\), is negative.

Further, note how x and y are combined:

>>> x = [-2.1, -1,  4.3]
>>> y = [3,  1.1,  0.12]
>>> X = np.stack((x, y), axis=0)
>>> np.cov(X)
array([[11.71      , -4.286     ], # may vary
       [-4.286     ,  2.144133]])
>>> np.cov(x, y)
array([[11.71      , -4.286     ], # may vary
       [-4.286     ,  2.144133]])
>>> np.cov(x)
array(11.71)
mxnet.numpy.multiarray.cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None)

Return the cross product of two (arrays of) vectors.

The cross product of a and b in \(R^3\) is a vector perpendicular to both a and b. If a and b are arrays of vectors, the vectors are defined by the last axis of a and b by default, and these axes can have dimensions 2 or 3. Where the dimension of either a or b is 2, the third component of the input vector is assumed to be zero and the cross product calculated accordingly. In cases where both input vectors have dimension 2, the z-component of the cross product is returned.

Parameters:
  • a (ndarray) – Components of the first vector(s).

  • b (ndarray) – Components of the second vector(s).

  • axisa (int, optional) – Axis of a that defines the vector(s). By default, the last axis.

  • axisb (int, optional) – Axis of b that defines the vector(s). By default, the last axis.

  • axisc (int, optional) – Axis of c containing the cross product vector(s). Ignored if both input vectors have dimension 2, as the return is scalar. By default, the last axis.

  • axis (int, optional) – If defined, the axis of a, b and c that defines the vector(s) and cross product(s). Overrides axisa, axisb and axisc.

Returns:

c – Vector cross product(s).

Return type:

ndarray

Raises:

ValueError – When the dimension of the vector(s) in a and/or b does not equal 2 or 3.

Notes

Supports full broadcasting of the inputs.

Examples

Vector cross-product.

>>> x = np.array([1., 2., 3.])
>>> y = np.array([4., 5., 6.])
>>> np.cross(x, y)
array([-3.,  6., -3.])

One vector with dimension 2.

>>> x = np.array([1., 2.])
>>> y = np.array([4., 5., 6.])
>>> np.cross(x, y)
array([12., -6., -3.])

Equivalently:

>>> x = np.array([1., 2., 0.])
>>> y = np.array([4., 5., 6.])
>>> np.cross(x, y)
array([12., -6., -3.])

Both vectors with dimension 2.

>>> x = np.array([1., 2.])
>>> y = np.array([4., 5.])
>>> np.cross(x, y)
array(-3.)

Multiple vector cross-products. Note that the direction of the cross product vector is defined by the right-hand rule.

>>> x = np.array([[1., 2., 3.], [4., 5., 6.]])
>>> y = np.array([[4., 5., 6.], [1., 2., 3.]])
>>> np.cross(x, y)
array([[-3.,  6., -3.],
       [ 3., -6.,  3.]])

The orientation of c can be changed using the axisc keyword.

>>> np.cross(x, y, axisc=0)
array([[-3.,  3.],
       [ 6., -6.],
       [-3.,  3.]])

Change the vector definition of x and y using axisa and axisb.

>>> x = np.array([[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]])
>>> y = np.array([[7., 8., 9.], [4., 5., 6.], [1., 2., 3.]])
>>> np.cross(x, y)
array([[ -6.,  12.,  -6.],
       [  0.,   0.,   0.],
       [  6., -12.,   6.]])
>>> np.cross(x, y, axisa=0, axisb=0)
array([[-24.,  48., -24.],
       [-30.,  60., -30.],
       [-36.,  72., -36.]])
mxnet.numpy.multiarray.cumprod(a, axis=None, dtype=None, out=None)

Return the cumulative product of elements along a given axis.

Parameters:
  • a (array_like) – Input array.

  • axis (int, optional) – Axis along which the cumulative product is computed. By default the input is flattened.

  • dtype (dtype, optional) – Type of the returned array, as well as of the accumulator in which the elements are multiplied. If dtype is not specified, it defaults to the dtype of a, unless a has an integer dtype with a precision less than that of the default platform integer. In that case, the default platform integer is used instead.

  • out (ndarray, optional) – Alternative output array in which to place the result. It must have the same shape and buffer length as the expected output but the type of the resulting values will be cast if necessary.

Returns:

cumprod – A new array holding the result is returned unless out is specified, in which case a reference to out is returned.

Return type:

ndarray

Notes

Arithmetic is modular when using integer types, and no error is raised on overflow.

Examples

>>> a = np.array([1,2,3])
>>> np.cumprod(a) # intermediate results 1, 1*2
...               # total product 1*2*3 = 6
array([1, 2, 6])
>>> a = np.array([[1, 2, 3], [4, 5, 6]])
>>> np.cumprod(a, dtype=float) # specify type of output
array([   1.,    2.,    6.,   24.,  120.,  720.])

The cumulative product for each column (i.e., over the rows) of a:

>>> np.cumprod(a, axis=0)
array([[ 1,  2,  3],
       [ 4, 10, 18]])

The cumulative product for each row (i.e. over the columns) of a:

>>> np.cumprod(a,axis=1)
array([[  1,   2,   6],
       [  4,  20, 120]])
mxnet.numpy.multiarray.cumsum(a, axis=None, dtype=None, out=None)

Return the cumulative sum of the elements along a given axis.

Parameters:
  • a (array_like) – Input array.

  • axis (int, optional) – Axis along which the cumulative sum is computed. The default (None) is to compute the cumsum over the flattened array.

  • dtype (dtype, optional) – Type of the returned array and of the accumulator in which the elements are summed. If dtype is not specified, it defaults to the dtype of a, unless a has an integer dtype with a precision less than that of the default platform integer. In that case, the default platform integer is used.

  • out (ndarray, optional) – Alternative output array in which to place the result. It must have the same shape and buffer length as the expected output but the type will be cast if necessary. See doc.ufuncs (Section “Output arguments”) for more details.

Returns:

cumsum_along_axis – A new array holding the result is returned unless out is specified, in which case a reference to out is returned. The result has the same size as a, and the same shape as a if axis is not None or a is a 1-d array.

Return type:

ndarray.

Examples

>>> a = np.array([[1,2,3], [4,5,6]])
>>> a
array([[1, 2, 3],
       [4, 5, 6]])
>>> np.cumsum(a)
array([ 1,  3,  6, 10, 15, 21])
>>> np.cumsum(a, dtype=float)     # specifies type of output value(s)
array([  1.,   3.,   6.,  10.,  15.,  21.])
>>> np.cumsum(a,axis=0)      # sum over rows for each of the 3 columns
array([[1, 2, 3],
       [5, 7, 9]])
>>> np.cumsum(a,axis=1)      # sum over columns for each of the 2 rows
array([[ 1,  3,  6],
       [ 4,  9, 15]])
mxnet.numpy.multiarray.deg2rad(x, out=None, **kwargs)

Convert angles from degrees to radians.

Parameters:
  • x (ndarray or scalar) – Angles in degrees.

  • out (ndarray or None, optional) – A location into which the result is stored. If not provided or None, a freshly-allocated array is returned.

Returns:

  • y (ndarray or scalar) – The corresponding angle in radians. This is a scalar if x is a scalar.

  • .. note:: – “deg2rad(x)” is “x * pi / 180”.

    This function differs from the original numpy.arange in the following aspects:

    • Only support float32 and float64.

    • out must be in the same size of input.

Examples

>>> np.deg2rad(180)
3.1415927
mxnet.numpy.multiarray.degrees(x, out=None, **kwargs)

Convert angles from radians to degrees.

Parameters:
  • x (ndarray) – Input value. Elements must be of real value.

  • out (ndarray or None, optional) – A location into which the result is stored. If provided, it must have the same shape and dtype as input ndarray. If not provided or None, a freshly-allocated array is returned.

Returns:

  • y (ndarray) – The corresponding degree values; if out was supplied this is a reference to it. This is a scalar if x is a scalar.

  • .. note:: – This function differs from the original numpy.degrees in the following aspects:

    • Input type does not support Python native iterables(list, tuple, …). Only ndarray is supported.

    • out param: cannot perform auto broadcasting. out ndarray’s shape must be the same as the expected output.

    • out param: cannot perform auto type cast. out ndarray’s dtype must be the same as the expected output.

    • out param does not support scalar input case.

Examples

>>> rad = np.arange(12.) * np.pi / 6
>>> np.degrees(rad)
array([  0.,  30.,  60.,  90., 120., 150., 180., 210., 240., 270., 300., 330.])
>>> # Use specified ``out`` ndarray:
>>> out = np.zeros((rad.shape))
>>> np.degrees(rad, out)
array([  0.,  30.,  60.,  90., 120., 150., 180., 210., 240., 270., 300., 330.])
>>> out
array([  0.,  30.,  60.,  90., 120., 150., 180., 210., 240., 270., 300., 330.])
mxnet.numpy.multiarray.delete(arr, obj, axis=None)

Return a new array with sub-arrays along an axis deleted. For a one dimensional array, this returns those entries not returned by arr[obj].

Parameters:
  • arr (ndarray) – Input array.

  • obj (slice, int or ndarray of ints) – Indicate indices of sub-arrays to remove along the specified axis.

  • axis (int, optional) – The axis along which to delete the subarray defined by obj. If axis is None, obj is applied to the flattened array.

Returns:

out – A copy of arr with the elements specified by obj removed. Note that delete does not occur in-place. If axis is None, out is a flattened array.

Return type:

ndarray

Examples

>>> arr = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
>>> arr
array([[ 1.,  2.,  3.,  4.],
       [ 5.,  6.,  7.,  8.],
       [ 9., 10., 11., 12.]])
>>> np.delete(arr, 1, 0)
array([[ 1.,  2.,  3.,  4.],
       [ 9., 10., 11., 12.]])
>>> np.delete(arr, slice(None, None, 2), 1)
array([[ 2.,  4.],
       [ 6.,  8.],
       [10., 12.]])
>>> np.delete(arr, np.array([1,3,5]), None)
array([ 1.,  3.,  5.,  7.,  8.,  9., 10., 11., 12.])
>>> np.delete(arr, np.array([1,1,5]), None)
array([ 1.,  3.,  4.,  5.,  7.,  8.,  9., 10., 11., 12.])
mxnet.numpy.multiarray.diag(array, k=0)

Extracts a diagonal or constructs a diagonal array. * 1-D arrays: constructs a 2-D array with the input as its diagonal, all other elements are zero. * 2-D arrays: extracts the k-th Diagonal

Parameters:
  • array (ndarray) – The array to apply diag method.

  • k (offset) – extracts or constructs kth diagonal given input array

Returns:

  • out (ndarray)

  • The extracted diagonal or constructed diagonal array.

Examples

>>> x = np.arange(9).reshape((3,3))
>>> x
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
>>> np.diag(x)
array([0, 4, 8])
>>> np.diag(x, k=1)
array([1, 5])
>>> np.diag(x, k=-1)
array([3, 7])
>>> np.diag(np.diag(x))
array([[0, 0, 0],
       [0, 4, 0],
       [0, 0, 8]])
mxnet.numpy.multiarray.diag_indices_from(arr)

This returns a tuple of indices that can be used to access the main diagonal of an array a with a.ndim >= 2 dimensions and shape (n, n, …, n). For a.ndim = 2 this is the usual diagonal, for a.ndim > 2 this is the set of indices to access a[i, i, …, i] for i = [0..n-1].

Parameters:
  • arr (ndarray) – Input array for acessing the main diagonal. All dimensions should have equal length.

  • Return

  • -------------

  • diag (tuple of ndarray) – indices of the main diagonal.

  • Examples

  • -------------

  • np.arange(16).reshape(4 (>>> a =)

  • 4)

  • a (>>>)

  • 0 (array([[) – [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]])

  • 1 – [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]])

  • 2 – [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]])

  • 3] – [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]])

:param[ 4, 5, 6, 7],

[ 8, 9, 10, 11], [12, 13, 14, 15]])

Parameters:
  • np.diag_indices_from(a) (>>> idx =)

  • idx (>>>)

  • (array([0

  • 1

  • 2

  • 3])

  • array([0

  • 1

  • 2

  • 3]))

  • 100 (>>> a[idx] =)

  • a (>>>)

  • array([[100 – [ 4, 100, 6, 7], [ 8, 9, 100, 11], [ 12, 13, 14, 100]])

  • 1 – [ 4, 100, 6, 7], [ 8, 9, 100, 11], [ 12, 13, 14, 100]])

  • 2 – [ 4, 100, 6, 7], [ 8, 9, 100, 11], [ 12, 13, 14, 100]])

  • 3] – [ 4, 100, 6, 7], [ 8, 9, 100, 11], [ 12, 13, 14, 100]])

:param[ 4, 100, 6, 7],

[ 8, 9, 100, 11], [ 12, 13, 14, 100]])

mxnet.numpy.multiarray.diagflat(array, k=0)

Create a two-dimensional array with the flattened input as a diagonal.

Parameters:
  • v (array_like) – Input data, which is flattened and set as the k-th diagonal of the output.

  • k (int, optional) – Diagonal to set; 0, the default, corresponds to the “main” diagonal, a positive (negative) k giving the number of the diagonal above (below) the main.

Returns:

out – The 2-D output array.

Return type:

ndarray

See also

diag

MATLAB work-alike for 1-D and 2-D arrays.

diagonal

Return specified diagonals.

trace

Sum along diagonals.

Examples

>>> np.diagflat([[1,2], [3,4]])
array([[1, 0, 0, 0],
       [0, 2, 0, 0],
       [0, 0, 3, 0],
       [0, 0, 0, 4]])
>>> np.diagflat([1,2], 1)
array([[0, 1, 0],
       [0, 0, 2],
       [0, 0, 0]])
mxnet.numpy.multiarray.diagonal(a, offset=0, axis1=0, axis2=1)

If a is 2-D, returns the diagonal of a with the given offset, i.e., the collection of elements of the form a[i, i+offset]. If a has more than two dimensions, then the axes specified by axis1 and axis2 are used to determine the 2-D sub-array whose diagonal is returned. The shape of the resulting array can be determined by removing axis1 and axis2 and appending an index to the right equal to the size of the resulting diagonals.

Parameters:
  • a (ndarray) – Input data from which diagonal are taken.

  • offset (int, Optional) – Offset of the diagonal from the main diagonal

  • axis1 (int, Optional) – Axis to be used as the first axis of the 2-D sub-arrays

  • axis2 (int, Optional) – Axis to be used as the second axis of the 2-D sub-arrays

Returns:

out – Output result

Return type:

ndarray

Raises:

ValueError – If the dimension of a is less than 2.:

Examples

>>> a = np.arange(4).reshape(2,2)
>>> a
array([[0, 1],
    [2, 3]])
>>> np.diagonal(a)
array([0, 3])
>>> np.diagonal(a, 1)
array([1])
>>> a = np.arange(8).reshape(2,2,2)
>>>a
array([[[0, 1],
        [2, 3]],
        [[4, 5],
        [6, 7]]])
>>> np.diagonal(a, 0, 0, 1)
array([[0, 6],
        [1, 7]])
mxnet.numpy.multiarray.diff(a, n=1, axis=-1, prepend=None, append=None)

Calculate the n-th discrete difference along the given axis.

Parameters:
  • a (ndarray) – Input array

  • n (int, optional) – The number of times values are differenced. If zero, the input is returned as-is.

  • axis (int, optional) – The axis along which the difference is taken, default is the last axis.

  • prepend (ndarray, optional) – Not supported yet

  • append (ndarray, optional) – Not supported yet

Returns:

diff – The n-th differences. The shape of the output is the same as a except along axis where the dimension is smaller by n. The type of the output is the same as the type of the difference between any two elements of a. This is the same as the type of a in most cases.

Return type:

ndarray

Examples

>>> x = np.array([1, 2, 4, 7, 0])
>>> np.diff(x)
array([ 1,  2,  3, -7])
>>> np.diff(x, n=2)
array([  1,   1, -10])
>>> x = np.array([[1, 3, 6, 10], [0, 5, 6, 8]])
>>> np.diff(x)
array([[2, 3, 4],
    [5, 1, 2]])
>>> np.diff(x, axis=0)
array([[-1,  2,  0, -2]])

Notes

Optional inputs prepend and append are not supported yet

mxnet.numpy.multiarray.digitize(x, bins, right=False)

Return the indices of the bins to which each value in input array belongs.

right

order of bins

returned index i satisfies

False

increasing

bins[i-1] <= x < bins[i]

True

increasing

bins[i-1] < x <= bins[i]

False

decreasing

bins[i-1] > x >= bins[i]

True

decreasing

bins[i-1] >= x > bins[i]

If values in x are beyond the bounds of bins, 0 or len(bins) is returned as appropriate.

Parameters:
  • x (array_like) – Input array to be binned. Prior to NumPy 1.10.0, this array had to be 1-dimensional, but can now have any shape.

  • bins (array_like) – Array of bins. It has to be 1-dimensional and monotonic.

  • right (bool, optional) – Indicating whether the intervals include the right or the left bin edge. Default behavior is (right==False) indicating that the interval does not include the right edge. The left bin end is open in this case, i.e., bins[i-1] <= x < bins[i] is the default behavior for monotonically increasing bins.

Returns:

indices – Output array of indices, of same shape as x.

Return type:

ndarray of ints

Raises:

Notes

If values in x are such that they fall outside the bin range, attempting to index bins with the indices that digitize returns will result in an IndexError.

Added in version 1.10.0.

np.digitize is implemented in terms of np.searchsorted. This means that a binary search is used to bin the values, which scales much better for larger number of bins than the previous linear search. It also removes the requirement for the input array to be 1-dimensional.

For monotonically _increasing_ bins, the following are equivalent:

np.digitize(x, bins, right=True)
np.searchsorted(bins, x, side='left')

Note that as the order of the arguments are reversed, the side must be too. The searchsorted call is marginally faster, as it does not do any monotonicity checks. Perhaps more importantly, it supports all dtypes.

Examples

>>> x = np.array([0.2, 6.4, 3.0, 1.6])
>>> bins = np.array([0.0, 1.0, 2.5, 4.0, 10.0])
>>> inds = np.digitize(x, bins)
>>> inds
array([1, 4, 3, 2])
>>> for n in range(x.size):
...   print(bins[inds[n]-1], "<=", x[n], "<", bins[inds[n]])
...
0.0 <= 0.2 < 1.0
4.0 <= 6.4 < 10.0
2.5 <= 3.0 < 4.0
1.0 <= 1.6 < 2.5
>>> x = np.array([1.2, 10.0, 12.4, 15.5, 20.])
>>> bins = np.array([0, 5, 10, 15, 20])
>>> np.digitize(x,bins,right=True)
array([1, 2, 3, 4, 4])
>>> np.digitize(x,bins,right=False)
array([1, 3, 3, 4, 5])
mxnet.numpy.multiarray.divide(x1, x2, out=None, **kwargs)

Returns a true division of the inputs, element-wise.

Note

This operator now supports automatic type promotion. The resulting type will be determined according to the following rules:

  • If both inputs are of floating number types, the output is the more precise type.

  • If only one of the inputs is floating number type, the result is that type.

  • If both inputs are of integer types including boolean, the output is of float32 or float64 type, which depends on your current default dtype:

    • When npx.is_np_default_dtype() returns False, default dtype is float32.

    • When npx.is_np_default_dtype() returns True, default dtype is float64.

Parameters:
  • x1 (ndarray or scalar) – Dividend array.

  • x2 (ndarray or scalar) – Divisor array.

  • out (ndarray) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned.

Returns:

out – This is a scalar if both x1 and x2 are scalars.

Return type:

ndarray or scalar

Examples

>>> np.true_divide(x, 4)
array([0.  , 0.25, 0.5 , 0.75, 1.  ])
mxnet.numpy.multiarray.divmod(x1, x2, [out1, out2, ]/, [out=(None, None), ]*, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])

Return element-wise quotient and remainder simultaneously.

Added in version 1.13.0.

np.divmod(x, y) is equivalent to (x // y, x % y), but faster because it avoids redundant work. It is used to implement the Python built-in function divmod on NumPy arrays.

Parameters:
  • x1 (array_like) – Dividend array.

  • x2 (array_like) – Divisor array. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • out (ndarray, None, or tuple of ndarray and None, optional) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.

  • where (array_like, optional) – This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.

Returns:

  • out1 (ndarray) – Element-wise quotient resulting from floor division. This is a scalar if both x1 and x2 are scalars.

  • out2 (ndarray) – Element-wise remainder from floor division. This is a scalar if both x1 and x2 are scalars.

See also

floor_divide

Equivalent to Python’s // operator.

remainder

Equivalent to Python’s % operator.

modf

Equivalent to divmod(x, 1) for positive x with the return values switched.

Examples

>>> np.divmod(np.arange(5), 3)
(array([0, 0, 0, 1, 1]), array([0, 1, 2, 0, 1]))

The divmod function can be used as a shorthand for np.divmod on ndarrays.

>>> x = np.arange(5)
>>> divmod(x, 3)
(array([0, 0, 0, 1, 1]), array([0, 1, 2, 0, 1]))
mxnet.numpy.multiarray.dot(a, b, out=None)

Dot product of two arrays. Specifically,

  • If both a and b are 1-D arrays, it is inner product of vectors

  • If both a and b are 2-D arrays, it is matrix multiplication,

  • If either a or b is 0-D (scalar), it is equivalent to multiply() and using np.multiply(a, b) or a * b is preferred.

  • If a is an N-D array and b is a 1-D array, it is a sum product over the last axis of a and b.

  • If a is an N-D array and b is a 2-D array, it is a sum product over the last axis of a and the second-to-last axis of b:

    dot(a, b)[i,j,k] = sum(a[i,j,:] * b[:,k])
    
Parameters:
  • a (ndarray) – First argument.

  • b (ndarray) – Second argument.

  • out (ndarray, optional) – Output argument. It must have the same shape and type as the expected output.

Returns:

output – Returns the dot product of a and b. If a and b are both scalars or both 1-D arrays then a scalar is returned; otherwise an array is returned. If out is given, then it is returned

Return type:

ndarray

Examples

>>> a = np.array(3)
>>> b = np.array(4)
>>> np.dot(a, b)
array(12.)

For 2-D arrays it is the matrix product:

>>> a = np.array([[1, 0], [0, 1]])
>>> b = np.array([[4, 1], [2, 2]])
>>> np.dot(a, b)
array([[4., 1.],
       [2., 2.]])
>>> a = np.arange(3*4*5*6).reshape((3,4,5,6))
>>> b = np.arange(5*6)[::-1].reshape((6,5))
>>> np.dot(a, b)[2,3,2,2]
array(29884.)
>>> np.sum(a[2,3,2,:] * b[:,2])
array(29884.)
mxnet.numpy.multiarray.dsplit(ary, indices_or_sections)

Split array into multiple sub-arrays along the 3rd axis (depth). Please refer to the split documentation. dsplit is equivalent to split with axis=2, the array is always split along the third axis provided the array dimension is greater than or equal to 3.

Parameters:
  • ary (ndarray) – Array to be divided into sub-arrays.

  • indices_or_sections (int or 1 - D Python tuple, list or set.) –

    If indices_or_sections is an integer, N, the array will be divided into N equal arrays along axis 2. If such a split is not possible, an error is raised.

    If indices_or_sections is a 1-D array of sorted integers, the entries indicate where along axis 2 the array is split. For example, [2, 3] would result in

    • ary[:, :, :2]

    • ary[:, :, 2:3]

    • ary[:, :, 3:]

    If an index exceeds the dimension of the array along axis 2, an error will be thrown.

Returns:

sub-arrays – A list of sub-arrays.

Return type:

list of ndarrays

See also

split

Split an array into multiple sub-arrays of equal size.

This function differs from the original numpy.dsplit in the following aspects: * Currently parameter indices_or_sections does not support ndarray, but supports scalar, tuple and list. * In indices_or_sections, if an index exceeds the dimension of the array along axis 2, an error will be thrown.

Examples

>>> x = np.arange(16.0).reshape(2, 2, 4)
>>> x
array([[[ 0.,   1.,   2.,   3.],
        [ 4.,   5.,   6.,   7.]],
       [[ 8.,   9.,  10.,  11.],
        [12.,  13.,  14.,  15.]]])
>>> np.dsplit(x, 2)
[array([[[ 0.,  1.],
        [ 4.,  5.]],
       [[ 8.,  9.],
        [12., 13.]]]), array([[[ 2.,  3.],
        [ 6.,  7.]],
       [[10., 11.],
        [14., 15.]]])]
>>> np.dsplit(x, np.array([3, 6]))
[array([[[ 0.,   1.,   2.],
        [ 4.,   5.,   6.]],
       [[ 8.,   9.,  10.],
        [12.,  13.,  14.]]]),
 array([[[ 3.],
        [ 7.]],
       [[11.],
        [15.]]]),
array([], shape=(2, 2, 0), dtype=float64)]
mxnet.numpy.multiarray.dstack(arrays)

Stack arrays in sequence depth wise (along third axis).

This is equivalent to concatenation along the third axis after 2-D arrays of shape (M,N) have been reshaped to (M,N,1) and 1-D arrays of shape (N,) have been reshaped to (1,N,1). Rebuilds arrays divided by dsplit.

This function makes most sense for arrays with up to 3 dimensions. For instance, for pixel-data with a height (first axis), width (second axis), and r/g/b channels (third axis). The functions concatenate, stack and block provide more general stacking and concatenation operations.

Parameters:

tup (sequence of arrays) – The arrays must have the same shape along all but the third axis. 1-D or 2-D arrays must have the same shape.

Returns:

stacked – The array formed by stacking the given arrays, will be at least 3-D.

Return type:

ndarray

Examples

>>> a = np.array((1,2,3))
>>> b = np.array((2,3,4))
>>> np.dstack((a,b))
array([[[1, 2],
        [2, 3],
        [3, 4]]])
>>> a = np.array([[1],[2],[3]])
>>> b = np.array([[2],[3],[4]])
>>> np.dstack((a,b))
array([[[1, 2]],
       [[2, 3]],
       [[3, 4]]])
mxnet.numpy.multiarray.dtype(dtype, align=False, copy=False[, metadata])

Create a data type object.

A numpy array is homogeneous, and contains elements described by a dtype object. A dtype object can be constructed from different combinations of fundamental numeric types.

Parameters:
  • dtype – Object to be converted to a data type object.

  • align (bool, optional) – Add padding to the fields to match what a C compiler would output for a similar C-struct. Can be True only if obj is a dictionary or a comma-separated string. If a struct dtype is being created, this also sets a sticky alignment flag isalignedstruct.

  • copy (bool, optional) – Make a new copy of the data-type object. If False, the result may just be a reference to a built-in data-type object.

  • metadata (dict, optional) – An optional dictionary with dtype metadata.

See also

result_type

Examples

Using array-scalar type:

>>> np.dtype(np.int16)
dtype('int16')

Structured type, one field name ‘f1’, containing int16:

>>> np.dtype([('f1', np.int16)])
dtype([('f1', '<i2')])

Structured type, one field named ‘f1’, in itself containing a structured type with one field:

>>> np.dtype([('f1', [('f1', np.int16)])])
dtype([('f1', [('f1', '<i2')])])

Structured type, two fields: the first field contains an unsigned int, the second an int32:

>>> np.dtype([('f1', np.uint64), ('f2', np.int32)])
dtype([('f1', '<u8'), ('f2', '<i4')])

Using array-protocol type strings:

>>> np.dtype([('a','f8'),('b','S10')])
dtype([('a', '<f8'), ('b', 'S10')])

Using comma-separated field formats. The shape is (2,3):

>>> np.dtype("i4, (2,3)f8")
dtype([('f0', '<i4'), ('f1', '<f8', (2, 3))])

Using tuples. int is a fixed type, 3 the field’s shape. void is a flexible type, here of size 10:

>>> np.dtype([('hello',(np.int64,3)),('world',np.void,10)])
dtype([('hello', '<i8', (3,)), ('world', 'V10')])

Subdivide int16 into 2 int8’s, called x and y. 0 and 1 are the offsets in bytes:

>>> np.dtype((np.int16, {'x':(np.int8,0), 'y':(np.int8,1)}))
dtype((numpy.int16, [('x', 'i1'), ('y', 'i1')]))

Using dictionaries. Two fields named ‘gender’ and ‘age’:

>>> np.dtype({'names':['gender','age'], 'formats':['S1',np.uint8]})
dtype([('gender', 'S1'), ('age', 'u1')])

Offsets in bytes, here 0 and 25:

>>> np.dtype({'surname':('S25',0),'age':(np.uint8,25)})
dtype([('surname', 'S25'), ('age', 'u1')])
mxnet.numpy.multiarray.ediff1d(ary, to_end=None, to_begin=None)

The differences between consecutive elements of an array.

Parameters:
  • ary (ndarray) – If necessary, will be flattened before the differences are taken.

  • to_end (ndarray or scalar, optional) – Number(s) to append at the end of the returned differences.

  • to_begin (ndarray or scalar, optional) – Number(s) to prepend at the beginning of the returned differences.

Returns:

ediff1d – The differences. Loosely, this is ary.flat[1:] - ary.flat[:-1].

Return type:

ndarray

Examples

>>> x = np.array([1, 2, 4, 7, 0])
>>> np.ediff1d(x)
array([ 1.,  2.,  3., -7.])
>>> np.ediff1d(x, to_begin=-99, to_end=np.array([88, 99]))
rray([-99.,   1.,   2.,   3.,  -7.,  88.,  99.])

The returned array is always 1D.

>>> y = np.array([[1, 2, 4], [1, 6, 24]])
>>> np.ediff1d(y)
array([ 1.,  2., -3.,  5., 18.])
>>> np.ediff1d(x, to_begin=y)
array([ 1.,  2.,  4.,  1.,  6., 24.,  1.,  2.,  3., -7.])
mxnet.numpy.multiarray.einsum(subscripts, *operands, out=None, optimize=False)

Evaluates the Einstein summation convention on the operands.

Using the Einstein summation convention, many common multi-dimensional, linear algebraic array operations can be represented in a simple fashion. In implicit mode einsum computes these values.

In explicit mode, einsum provides further flexibility to compute other array operations that might not be considered classical Einstein summation operations, by disabling, or forcing summation over specified subscript labels.

See the notes and examples for clarification.

Parameters:
  • subscripts (str) – Specifies the subscripts for summation as comma separated list of subscript labels. An implicit (classical Einstein summation) calculation is performed unless the explicit indicator ‘->’ is included as well as subscript labels of the precise output form.

  • operands (list of ndarray) – These are the arrays for the operation.

  • out (ndarray, optional) – If provided, the calculation is done into this array.

  • optimize ({False, True}, optional) – Controls if intermediate optimization should occur. No optimization will occur if False. Defaults to False.

Returns:

output – The calculation based on the Einstein summation convention.

Return type:

ndarray

Notes

The Einstein summation convention can be used to compute many multi-dimensional, linear algebraic array operations. einsum provides a succinct way of representing these.

A non-exhaustive list of these operations, which can be computed by einsum, is shown below along with examples:

  • Trace of an array, np.trace().

  • Return a diagonal, np.diag().

  • Array axis summations, np.sum().

  • Transpositions and permutations, np.transpose().

  • Matrix multiplication and dot product, np.matmul() np.dot().

  • Vector inner and outer products, np.inner() np.outer().

  • Broadcasting, element-wise and scalar multiplication, np.multiply().

  • Tensor contractions, np.tensordot().

The subscripts string is a comma-separated list of subscript labels, where each label refers to a dimension of the corresponding operand. Whenever a label is repeated it is summed, so np.einsum('i,i', a, b) is equivalent to np.inner(a,b). If a label appears only once, it is not summed, so np.einsum('i', a) produces a view of a with no changes. A further example np.einsum('ij,jk', a, b) describes traditional matrix multiplication and is equivalent to np.matmul(a,b). Repeated subscript labels in one operand take the diagonal. For example, np.einsum('ii', a) is equivalent to np.trace(a).

In implicit mode, the chosen subscripts are important since the axes of the output are reordered alphabetically. This means that np.einsum('ij', a) doesn’t affect a 2D array, while np.einsum('ji', a) takes its transpose. Additionally, np.einsum('ij,jk', a, b) returns a matrix multiplication, while, np.einsum('ij,jh', a, b) returns the transpose of the multiplication since subscript ‘h’ precedes subscript ‘i’.

In explicit mode the output can be directly controlled by specifying output subscript labels. This requires the identifier ‘->’ as well as the list of output subscript labels. This feature increases the flexibility of the function since summing can be disabled or forced when required. The call np.einsum('i->', a) is like np.sum(a, axis=-1), and np.einsum('ii->i', a) is like np.diag(a). The difference is that einsum does not allow broadcasting by default. Additionally np.einsum('ij,jh->ih', a, b) directly specifies the order of the output subscript labels and therefore returns matrix multiplication, unlike the example above in implicit mode.

To enable and control broadcasting, use an ellipsis. Default NumPy-style broadcasting is done by adding an ellipsis to the left of each term, like np.einsum('...ii->...i', a). To take the trace along the first and last axes, you can do np.einsum('i...i', a), or to do a matrix-matrix product with the left-most indices instead of rightmost, one can do np.einsum('ij...,jk...->ik...', a, b).

When there is only one operand, no axes are summed, and no output parameter is provided, a view into the operand is returned instead of a new array. Thus, taking the diagonal as np.einsum('ii->i', a) produces a view.

The optimize argument which will optimize the contraction order of an einsum expression. For a contraction with three or more operands this can greatly increase the computational efficiency at the cost of a larger memory footprint during computation.

Typically a ‘greedy’ algorithm is applied which empirical tests have shown returns the optimal path in the majority of cases. ‘optimal’ is not supported for now.

Note

This function differs from the original numpy.einsum in the following way(s):

  • Does not support ‘optimal’ strategy

  • Does not support the alternative subscript like

    einsum(op0, sublist0, op1, sublist1, …, [sublistout])

  • Does not produce view in any cases

Examples

>>> a = np.arange(25).reshape(5,5)
>>> b = np.arange(5)
>>> c = np.arange(6).reshape(2,3)

Trace of a matrix:

>>> np.einsum('ii', a)
array(60.)

Extract the diagonal (requires explicit form):

>>> np.einsum('ii->i', a)
array([ 0.,  6., 12., 18., 24.])

Sum over an axis (requires explicit form):

>>> np.einsum('ij->i', a)
array([ 10.,  35.,  60.,  85., 110.])
>>> np.sum(a, axis=1)
array([ 10.,  35.,  60.,  85., 110.])

For higher dimensional arrays summing a single axis can be done with ellipsis:

>>> np.einsum('...j->...', a)
array([ 10.,  35.,  60.,  85., 110.])

Compute a matrix transpose, or reorder any number of axes:

>>> np.einsum('ji', c)
array([[0., 3.],
       [1., 4.],
       [2., 5.]])
>>> np.einsum('ij->ji', c)
array([[0., 3.],
       [1., 4.],
       [2., 5.]])
>>> np.transpose(c)
array([[0., 3.],
       [1., 4.],
       [2., 5.]])

Vector inner products:

>>> np.einsum('i,i', b, b)
array(30.)

Matrix vector multiplication:

>>> np.einsum('ij,j', a, b)
array([ 30.,  80., 130., 180., 230.])
>>> np.dot(a, b)
array([ 30.,  80., 130., 180., 230.])
>>> np.einsum('...j,j', a, b)
array([ 30.,  80., 130., 180., 230.])

Broadcasting and scalar multiplication:

>>> np.einsum('..., ...', np.array(3), c)
array([[ 0.,  3.,  6.],
       [ 9., 12., 15.]])
>>> np.einsum(',ij', np.array(3), c)
array([[ 0.,  3.,  6.],
       [ 9., 12., 15.]])
>>> np.multiply(3, c)
array([[ 0.,  3.,  6.],
       [ 9., 12., 15.]])

Vector outer product:

>>> np.einsum('i,j', np.arange(2)+1, b)
array([[0., 1., 2., 3., 4.],
       [0., 2., 4., 6., 8.]])

Tensor contraction:

>>> a = np.arange(60.).reshape(3,4,5)
>>> b = np.arange(24.).reshape(4,3,2)
>>> np.einsum('ijk,jil->kl', a, b)
array([[4400., 4730.],
       [4532., 4874.],
       [4664., 5018.],
       [4796., 5162.],
       [4928., 5306.]])

Example of ellipsis use:

>>> a = np.arange(6).reshape((3,2))
>>> b = np.arange(12).reshape((4,3))
>>> np.einsum('ki,jk->ij', a, b)
array([[10., 28., 46., 64.],
       [13., 40., 67., 94.]])
>>> np.einsum('ki,...k->i...', a, b)
array([[10., 28., 46., 64.],
       [13., 40., 67., 94.]])
>>> np.einsum('k...,jk', a, b)
array([[10., 28., 46., 64.],
       [13., 40., 67., 94.]])

Chained array operations. For more complicated contractions, speed ups might be achieved by repeatedly computing a ‘greedy’ path. Performance improvements can be particularly significant with larger arrays:

>>> a = np.ones(64).reshape(2,4,8)
# Basic `einsum`: ~42.22ms  (benchmarked on 3.4GHz Intel Xeon.)
>>> for iteration in range(500):
...     np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a)
# Greedy `einsum` (faster optimal path approximation): ~0.117ms
>>> for iteration in range(500):
...     np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a, optimize=True)
mxnet.numpy.multiarray.empty(shape, dtype=None, order='C', device=None)

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

Parameters:
  • shape (int or tuple of int Shape of the empty array, e.g., (2, 3) or 2.)

  • dtype (data-type, optional) – Desired output data-type for the array, e.g, numpy.int8. Note that this behavior is different from NumPy’s empty function where float64 is the default value, here you can set your default dtype as ‘float32’ or ‘float64’ because float32 is considered as the default data type in deep learning. When npx.is_np_default_dtype() returns False, default dtype is float32; When npx.is_np_default_dtype() returns True, default dtype is float64.

  • order ({'C'}, optional, default: 'C') – How to store multi-dimensional data in memory, currently only row-major (C-style) is supported.

  • device (Device, optional) – Device context on which the memory is allocated. Default is mxnet.device.current_device().

Returns:

out – Array of uninitialized (arbitrary) data of the given shape, dtype, and order.

Return type:

ndarray

Examples

>>> np.empty([2, 2])
array([[ 0.000000e+00, -2.524355e-29],
       [          nan, -8.592023e+09]])  # uninitialized
>>> np.empty([2, 2], dtype=int)
array([[8751743591039004782, 3196766424264760104],
       [7583328881310196768,     562950123910254]], dtype=int64)  # uninitialized
mxnet.numpy.multiarray.empty_like(prototype, dtype=None, device=None, order='C', subok=False, shape=None)

Return a new array with the same shape and type as a given array.

Parameters:
  • prototype (ndarray) – The shape and data-type of prototype define these same attributes of the returned array.

  • dtype (data-type, optional) – Overrides the data type of the result.

  • device (Device, optional) – Device context on which the memory is allocated. Default is mxnet.device.current_device().

  • order ({'C'}, optional) – Whether to store multidimensional data in C- or Fortran-contiguous (row- or column-wise) order in memory. Currently only supports C order.

  • subok ({False}, optional) – If True, then the newly created array will use the sub-class type of ‘a’, otherwise it will be a base-class array. Defaults to False. (Only support False at this moment)

  • shape (int or sequence of ints, optional.) – Overrides the shape of the result. If order=’K’ and the number of dimensions is unchanged, will try to keep order, otherwise, order=’C’ is implied. (Not supported at this moment)

Returns:

out – Array of uninitialized (arbitrary) data with the same shape and type as prototype.

Return type:

ndarray

See also

ones_like

Return an array of ones with shape and type of input.

zeros_like

Return an array of zeros with shape and type of input.

full_like

Return a new array with shape of input filled with value.

empty

Return a new uninitialized array.

Notes

This function does not initialize the returned array; to do that use zeros_like or ones_like instead. It may be marginally faster than the functions that do set the array values.

Examples

>>> a = np.array([[1,2,3], [4,5,6]])
>>> np.empty_like(a)
array([[-5764607523034234880, -2305834244544065442,           4563075075], # uninitialized
       [          4567052944, -5764607523034234880,      844424930131968]])
>>> a = np.array([[1., 2., 3.],[4.,5.,6.]])
>>> np.empty_like(a)
array([[4.9e-324, 9.9e-324, 1.5e-323], # uninitialized
       [2.0e-323, 2.5e-323, 3.0e-323]])
mxnet.numpy.multiarray.equal(x1, x2, out=None)

Return (x1 == x2) element-wise.

Parameters:
  • x1 (ndarrays or scalars) – Input arrays. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • x2 (ndarrays or scalars) – Input arrays. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • out (ndarray, None, or tuple of ndarray and None, optional) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned.

Returns:

out – Output array of type bool, element-wise comparison of x1 and x2. This is a scalar if both x1 and x2 are scalars.

Return type:

ndarray or scalar

Examples

>>> np.equal(np.ones(2, 1)), np.zeros(1, 3))
array([[False, False, False],
       [False, False, False]])
>>> np.equal(1, np.ones(1))
array([ True])
mxnet.numpy.multiarray.exp(x, out=None, **kwargs)

Calculate the exponential of all elements in the input array.

Parameters:
  • x (ndarray or scalar) – Input values.

  • out (ndarray or None, optional) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned.

Returns:

out – Output array, element-wise exponential of x. This is a scalar if x is a scalar.

Return type:

ndarray or scalar

Examples

>>> np.exp(1)
2.718281828459045
>>> x = np.array([-1, 1, -2, 2])
>>> np.exp(x)
array([0.36787945, 2.7182817 , 0.13533528, 7.389056  ])
mxnet.numpy.multiarray.expand_dims(a, axis)

Expand the shape of an array.

Insert a new axis that will appear at the axis position in the expanded array shape.

Parameters:
  • a (ndarray) – Input array.

  • axis (int) – Position in the expanded axes where the new axis is placed.

Returns:

res – Output array. The number of dimensions is one greater than that of the input array.

Return type:

ndarray

See also

squeeze

The inverse operation, removing singleton dimensions

reshape

Insert, remove, and combine dimensions, and resize existing ones

Examples

>>> x = np.array([1,2])
>>> x.shape
(2,)
>>> y = np.expand_dims(x, axis=0)
>>> y
array([[1., 2.]])
>>> y.shape
(1, 2)
>>> y = np.expand_dims(x, axis=1)  # Equivalent to x[:,np.newaxis]
>>> y
array([[1.],
       [2.]])
>>> y.shape
(2, 1)

Note that some examples may use None instead of np.newaxis. These are the same objects:

>>> np.newaxis is None
True
mxnet.numpy.multiarray.expm1(x, out=None, **kwargs)

Calculate exp(x) - 1 for all elements in the array.

Parameters:
  • x (ndarray or scalar) – Input values.

  • out (ndarray or None, optional) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned.

Returns:

out – Output array, element-wise exponential minus one: out = exp(x) - 1. This is a scalar if x is a scalar.

Return type:

ndarray or scalar

Examples

>>> np.expm1(1)
1.718281828459045
>>> x = np.array([-1, 1, -2, 2])
>>> np.exp(x)
array([-0.63212056,  1.71828183, -0.86466472,  6.3890561])
mxnet.numpy.multiarray.extract(condition, arr)

Return the elements of an array that satisfy some condition.

This is equivalent to np.compress(ravel(condition), ravel(arr)). If condition is boolean np.extract is equivalent to arr[condition].

Note that place does the exact opposite of extract.

Parameters:
  • condition (array_like) – An array whose nonzero or True entries indicate the elements of arr to extract.

  • arr (array_like) – Input array of the same size as condition.

Returns:

extract – Rank 1 array of values from arr where condition is True.

Return type:

ndarray

See also

take, put, copyto, compress, place

Examples

>>> arr = np.arange(12).reshape((3, 4))
>>> arr
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
>>> condition = np.mod(arr, 3)==0
>>> condition
array([[ True, False, False,  True],
       [False, False,  True, False],
       [False,  True, False, False]])
>>> np.extract(condition, arr)
array([0, 3, 6, 9])

If condition is boolean:

>>> arr[condition]
array([0, 3, 6, 9])
mxnet.numpy.multiarray.eye(N, M=None, k=0, dtype=None, device=None, **kwargs)

Return a 2-D array with ones on the diagonal and zeros elsewhere.

Parameters:
  • N (int) – Number of rows in the output.

  • M (int, optional) – Number of columns in the output. If None, defaults to N.

  • k (int, optional) – Index of the diagonal: 0 (the default) refers to the main diagonal, a positive value refers to an upper diagonal, and a negative value to a lower diagonal.

  • dtype (data-type, optional) – Data-type of the returned array. When npx.is_np_default_dtype() returns False, default dtype is float32; When npx.is_np_default_dtype() returns True, default dtype is float64.

  • device (Device, optional) – Device context on which the memory is allocated. Default is mxnet.device.current_device().

Returns:

I – An array where all elements are equal to zero, except for the k-th diagonal, whose values are equal to one.

Return type:

ndarray of shape (N,M)

Examples

>>> np.eye(2, dtype=int)
array([[1, 0],
       [0, 1]], dtype=int64)
>>> np.eye(3, k=1)
array([[0., 1., 0.],
       [0., 0., 1.],
       [0., 0., 0.]])
mxnet.numpy.multiarray.fabs(x, out=None, **kwargs)

Calculate the absolute value element-wise.

This function returns the absolute values (positive magnitude) of the data in x. Complex values are not handled, use absolute to find the absolute values of complex data.

Parameters:
  • x (ndarray or scalar) – Input array.

  • out (ndarray or None, optional) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned.

Returns:

absolute – An ndarray containing the absolute value of each element in x. This is a scalar if x is a scalar.

Return type:

ndarray

Examples

>>> np.fabs(-1)
1.0
>>> np.fabs(np.array([-1.2, 1.2]))s
array([ 1.2,  1.2])
mxnet.numpy.multiarray.fill_diagonal(a, val, wrap=False)

Fill the main diagonal of the given array of any dimensionality. For an array a with a.ndim >= 2, the diagonal is the list of locations with indices a[i, ..., i] all identical. This function modifies the input array in-place, it does not return a value.

Parameters:
  • a (array, at least 2-D.) – Array whose diagonal is to be filled, it gets modified in-place.

  • val (scalar) – Value to be written on the diagonal, its type must be compatible with that of the array a.

  • wrap (bool) – For tall matrices in NumPy version up to 1.6.2, the diagonal “wrapped” after N columns. You can have this behavior with this option. This affects only tall matrices.

Examples

>>> a = np.zeros((3, 3), int)
>>> np.fill_diagonal(a, 5)
>>> a
array([[5, 0, 0],
       [0, 5, 0],
       [0, 0, 5]])
The same function can operate on a 4-D array:
>>> a = np.zeros((3, 3, 3, 3), int)
>>> np.fill_diagonal(a, 4)
We only show a few blocks for clarity:
>>> a[0, 0]
array([[4, 0, 0],
       [0, 0, 0],
       [0, 0, 0]])
>>> a[1, 1]
array([[0, 0, 0],
       [0, 4, 0],
       [0, 0, 0]])
>>> a[2, 2]
array([[0, 0, 0],
       [0, 0, 0],
       [0, 0, 4]])
The wrap option affects only tall matrices:
>>> # tall matrices no wrap
>>> a = np.zeros((5, 3), int)
>>> np.fill_diagonal(a, 4)
>>> a
array([[4, 0, 0],
       [0, 4, 0],
       [0, 0, 4],
       [0, 0, 0],
       [0, 0, 0]])
>>> # tall matrices wrap
>>> a = np.zeros((5, 3), int)
>>> np.fill_diagonal(a, 4, wrap=True)
>>> a
array([[4, 0, 0],
       [0, 4, 0],
       [0, 0, 4],
       [0, 0, 0],
       [4, 0, 0]])
>>> # wide matrices
>>> a = np.zeros((3, 5), int)
>>> np.fill_diagonal(a, 4, wrap=True)
>>> a
array([[4, 0, 0, 0, 0],
       [0, 4, 0, 0, 0],
       [0, 0, 4, 0, 0]])
The anti-diagonal can be filled by reversing the order of elements
using either `numpy.flipud` or `numpy.fliplr`.
>>> a = np.zeros((3, 3), int);
>>> np.fill_diagonal(np.fliplr(a), [1,2,3])  # Horizontal flip
>>> a
array([[0, 0, 1],
       [0, 2, 0],
       [3, 0, 0]])
>>> np.fill_diagonal(np.flipud(a), [1,2,3])  # Vertical flip
>>> a
array([[0, 0, 3],
       [0, 2, 0],
       [1, 0, 0]])
Note that the order in which the diagonal is filled varies depending
on the flip function.
mxnet.numpy.multiarray.fix(x, out=None, **kwargs)

Round an array of floats element-wise to nearest integer towards zero. The rounded values are returned as floats.

Parameters:
  • x (ndarray) – An array of floats to be rounded

  • out (ndarray, optional) – Output array

Returns:

  • y (ndarray or scalar)

  • Returned array or scalar (y = -x. This is a scalar if x is a scalar.ndarray of floats)

Examples

>>> np.fix(3.14)
3
mxnet.numpy.multiarray.flatnonzero(a)

Return indices that are non-zero in the flattened version of a.

This is equivalent to np.nonzero(np.ravel(a))[0].

Parameters:

a (array_like) – Input data.

Returns:

res – Output array, containing the indices of the elements of a.ravel() that are non-zero.

Return type:

ndarray

See also

nonzero

Return the indices of the non-zero elements of the input array.

ravel

Return a 1-D array containing the elements of the input array.

Examples

>>> x = np.arange(-2, 3)
>>> x
array([-2, -1,  0,  1,  2])
>>> np.flatnonzero(x)
array([0, 1, 3, 4])

Use the indices of the non-zero elements as an index array to extract these elements:

>>> x.ravel()[np.flatnonzero(x)]
array([-2, -1,  1,  2])
mxnet.numpy.multiarray.flip(m, axis=None, out=None)

Reverse the order of elements in an array along the given axis.

The shape of the array is preserved, but the elements are reordered.

Parameters:
  • m (ndarray or scalar) – Input array.

  • axis (None or int or tuple of ints, optional) –

    Axis or axes along which to flip over. The default, axis=None, will flip over all of the axes of the input array. If axis is negative it counts from the last to the first axis.

    If axis is a tuple of ints, flipping is performed on all of the axes specified in the tuple.

  • out (ndarray or scalar, optional) – Alternative output array in which to place the result. It must have the same shape and type as the expected output.

Returns:

out – A view of m with the entries of axis reversed. Since a view is returned, this operation is done in constant time.

Return type:

ndarray or scalar

Examples

>>> A = np.arange(8).reshape((2,2,2))
>>> A
array([[[0, 1],
        [2, 3]],
       [[4, 5],
        [6, 7]]])
>>> np.flip(A, 0)
array([[[4, 5],
        [6, 7]],
       [[0, 1],
        [2, 3]]])
>>> np.flip(A, 1)
array([[[2, 3],
        [0, 1]],
       [[6, 7],
        [4, 5]]])
>>> np.flip(A)
array([[[7, 6],
        [5, 4]],
       [[3, 2],
        [1, 0]]])
>>> np.flip(A, (0, 2))
array([[[5, 4],
        [7, 6]],
       [[1, 0],
        [3, 2]]])
mxnet.numpy.multiarray.fliplr(*args, **kwargs)

Flip array in the left/right direction.

Flip the entries in each row in the left/right direction. Columns are preserved, but appear in a different order than before.

Parameters:

m (array_like) – Input array, must be at least 2-D.

Returns:

f – A view of m with the columns reversed. Since a view is returned, this operation is \(\mathcal O(1)\).

Return type:

ndarray

See also

flipud

Flip array in the up/down direction.

rot90

Rotate array counterclockwise.

Notes

Equivalent to m[:,::-1]. Requires the array to be at least 2-D.

Examples

>>> A = np.diag([1.,2.,3.])
>>> A
array([[1.,  0.,  0.],
    [0.,  2.,  0.],
    [0.,  0.,  3.]])
>>> np.fliplr(A)
array([[0.,  0.,  1.],
    [0.,  2.,  0.],
    [3.,  0.,  0.]])
>>> A = np.random.randn(2,3,5)
>>> np.all(np.fliplr(A) == A[:,::-1,...])
array(True)
mxnet.numpy.multiarray.flipud(*args, **kwargs)

Flip array in the up/down direction.

Flip the entries in each column in the up/down direction. Rows are preserved, but appear in a different order than before.

Parameters:

m (array_like) – Input array.

Returns:

out – A view of m with the rows reversed. Since a view is returned, this operation is \(\mathcal O(1)\).

Return type:

array_like

See also

fliplr

Flip array in the left/right direction.

rot90

Rotate array counterclockwise.

Notes

Equivalent to m[::-1,...]. Does not require the array to be two-dimensional.

Examples

>>> A = np.diag(np.array([1.0, 2, 3]))
>>> A
array([[1.,  0.,  0.],
       [0.,  2.,  0.],
       [0.,  0.,  3.]])
>>> np.flipud(A)
array([[0.,  0.,  3.],
       [0.,  2.,  0.],
       [1.,  0.,  0.]])
>>> A = np.random.randn(2,3,5)
>>> np.all(np.flipud(A) == A[::-1,...])
array(True)
>>> np.flipud(np.array([1,2]))
array([2., 1.])
mxnet.numpy.multiarray.float_power(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])

First array elements raised to powers from second array, element-wise.

Raise each base in x1 to the positionally-corresponding power in x2. x1 and x2 must be broadcastable to the same shape. This differs from the power function in that integers, float16, and float32 are promoted to floats with a minimum precision of float64 so that the result is always inexact. The intent is that the function will return a usable result for negative powers and seldom overflow for positive powers.

Negative values raised to a non-integral value will return nan. To get complex results, cast the input to complex, or specify the dtype to be complex (see the example below).

Added in version 1.12.0.

Parameters:
  • x1 (array_like) – The bases.

  • x2 (array_like) – The exponents. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • out (ndarray, None, or tuple of ndarray and None, optional) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.

  • where (array_like, optional) – This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.

Returns:

y – The bases in x1 raised to the exponents in x2. This is a scalar if both x1 and x2 are scalars.

Return type:

ndarray

See also

power

power function that preserves type

Examples

Cube each element in a list.

>>> x1 = range(6)
>>> x1
[0, 1, 2, 3, 4, 5]
>>> np.float_power(x1, 3)
array([   0.,    1.,    8.,   27.,   64.,  125.])

Raise the bases to different exponents.

>>> x2 = [1.0, 2.0, 3.0, 3.0, 2.0, 1.0]
>>> np.float_power(x1, x2)
array([  0.,   1.,   8.,  27.,  16.,   5.])

The effect of broadcasting.

>>> x2 = np.array([[1, 2, 3, 3, 2, 1], [1, 2, 3, 3, 2, 1]])
>>> x2
array([[1, 2, 3, 3, 2, 1],
       [1, 2, 3, 3, 2, 1]])
>>> np.float_power(x1, x2)
array([[  0.,   1.,   8.,  27.,  16.,   5.],
       [  0.,   1.,   8.,  27.,  16.,   5.]])

Negative values raised to a non-integral value will result in nan (and a warning will be generated).

>>> x3 = np.array([-1, -4])
>>> with np.errstate(invalid='ignore'):
...     p = np.float_power(x3, 1.5)
...
>>> p
array([nan, nan])

To get complex results, give the argument dtype=complex.

>>> np.float_power(x3, 1.5, dtype=complex)
array([-1.83697020e-16-1.j, -1.46957616e-15-8.j])
mxnet.numpy.multiarray.floor(x, out=None, **kwargs)

Return the floor of the input, element-wise. The ceil of the ndarray x is the largest integer i, such that i <= x. It is often denoted as \(\lfloor x \rfloor\).

Parameters:
  • x (ndarray or scalar) – Input array.

  • out (ndarray or None) – A location into which the result is stored. If provided, it must have a shape that the inputs fill into. If not provided or None, a freshly-allocated array is returned. The dtype of the output and input must be the same.

Returns:

y – The floor of each element in x, with float dtype. This is a scalar if x is a scalar.

Return type:

ndarray or scalar

Examples

>>> a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0])
>>> np.floor(a)
array([-2., -2., -1.,  0.,  1.,  1.,  2.])
>>> # if you use parameter out, x and out must be ndarray.
>>> a = np.array(1)
>>> np.floor(np.array(3.5), a)
array(3.)
>>> a
array(3.)
mxnet.numpy.multiarray.floor_divide(x1, x2, out=None)

Return the largest integer smaller or equal to the division of the inputs.

It is equivalent to the Python // operator and pairs with the Python % (remainder), function so that a = a % b + b * (a // b) up to roundoff.

Parameters:
  • x1 (ndarray or scalar) – Dividend array.

  • x2 (ndarray or scalar) – Divisor array.

  • out (ndarray) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned.

Returns:

  • out (ndarray or scalar) – This is a scalar if both x1 and x2 are scalars.

  • .. note:: – This operator now supports automatic type promotion. The resulting type will be determined according to the following rules:

    • If both inputs are of floating number types, the output is the more precise type.

    • If only one of the inputs is floating number type, the result is that type.

    • If both inputs are of integer types (including boolean), the output is the more precise type

Examples

>>> np.floor_divide(7,3)
2
>>> np.floor_divide([1., 2., 3., 4.], 2.5)
array([ 0.,  0.,  1.,  1.])
mxnet.numpy.multiarray.fmax(x1, x2, out=None, **kwargs)

Returns element-wise maximum of the input arrays with broadcasting. (Ignores NaNs)

Parameters:
  • x1 (scalar or mxnet.numpy.ndarray) – The arrays holding the elements to be compared. They must have the same shape, or shapes that can be broadcast to a single shape.

  • x2 (scalar or mxnet.numpy.ndarray) – The arrays holding the elements to be compared. They must have the same shape, or shapes that can be broadcast to a single shape.

Returns:

out – The maximum of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars.

Return type:

mxnet.numpy.ndarray or scalar

Examples

>>> np.fmax(np.array([2, 3, 4]), np.array([1, 5, 2]))
array([2., 5., 4.])
>>> np.fmax(np.eye(2), np.array([0.5, 2])) # broadcasting
array([[1. , 2. ],
       [0.5, 2. ]])
mxnet.numpy.multiarray.fmin(x1, x2, out=None, **kwargs)

Returns element-wise minimum of the input arrays with broadcasting. (Ignores NaNs)

Parameters:
  • x1 (scalar or mxnet.numpy.ndarray) – The arrays holding the elements to be compared. They must have the same shape, or shapes that can be broadcast to a single shape.

  • x2 (scalar or mxnet.numpy.ndarray) – The arrays holding the elements to be compared. They must have the same shape, or shapes that can be broadcast to a single shape.

Returns:

out – The fmin of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars.

Return type:

mxnet.numpy.ndarray or scalar

Examples

>>> np.fmin(np.array([2, 3, 4]), np.array([1, 5, 2]))
array([1., 3., 2.])
>>> np.fmin(np.eye(2), np.array([0.5, 2])) # broadcasting
array([[0.5, 0. ],
       [0. , 1. ]])
mxnet.numpy.multiarray.fmod(x1, x2, out=None, **kwargs)

Return element-wise remainder of division.

Parameters:
  • x1 (ndarray or scalar) – Dividend array.

  • x2 (ndarray or scalar) – Divisor array.

  • out (ndarray) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned.

Returns:

out – This is a scalar if both x1 and x2 are scalars.

Return type:

ndarray or scalar

Examples

>>> np.fmod(np.arange(7), 5)
array([0., 1., 2., 3., 4., 0., 1.])
mxnet.numpy.multiarray.frexp(x, [out1, out2, ]/, [out=(None, None), ]*, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])

Decompose the elements of x into mantissa and twos exponent.

Returns (mantissa, exponent), where x = mantissa * 2**exponent. The mantissa lies in the open interval(-1, 1), while the twos exponent is a signed integer.

Parameters:
  • x (array_like) – Array of numbers to be decomposed.

  • out1 (ndarray, optional) – Output array for the mantissa. Must have the same shape as x.

  • out2 (ndarray, optional) – Output array for the exponent. Must have the same shape as x.

  • out (ndarray, None, or tuple of ndarray and None, optional) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.

  • where (array_like, optional) – This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.

Returns:

  • mantissa (ndarray) – Floating values between -1 and 1. This is a scalar if x is a scalar.

  • exponent (ndarray) – Integer exponents of 2. This is a scalar if x is a scalar.

See also

ldexp

Compute y = x1 * 2**x2, the inverse of frexp.

Notes

Complex dtypes are not supported, they will raise a TypeError.

Examples

>>> x = np.arange(9)
>>> y1, y2 = np.frexp(x)
>>> y1
array([ 0.   ,  0.5  ,  0.5  ,  0.75 ,  0.5  ,  0.625,  0.75 ,  0.875,
        0.5  ])
>>> y2
array([0, 1, 2, 2, 3, 3, 3, 3, 4])
>>> y1 * 2**y2
array([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.])
mxnet.numpy.multiarray.from_dlpack(x)

Returns a np.ndarray backed by a dlpack tensor.

Parameters:

dlpack (an object with __dlpack__ method or PyCapsule (the pointer of DLManagedTensor)) – input data

Returns:

out – an ndarray backed by a dlpack tensor

Return type:

np.ndarray

Examples

>>> x = mx.np.ones((2,3))
>>> y = mx.np.from_dlpack(x)
>>> y
array([[1., 1., 1.],
       [1., 1., 1.]])
>>> y += 1
>>> x
array([[2., 2., 2.],
       [2., 2., 2.]])
mxnet.numpy.multiarray.full(shape, fill_value, dtype=None, order='C', device=None, out=None)

Return a new array of given shape and type, filled with fill_value.

Parameters:
  • shape (int or sequence of ints) – Shape of the new array, e.g., (2, 3) or 2.

  • fill_value (scalar or ndarray) – Fill value.

  • dtype (data-type, optional) – If dtype is None, the output array data type must be inferred from fill_value. If it’s an int, the output array dtype must be the default integer dtype; If it’s a float, then the output array dtype must be the default floating-point data type; If it’s a bool then the output array must have boolean dtype. Default: None.

  • order ({'C'}, optional) – Whether to store multidimensional data in C- or Fortran-contiguous (row- or column-wise) order in memory. Currently only supports C order.

  • device (Device, optional) – Device context on which the memory is allocated. Default is mxnet.device.current_device().

  • out (ndarray or None, optional) – A location into which the result is stored. If provided, it must have the same shape and dtype as input ndarray. If not provided or None, a freshly-allocated array is returned.

Returns:

  • out (ndarray) – Array of fill_value with the given shape, dtype, and order. If fill_value is an ndarray, out will have the same device as fill_value regardless of the provided device.

  • .. note:: – This function differs from the original numpy.full in the following way(s):

    • Has an additional device argument to specify the device

    • Has an additional out argument

    • Currently does not support order selection

See also

empty

Return a new uninitialized array.

ones

Return a new array setting values to one.

zeros

Return a new array setting values to zero.

Examples

>>> np.full((2, 2), 10)
array([[10., 10.],
       [10., 10.]])
>>> np.full((2, 2), 2, dtype=np.int32, device=mx.cpu(0))
array([[2, 2],
       [2, 2]], dtype=int32)
mxnet.numpy.multiarray.full_like(a, fill_value, dtype=None, order='C', device=None, out=None)

Return a full array with the same shape and type as a given array.

Parameters:
  • a (ndarray) – The shape and data-type of a define these same attributes of the returned array.

  • fill_value (scalar) – Fill value.

  • dtype (data-type, optional) – Overrides the data type of the result. Temporarily do not support boolean type.

  • order ({'C'}, optional) – Whether to store multidimensional data in C- or Fortran-contiguous (row- or column-wise) order in memory. Currently only supports C order.

  • device (Device, optional) – Device context on which the memory is allocated. Default is mxnet.device.current_device().

  • out (ndarray or None, optional) – A location into which the result is stored. If provided, it must have the same shape and dtype as input ndarray. If not provided or None, a freshly-allocated array is returned.

Returns:

out – Array of fill_value with the same shape and type as a.

Return type:

ndarray

See also

empty_like

Return an empty array with shape and type of input.

ones_like

Return an array of ones with shape and type of input.

zeros_like

Return an array of zeros with shape and type of input.

full

Return a new array of given shape filled with value.

Examples

>>> x = np.arange(6, dtype=int)
>>> np.full_like(x, 1)
array([1, 1, 1, 1, 1, 1], dtype=int64)
>>> np.full_like(x, 0.1)
array([0, 0, 0, 0, 0, 0], dtype=int64)
>>> np.full_like(x, 0.1, dtype=np.float64)
array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1], dtype=float64)
>>> np.full_like(x, np.nan, dtype=np.float64)
array([nan, nan, nan, nan, nan, nan], dtype=float64)
>>> y = np.arange(6, dtype=np.float32)
>>> np.full_like(y, 0.1)
array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1])
mxnet.numpy.multiarray.gcd(x1, x2, out=None, **kwargs)

Returns the greatest common divisor of |x1| and |x2|

Parameters:
  • x1 (ndarrays or scalar values) – The arrays for computing greatest common divisor. If x1.shape != x2.shape, they must be broadcastable to a common shape (which may be the shape of one or the other).

  • x2 (ndarrays or scalar values) – The arrays for computing greatest common divisor. If x1.shape != x2.shape, they must be broadcastable to a common shape (which may be the shape of one or the other).

  • out (ndarray or None, optional) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned.

Returns:

y – The greatest common divisor of the absolute value of the inputs This is a scalar if both x1 and x2 are scalars.

Return type:

ndarray or scalar

See also

gcd

The lowest common multiple

Examples

>>> np.gcd(12, 20)
4
>>> np.gcd(np.arange(6, dtype=int), 20)
array([20,  1,  2,  1,  4,  5], dtype=int64)
mxnet.numpy.multiarray.greater(x1, x2, out=None)

Return the truth value of (x1 > x2) element-wise.

Parameters:
  • x1 (ndarrays or scalars) – Input arrays. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • x2 (ndarrays or scalars) – Input arrays. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • out (ndarray, None, or tuple of ndarray and None, optional) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned.

Returns:

out – Output array of type bool, element-wise comparison of x1 and x2. This is a scalar if both x1 and x2 are scalars.

Return type:

ndarray or scalar

Examples

>>> np.greater(np.ones(2, 1)), np.zeros(1, 3))
array([[ True,  True,  True],
       [ True,  True,  True]])
>>> np.greater(1, np.ones(1))
array([False])
mxnet.numpy.multiarray.greater_equal(x1, x2, out=None)

Return the truth value of (x1 >= x2) element-wise.

Parameters:
  • x1 (ndarrays or scalars) – Input arrays. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • x2 (ndarrays or scalars) – Input arrays. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • out (ndarray, None, or tuple of ndarray and None, optional) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned.

Returns:

out – Output array of type bool, element-wise comparison of x1 and x2. This is a scalar if both x1 and x2 are scalars.

Return type:

ndarray or scalar

Examples

>>> np.greater_equal(np.ones(2, 1)), np.zeros(1, 3))
array([[ True,  True,  True],
       [ True,  True,  True]])
>>> np.greater_equal(1, np.ones(1))
array([True])
mxnet.numpy.multiarray.hamming(M, dtype=None, device=None)

Return the hamming window.

The hamming window is a taper formed by using a weighted cosine.

Parameters:
  • M (int) – Number of points in the output window. If zero or less, an empty array is returned.

  • device (Device, optional) – Device context on which the memory is allocated. Default is mxnet.device.current_device().

Returns:

out – The window, with the maximum value normalized to one (the value one appears only if M is odd). When npx.is_np_default_dtype() returns False, default dtype is float32; When npx.is_np_default_dtype() returns True, default dtype is float64. Note that you need select numpy.float32 or float64 in this operator.

Return type:

ndarray, shape(M,)

See also

blackman, hanning

Notes

The Hamming window is defined as

\[w(n) = 0.54 - 0.46cos\left(\frac{2\pi{n}}{M-1}\right) \qquad 0 \leq n \leq M-1\]

The Hamming was named for R. W. Hamming, an associate of J. W. Tukey and is described in Blackman and Tukey. It was recommended for smoothing the truncated autocovariance function in the time domain. Most references to the Hamming window come from the signal processing literature, where it is used as one of many windowing functions for smoothing values. It is also known as an apodization (which means “removing the foot”, i.e. smoothing discontinuities at the beginning and end of the sampled signal) or tapering function.

References

Examples

>>> np.hamming(12)
array([0.08000001, 0.15302339, 0.34890914, 0.6054648 , 0.841236  ,
       0.9813669 , 0.9813668 , 0.8412359 , 0.6054647 , 0.34890908,
       0.15302327, 0.08000001])

Plot the window and its frequency response:

>>> import matplotlib.pyplot as plt
>>> window = np.hamming(51)
>>> plt.plot(window.asnumpy())
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.title("hamming window")
Text(0.5, 1.0, 'hamming window')
>>> plt.ylabel("Amplitude")
Text(0, 0.5, 'Amplitude')
>>> plt.xlabel("Sample")
Text(0.5, 0, 'Sample')
>>> plt.show()
mxnet.numpy.multiarray.hanning(M, dtype=None, device=None)

Return the Hanning window.

The Hanning window is a taper formed by using a weighted cosine.

Parameters:
  • M (int) – Number of points in the output window. If zero or less, an empty array is returned.

  • device (Device, optional) – Device context on which the memory is allocated. Default is mxnet.device.current_device().

Returns:

out – The window, with the maximum value normalized to one (the value one appears only if M is odd). When npx.is_np_default_dtype() returns False, default dtype is float32; When npx.is_np_default_dtype() returns True, default dtype is float64. Note that you need select numpy.float32 or float64 in this operator.

Return type:

ndarray, shape(M,)

See also

blackman, hamming

Notes

The Hanning window is defined as

\[w(n) = 0.5 - 0.5cos\left(\frac{2\pi{n}}{M-1}\right) \qquad 0 \leq n \leq M-1\]

The Hanning was named for Julius von Hann, an Austrian meteorologist. It is also known as the Cosine Bell. Some authors prefer that it be called a Hann window, to help avoid confusion with the very similar Hamming window.

Most references to the Hanning window come from the signal processing literature, where it is used as one of many windowing functions for smoothing values. It is also known as an apodization (which means “removing the foot”, i.e. smoothing discontinuities at the beginning and end of the sampled signal) or tapering function.

References

Examples

>>> np.hanning(12)
array([0.        , 0.07937324, 0.29229254, 0.5711574 , 0.8274304 ,
       0.9797465 , 0.97974646, 0.82743025, 0.5711573 , 0.29229245,
       0.07937312, 0.        ])

Plot the window and its frequency response:

>>> import matplotlib.pyplot as plt
>>> window = np.hanning(51)
>>> plt.plot(window.asnumpy())
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.title("Hann window")
Text(0.5, 1.0, 'Hann window')
>>> plt.ylabel("Amplitude")
Text(0, 0.5, 'Amplitude')
>>> plt.xlabel("Sample")
Text(0.5, 0, 'Sample')
>>> plt.show()
mxnet.numpy.multiarray.heaviside(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])

Compute the Heaviside step function.

The Heaviside step function is defined as:

                      0   if x1 < 0
heaviside(x1, x2) =  x2   if x1 == 0
                      1   if x1 > 0

where x2 is often taken to be 0.5, but 0 and 1 are also sometimes used.

Parameters:
  • x1 (array_like) – Input values.

  • x2 (array_like) – The value of the function when x1 is 0. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • out (ndarray, None, or tuple of ndarray and None, optional) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.

  • where (array_like, optional) – This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.

Returns:

out – The output array, element-wise Heaviside step function of x1. This is a scalar if both x1 and x2 are scalars.

Return type:

ndarray or scalar

Notes

Added in version 1.13.0.

References

Examples

>>> np.heaviside([-1.5, 0, 2.0], 0.5)
array([ 0. ,  0.5,  1. ])
>>> np.heaviside([-1.5, 0, 2.0], 1)
array([ 0.,  1.,  1.])
mxnet.numpy.multiarray.histogram(a, bins=10, range=None, normed=None, weights=None, density=None)

Compute the histogram of a set of data.

Parameters:
  • a (ndarray) – Input data. The histogram is computed over the flattened array.

  • bins (int or ndarray) – If bins is an int, it defines the number of equal-width bins in the given range (10, by default). If bins is a sequence, it defines a monotonically increasing array of bin edges, including the rightmost edge, allowing for non-uniform bin widths. .. versionadded:: 1.11.0 If bins is a string, it defines the method used to calculate the optimal bin width, as defined by histogram_bin_edges.

  • range ((float, float)) – The lower and upper range of the bins. Required when bins is an integer. Values outside the range are ignored. The first element of the range must be less than or equal to the second.

  • normed (bool, optional) – Not supported yet, coming soon.

  • weights (array_like, optional) – Not supported yet, coming soon.

  • density (bool, optional) – Not supported yet, coming soon.

Examples

>>> np.histogram(np.arange(4), bins=np.arange(5))
[array([1, 1, 1, 1], dtype=int64), array([0., 1., 2., 3., 4.])]
mxnet.numpy.multiarray.histogram2d(x, y, bins=10, range=None, density=None, weights=None)

Compute the bi-dimensional histogram of two data samples.

Parameters:
  • x (array_like, shape (N,)) – An array containing the x coordinates of the points to be histogrammed.

  • y (array_like, shape (N,)) – An array containing the y coordinates of the points to be histogrammed.

  • bins (int or array_like or [int, int] or [array, array], optional) –

    The bin specification:

    • If int, the number of bins for the two dimensions (nx=ny=bins).

    • If array_like, the bin edges for the two dimensions (x_edges=y_edges=bins).

    • If [int, int], the number of bins in each dimension (nx, ny = bins).

    • If [array, array], the bin edges in each dimension (x_edges, y_edges = bins).

    • A combination [int, array] or [array, int], where int is the number of bins and array is the bin edges.

  • range (array_like, shape(2,2), optional) – The leftmost and rightmost edges of the bins along each dimension (if not specified explicitly in the bins parameters): [[xmin, xmax], [ymin, ymax]]. All values outside of this range will be considered outliers and not tallied in the histogram.

  • density (bool, optional) – If False, the default, returns the number of samples in each bin. If True, returns the probability density function at the bin, bin_count / sample_count / bin_area.

  • weights (array_like, shape(N,), optional) – An array of values w_i weighing each sample (x_i, y_i). Weights are normalized to 1 if density is True. If density is False, the values of the returned histogram are equal to the sum of the weights belonging to the samples falling into each bin.

Returns:

  • H (ndarray, shape(nx, ny)) – The bi-dimensional histogram of samples x and y. Values in x are histogrammed along the first dimension and values in y are histogrammed along the second dimension.

  • xedges (ndarray, shape(nx+1,)) – The bin edges along the first dimension.

  • yedges (ndarray, shape(ny+1,)) – The bin edges along the second dimension.

See also

histogram

1D histogram

histogramdd

Multidimensional histogram

Notes

When density is True, then the returned histogram is the sample density, defined such that the sum over bins of the product bin_value * bin_area is 1.

Please note that the histogram does not follow the Cartesian convention where x values are on the abscissa and y values on the ordinate axis. Rather, x is histogrammed along the first dimension of the array (vertical), and y along the second dimension of the array (horizontal). This ensures compatibility with histogramdd.

Examples

>>> from matplotlib.image import NonUniformImage
>>> import matplotlib.pyplot as plt

Construct a 2-D histogram with variable bin width. First define the bin edges:

>>> xedges = [0, 1, 3, 5]
>>> yedges = [0, 2, 3, 4, 6]

Next we create a histogram H with random bin content:

>>> x = np.random.normal(2, 1, 100)
>>> y = np.random.normal(1, 1, 100)
>>> H, xedges, yedges = np.histogram2d(x, y, bins=(xedges, yedges))
>>> # Histogram does not follow Cartesian convention (see Notes),
>>> # therefore transpose H for visualization purposes.
>>> H = H.T

imshow can only display square bins:

>>> fig = plt.figure(figsize=(7, 3))
>>> ax = fig.add_subplot(131, title='imshow: square bins')
>>> plt.imshow(H, interpolation='nearest', origin='lower',
...         extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]])
<matplotlib.image.AxesImage object at 0x...>

pcolormesh can display actual edges:

>>> ax = fig.add_subplot(132, title='pcolormesh: actual edges',
...         aspect='equal')
>>> X, Y = np.meshgrid(xedges, yedges)
>>> ax.pcolormesh(X, Y, H)
<matplotlib.collections.QuadMesh object at 0x...>

NonUniformImage can be used to display actual bin edges with interpolation:

>>> ax = fig.add_subplot(133, title='NonUniformImage: interpolated',
...         aspect='equal', xlim=xedges[[0, -1]], ylim=yedges[[0, -1]])
>>> im = NonUniformImage(ax, interpolation='bilinear')
>>> xcenters = (xedges[:-1] + xedges[1:]) / 2
>>> ycenters = (yedges[:-1] + yedges[1:]) / 2
>>> im.set_data(xcenters, ycenters, H)
>>> ax.add_image(im)
>>> plt.show()

It is also possible to construct a 2-D histogram without specifying bin edges:

>>> # Generate non-symmetric test data
>>> n = 10000
>>> x = np.linspace(1, 100, n)
>>> y = 2*np.log(x) + np.random.rand(n) - 0.5
>>> # Compute 2d histogram. Note the order of x/y and xedges/yedges
>>> H, yedges, xedges = np.histogram2d(y, x, bins=20)

Now we can plot the histogram using pcolormesh, and a hexbin for comparison.

>>> # Plot histogram using pcolormesh
>>> fig, (ax1, ax2) = plt.subplots(ncols=2, sharey=True)
>>> ax1.pcolormesh(xedges, yedges, H, cmap='rainbow')
>>> ax1.plot(x, 2*np.log(x), 'k-')
>>> ax1.set_xlim(x.min(), x.max())
>>> ax1.set_ylim(y.min(), y.max())
>>> ax1.set_xlabel('x')
>>> ax1.set_ylabel('y')
>>> ax1.set_title('histogram2d')
>>> ax1.grid()
>>> # Create hexbin plot for comparison
>>> ax2.hexbin(x, y, gridsize=20, cmap='rainbow')
>>> ax2.plot(x, 2*np.log(x), 'k-')
>>> ax2.set_title('hexbin')
>>> ax2.set_xlim(x.min(), x.max())
>>> ax2.set_xlabel('x')
>>> ax2.grid()
>>> plt.show()
mxnet.numpy.multiarray.histogram_bin_edges(a, bins=10, range=None, weights=None)

Function to calculate only the edges of the bins used by the histogram function.

Parameters:
  • a (array_like) – Input data. The histogram is computed over the flattened array.

  • bins (int or sequence of scalars or str, optional) –

    If bins is an int, it defines the number of equal-width bins in the given range (10, by default). If bins is a sequence, it defines the bin edges, including the rightmost edge, allowing for non-uniform bin widths.

    If bins is a string from the list below, histogram_bin_edges will use the method chosen to calculate the optimal bin width and consequently the number of bins (see Notes for more detail on the estimators) from the data that falls within the requested range. While the bin width will be optimal for the actual data in the range, the number of bins will be computed to fill the entire range, including the empty portions. For visualisation, using the ‘auto’ option is suggested. Weighted data is not supported for automated bin size selection.

    ’auto’

    Maximum of the ‘sturges’ and ‘fd’ estimators. Provides good all around performance.

    ’fd’ (Freedman Diaconis Estimator)

    Robust (resilient to outliers) estimator that takes into account data variability and data size.

    ’doane’

    An improved version of Sturges’ estimator that works better with non-normal datasets.

    ’scott’

    Less robust estimator that takes into account data variability and data size.

    ’stone’

    Estimator based on leave-one-out cross-validation estimate of the integrated squared error. Can be regarded as a generalization of Scott’s rule.

    ’rice’

    Estimator does not take variability into account, only data size. Commonly overestimates number of bins required.

    ’sturges’

    R’s default method, only accounts for data size. Only optimal for gaussian data and underestimates number of bins for large non-gaussian datasets.

    ’sqrt’

    Square root (of data size) estimator, used by Excel and other programs for its speed and simplicity.

  • range ((float, float), optional) – The lower and upper range of the bins. If not provided, range is simply (a.min(), a.max()). Values outside the range are ignored. The first element of the range must be less than or equal to the second. range affects the automatic bin computation as well. While bin width is computed to be optimal based on the actual data within range, the bin count will fill the entire range including portions containing no data.

  • weights (array_like, optional) – An array of weights, of the same shape as a. Each value in a only contributes its associated weight towards the bin count (instead of 1). This is currently not used by any of the bin estimators, but may be in the future.

Returns:

bin_edges – The edges to pass into histogram

Return type:

array of dtype float

See also

histogram

Notes

The methods to estimate the optimal number of bins are well founded in literature, and are inspired by the choices R provides for histogram visualisation. Note that having the number of bins proportional to \(n^{1/3}\) is asymptotically optimal, which is why it appears in most estimators. These are simply plug-in methods that give good starting points for number of bins. In the equations below, \(h\) is the binwidth and \(n_h\) is the number of bins. All estimators that compute bin counts are recast to bin width using the ptp of the data. The final bin count is obtained from np.round(np.ceil(range / h)). The final bin width is often less than what is returned by the estimators below.

‘auto’ (maximum of the ‘sturges’ and ‘fd’ estimators)

A compromise to get a good value. For small datasets the Sturges value will usually be chosen, while larger datasets will usually default to FD. Avoids the overly conservative behaviour of FD and Sturges for small and large datasets respectively. Switchover point is usually \(a.size \approx 1000\).

‘fd’ (Freedman Diaconis Estimator)
\[h = 2 \frac{IQR}{n^{1/3}}\]

The binwidth is proportional to the interquartile range (IQR) and inversely proportional to cube root of a.size. Can be too conservative for small datasets, but is quite good for large datasets. The IQR is very robust to outliers.

‘scott’
\[h = \sigma \sqrt[3]{\frac{24 \sqrt{\pi}}{n}}\]

The binwidth is proportional to the standard deviation of the data and inversely proportional to cube root of x.size. Can be too conservative for small datasets, but is quite good for large datasets. The standard deviation is not very robust to outliers. Values are very similar to the Freedman-Diaconis estimator in the absence of outliers.

‘rice’
\[n_h = 2n^{1/3}\]

The number of bins is only proportional to cube root of a.size. It tends to overestimate the number of bins and it does not take into account data variability.

‘sturges’
\[n_h = \log _{2}(n) + 1\]

The number of bins is the base 2 log of a.size. This estimator assumes normality of data and is too conservative for larger, non-normal datasets. This is the default method in R’s hist method.

‘doane’
\[ \begin{align}\begin{aligned}n_h = 1 + \log_{2}(n) + \log_{2}\left(1 + \frac{|g_1|}{\sigma_{g_1}}\right)\\g_1 = mean\left[\left(\frac{x - \mu}{\sigma}\right)^3\right]\\\sigma_{g_1} = \sqrt{\frac{6(n - 2)}{(n + 1)(n + 3)}}\end{aligned}\end{align} \]

An improved version of Sturges’ formula that produces better estimates for non-normal datasets. This estimator attempts to account for the skew of the data.

‘sqrt’
\[n_h = \sqrt n\]

The simplest and fastest estimator. Only takes into account the data size.

Examples

>>> arr = np.array([0, 0, 0, 1, 2, 3, 3, 4, 5])
>>> np.histogram_bin_edges(arr, bins='auto', range=(0, 1))
array([0.  , 0.25, 0.5 , 0.75, 1.  ])
>>> np.histogram_bin_edges(arr, bins=2)
array([0. , 2.5, 5. ])

For consistency with histogram, an array of pre-computed bins is passed through unmodified:

>>> np.histogram_bin_edges(arr, [1, 2])
array([1, 2])

This function allows one set of bins to be computed, and reused across multiple histograms:

>>> shared_bins = np.histogram_bin_edges(arr, bins='auto')
>>> shared_bins
array([0., 1., 2., 3., 4., 5.])
>>> group_id = np.array([0, 1, 1, 0, 1, 1, 0, 1, 1])
>>> hist_0, _ = np.histogram(arr[group_id == 0], bins=shared_bins)
>>> hist_1, _ = np.histogram(arr[group_id == 1], bins=shared_bins)
>>> hist_0; hist_1
array([1, 1, 0, 1, 0])
array([2, 0, 1, 1, 2])

Which gives more easily comparable results than using separate bins for each histogram:

>>> hist_0, bins_0 = np.histogram(arr[group_id == 0], bins='auto')
>>> hist_1, bins_1 = np.histogram(arr[group_id == 1], bins='auto')
>>> hist_0; hist_1
array([1, 1, 1])
array([2, 1, 1, 2])
>>> bins_0; bins_1
array([0., 1., 2., 3.])
array([0.  , 1.25, 2.5 , 3.75, 5.  ])
mxnet.numpy.multiarray.histogramdd(sample, bins=10, range=None, density=None, weights=None)

Compute the multidimensional histogram of some data.

Parameters:
  • sample ((N, D) array, or (N, D) array_like) –

    The data to be histogrammed.

    Note the unusual interpretation of sample when an array_like:

    • When an array, each row is a coordinate in a D-dimensional space - such as histogramdd(np.array([p1, p2, p3])).

    • When an array_like, each element is the list of values for single coordinate - such as histogramdd((X, Y, Z)).

    The first form should be preferred.

  • bins (sequence or int, optional) –

    The bin specification:

    • A sequence of arrays describing the monotonically increasing bin edges along each dimension.

    • The number of bins for each dimension (nx, ny, … =bins)

    • The number of bins for all dimensions (nx=ny=…=bins).

  • range (sequence, optional) – A sequence of length D, each an optional (lower, upper) tuple giving the outer bin edges to be used if the edges are not given explicitly in bins. An entry of None in the sequence results in the minimum and maximum values being used for the corresponding dimension. The default, None, is equivalent to passing a tuple of D None values.

  • density (bool, optional) – If False, the default, returns the number of samples in each bin. If True, returns the probability density function at the bin, bin_count / sample_count / bin_volume.

  • weights ((N,) array_like, optional) – An array of values w_i weighing each sample (x_i, y_i, z_i, …). Weights are normalized to 1 if density is True. If density is False, the values of the returned histogram are equal to the sum of the weights belonging to the samples falling into each bin.

Returns:

  • H (ndarray) – The multidimensional histogram of sample x. See density and weights for the different possible semantics.

  • edges (list) – A list of D arrays describing the bin edges for each dimension.

See also

histogram

1-D histogram

histogram2d

2-D histogram

Examples

>>> r = np.random.randn(100,3)
>>> H, edges = np.histogramdd(r, bins = (5, 8, 4))
>>> H.shape, edges[0].size, edges[1].size, edges[2].size
((5, 8, 4), 6, 9, 5)
mxnet.numpy.multiarray.hsplit(ary, indices_or_sections)

Split an array into multiple sub-arrays horizontally (column-wise). This is equivalent to split with axis=0 if ary has one dimension, and otherwise that with axis=1.

Parameters:
  • ary (ndarray) – Array to be divided into sub-arrays.

  • indices_or_sections (int, list of ints or tuple of ints.) – If indices_or_sections is an integer, N, the array will be divided into N equal arrays along axis. If such a split is not possible, an error is raised. If indices_or_sections is a list of sorted integers, the entries indicate where along axis the array is split. If an index exceeds the dimension of the array along axis, it will raises errors. so index must less than or euqal to the dimension of the array along axis.

Returns:

  • sub-arrays (list of ndarrays) – A list of sub-arrays.

  • .. note::

    • If indices_or_sections is given as an integer, but a split does not result in equal division.It will raises ValueErrors.

    • If indices_or_sections is an integer, and the number is 1, it will raises an error. Because single output from split is not supported yet…

See also

split

Split an array into multiple sub-arrays of equal size.

Examples

>>> x = np.arange(16.0).reshape(4, 4)
>>> x
array([[ 0.,  1.,  2.,  3.],
       [ 4.,  5.,  6.,  7.],
       [ 8.,  9., 10., 11.],
       [12., 13., 14., 15.]])
>>> np.hsplit(x, 2)
[array([[ 0.,  1.],
       [ 4.,  5.],
       [ 8.,  9.],
       [12., 13.]]),
array([[ 2.,  3.],
       [ 6.,  7.],
       [10., 11.],
       [14., 15.]])]
>>> np.hsplit(x, [3, 6])
[array([[ 0.,  1.,  2.],
       [ 4.,  5.,  6.],
       [ 8.,  9., 10.],
       [12., 13., 14.]]),
array([[ 3.],
       [ 7.],
       [11.],
       [15.]]),
array([], shape=(4, 0), dtype=float32)]
With a higher dimensional array the split is still along the second axis.
>>> x = np.arange(8.0).reshape(2, 2, 2)
>>> x
array([[[ 0.,  1.],
        [ 2.,  3.]],
       [[ 4.,  5.],
        [ 6.,  7.]]])
>>> np.hsplit(x, 2)
[array([[[ 0.,  1.]],
        [[ 4.,  5.]]]),
 array([[[ 2.,  3.]],
        [[ 6.,  7.]]])]
If ``ary`` has one dimension, 'axis' = 0.
>>> x = np.arange(4)
array([0., 1., 2., 3.])
>>> np.hsplit(x, 2)
[array([0., 1.]), array([2., 3.])]
If you want to produce an empty sub-array, you can see an example.
>>> np.hsplit(x, [2, 2])
[array([0., 1.]), array([], dtype=float32), array([2., 3.])]
mxnet.numpy.multiarray.hstack(arrays)

Stack arrays in sequence horizontally (column wise). This is equivalent to concatenation along the second axis, except for 1-D arrays where it concatenates along the first axis. Rebuilds arrays divided by hsplit. This function makes most sense for arrays with up to 3 dimensions. For instance, for pixel-data with a height (first axis), width (second axis), and r/g/b channels (third axis). The functions concatenate, stack and block provide more general stacking and concatenation operations.

Parameters:

tup (sequence of ndarrays) – The arrays must have the same shape along all but the second axis, except 1-D arrays which can be any length.

Returns:

stacked – The array formed by stacking the given arrays.

Return type:

ndarray

Examples

>>> from mxnet import np,npx
>>> a = np.array((1,2,3))
>>> b = np.array((2,3,4))
>>> np.hstack((a,b))
array([1., 2., 3., 2., 3., 4.])
>>> a = np.array([[1],[2],[3]])
>>> b = np.array([[2],[3],[4]])
>>> np.hstack((a,b))
array([[1., 2.],
       [2., 3.],
       [3., 4.]])
mxnet.numpy.multiarray.hypot(x1, x2, out=None, **kwargs)

Given the “legs” of a right triangle, return its hypotenuse.

Equivalent to sqrt(x1**2 + x2**2), element-wise. If x1 or x2 is scalar_like (i.e., unambiguously cast-able to a scalar type), it is broadcast for use with each element of the other argument.

Parameters:
  • x1 (array_like) – Leg of the triangle(s).

  • x2 (array_like) – Leg of the triangle(s).

  • out (ndarray, None, or tuple of ndarray and None, optional) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.

Returns:

  • z (ndarray) – The hypotenuse of the triangle(s). This is a scalar if both x1 and x2 are scalars.

  • .. note:: – This function differs from the original numpy.arange in the following aspects:

    • Only support float16, float32 and float64.

Examples

>>> np.hypot(3*np.ones((3, 3)), 4*np.ones((3, 3)))
array([[ 5.,  5.,  5.],
       [ 5.,  5.,  5.],
       [ 5.,  5.,  5.]])

Example showing broadcast of scalar_like argument:

>>> np.hypot(3*np.ones((3, 3)), [4])
array([[ 5.,  5.,  5.],
       [ 5.,  5.,  5.],
       [ 5.,  5.,  5.]])
mxnet.numpy.multiarray.i0(x)

Modified Bessel function of the first kind, order 0.

Usually denoted \(I_0\).

Parameters:

x (array_like of float) – Argument of the Bessel function.

Returns:

out – The modified Bessel function evaluated at each of the elements of x.

Return type:

ndarray, shape = x.shape, dtype = float

See also

scipy.special.i0, scipy.special.iv, scipy.special.ive

Notes

The scipy implementation is recommended over this function: it is a proper ufunc written in C, and more than an order of magnitude faster.

We use the algorithm published by Clenshaw [1]_ and referenced by Abramowitz and Stegun [2]_, for which the function domain is partitioned into the two intervals [0,8] and (8,inf), and Chebyshev polynomial expansions are employed in each interval. Relative error on the domain [0,30] using IEEE arithmetic is documented [3]_ as having a peak of 5.8e-16 with an rms of 1.4e-16 (n = 30000).

References

Examples

>>> np.i0(0.)
array(1.0)
>>> np.i0([0, 1, 2, 3])
array([1.        , 1.26606588, 2.2795853 , 4.88079259])
mxnet.numpy.multiarray.identity(n, dtype=None, device=None)

Return the identity array.

The identity array is a square array with ones on the main diagonal.

Parameters:
  • n (int) – Number of rows (and columns) in n x n output.

  • dtype (data-type, optional) – Data-type of the output. When npx.is_np_default_dtype() returns False, default dtype is float32; When npx.is_np_default_dtype() returns True, default dtype is float64.

  • device (Device, optional) – Device context on which the memory is allocated. Default is mxnet.device.current_device().

Returns:

outn x n array with its main diagonal set to one, and all other elements 0.

Return type:

ndarray

Examples

>>> np.identity(3)
>>> np.identity(3)
array([[1., 0., 0.],
       [0., 1., 0.],
       [0., 0., 1.]])
mxnet.numpy.multiarray.in1d(ar1, ar2, assume_unique=False, invert=False, *, kind=None)

Test whether each element of a 1-D array is also present in a second array.

Returns a boolean array the same length as ar1 that is True where an element of ar1 is in ar2 and False otherwise.

We recommend using isin() instead of in1d for new code.

Parameters:
  • ar1 ((M,) array_like) – Input array.

  • ar2 (array_like) – The values against which to test each value of ar1.

  • assume_unique (bool, optional) – If True, the input arrays are both assumed to be unique, which can speed up the calculation. Default is False.

  • invert (bool, optional) – If True, the values in the returned array are inverted (that is, False where an element of ar1 is in ar2 and True otherwise). Default is False. np.in1d(a, b, invert=True) is equivalent to (but is faster than) np.invert(in1d(a, b)).

  • kind ({None, 'sort', 'table'}, optional) –

    The algorithm to use. This will not affect the final result, but will affect the speed and memory use. The default, None, will select automatically based on memory considerations.

    • If ‘sort’, will use a mergesort-based approach. This will have a memory usage of roughly 6 times the sum of the sizes of ar1 and ar2, not accounting for size of dtypes.

    • If ‘table’, will use a lookup table approach similar to a counting sort. This is only available for boolean and integer arrays. This will have a memory usage of the size of ar1 plus the max-min value of ar2. assume_unique has no effect when the ‘table’ option is used.

    • If None, will automatically choose ‘table’ if the required memory allocation is less than or equal to 6 times the sum of the sizes of ar1 and ar2, otherwise will use ‘sort’. This is done to not use a large amount of memory by default, even though ‘table’ may be faster in most cases. If ‘table’ is chosen, assume_unique will have no effect.

    Added in version 1.8.0.

Returns:

in1d – The values ar1[in1d] are in ar2.

Return type:

(M,) ndarray, bool

See also

isin

Version of this function that preserves the shape of ar1.

numpy.lib.arraysetops

Module with a number of other functions for performing set operations on arrays.

Notes

in1d can be considered as an element-wise function version of the python keyword in, for 1-D sequences. in1d(a, b) is roughly equivalent to np.array([item in b for item in a]). However, this idea fails if ar2 is a set, or similar (non-sequence) container: As ar2 is converted to an array, in those cases asarray(ar2) is an object array rather than the expected array of contained values.

Using kind='table' tends to be faster than kind=’sort’ if the following relationship is true: log10(len(ar2)) > (log10(max(ar2)-min(ar2)) - 2.27) / 0.927, but may use greater memory. The default value for kind will be automatically selected based only on memory usage, so one may manually set kind='table' if memory constraints can be relaxed.

Added in version 1.4.0.

Examples

>>> test = np.array([0, 1, 2, 5, 0])
>>> states = [0, 2]
>>> mask = np.in1d(test, states)
>>> mask
array([ True, False,  True, False,  True])
>>> test[mask]
array([0, 2, 0])
>>> mask = np.in1d(test, states, invert=True)
>>> mask
array([False,  True, False,  True, False])
>>> test[mask]
array([1, 5])
mxnet.numpy.multiarray.indices(dimensions, dtype=None, device=None)

Return an array representing the indices of a grid.

Compute an array where the subarrays contain index values 0,1,… varying only along the corresponding axis.

Parameters:
  • dimensions (sequence of ints) – The shape of the grid.

  • dtype (data-type, optional) – The desired data-type for the array. Default is int64.

  • device (Device, optional) – Device context on which the memory is allocated. Default is mxnet.device.current_device().

Returns:

grid – The array of grid indices, grid.shape = (len(dimensions),) + tuple(dimensions).

Return type:

ndarray

Notes

The output shape is obtained by prepending the number of dimensions in front of the tuple of dimensions, i.e. if dimensions is a tuple (r0, ..., rN-1) of length N, the output shape is (N,r0,...,rN-1).

The subarrays grid[k] contains the N-D array of indices along the k-th axis. Explicitly:

grid[k,i0,i1,...,iN-1] = ik

Examples

>>> grid = np.indices((2, 3))
>>> grid.shape
(2, 2, 3)
>>> grid[0]        # row indices
array([[0, 0, 0],
       [1, 1, 1]], dtype=int64)
>>> grid[1]        # column indices
array([[0, 0, 0],
       [1, 1, 1]], dtype=int64)

The indices can be used as an index into an array.

>>> x = np.arange(20).reshape(5, 4)
>>> row, col = np.indices((2, 3))
>>> x[row, col]
array([[0., 1., 2.],
       [4., 5., 6.]])

Note that it would be more straightforward in the above example to extract the required elements directly with x[:2, :3].

mxnet.numpy.multiarray.inner(a, b)

Inner product of two arrays. Ordinary inner product of vectors for 1-D arrays (without complex conjugation), in higher dimensions a sum product over the last axes.

Parameters:
  • a (ndarray) – If a and b are nonscalar, their last dimensions must match.

  • b (ndarray) – If a and b are nonscalar, their last dimensions must match.

Returns:

outout.shape = a.shape[:-1] + b.shape[:-1]

Return type:

ndarray

Raises:

ValueError – If the last dimension of a and b has different size.

See also

tensordot

Sum products over arbitrary axes.

dot

Generalised matrix product, using second last dimension of b.

einsum

Einstein summation convention.

For vectors (1-D arrays) it computes the ordinary inner-product:: np.inner(a, b) = sum(a[:]*b[:]) More generally, if ndim(a) = r > 0 and ndim(b) = s > 0:: np.inner(a, b) = np.tensordot(a, b, axes=(-1,-1)) or explicitly:: np.inner(a, b)[i0,…,ir-1,j0,…,js-1] = sum(a[i0,…,ir-1,:]*b[j0,…,js-1,:]) In addition a or b may be scalars, in which case:: np.inner(a,b) = a*b

Examples

Ordinary inner product for vectors:

>>> a = np.array([1,2,3])
>>> b = np.array([0,1,0])
>>> np.inner(a, b)
array(2.)

A multidimensional example:

>>> a = np.arange(24).reshape((2,3,4))
>>> b = np.arange(4)
>>> np.inner(a, b)
array([[ 14.,  38.,  62.],
       [ 86., 110., 134.]])
mxnet.numpy.multiarray.insert(arr, obj, values, axis=None)

Insert values along the given axis before the given indices.

Parameters:
  • arr (ndarray) – Input array.

  • obj (int, slice or ndarray of int64) – Object that defines the index or indices before which values is inserted. Support for multiple insertions when obj is a single scalar or a sequence with one element (only support int32 and int64 element).

  • values (ndarray) – Values to insert into arr. If the type of values is different from that of arr, values is converted to the type of arr.

  • axis (int, optional) – Axis along which to insert values. If axis is None then arr is flattened first.

Returns:

  • out (ndarray) – A copy of arr with values inserted. Note that insert does not occur in-place: a new array is returned. If axis is None, out is a flattened array.

  • .. note::

    • Note that for higher dimensional inserts obj=0 behaves very different from obj=[0] just like arr[:,0,:] = values is different from arr[:,[0],:] = values.

    • If obj is a ndarray, it’s dtype only supports int64

Examples

>>> a = np.array([[1, 1], [2, 2], [3, 3]])
>>> a
array([[1., 1.],
       [2., 2.],
       [3., 3.]])
>>> np.insert(a, 1, np.array(5))
array([1., 5., 1., 2., 2., 3., 3.])
>>> np.insert(a, 1, np.array(5), axis=1)
array([[1., 5., 1.],
       [2., 5., 2.],
       [3., 5., 3.]])

Difference between sequence and scalars:

>>> np.insert(a, np.array([1], dtype=np.int64), np.array([[1],[2],[3]]), axis=1)
array([[1., 1., 1.],
       [2., 2., 2.],
       [3., 3., 3.]])
>>> np.insert(a, 1, np.array([1, 2, 3]), axis=1)
array([[1., 1., 1.],
       [2., 2., 2.],
       [3., 3., 3.]])
>>> b = a.flatten()
>>> b
array([1., 1., 2., 2., 3., 3.])
>>> np.insert(b, np.array([2, 2], dtype=np.int64), np.array([5, 6]))
array([1., 1., 5., 6., 2., 2., 3., 3.])
>>> np.insert(b, slice(2, 4), np.array([5, 6]))
array([1., 1., 5., 2., 6., 2., 3., 3.])

# type casting >>> np.insert(b.astype(np.int32), np.array([2, 2],dtype=’int64’), np.array([7.13, False])) array([1, 1, 7, 0, 2, 2, 3, 3], dtype=int32)

>>> x = np.arange(8).reshape(2, 4)
>>> idx = np.array([1, 3], dtype=np.int64)
>>> np.insert(x, idx, np.array([999]), axis=1)
array([[  0., 999.,   1.,   2., 999.,   3.],
       [  4., 999.,   5.,   6., 999.,   7.]])
mxnet.numpy.multiarray.interp(x, xp, fp, left=None, right=None, period=None)

One-dimensional linear interpolation.

Returns the one-dimensional piecewise linear interpolant to a function with given values at discrete data-points.

Parameters:
  • x (ndarray) – The x-coordinates of the interpolated values.

  • xp (1-D array of floats) – The x-coordinates of the data points, must be increasing if argument period is not specified. Otherwise, xp is internally sorted after normalizing the periodic boundaries with xp = xp % period.

  • fp (1-D array of floats) – The y-coordinates of the data points, same length as xp.

  • left (optional float corresponding to fp) – Value to return for x < xp[0], default is fp[0].

  • right (optional float corresponding to fp) – Value to return for x > xp[-1], default is fp[-1].

  • period (None or float, optional) – A period for the x-coordinates. This parameter allows the proper interpolation of angular x-coordinates. Parameters left and right are ignored if period is specified.

Returns:

y – The interpolated values, same shape as x.

Return type:

float (corresponding to fp) or ndarray

Raises:
  • ValueError – If xp and fp have different length If xp or fp are not 1-D sequences If period == 0

  • .. note:: – Does not check that the x-coordinate sequence xp is increasing. If xp is not increasing, the results are nonsense. A simple check for increasing is:: np.all(np.diff(xp) > 0)

Examples

>>> xp = [1, 2, 3]
>>> fp = [3, 2, 0]
>>> np.interp(2.5, xp, fp)
1.0
>>> np.interp([0, 1, 1.5, 2.72, 3.14], xp, fp)
array([ 3. ,  3. ,  2.5 ,  0.56,  0. ])
>>> UNDEF = -99.0
>>> np.interp(3.14, xp, fp, right=UNDEF)
-99.0
Plot an interpolant to the sine function:
>>> x = np.linspace(0, 2*np.pi, 10)
>>> y = np.sin(x)
>>> xvals = np.linspace(0, 2*np.pi, 50)
>>> yinterp = np.interp(xvals, x, y)
>>> import matplotlib.pyplot as plt
>>> plt.plot(x, y, 'o')
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.plot(xvals, yinterp, '-x')
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.show()
Interpolation with periodic x-coordinates:
>>> x = [-180, -170, -185, 185, -10, -5, 0, 365]
>>> xp = [190, -190, 350, -350]
>>> fp = [5, 10, 3, 4]
>>> np.interp(x, xp, fp, period=360)
array([7.5, 5., 8.75, 6.25, 3., 3.25, 3.5, 3.75])
mxnet.numpy.multiarray.intersect1d(ar1, ar2, assume_unique=False, return_indices=False)

Find the intersection of two arrays.

Return the sorted, unique values that are in both of the input arrays.

Parameters:
  • ar1 (array_like) – Input arrays. Will be flattened if not already 1D.

  • ar2 (array_like) – Input arrays. Will be flattened if not already 1D.

  • assume_unique (bool) – If True, the input arrays are both assumed to be unique, which can speed up the calculation. If True but ar1 or ar2 are not unique, incorrect results and out-of-bounds indices could result. Default is False.

  • return_indices (bool) –

    If True, the indices which correspond to the intersection of the two arrays are returned. The first instance of a value is used if there are multiple. Default is False.

    Added in version 1.15.0.

Returns:

  • intersect1d (ndarray) – Sorted 1D array of common and unique elements.

  • comm1 (ndarray) – The indices of the first occurrences of the common values in ar1. Only provided if return_indices is True.

  • comm2 (ndarray) – The indices of the first occurrences of the common values in ar2. Only provided if return_indices is True.

See also

numpy.lib.arraysetops

Module with a number of other functions for performing set operations on arrays.

Examples

>>> np.intersect1d([1, 3, 4, 3], [3, 1, 2, 1])
array([1, 3])

To intersect more than two arrays, use functools.reduce:

>>> from functools import reduce
>>> reduce(np.intersect1d, ([1, 3, 4, 3], [3, 1, 2, 1], [6, 3, 4, 2]))
array([3])

To return the indices of the values common to the input arrays along with the intersected values:

>>> x = np.array([1, 1, 2, 3, 4])
>>> y = np.array([2, 1, 4, 6])
>>> xy, x_ind, y_ind = np.intersect1d(x, y, return_indices=True)
>>> x_ind, y_ind
(array([0, 2, 4]), array([1, 0, 2]))
>>> xy, x[x_ind], y[y_ind]
(array([1, 2, 4]), array([1, 2, 4]), array([1, 2, 4]))
mxnet.numpy.multiarray.invert(x, out=None, **kwargs)

Compute bit-wise inversion, or bit-wise NOT, element-wise. Computes the bit-wise NOT of the underlying binary representation of the integers in the input arrays. This ufunc implements the C/Python operator ~.

Parameters:
  • x (array_like) – Only integer and boolean types are handled.

  • out (ndarray, None, or tuple of ndarray and None, optional) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.

Returns:

out – Result. This is a scalar if x is a scalar.

Return type:

ndarray or scalar

See also

bitwise_and, bitwise_or, bitwise_xor, logical_not

binary_repr

Return the binary representation of the input number as a string.

Examples

We’ve seen that 13 is represented by 00001101. The invert or bit-wise NOT of 13 is then:

>>> x = np.invert(np.array(13, dtype=np.uint8))
>>> x
242
>>> np.binary_repr(x, width=8)
'11110010'

Notes

bitwise_not is an alias for invert:

>>> np.bitwise_not is np.invert
True
mxnet.numpy.multiarray.isclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False)

Returns a boolean array where two arrays are element-wise equal within a tolerance.

The tolerance values are positive, typically very small numbers. The relative difference (rtol * abs(b)) and the absolute difference atol are added together to compare against the absolute difference between a and b.

Warning

The default atol is not appropriate for comparing numbers that are much smaller than one (see Notes).

Parameters:
  • a (array_like) – Input arrays to compare.

  • b (array_like) – Input arrays to compare.

  • rtol (float) – The relative tolerance parameter (see Notes).

  • atol (float) – The absolute tolerance parameter (see Notes).

  • equal_nan (bool) – Whether to compare NaN’s as equal. If True, NaN’s in a will be considered equal to NaN’s in b in the output array.

Returns:

y – Returns a boolean array of where a and b are equal within the given tolerance. If both a and b are scalars, returns a single boolean value.

Return type:

array_like

Notes

Added in version 1.7.0.

For finite values, isclose uses the following equation to test whether two floating point values are equivalent.

absolute(a - b) <= (atol + rtol * absolute(b))

Unlike the built-in math.isclose, the above equation is not symmetric in a and b – it assumes b is the reference value – so that isclose(a, b) might be different from isclose(b, a). Furthermore, the default value of atol is not zero, and is used to determine what small values should be considered close to zero. The default value is appropriate for expected values of order unity: if the expected values are significantly smaller than one, it can result in false positives. atol should be carefully selected for the use case at hand. A zero value for atol will result in False if either a or b is zero.

isclose is not defined for non-numeric data types. bool is considered a numeric data-type for this purpose.

Examples

>>> np.isclose([1e10,1e-7], [1.00001e10,1e-8])
array([ True, False])
>>> np.isclose([1e10,1e-8], [1.00001e10,1e-9])
array([ True, True])
>>> np.isclose([1e10,1e-8], [1.0001e10,1e-9])
array([False,  True])
>>> np.isclose([1.0, np.nan], [1.0, np.nan])
array([ True, False])
>>> np.isclose([1.0, np.nan], [1.0, np.nan], equal_nan=True)
array([ True, True])
>>> np.isclose([1e-8, 1e-7], [0.0, 0.0])
array([ True, False])
>>> np.isclose([1e-100, 1e-7], [0.0, 0.0], atol=0.0)
array([False, False])
>>> np.isclose([1e-10, 1e-10], [1e-20, 0.0])
array([ True,  True])
>>> np.isclose([1e-10, 1e-10], [1e-20, 0.999999e-10], atol=0.0)
array([False,  True])
mxnet.numpy.multiarray.isfinite(x, out=None, **kwargs)

Test element-wise for finiteness (not infinity or not Not a Number).

Parameters:
  • x (ndarray) – Input array.

  • out (ndarray or None, optional) – A location into which the result is stored. If provided, it must have the same shape and dtype as input ndarray. If not provided or None, a freshly-allocated array is returned.

Returns:

y – True where x is negative infinity, false otherwise. This is a scalar if x is a scalar.

Return type:

ndarray or bool

Notes

Not a Number, positive infinity and negative infinity are considered to be non-finite.

NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). This means that Not a Number is not equivalent to infinity. Also that positive infinity is not equivalent to negative infinity. But infinity is equivalent to positive infinity. Errors result if the second argument is also supplied when x is a scalar input, or if first and second arguments have different shapes.

Examples

>>> np.isfinite(1)
True
>>> np.isfinite(0)
True
>>> np.isfinite(np.nan)
False
>>> np.isfinite(np.inf)
False
>>> np.isfinite(-np.inf)
False
>>> np.isfinite(np.array([np.log(-1.),1.,np.log(0)]))
array([False,  True, False])
>>> x = np.array([-np.inf, 0., np.inf])
>>> y = np.array([True, True, True], dtype=np.bool_)
>>> np.isfinite(x, y)
array([False,  True, False])
>>> y
array([False,  True, False])
mxnet.numpy.multiarray.isin(element, test_elements, assume_unique=False, invert=False, *, kind=None)

Calculates element in test_elements, broadcasting over element only. Returns a boolean array of the same shape as element that is True where an element of element is in test_elements and False otherwise.

Parameters:
  • element (array_like) – Input array.

  • test_elements (array_like) – The values against which to test each value of element. This argument is flattened if it is an array or array_like. See notes for behavior with non-array-like parameters.

  • assume_unique (bool, optional) – If True, the input arrays are both assumed to be unique, which can speed up the calculation. Default is False.

  • invert (bool, optional) – If True, the values in the returned array are inverted, as if calculating element not in test_elements. Default is False. np.isin(a, b, invert=True) is equivalent to (but faster than) np.invert(np.isin(a, b)).

  • kind ({None, 'sort', 'table'}, optional) –

    The algorithm to use. This will not affect the final result, but will affect the speed and memory use. The default, None, will select automatically based on memory considerations.

    • If ‘sort’, will use a mergesort-based approach. This will have a memory usage of roughly 6 times the sum of the sizes of ar1 and ar2, not accounting for size of dtypes.

    • If ‘table’, will use a lookup table approach similar to a counting sort. This is only available for boolean and integer arrays. This will have a memory usage of the size of ar1 plus the max-min value of ar2. assume_unique has no effect when the ‘table’ option is used.

    • If None, will automatically choose ‘table’ if the required memory allocation is less than or equal to 6 times the sum of the sizes of ar1 and ar2, otherwise will use ‘sort’. This is done to not use a large amount of memory by default, even though ‘table’ may be faster in most cases. If ‘table’ is chosen, assume_unique will have no effect.

Returns:

isin – Has the same shape as element. The values element[isin] are in test_elements.

Return type:

ndarray, bool

See also

in1d

Flattened version of this function.

numpy.lib.arraysetops

Module with a number of other functions for performing set operations on arrays.

Notes

isin is an element-wise function version of the python keyword in. isin(a, b) is roughly equivalent to np.array([item in b for item in a]) if a and b are 1-D sequences.

element and test_elements are converted to arrays if they are not already. If test_elements is a set (or other non-sequence collection) it will be converted to an object array with one element, rather than an array of the values contained in test_elements. This is a consequence of the array constructor’s way of handling non-sequence collections. Converting the set to a list usually gives the desired behavior.

Using kind='table' tends to be faster than kind=’sort’ if the following relationship is true: log10(len(ar2)) > (log10(max(ar2)-min(ar2)) - 2.27) / 0.927, but may use greater memory. The default value for kind will be automatically selected based only on memory usage, so one may manually set kind='table' if memory constraints can be relaxed.

Added in version 1.13.0.

Examples

>>> element = 2*np.arange(4).reshape((2, 2))
>>> element
array([[0, 2],
       [4, 6]])
>>> test_elements = [1, 2, 4, 8]
>>> mask = np.isin(element, test_elements)
>>> mask
array([[False,  True],
       [ True, False]])
>>> element[mask]
array([2, 4])

The indices of the matched values can be obtained with nonzero:

>>> np.nonzero(mask)
(array([0, 1]), array([1, 0]))

The test can also be inverted:

>>> mask = np.isin(element, test_elements, invert=True)
>>> mask
array([[ True, False],
       [False,  True]])
>>> element[mask]
array([0, 6])

Because of how array handles sets, the following does not work as expected:

>>> test_set = {1, 2, 4, 8}
>>> np.isin(element, test_set)
array([[False, False],
       [False, False]])

Casting the set to a list gives the expected result:

>>> np.isin(element, list(test_set))
array([[False,  True],
       [ True, False]])
mxnet.numpy.multiarray.isinf(x, out=None, **kwargs)

Test element-wise for positive or negative infinity.

Parameters:
  • x (ndarray) – Input array.

  • out (ndarray or None, optional) – A location into which the result is stored. If provided, it must have the same shape and dtype as input ndarray. If not provided or None, a freshly-allocated array is returned.

Returns:

y – True where x is positive or negative infinity, false otherwise. This is a scalar if x is a scalar.

Return type:

ndarray or bool

Notes

NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). This means that Not a Number is not equivalent to infinity.

Note

This function differs from the original numpy.isnan in the following aspects:

  • Does not support complex number for now

  • Input type does not support Python native iterables(list, tuple, …).

  • out param: cannot perform auto broadcasting. out ndarray’s shape must be the same as the expected output.

  • out param: cannot perform auto type cast. out ndarray’s dtype must be the same as the expected output.

  • out param does not support scalar input case.

Examples

>>> np.isinf(np.inf)
True
>>> np.isinf(np.nan)
False
>>> np.isinf(np.array([np.inf, -np.inf, 1.0, np.nan]))
array([ True,  True, False, False])
>>> x = np.array([-np.inf, 0., np.inf])
>>> y = np.array([True, True, True], dtype=np.bool_)
>>> np.isinf(x, y)
array([ True, False,  True])
>>> y
array([ True, False,  True])
mxnet.numpy.multiarray.isnan(x, out=None, **kwargs)

Test element-wise for NaN and return result as a boolean array.

Parameters:
  • x (ndarray) – Input array.

  • out (ndarray or None, optional) – A location into which the result is stored. If provided, it must have the same shape and dtype as input ndarray. If not provided or None, a freshly-allocated array is returned.

Returns:

y – True where x is NaN, false otherwise. This is a scalar if x is a scalar.

Return type:

ndarray or bool

Notes

NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754).

Note

This function differs from the original numpy.isinf in the following aspects:

  • Does not support complex number for now

  • Input type does not support Python native iterables(list, tuple, …).

  • out param: cannot perform auto broadcasting. out ndarray’s shape must be the same as the expected output.

  • out param: cannot perform auto type cast. out ndarray’s dtype must be the same as the expected output.

  • out param does not support scalar input case.

Examples

>>> np.isnan(np.nan)
True
>>> np.isnan(np.inf)
False
>>> np.isnan(np.array([np.log(-1.),1.,np.log(0)]))
array([ True, False, False])
mxnet.numpy.multiarray.isneginf(x, out=None, **kwargs)

Test element-wise for negative infinity, return result as bool array.

Parameters:
  • x (ndarray) – Input array.

  • out (ndarray or None, optional) – A location into which the result is stored. If provided, it must have the same shape and dtype as input ndarray. If not provided or None, a freshly-allocated array is returned.

Returns:

y – True where x is negative infinity, false otherwise. This is a scalar if x is a scalar.

Return type:

ndarray or bool

Notes

NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). This means that Not a Number is not equivalent to infinity.

Examples

>>> np.isneginf(-np.inf)
True
>>> np.isneginf(np.inf)
False
>>> np.isneginf(float('-inf'))
True
>>> np.isneginf(np.array([-np.inf, 0., np.inf]))
array([ True, False, False])
>>> x = np.array([-np.inf, 0., np.inf])
>>> y = np.array([True, True, True], dtype=np.bool_)
>>> np.isneginf(x, y)
array([ True, False, False])
>>> y
array([ True, False, False])
mxnet.numpy.multiarray.isposinf(x, out=None, **kwargs)

Test element-wise for positive infinity, return result as bool array.

Parameters:
  • x (ndarray) – Input array.

  • out (ndarray or None, optional) – A location into which the result is stored. If provided, it must have the same shape and dtype as input ndarray. If not provided or None, a freshly-allocated array is returned.

Returns:

y – True where x is positive infinity, false otherwise. This is a scalar if x is a scalar.

Return type:

ndarray or bool

Notes

NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). This means that Not a Number is not equivalent to infinity.

Examples

>>> np.isposinf(np.inf)
True
>>> np.isposinf(-np.inf)
False
>>> np.isposinf(np.nan)
False
>>> np.isposinf(np.array([-np.inf, 0., np.inf]))
array([False, False,  True])
>>> x = np.array([-np.inf, 0., np.inf])
>>> y = np.array([True, True, True], dtype=np.bool_)
>>> np.isposinf(x, y)
array([False, False,  True])
>>> y
array([False, False,  True])
mxnet.numpy.multiarray.ix_(*args)

Construct an open mesh from multiple sequences.

This function takes N 1-D sequences and returns N outputs with N dimensions each, such that the shape is 1 in all but one dimension and the dimension with the non-unit shape value cycles through all N dimensions.

Using ix_ one can quickly construct index arrays that will index the cross product. a[np.ix_([1,3],[2,5])] returns the array [[a[1,2] a[1,5]], [a[3,2] a[3,5]]].

Parameters:

args (1-D sequences) – Each sequence should be of integer or boolean type. Boolean sequences will be interpreted as boolean masks for the corresponding dimension (equivalent to passing in np.nonzero(boolean_sequence)).

Returns:

out – N arrays with N dimensions each, with N the number of input sequences. Together these arrays form an open mesh.

Return type:

tuple of ndarrays

See also

ogrid, mgrid, meshgrid

Examples

>>> a = np.arange(10).reshape(2, 5)
>>> a
array([[0, 1, 2, 3, 4],
       [5, 6, 7, 8, 9]])
>>> ixgrid = np.ix_([0, 1], [2, 4])
>>> ixgrid
(array([[0],
       [1]]), array([[2, 4]]))
>>> ixgrid[0].shape, ixgrid[1].shape
((2, 1), (1, 2))
>>> a[ixgrid]
array([[2, 4],
       [7, 9]])
>>> ixgrid = np.ix_([True, True], [2, 4])
>>> a[ixgrid]
array([[2, 4],
       [7, 9]])
>>> ixgrid = np.ix_([True, True], [False, False, True, False, True])
>>> a[ixgrid]
array([[2, 4],
       [7, 9]])
mxnet.numpy.multiarray.kron(a, b)

Kronecker product of two arrays.

Computes the Kronecker product, a composite array made of blocks of the second array scaled by the first.

Parameters:
Returns:

out

Return type:

ndarray

See also

outer

The outer product

The function assumes that the number of dimensions of a and b are the same, if necessary prepending the smallest with ones. If a.shape = (r0,r1,..,rN) and b.shape = (s0,s1,…,sN), the Kronecker product has shape (r0*s0, r1*s1, …, rN*SN). The elements are products of elements from a and b, organized explicitly by:: kron(a,b)[k0,k1,…,kN] = a[i0,i1,…,iN] * b[j0,j1,…,jN]

where

: kt = it * st + jt, t = 0,…,N In the common 2-D case (N=1), the block structure can be visualized:: [[ a[0,0]*b, a[0,1]*b, … , a[0,-1]*b ], [ … … ], [ a[-1,0]*b, a[-1,1]*b, … , a[-1,-1]*b ]]

Examples

>>> np.kron([1,10,100], [5,6,7])
array([  5,   6,   7,  50,  60,  70, 500, 600, 700])
>>> np.kron([5,6,7], [1,10,100])
array([  5,  50, 500,   6,  60, 600,   7,  70, 700])
mxnet.numpy.multiarray.lcm(x1, x2, out=None, **kwargs)

Returns the lowest common multiple of |x1| and |x2|

Parameters:
  • x1 (ndarrays or scalar values) – The arrays for computing lowest common multiple. If x1.shape != x2.shape, they must be broadcastable to a common shape (which may be the shape of one or the other).

  • x2 (ndarrays or scalar values) – The arrays for computing lowest common multiple. If x1.shape != x2.shape, they must be broadcastable to a common shape (which may be the shape of one or the other).

  • out (ndarray or None, optional) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned.

Returns:

y – The lowest common multiple of the absolute value of the inputs This is a scalar if both x1 and x2 are scalars.

Return type:

ndarray or scalar

See also

gcd

The greatest common divisor

Examples

>>> np.lcm(12, 20)
60
>>> np.lcm(np.arange(6, dtype=int), 20)
array([ 0, 20, 20, 60, 20, 20], dtype=int64)
mxnet.numpy.multiarray.ldexp(x1, x2, out=None, **kwargs)

Returns x1 * 2**x2, element-wise. The mantissas x1 and twos exponents x2 are used to construct floating point numbers x1 * 2**x2.

Parameters:
  • x1 (ndarray or scalar) – Array of multipliers.

  • x2 (ndarray or scalar, int) – Array of twos exponents.

  • out (ndarray, optional) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not, a freshly-allocated array is returned.

Returns:

y – The result of x1 * 2**x2. This is a scalar if both x1 and x2 are scalars.

Return type:

ndarray or scalar

Notes

Complex dtypes are not supported, they will raise a TypeError. Different from numpy, we allow x2 to be float besides int. ldexp is useful as the inverse of frexp, if used by itself it is more clear to simply use the expression x1 * 2**x2.

Examples

>>> np.ldexp(5, np.arange(4))
array([  5.,  10.,  20.,  40.])
mxnet.numpy.multiarray.less(x1, x2, out=None)

Return the truth value of (x1 < x2) element-wise.

Parameters:
  • x1 (ndarrays or scalars) – Input arrays. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • x2 (ndarrays or scalars) – Input arrays. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • out (ndarray, None, or tuple of ndarray and None, optional) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned.

Returns:

out – Output array of type bool, element-wise comparison of x1 and x2. This is a scalar if both x1 and x2 are scalars.

Return type:

ndarray or scalar

Examples

>>> np.less(np.ones(2, 1)), np.zeros(1, 3))
array([[ True,  True,  True],
       [ True,  True,  True]])
>>> np.less(1, np.ones(1))
array([False])
mxnet.numpy.multiarray.less_equal(x1, x2, out=None)

Return the truth value of (x1 <= x2) element-wise.

Parameters:
  • x1 (ndarrays or scalars) – Input arrays. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • x2 (ndarrays or scalars) – Input arrays. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • out (ndarray, None, or tuple of ndarray and None, optional) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned.

Returns:

out – Output array of type bool, element-wise comparison of x1 and x2. This is a scalar if both x1 and x2 are scalars.

Return type:

ndarray or scalar

Examples

>>> np.less_equal(np.ones(2, 1)), np.zeros(1, 3))
array([[False, False, False],
       [False, False, False]])
>>> np.less_equal(1, np.ones(1))
array([True])
mxnet.numpy.multiarray.lexsort(keys, axis=-1)

Perform an indirect stable sort using a sequence of keys.

Given multiple sorting keys, which can be interpreted as columns in a spreadsheet, lexsort returns an array of integer indices that describes the sort order by multiple columns. The last key in the sequence is used for the primary sort order, the second-to-last key for the secondary sort order, and so on. The keys argument must be a sequence of objects that can be converted to arrays of the same shape. If a 2D array is provided for the keys argument, its rows are interpreted as the sorting keys and sorting is according to the last row, second last row etc.

Parameters:
  • keys ((k, N) array or tuple containing k (N,)-shaped sequences) – The k different “columns” to be sorted. The last column (or row if keys is a 2D array) is the primary sort key.

  • axis (int, optional) – Axis to be indirectly sorted. By default, sort over the last axis.

Returns:

indices – Array of indices that sort the keys along the specified axis.

Return type:

(N,) ndarray of ints

See also

argsort

Indirect sort.

ndarray.sort

In-place sort.

sort

Return a sorted copy of an array.

Examples

Sort names: first by surname, then by name.

>>> surnames =    ('Hertz',    'Galilei', 'Hertz')
>>> first_names = ('Heinrich', 'Galileo', 'Gustav')
>>> ind = np.lexsort((first_names, surnames))
>>> ind
array([1, 2, 0])
>>> [surnames[i] + ", " + first_names[i] for i in ind]
['Galilei, Galileo', 'Hertz, Gustav', 'Hertz, Heinrich']

Sort two columns of numbers:

>>> a = [1,5,1,4,3,4,4] # First column
>>> b = [9,4,0,4,0,2,1] # Second column
>>> ind = np.lexsort((b,a)) # Sort by a, then by b
>>> ind
array([2, 0, 4, 6, 5, 3, 1])
>>> [(a[i],b[i]) for i in ind]
[(1, 0), (1, 9), (3, 0), (4, 1), (4, 2), (4, 4), (5, 4)]

Note that sorting is first according to the elements of a. Secondary sorting is according to the elements of b.

A normal argsort would have yielded:

>>> [(a[i],b[i]) for i in np.argsort(a)]
[(1, 9), (1, 0), (3, 0), (4, 4), (4, 2), (4, 1), (5, 4)]

Structured arrays are sorted lexically by argsort:

>>> x = np.array([(1,9), (5,4), (1,0), (4,4), (3,0), (4,2), (4,1)],
...              dtype=np.dtype([('x', int), ('y', int)]))
>>> np.argsort(x) # or np.argsort(x, order=('x', 'y'))
array([2, 0, 4, 6, 5, 3, 1])
mxnet.numpy.multiarray.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0, device=None)

Return evenly spaced numbers over a specified interval.

Returns num evenly spaced samples, calculated over the interval [start, stop]. The endpoint of the interval can optionally be excluded.

Parameters:
  • start (int or float) – The starting value of the sequence.

  • stop (int or float) – The end value of the sequence, unless endpoint is set to False. In that case, the sequence consists of all but the last of num + 1 evenly spaced samples, so that stop is excluded. Note that the step size changes when endpoint is False.

  • num (int, optional) – Number of samples to generate. Default is 50. Must be non-negative.

  • endpoint (bool, optional) – If True, stop is the last sample. Otherwise, it is not included. Default is True.

  • retstep (bool, optional) – If True, return (samples, step), where step is the spacing between samples.

  • dtype (dtype, optional) – The type of the output array. If dtype is not given, infer the data type from the other input arguments.

  • axis (int, optional) – The axis in the result to store the samples. Relevant only if start or stop are array-like. By default (0), the samples will be along a new axis inserted at the beginning. Use -1 to get an axis at the end.

  • device (Device, optional) – Device context on which the memory is allocated. Default is mxnet.device.current_device().

Returns:

  • samples (ndarray) – There are num equally spaced samples in the closed interval [start, stop] or the half-open interval [start, stop) (depending on whether endpoint is True or False).

  • step (float, optional) – Only returned if retstep is True Size of spacing between samples.

See also

arange

Similar to linspace, but uses a step size (instead of the number of samples).

Examples

>>> np.linspace(2.0, 3.0, num=5)
array([2.  , 2.25, 2.5 , 2.75, 3.  ])
>>> np.linspace(2.0, 3.0, num=5, endpoint=False)
array([2. , 2.2, 2.4, 2.6, 2.8])
>>> np.linspace(2.0, 3.0, num=5, retstep=True)
(array([2.  , 2.25, 2.5 , 2.75, 3.  ]), 0.25)

Graphical illustration:

>>> import matplotlib.pyplot as plt
>>> N = 8
>>> y = np.zeros(N)
>>> x1 = np.linspace(0, 10, N, endpoint=True)
>>> x2 = np.linspace(0, 10, N, endpoint=False)
>>> plt.plot(x1.asnumpy(), y.asnumpy(), 'o')
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.plot(x2.asnumpy(), (y + 0.5).asnumpy(), 'o')
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.ylim([-0.5, 1])
(-0.5, 1)
>>> plt.show()

Note

This function differs from the original numpy.linspace in the following aspects:

  • start and stop do not support list, numpy ndarray and mxnet ndarray

  • axis could only be 0

  • There could be an additional device argument to specify the device, e.g. the i-th GPU.

mxnet.numpy.multiarray.log(x, out=None, **kwargs)

Natural logarithm, element-wise. The natural logarithm log is the inverse of the exponential function, so that log(exp(x)) = x. The natural logarithm is logarithm in base e.

Parameters:
  • x (ndarray) – Input value. Elements must be of real value.

  • out (ndarray or None, optional) – A location into which the result is stored. If provided, it must have the same shape and dtype as input ndarray. If not provided or None, a freshly-allocated array is returned.

Returns:

  • y (ndarray) – The natural logarithm of x, element-wise. This is a scalar if x is a scalar.

  • .. note:: – Currently only supports data of real values and inf as input. Returns data of real value, inf, -inf and nan according to the input. This function differs from the original numpy.log in the following aspects:

    • Does not support complex number for now

    • Input type does not support Python native iterables(list, tuple, …).

    • out param: cannot perform auto broadcasting. out ndarray’s shape must be the same as the expected output.

    • out param: cannot perform auto type cast. out ndarray’s dtype must be the same as the expected output.

    • out param does not support scalar input case.

Examples

>>> a = np.array([1, np.exp(1), np.exp(2), 0], dtype=np.float64)
>>> np.log(a)
array([  0.,   1.,   2., -inf], dtype=float64)
>>> # Using the default float32 dtype leads to slightly different behavior
>>> a = np.array([1, np.exp(1), np.exp(2), 0])
>>> np.log(a)
array([  0.,  0.99999994,   2., -inf])
>>> np.log(1)
0.0
mxnet.numpy.multiarray.log10(x, out=None, **kwargs)

Return the base 10 logarithm of the input array, element-wise.

Parameters:
  • x (ndarray or scalar) – Input array or scalar.

  • out (ndarray or None) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. The dtype of the output is the same as that of the input if the input is an ndarray.

Returns:

y – The logarithm to the base 10 of x, element-wise. NaNs are returned where x is negative. This is a scalar if x is a scalar.

Return type:

ndarray or scalar

Notes

This function only supports input type of float.

Examples

>>> np.log10(np.array([1e-15, -3.]))
array([-15.,  nan])
mxnet.numpy.multiarray.log1p(x, out=None, **kwargs)

Return the natural logarithm of one plus the input array, element-wise. Calculates log(1 + x).

Parameters:
  • x (ndarray or scalar) – Input array.

  • out (ndarray or None) – A location into which the result is stored. If provided, it must have a shape that the inputs fill into. If not provided or None, a freshly-allocated array is returned. The dtype of the output and input must be the same.

Returns:

y – Natural logarithm of 1 + x, element-wise. This is a scalar if x is a scalar.

Return type:

ndarray or scalar

Notes

For real-valued input, log1p is accurate also for x so small that 1 + x == 1 in floating-point accuracy. Logarithm is a multivalued function: for each x there is an infinite number of z such that exp(z) = 1 + x. The convention is to return the z whose imaginary part lies in [-pi, pi]. For real-valued input data types, log1p always returns real output. For each value that cannot be expressed as a real number or infinity, it yields nan and sets the invalid floating point error flag. cannot support complex-valued input.

Examples

>>> np.log1p(1e-99)
1e-99
>>> a = np.array([3, 4, 5])
>>> np.log1p(a)
array([1.3862944, 1.609438 , 1.7917595])
mxnet.numpy.multiarray.log2(x, out=None, **kwargs)

Base-2 logarithm of x.

Parameters:
  • x (ndarray or scalar) – Input values.

  • out (ndarray or None) – A location into which the result is stored. If provided, it must have the same shape and type as the input. If not provided or None, a freshly-allocated array is returned.

Returns:

  • y (ndarray) – The logarithm base two of x, element-wise. This is a scalar if x is a scalar.

  • .. note:: – This function differs from the original numpy.log2 in the following way(s):

    • only ndarray or scalar is accpted as valid input, tuple of ndarray is not supported

    • broadcasting to out of different shape is currently not supported

    • when input is plain python numerics, the result will not be stored in the out param

Examples

>>> x = np.array([0, 1, 2, 2**4])
>>> np.log2(x)
array([-inf,   0.,   1.,   4.])
mxnet.numpy.multiarray.logaddexp(x1, x2, out=None, **kwargs)

Logarithm of the sum of exponentiations of the inputs.

Calculates log(exp(x1) + exp(x2)). This function is useful in statistics where the calculated probabilities of events may be so small as to exceed the range of normal floating point numbers. In such cases the logarithm of the calculate probability is stored. This function allows adding probabilities stored in such a fashion.

Parameters:
  • x1 (ndarray or scalar) – Array of multipliers.

  • x2 (ndarray or scalar, int) – Array of twos exponents.

  • out (ndarray, optional) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not, a freshly-allocated array is returned.

Returns:

y – Logarithm of exp(x1) + exp(x2). This is a scalar if both x1 and x2 are scalars.

Return type:

ndarray or scalar

Examples

>>> prob1 = np.log(1e-50)
>>> prob2 = np.log(2.5e-50)
>>> prob12 = np.logaddexp(prob1, prob2)
>>> prob12
-113.87649168120691
>>> np.exp(prob12)
3.5000000000000057e-50
mxnet.numpy.multiarray.logical_and(x1, x2, out=None)

Compute the truth value of x1 AND x2 element-wise.

Parameters:
  • x1 (array_like) – Logical AND is applied to the elements of x1 and x2. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • x2 (array_like) – Logical AND is applied to the elements of x1 and x2. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • out (ndarray, None, or tuple of ndarray and None, optional) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.

Returns:

y – Boolean result of the logical AND operation applied to the elements of x1 and x2; the shape is determined by broadcasting. This is a scalar if both x1 and x2 are scalars.

Return type:

ndarray or bool

Examples

>>> np.logical_and(True, False)
False
>>> np.logical_and(np.array([True, True], dtype='bool'), np.array([False, True], dtype='bool'))
array([False,  True])
mxnet.numpy.multiarray.logical_not(x, out=None, **kwargs)

Compute the truth value of NOT x element-wise.

Parameters:
  • x (ndarray or scalar) – Logical NOT is applied to the elements of x.

  • out (ndarray or None, optional) – A location into which the result is stored.

Returns:

  • y (bool or ndarray of bool) – Boolean result with the same shape as x of the NOT operation on elements of x. This is a scalar if x is a scalar.

  • .. note:: – This function differs from the original numpy.logical_not in the following aspects: * Do not support where, a parameter in numpy which indicates where to calculate. * Cannot cast type automatically. Dtype of out must be same as the expected one. * Cannot broadcast automatically. Shape of out must be same as the expected one. * If x is plain python numeric, the result won’t be stored in out.

Examples

>>> x= np.array([True, False, 0, 1])
>>> np.logical_not(x)
array([False,  True,  True, False])
>>> x = np.arange(5)
>>> np.logical_not(x<3)
array([False, False, False,  True,  True])
mxnet.numpy.multiarray.logical_or(x1, x2, out=None)

Compute the truth value of x1 OR x2 element-wise.

Parameters:
  • x1 (array_like) – Logical OR is applied to the elements of x1 and x2. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • x2 (array_like) – Logical OR is applied to the elements of x1 and x2. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • out (ndarray, None, or tuple of ndarray and None, optional) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.

Returns:

y – Boolean result of the logical OR operation applied to the elements of x1 and x2; the shape is determined by broadcasting. This is a scalar if both x1 and x2 are scalars.

Return type:

ndarray or bool

Examples

>>> np.logical_or(True, False)
True
>>> np.logical_or(np.array([True, True], dtype='bool'), np.array([False, True], dtype='bool'))
array([True,  True])
mxnet.numpy.multiarray.logical_xor(x1, x2, out=None)

Compute the truth value of x1 XOR x2 element-wise.

Parameters:
  • x1 (array_like) – Logical XOR is applied to the elements of x1 and x2. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • x2 (array_like) – Logical XOR is applied to the elements of x1 and x2. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • out (ndarray, None, or tuple of ndarray and None, optional) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.

Returns:

y – Boolean result of the logical XOR operation applied to the elements of x1 and x2; the shape is determined by broadcasting. This is a scalar if both x1 and x2 are scalars.

Return type:

ndarray or bool

Examples

>>> np.logical_xor(True, False)
True
>>> np.logical_xor(np.array([True, True], dtype='bool'), np.array([False, True], dtype='bool'))
array([ True, False])
mxnet.numpy.multiarray.logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None, axis=0, device=None)

Return numbers spaced evenly on a log scale.

In linear space, the sequence starts at base ** start (base to the power of start) and ends with base ** stop (see endpoint below).

Non-scalar start and stop are now supported.

Parameters:
  • start (int or float) – base ** start is the starting value of the sequence.

  • stop (int or float) – base ** stop is the final value of the sequence, unless endpoint is False. In that case, num + 1 values are spaced over the interval in log-space, of which all but the last (a sequence of length num) are returned.

  • num (integer, optional) – Number of samples to generate. Default is 50.

  • endpoint (boolean, optional) – If true, stop is the last sample. Otherwise, it is not included. Default is True.

  • base (float, optional) – The base of the log space. The step size between the elements in ln(samples) / ln(base) (or log_base(samples)) is uniform. Default is 10.0.

  • dtype (dtype) – The type of the output array. If dtype is not given, infer the data type from the other input arguments.

  • axis (int, optional) – The axis in the result to store the samples. Relevant only if start or stop are array-like. By default (0), the samples will be along a new axis inserted at the beginning. Now, axis only support axis = 0.

  • device (Device, optional) – Device context on which the memory is allocated. Default is mxnet.device.current_device().

Returns:

samplesnum samples, equally spaced on a log scale.

Return type:

ndarray

See also

arange

Similar to linspace, with the step size specified instead of the number of samples. Note that, when used with a float endpoint, the endpoint may or may not be included.

linspace

Similar to logspace, but with the samples uniformly distributed in linear space, instead of log space.

Notes

Logspace is equivalent to the code

>>> y = np.linspace(start, stop, num=num, endpoint=endpoint)
...
>>> power(base, y).astype(dtype)
...

Examples

>>> np.logspace(2.0, 3.0, num=4)
array([ 100.     ,  215.44347,  464.15887, 1000.     ])
>>> np.logspace(2.0, 3.0, num=4, endpoint=False)
array([100.     , 177.82794, 316.22775, 562.3413 ])
>>> np.logspace(2.0, 3.0, num=4, base=2.0)
array([4.       , 5.0396843, 6.349604 , 8.       ])
>>> np.logspace(2.0, 3.0, num=4, base=2.0, dtype=np.int32)
array([4, 5, 6, 8], dtype=int32)
>>> np.logspace(2.0, 3.0, num=4, device=npx.gpu(0))
array([ 100.     ,  215.44347,  464.15887, 1000.     ], device=gpu(0))
mxnet.numpy.multiarray.matmul(a, b, out=None, **kwargs)

Matrix product of two arrays.

Parameters:
  • a (ndarray) – Input arrays, scalars not allowed.

  • b (ndarray) – Input arrays, scalars not allowed.

  • out (ndarray, optional) – A location into which the result is stored. If provided, it must have a shape that matches the signature (n,k),(k,m)->(n,m). If not provided or None, a freshly-allocated array is returned.

Returns:

y – The matrix product of the inputs. This is a scalar only when both x1, x2 are 1-d vectors.

Return type:

ndarray

Raises:

MXNetError – If the last dimension of a is not the same size as the second-to-last dimension of b. If a scalar value is passed in.

See also

tensordot

Sum products over arbitrary axes.

dot

alternative matrix product with different broadcasting rules.

einsum

Einstein summation convention.

The behavior depends on the arguments in the following way. * If both arguments are 2-D they are multiplied like conventional matrices. * If either argument is N-D, N > 2, it is treated as a stack of matrices residing in the last two indexes and broadcast accordingly. * If the first argument is 1-D, it is promoted to a matrix by prepending a 1 to its dimensions. After matrix multiplication the prepended 1 is removed. * If the second argument is 1-D, it is promoted to a matrix by appending a 1 to its dimensions. After matrix multiplication the appended 1 is removed. matmul differs from dot in two important ways: * Multiplication by scalars is not allowed, use multiply instead. * Stacks of matrices are broadcast together as if the matrices were elements, respecting the signature (n,k),(k,m)->(n,m): >>> a = np.ones([9, 5, 7, 4]) >>> c = np.ones([9, 5, 4, 3]) >>> np.dot(a, c).shape (9, 5, 7, 9, 5, 3) >>> np.matmul(a, c).shape (9, 5, 7, 3) >>> # n is 7, k is 4, m is 3

Examples

For 2-D arrays it is the matrix product:

>>> a = np.array([[1, 0],
...               [0, 1]])
>>> b = np.array([[4, 1],
...               [2, 2]])
>>> np.matmul(a, b)
array([[4., 1.],
       [2., 2.]])

For 2-D mixed with 1-D, the result is the usual.

>>> a = np.array([[1, 0],
...               [0, 1]])
>>> b = np.array([1, 2])
>>> np.matmul(a, b)
array([1., 2.])
>>> np.matmul(b, a)
array([1., 2.])

Broadcasting is conventional for stacks of arrays

>>> a = np.arange(2 * 2 * 4).reshape((2, 2, 4))
>>> b = np.arange(2 * 2 * 4).reshape((2, 4, 2))
>>> np.matmul(a, b).shape
(2, 2, 2)
>>> np.matmul(a, b)[0, 1, 1]
array(98.)
>>> sum(a[0, 1, :] * b[0, :, 1])
array(98.)

Scalar multiplication raises an error.

>>> np.matmul([1, 2], 3)
Traceback (most recent call last):
...
mxnet.base.MXNetError: ... : Multiplication by scalars is not allowed.
mxnet.numpy.multiarray.max(a, axis=None, out=None, keepdims=False)

Return the maximum of an array or maximum along an axis.

Parameters:
  • a (ndarray) – Input data.

  • axis (int, optional) – Axis along which to operate. By default, flattened input is used.

  • out (ndarray, optional) – Alternative output array in which to place the result. Must be of the same shape and buffer length as the expected output. See doc.ufuncs (Section “Output arguments”) for more details.

  • keepdims (bool, optional) – If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original arr.

Returns:

max – Maximum of a. If axis is None, the result is an array of dimension 1. If axis is given, the result is an array of dimension a.ndim - 1.

Return type:

ndarray

See also

min

The minimum value of an array along a given axis, ignoring any nan.

maximum

Element-wise maximum of two arrays, ignoring any nan.

argmax

Return the indices of the maximum values.

Notes

NaN in the orginal numpy is denoted as nan and will be ignored.

Don’t use max for element-wise comparison of 2 arrays; when a.shape[0] is 2, maximum(a[0], a[1]) is faster than max(a, axis=0).

Examples

>>> a = np.arange(4).reshape((2,2))
>>> a
array([[0., 1.],
    [2., 3.]])
>>> np.max(a)            # Maximum of the flattened array
array(3.)
>>> np.max(a, axis=0)    # Maxima along the first axis
array([2., 3.])
>>> np.max(a, axis=1)    # Maxima along the second axis
array([1., 3.])
>>> b = np.arange(5, dtype=np.float32)
>>> b[2] = np.nan
>>> np.max(b)
array(4.)
mxnet.numpy.multiarray.maximum(x1, x2, out=None, **kwargs)

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

Parameters:
  • x1 (scalar or mxnet.numpy.ndarray) – The arrays holding the elements to be compared. They must have the same shape, or shapes that can be broadcast to a single shape.

  • x2 (scalar or mxnet.numpy.ndarray) – The arrays holding the elements to be compared. They must have the same shape, or shapes that can be broadcast to a single shape.

Returns:

out – The maximum of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars.

Return type:

mxnet.numpy.ndarray or scalar

Examples

>>> np.maximum(np.array([2, 3, 4]), np.array([1, 5, 2]))
array([2., 5., 4.])
>>> np.maximum(np.eye(2), np.array([0.5, 2])) # broadcasting
array([[1. , 2. ],
       [0.5, 2. ]])
mxnet.numpy.multiarray.may_share_memory(a, b, max_work=None)

Determine if two arrays might share memory

A return of True does not necessarily mean that the two arrays share any element. It just means that they might.

Only the memory bounds of a and b are checked by default.

Parameters:
Returns:

out

Return type:

bool

See also

shares_memory

Examples

>>> np.may_share_memory(np.array([1,2]), np.array([5,8,9]))
False
>>> x = np.zeros([3, 4])
>>> np.may_share_memory(x[:,0], x[:,1])
True

Note

This function differs from the original numpy.may_share_memory in the following way(s):

  • Does not support max_work, it is a dummy argument

  • Actually it is same as shares_memory in MXNet np

mxnet.numpy.multiarray.mean(a, axis=None, dtype=None, out=None, keepdims=False)

Compute the arithmetic mean along the specified axis. Returns the average of the array elements. The average is taken over the flattened array by default, otherwise over the specified axis.

Parameters:
  • a (ndarray) – ndarray containing numbers whose mean is desired.

  • axis (None or int or tuple of ints, optional) – Axis or axes along which the means are computed. The default is to compute the mean of the flattened array. If this is a tuple of ints, a mean is performed over multiple axes, instead of a single axis or all the axes as before.

  • dtype (data-type, optional) – Type to use in computing the mean. For integer inputs, the default is of your current default dtype, When npx.is_np_default_dtype() returns False, default dtype is float32, When npx.is_np_default_dtype() returns True, default dtype is float64; For floating point inputs, it is the same as the input dtype.

  • out (ndarray, optional) – Alternate output array in which to place the result. The default is None; if provided, it must have the same shape and type as the expected output.

  • keepdims (bool, optional) – If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. If the default value is passed, then keepdims will not be passed through to the mean method of sub-classes of ndarray, however any non-default value will be. If the sub-class method does not implement keepdims any exceptions will be raised.

Returns:

  • m (ndarray, see dtype parameter above) – If out=None, returns a new array containing the mean values, otherwise a reference to the output array is returned.

  • .. note:: – This function differs from the original numpy.mean in the following way(s):

    • only ndarray is accepted as valid input, python iterables or scalar is not supported

    • default data type for integer input is float32 or float64, which depends on your current default dtype

Examples

>>> a = np.array([[1, 2], [3, 4]])
>>> np.mean(a)
array(2.5)
>>> a = np.zeros((2, 512*512), dtype=np.float32)
>>> a[0,:] = 1.0
>>> a[1,:] = 0.1
>>> np.mean(a)
array(0.55)
>>> np.mean(a, dtype=np.float64)
array(0.55, dtype=float64)
mxnet.numpy.multiarray.median(a, axis=None, out=None, overwrite_input=None, keepdims=False)

Compute the median along the specified axis. Returns the median of the array elements.

Parameters:
  • a (array_like) – Input array or object that can be converted to an array.

  • axis ({int, sequence of int, None}, optional) – Axis or axes along which the medians are computed. The default is to compute the median along a flattened version of the array. A sequence of axes is supported since version 1.9.0.

  • out (ndarray, optional) – Alternative output array in which to place the result. It must have the same shape and buffer length as the expected output, but the type (of the output) will be cast if necessary.

  • keepdims (bool, optional) – If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original arr.

Returns:

median – A new array holding the result. If the input contains integers or floats smaller than float32, then the output data-type is np.float32. Otherwise, the data-type of the output is the same as that of the input. If out is specified, that array is returned instead.

Return type:

ndarray

See also

mean, percentile

Examples

>>> a = np.array([[10, 7, 4], [3, 2, 1]])
>>> a
array([[10,  7,  4],
    [ 3,  2,  1]])
>>> np.median(a)
3.5
>>> np.median(a, axis=0)
array([6.5, 4.5, 2.5])
>>> np.median(a, axis=1)
array([7.,  2.])
mxnet.numpy.multiarray.min(a, axis=None, out=None, keepdims=False)

Return the minimum of an array or minimum along an axis.

Parameters:
  • a (ndarray) – Input data.

  • axis (int, optional) – Axis along which to operate. By default, flattened input is used.

  • out (ndarray, optional) – Alternative output array in which to place the result. Must be of the same shape and buffer length as the expected output. See doc.ufuncs (Section “Output arguments”) for more details.

  • keepdims (bool, optional) – If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original arr.

Returns:

min – Minimum of a. If axis is None, the result is an array of dimension 1. If axis is given, the result is an array of dimension a.ndim - 1.

Return type:

ndarray

See also

max

The maximum value of an array along a given axis, ignoring any nan.

minimum

Element-wise minimum of two arrays, ignoring any nan.

Notes

NaN in the orginal numpy is denoted as nan and will be ignored.

Don’t use min for element-wise comparison of 2 arrays; when a.shape[0] is 2, minimum(a[0], a[1]) is faster than min(a, axis=0).

Examples

>>> a = np.arange(4).reshape((2,2))
>>> a
array([[0., 1.],
    [2., 3.]])
>>> np.min(a)           # Minimum of the flattened array
array(0.)
>>> np.min(a, axis=0)   # Minima along the first axis
array([0., 1.])
>>> np.min(a, axis=1)   # Minima along the second axis
array([0., 2.])
>>> b = np.arange(5, dtype=np.float32)
>>> b[2] = np.nan
>>> np.min(b)
array(0.) # nan will be ignored
mxnet.numpy.multiarray.min_scalar_type(a, /)

For scalar a, returns the data type with the smallest size and smallest scalar kind which can hold its value. For non-scalar array a, returns the vector’s dtype unmodified.

Floating point values are not demoted to integers, and complex values are not demoted to floats.

Parameters:

a (scalar or array_like) – The value whose minimal data type is to be found.

Returns:

out – The minimal data type.

Return type:

dtype

Notes

Added in version 1.6.0.

See also

result_type, promote_types, dtype, can_cast

Examples

>>> np.min_scalar_type(10)
dtype('uint8')
>>> np.min_scalar_type(-260)
dtype('int16')
>>> np.min_scalar_type(3.1)
dtype('float16')
>>> np.min_scalar_type(1e50)
dtype('float64')
>>> np.min_scalar_type(np.arange(4,dtype='f8'))
dtype('float64')
mxnet.numpy.multiarray.minimum(x1, x2, out=None, **kwargs)

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

Parameters:
  • x1 (scalar or mxnet.numpy.ndarray) – The arrays holding the elements to be compared. They must have the same shape, or shapes that can be broadcast to a single shape.

  • x2 (scalar or mxnet.numpy.ndarray) – The arrays holding the elements to be compared. They must have the same shape, or shapes that can be broadcast to a single shape.

Returns:

out – The minimum of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars.

Return type:

mxnet.numpy.ndarray or scalar

Examples

>>> np.minimum(np.array([2, 3, 4]), np.array([1, 5, 2]))
array([1., 3., 2.])
>>> np.minimum(np.eye(2), np.array([0.5, 2])) # broadcasting
array([[0.5, 0. ],
       [0. , 1. ]])
mxnet.numpy.multiarray.mod(x1, x2, out=None, **kwargs)

Return element-wise remainder of division.

Parameters:
  • x1 (ndarray or scalar) – Dividend array.

  • x2 (ndarray or scalar) – Divisor array.

  • out (ndarray) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned.

Returns:

out – This is a scalar if both x1 and x2 are scalars.

Return type:

ndarray or scalar

Examples

>>> np.mod(np.arange(7), 5)
array([0., 1., 2., 3., 4., 0., 1.])
mxnet.numpy.multiarray.modf(x, [out1, out2, ]/, [out=(None, None), ]*, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])

Return the fractional and integral parts of an array, element-wise.

The fractional and integral parts are negative if the given number is negative.

Parameters:
  • x (array_like) – Input array.

  • out (ndarray, None, or tuple of ndarray and None, optional) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.

  • where (array_like, optional) – This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.

Returns:

  • y1 (ndarray) – Fractional part of x. This is a scalar if x is a scalar.

  • y2 (ndarray) – Integral part of x. This is a scalar if x is a scalar.

Notes

For integer input the return values are floats.

See also

divmod

divmod(x, 1) is equivalent to modf with the return values switched, except it always has a positive remainder.

Examples

>>> np.modf([0, 3.5])
(array([ 0. ,  0.5]), array([ 0.,  3.]))
>>> np.modf(-0.5)
(-0.5, -0)
mxnet.numpy.multiarray.moveaxis(a, source, destination)

Move axes of an array to new positions. Other axes remain in their original order.

Parameters:

a (ndarray) – The array whose axes should be reordered. source : int or sequence of int Original positions of the axes to move. These must be unique. destination : int or sequence of int Destination positions for each of the original axes. These must also be unique.

Returns:

result – Array with moved axes. This array is a view of the input array.

Return type:

ndarray

See also

transpose

Permute the dimensions of an array.

swapaxes

Interchange two axes of an array.

Examples

>>> x = np.zeros((3, 4, 5))
>>> np.moveaxis(x, 0, -1).shape
(4, 5, 3)
>>> np.moveaxis(x, -1, 0).shape
(5, 3, 4)
These all achieve the same result:
>>> np.transpose(x).shape
(5, 4, 3)
>>> np.swapaxes(x, 0, -1).shape
(5, 4, 3)
>>> np.moveaxis(x, [0, 1], [-1, -2]).shape
(5, 4, 3)
>>> np.moveaxis(x, [0, 1, 2], [-1, -2, -3]).shape
(5, 4, 3)
mxnet.numpy.multiarray.multiply(x1, x2, out=None, **kwargs)

Multiply arguments element-wise.

Parameters:
  • x1 (ndarrays or scalar values) – The arrays to be multiplied. If x1.shape != x2.shape, they must be broadcastable to a common shape (which may be the shape of one or the other).

  • x2 (ndarrays or scalar values) – The arrays to be multiplied. If x1.shape != x2.shape, they must be broadcastable to a common shape (which may be the shape of one or the other).

  • out (ndarray) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned.

Returns:

  • out (ndarray or scalar) – The difference of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars.

  • .. note:: – This operator now supports automatic type promotion. The resulting type will be determined according to the following rules:

    • If both inputs are of floating number types, the output is the more precise type.

    • If only one of the inputs is floating number type, the result is that type.

    • If both inputs are of integer types (including boolean), not supported yet.

Examples

>>> np.multiply(2.0, 4.0)
8.0
>>> x1 = np.arange(9.0).reshape((3, 3))
>>> x2 = np.arange(3.0)
>>> np.multiply(x1, x2)
array([[ 0.,  1.,  4.],
       [ 0.,  4., 10.],
       [ 0.,  7., 16.]])
mxnet.numpy.multiarray.nan_to_num(x, copy=True, nan=0.0, posinf=None, neginf=None, **kwargs)

Replace NaN with zero and infinity with large finite numbers (default behaviour) or with the numbers defined by the user using the nan, posinf and/or neginf keywords.

If x is inexact, NaN is replaced by zero or by the user defined value in nan keyword, infinity is replaced by the largest finite floating point values representable by x.dtype or by the user defined value in posinf keyword and -infinity is replaced by the most negative finite floating point values representable by x.dtype or by the user defined value in neginf keyword.

For complex dtypes, the above is applied to each of the real and imaginary components of x separately.

If x is not inexact, then no replacements are made.

Parameters:
  • x (scalar) – ndarray Input data.

  • copy (bool, optional) – Whether to create a copy of x (True) or to replace values in-place (False). The in-place operation only occurs if casting to an array does not require a copy. Default is True. Gluon does not support copy = False.

  • nan (int, float, optional) – Value to be used to fill NaN values. If no value is passed then NaN values will be replaced with 0.0.

  • posinf (int, float, optional) – Value to be used to fill positive infinity values. If no value is passed then positive infinity values will be replaced with a very large number.

  • neginf (int, float, optional) –

    Value to be used to fill negative infinity values. If no value is passed then negative infinity values will be replaced with a very small (or negative) number.

    Added in version 1.13.

Returns:

outx, with the non-finite values replaced. If copy is False, this may be x itself.

Return type:

ndarray

Notes

NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). This means that Not a Number is not equivalent to infinity.

Examples

>>> np.nan_to_num(np.inf)
1.7976931348623157e+308
>>> np.nan_to_num(-np.inf)
-1.7976931348623157e+308
>>> np.nan_to_num(np.nan)
0.0
>>> x = np.array([np.inf, -np.inf, np.nan, -128, 128])
>>> np.nan_to_num(x)
array([ 3.4028235e+38, -3.4028235e+38,  0.0000000e+00, -1.2800000e+02,
        1.2800000e+02])
>>> np.nan_to_num(x, nan=-9999, posinf=33333333, neginf=33333333)
array([ 3.3333332e+07,  3.3333332e+07, -9.9990000e+03, -1.2800000e+02,
        1.2800000e+02])
>>> y = np.array([[-1, 0, 1],[9999,234,-14222]],dtype="float64")/0
array([[-inf,  nan,  inf],
    [ inf,  inf, -inf]], dtype=float64)
>>> np.nan_to_num(y)
array([[-1.79769313e+308,  0.00000000e+000,  1.79769313e+308],
    [ 1.79769313e+308,  1.79769313e+308, -1.79769313e+308]], dtype=float64)
>>> np.nan_to_num(y, nan=111111, posinf=222222)
array([[-1.79769313e+308,  1.11111000e+005,  2.22222000e+005],
    [ 2.22222000e+005,  2.22222000e+005, -1.79769313e+308]], dtype=float64)
>>> y
array([[-inf,  nan,  inf],
   [ inf,  inf, -inf]], dtype=float64)
>>> np.nan_to_num(y, copy=False, nan=111111, posinf=222222)
array([[-1.79769313e+308,  1.11111000e+005,  2.22222000e+005],
   [ 2.22222000e+005,  2.22222000e+005, -1.79769313e+308]], dtype=float64)
>>> y
array([[-1.79769313e+308,  1.11111000e+005,  2.22222000e+005],
   [ 2.22222000e+005,  2.22222000e+005, -1.79769313e+308]], dtype=float64)
mxnet.numpy.multiarray.nanargmax(a, axis=None, out=None, *, keepdims=<no value>)

Return the indices of the maximum values in the specified axis ignoring NaNs. For all-NaN slices ValueError is raised. Warning: the results cannot be trusted if a slice contains only NaNs and -Infs.

Parameters:
  • a (array_like) – Input data.

  • axis (int, optional) – Axis along which to operate. By default flattened input is used.

  • out (array, optional) –

    If provided, the result will be inserted into this array. It should be of the appropriate shape and dtype.

    Added in version 1.22.0.

  • keepdims (bool, optional) –

    If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the array.

    Added in version 1.22.0.

Returns:

index_array – An array of indices or a single index value.

Return type:

ndarray

See also

argmax, nanargmin

Examples

>>> a = np.array([[np.nan, 4], [2, 3]])
>>> np.argmax(a)
0
>>> np.nanargmax(a)
1
>>> np.nanargmax(a, axis=0)
array([1, 0])
>>> np.nanargmax(a, axis=1)
array([1, 1])
mxnet.numpy.multiarray.nanargmin(a, axis=None, out=None, *, keepdims=<no value>)

Return the indices of the minimum values in the specified axis ignoring NaNs. For all-NaN slices ValueError is raised. Warning: the results cannot be trusted if a slice contains only NaNs and Infs.

Parameters:
  • a (array_like) – Input data.

  • axis (int, optional) – Axis along which to operate. By default flattened input is used.

  • out (array, optional) –

    If provided, the result will be inserted into this array. It should be of the appropriate shape and dtype.

    Added in version 1.22.0.

  • keepdims (bool, optional) –

    If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the array.

    Added in version 1.22.0.

Returns:

index_array – An array of indices or a single index value.

Return type:

ndarray

See also

argmin, nanargmax

Examples

>>> a = np.array([[np.nan, 4], [2, 3]])
>>> np.argmin(a)
0
>>> np.nanargmin(a)
2
>>> np.nanargmin(a, axis=0)
array([1, 1])
>>> np.nanargmin(a, axis=1)
array([1, 0])
mxnet.numpy.multiarray.nancumprod(a, axis=None, dtype=None, out=None)

Return the cumulative product of array elements over a given axis treating Not a Numbers (NaNs) as one. The cumulative product does not change when NaNs are encountered and leading NaNs are replaced by ones.

Ones are returned for slices that are all-NaN or empty.

Added in version 1.12.0.

Parameters:
  • a (array_like) – Input array.

  • axis (int, optional) – Axis along which the cumulative product is computed. By default the input is flattened.

  • dtype (dtype, optional) – Type of the returned array, as well as of the accumulator in which the elements are multiplied. If dtype is not specified, it defaults to the dtype of a, unless a has an integer dtype with a precision less than that of the default platform integer. In that case, the default platform integer is used instead.

  • out (ndarray, optional) – Alternative output array in which to place the result. It must have the same shape and buffer length as the expected output but the type of the resulting values will be cast if necessary.

Returns:

nancumprod – A new array holding the result is returned unless out is specified, in which case it is returned.

Return type:

ndarray

See also

numpy.cumprod

Cumulative product across array propagating NaNs.

isnan

Show which elements are NaN.

Examples

>>> np.nancumprod(1)
array([1])
>>> np.nancumprod([1])
array([1])
>>> np.nancumprod([1, np.nan])
array([1.,  1.])
>>> a = np.array([[1, 2], [3, np.nan]])
>>> np.nancumprod(a)
array([1.,  2.,  6.,  6.])
>>> np.nancumprod(a, axis=0)
array([[1.,  2.],
       [3.,  2.]])
>>> np.nancumprod(a, axis=1)
array([[1.,  2.],
       [3.,  3.]])
mxnet.numpy.multiarray.nancumsum(a, axis=None, dtype=None, out=None)

Return the cumulative sum of array elements over a given axis treating Not a Numbers (NaNs) as zero. The cumulative sum does not change when NaNs are encountered and leading NaNs are replaced by zeros.

Zeros are returned for slices that are all-NaN or empty.

Added in version 1.12.0.

Parameters:
  • a (array_like) – Input array.

  • axis (int, optional) – Axis along which the cumulative sum is computed. The default (None) is to compute the cumsum over the flattened array.

  • dtype (dtype, optional) – Type of the returned array and of the accumulator in which the elements are summed. If dtype is not specified, it defaults to the dtype of a, unless a has an integer dtype with a precision less than that of the default platform integer. In that case, the default platform integer is used.

  • out (ndarray, optional) – Alternative output array in which to place the result. It must have the same shape and buffer length as the expected output but the type will be cast if necessary. See Output type determination for more details.

Returns:

nancumsum – A new array holding the result is returned unless out is specified, in which it is returned. The result has the same size as a, and the same shape as a if axis is not None or a is a 1-d array.

Return type:

ndarray.

See also

numpy.cumsum

Cumulative sum across array propagating NaNs.

isnan

Show which elements are NaN.

Examples

>>> np.nancumsum(1)
array([1])
>>> np.nancumsum([1])
array([1])
>>> np.nancumsum([1, np.nan])
array([1.,  1.])
>>> a = np.array([[1, 2], [3, np.nan]])
>>> np.nancumsum(a)
array([1.,  3.,  6.,  6.])
>>> np.nancumsum(a, axis=0)
array([[1.,  2.],
       [4.,  2.]])
>>> np.nancumsum(a, axis=1)
array([[1.,  3.],
       [3.,  3.]])
mxnet.numpy.multiarray.nanmax(a, axis=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)

Return the maximum of an array or maximum along an axis, ignoring any NaNs. When all-NaN slices are encountered a RuntimeWarning is raised and NaN is returned for that slice.

Parameters:
  • a (array_like) – Array containing numbers whose maximum is desired. If a is not an array, a conversion is attempted.

  • axis ({int, tuple of int, None}, optional) – Axis or axes along which the maximum is computed. The default is to compute the maximum of the flattened array.

  • out (ndarray, optional) –

    Alternate output array in which to place the result. The default is None; if provided, it must have the same shape as the expected output, but the type will be cast if necessary. See Output type determination for more details.

    Added in version 1.8.0.

  • keepdims (bool, optional) –

    If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original a.

    If the value is anything but the default, then keepdims will be passed through to the max method of sub-classes of ndarray. If the sub-classes methods does not implement keepdims any exceptions will be raised.

    Added in version 1.8.0.

  • initial (scalar, optional) –

    The minimum value of an output element. Must be present to allow computation on empty slice. See ~numpy.ufunc.reduce for details.

    Added in version 1.22.0.

  • where (array_like of bool, optional) –

    Elements to compare for the maximum. See ~numpy.ufunc.reduce for details.

    Added in version 1.22.0.

Returns:

nanmax – An array with the same shape as a, with the specified axis removed. If a is a 0-d array, or if axis is None, an ndarray scalar is returned. The same dtype as a is returned.

Return type:

ndarray

See also

nanmin

The minimum value of an array along a given axis, ignoring any NaNs.

amax

The maximum value of an array along a given axis, propagating any NaNs.

fmax

Element-wise maximum of two arrays, ignoring any NaNs.

maximum

Element-wise maximum of two arrays, propagating any NaNs.

isnan

Shows which elements are Not a Number (NaN).

isfinite

Shows which elements are neither NaN nor infinity.

amin, fmin, minimum

Notes

NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). This means that Not a Number is not equivalent to infinity. Positive infinity is treated as a very large number and negative infinity is treated as a very small (i.e. negative) number.

If the input has a integer type the function is equivalent to np.max.

Examples

>>> a = np.array([[1, 2], [3, np.nan]])
>>> np.nanmax(a)
3.0
>>> np.nanmax(a, axis=0)
array([3.,  2.])
>>> np.nanmax(a, axis=1)
array([2.,  3.])

When positive infinity and negative infinity are present:

>>> np.nanmax([1, 2, np.nan, np.NINF])
2.0
>>> np.nanmax([1, 2, np.nan, np.inf])
inf
mxnet.numpy.multiarray.nanmedian(a, axis=None, out=None, overwrite_input=False, keepdims=<no value>)

Compute the median along the specified axis, while ignoring NaNs.

Returns the median of the array elements.

Added in version 1.9.0.

Parameters:
  • a (array_like) – Input array or object that can be converted to an array.

  • axis ({int, sequence of int, None}, optional) – Axis or axes along which the medians are computed. The default is to compute the median along a flattened version of the array. A sequence of axes is supported since version 1.9.0.

  • out (ndarray, optional) – Alternative output array in which to place the result. It must have the same shape and buffer length as the expected output, but the type (of the output) will be cast if necessary.

  • overwrite_input (bool, optional) – If True, then allow use of memory of input array a for calculations. The input array will be modified by the call to median. This will save memory when you do not need to preserve the contents of the input array. Treat the input as undefined, but it will probably be fully or partially sorted. Default is False. If overwrite_input is True and a is not already an ndarray, an error will be raised.

  • keepdims (bool, optional) –

    If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original a.

    If this is anything but the default value it will be passed through (in the special case of an empty array) to the mean function of the underlying array. If the array is a sub-class and mean does not have the kwarg keepdims this will raise a RuntimeError.

Returns:

median – A new array holding the result. If the input contains integers or floats smaller than float64, then the output data-type is np.float64. Otherwise, the data-type of the output is the same as that of the input. If out is specified, that array is returned instead.

Return type:

ndarray

See also

mean, median, percentile

Notes

Given a vector V of length N, the median of V is the middle value of a sorted copy of V, V_sorted - i.e., V_sorted[(N-1)/2], when N is odd and the average of the two middle values of V_sorted when N is even.

Examples

>>> a = np.array([[10.0, 7, 4], [3, 2, 1]])
>>> a[0, 1] = np.nan
>>> a
array([[10., nan,  4.],
       [ 3.,  2.,  1.]])
>>> np.median(a)
nan
>>> np.nanmedian(a)
3.0
>>> np.nanmedian(a, axis=0)
array([6.5, 2. , 2.5])
>>> np.median(a, axis=1)
array([nan,  2.])
>>> b = a.copy()
>>> np.nanmedian(b, axis=1, overwrite_input=True)
array([7.,  2.])
>>> assert not np.all(a==b)
>>> b = a.copy()
>>> np.nanmedian(b, axis=None, overwrite_input=True)
3.0
>>> assert not np.all(a==b)
mxnet.numpy.multiarray.nanmin(a, axis=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)

Return minimum of an array or minimum along an axis, ignoring any NaNs. When all-NaN slices are encountered a RuntimeWarning is raised and Nan is returned for that slice.

Parameters:
  • a (array_like) – Array containing numbers whose minimum is desired. If a is not an array, a conversion is attempted.

  • axis ({int, tuple of int, None}, optional) – Axis or axes along which the minimum is computed. The default is to compute the minimum of the flattened array.

  • out (ndarray, optional) –

    Alternate output array in which to place the result. The default is None; if provided, it must have the same shape as the expected output, but the type will be cast if necessary. See Output type determination for more details.

    Added in version 1.8.0.

  • keepdims (bool, optional) –

    If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original a.

    If the value is anything but the default, then keepdims will be passed through to the min method of sub-classes of ndarray. If the sub-classes methods does not implement keepdims any exceptions will be raised.

    Added in version 1.8.0.

  • initial (scalar, optional) –

    The maximum value of an output element. Must be present to allow computation on empty slice. See ~numpy.ufunc.reduce for details.

    Added in version 1.22.0.

  • where (array_like of bool, optional) –

    Elements to compare for the minimum. See ~numpy.ufunc.reduce for details.

    Added in version 1.22.0.

Returns:

nanmin – An array with the same shape as a, with the specified axis removed. If a is a 0-d array, or if axis is None, an ndarray scalar is returned. The same dtype as a is returned.

Return type:

ndarray

See also

nanmax

The maximum value of an array along a given axis, ignoring any NaNs.

amin

The minimum value of an array along a given axis, propagating any NaNs.

fmin

Element-wise minimum of two arrays, ignoring any NaNs.

minimum

Element-wise minimum of two arrays, propagating any NaNs.

isnan

Shows which elements are Not a Number (NaN).

isfinite

Shows which elements are neither NaN nor infinity.

amax, fmax, maximum

Notes

NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). This means that Not a Number is not equivalent to infinity. Positive infinity is treated as a very large number and negative infinity is treated as a very small (i.e. negative) number.

If the input has a integer type the function is equivalent to np.min.

Examples

>>> a = np.array([[1, 2], [3, np.nan]])
>>> np.nanmin(a)
1.0
>>> np.nanmin(a, axis=0)
array([1.,  2.])
>>> np.nanmin(a, axis=1)
array([1.,  3.])

When positive infinity and negative infinity are present:

>>> np.nanmin([1, 2, np.nan, np.inf])
1.0
>>> np.nanmin([1, 2, np.nan, np.NINF])
-inf
mxnet.numpy.multiarray.nanpercentile(a, q, axis=None, out=None, overwrite_input=False, method='linear', keepdims=<no value>, *, interpolation=None)

Compute the qth percentile of the data along the specified axis, while ignoring nan values.

Returns the qth percentile(s) of the array elements.

Added in version 1.9.0.

Parameters:
  • a (array_like) – Input array or object that can be converted to an array, containing nan values to be ignored.

  • q (array_like of float) – Percentile or sequence of percentiles to compute, which must be between 0 and 100 inclusive.

  • axis ({int, tuple of int, None}, optional) – Axis or axes along which the percentiles are computed. The default is to compute the percentile(s) along a flattened version of the array.

  • out (ndarray, optional) – Alternative output array in which to place the result. It must have the same shape and buffer length as the expected output, but the type (of the output) will be cast if necessary.

  • overwrite_input (bool, optional) – If True, then allow the input array a to be modified by intermediate calculations, to save memory. In this case, the contents of the input a after this function completes is undefined.

  • method (str, optional) –

    This parameter specifies the method to use for estimating the percentile. There are many different methods, some unique to NumPy. See the notes for explanation. The options sorted by their R type as summarized in the H&F paper [1]_ are:

    1. ’inverted_cdf’

    2. ’averaged_inverted_cdf’

    3. ’closest_observation’

    4. ’interpolated_inverted_cdf’

    5. ’hazen’

    6. ’weibull’

    7. ’linear’ (default)

    8. ’median_unbiased’

    9. ’normal_unbiased’

    The first three methods are discontinuous. NumPy further defines the following discontinuous variations of the default ‘linear’ (7.) option:

    • ’lower’

    • ’higher’,

    • ’midpoint’

    • ’nearest’

    Changed in version 1.22.0: This argument was previously called “interpolation” and only offered the “linear” default and last four options.

  • keepdims (bool, optional) –

    If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original array a.

    If this is anything but the default value it will be passed through (in the special case of an empty array) to the mean function of the underlying array. If the array is a sub-class and mean does not have the kwarg keepdims this will raise a RuntimeError.

  • interpolation (str, optional) –

    Deprecated name for the method keyword argument.

    Deprecated since version 1.22.0.

Returns:

percentile – If q is a single percentile and axis=None, then the result is a scalar. If multiple percentiles are given, first axis of the result corresponds to the percentiles. The other axes are the axes that remain after the reduction of a. If the input contains integers or floats smaller than float64, the output data-type is float64. Otherwise, the output data-type is the same as that of the input. If out is specified, that array is returned instead.

Return type:

scalar or ndarray

See also

nanmean

nanmedian

equivalent to nanpercentile(..., 50)

percentile, median, mean

nanquantile

equivalent to nanpercentile, except q in range [0, 1].

Notes

For more information please see numpy.percentile

Examples

>>> a = np.array([[10., 7., 4.], [3., 2., 1.]])
>>> a[0][1] = np.nan
>>> a
array([[10.,  nan,   4.],
      [ 3.,   2.,   1.]])
>>> np.percentile(a, 50)
nan
>>> np.nanpercentile(a, 50)
3.0
>>> np.nanpercentile(a, 50, axis=0)
array([6.5, 2. , 2.5])
>>> np.nanpercentile(a, 50, axis=1, keepdims=True)
array([[7.],
       [2.]])
>>> m = np.nanpercentile(a, 50, axis=0)
>>> out = np.zeros_like(m)
>>> np.nanpercentile(a, 50, axis=0, out=out)
array([6.5, 2. , 2.5])
>>> m
array([6.5,  2. ,  2.5])
>>> b = a.copy()
>>> np.nanpercentile(b, 50, axis=1, overwrite_input=True)
array([7., 2.])
>>> assert not np.all(a==b)

References

mxnet.numpy.multiarray.nanprod(a, axis=None, dtype=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)

Return the product of array elements over a given axis treating Not a Numbers (NaNs) as ones.

One is returned for slices that are all-NaN or empty.

Added in version 1.10.0.

Parameters:
  • a (array_like) – Array containing numbers whose product is desired. If a is not an array, a conversion is attempted.

  • axis ({int, tuple of int, None}, optional) – Axis or axes along which the product is computed. The default is to compute the product of the flattened array.

  • dtype (data-type, optional) – The type of the returned array and of the accumulator in which the elements are summed. By default, the dtype of a is used. An exception is when a has an integer type with less precision than the platform (u)intp. In that case, the default will be either (u)int32 or (u)int64 depending on whether the platform is 32 or 64 bits. For inexact inputs, dtype must be inexact.

  • out (ndarray, optional) – Alternate output array in which to place the result. The default is None. If provided, it must have the same shape as the expected output, but the type will be cast if necessary. See Output type determination for more details. The casting of NaN to integer can yield unexpected results.

  • keepdims (bool, optional) – If True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original arr.

  • initial (scalar, optional) –

    The starting value for this product. See ~numpy.ufunc.reduce for details.

    Added in version 1.22.0.

  • where (array_like of bool, optional) –

    Elements to include in the product. See ~numpy.ufunc.reduce for details.

    Added in version 1.22.0.

Returns:

nanprod – A new array holding the result is returned unless out is specified, in which case it is returned.

Return type:

ndarray

See also

numpy.prod

Product across array propagating NaNs.

isnan

Show which elements are NaN.

Examples

>>> np.nanprod(1)
1
>>> np.nanprod([1])
1
>>> np.nanprod([1, np.nan])
1.0
>>> a = np.array([[1, 2], [3, np.nan]])
>>> np.nanprod(a)
6.0
>>> np.nanprod(a, axis=0)
array([3., 2.])
mxnet.numpy.multiarray.nanquantile(a, q, axis=None, out=None, overwrite_input=False, method='linear', keepdims=<no value>, *, interpolation=None)

Compute the qth quantile of the data along the specified axis, while ignoring nan values. Returns the qth quantile(s) of the array elements.

Added in version 1.15.0.

Parameters:
  • a (array_like) – Input array or object that can be converted to an array, containing nan values to be ignored

  • q (array_like of float) – Probability or sequence of probabilities for the quantiles to compute. Values must be between 0 and 1 inclusive.

  • axis ({int, tuple of int, None}, optional) – Axis or axes along which the quantiles are computed. The default is to compute the quantile(s) along a flattened version of the array.

  • out (ndarray, optional) – Alternative output array in which to place the result. It must have the same shape and buffer length as the expected output, but the type (of the output) will be cast if necessary.

  • overwrite_input (bool, optional) – If True, then allow the input array a to be modified by intermediate calculations, to save memory. In this case, the contents of the input a after this function completes is undefined.

  • method (str, optional) –

    This parameter specifies the method to use for estimating the quantile. There are many different methods, some unique to NumPy. See the notes for explanation. The options sorted by their R type as summarized in the H&F paper [1]_ are:

    1. ’inverted_cdf’

    2. ’averaged_inverted_cdf’

    3. ’closest_observation’

    4. ’interpolated_inverted_cdf’

    5. ’hazen’

    6. ’weibull’

    7. ’linear’ (default)

    8. ’median_unbiased’

    9. ’normal_unbiased’

    The first three methods are discontinuous. NumPy further defines the following discontinuous variations of the default ‘linear’ (7.) option:

    • ’lower’

    • ’higher’,

    • ’midpoint’

    • ’nearest’

    Changed in version 1.22.0: This argument was previously called “interpolation” and only offered the “linear” default and last four options.

  • keepdims (bool, optional) –

    If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original array a.

    If this is anything but the default value it will be passed through (in the special case of an empty array) to the mean function of the underlying array. If the array is a sub-class and mean does not have the kwarg keepdims this will raise a RuntimeError.

  • interpolation (str, optional) –

    Deprecated name for the method keyword argument.

    Deprecated since version 1.22.0.

Returns:

quantile – If q is a single probability and axis=None, then the result is a scalar. If multiple probability levels are given, first axis of the result corresponds to the quantiles. The other axes are the axes that remain after the reduction of a. If the input contains integers or floats smaller than float64, the output data-type is float64. Otherwise, the output data-type is the same as that of the input. If out is specified, that array is returned instead.

Return type:

scalar or ndarray

See also

quantile, nanmean, nanmedian

nanmedian

equivalent to nanquantile(..., 0.5)

nanpercentile

same as nanquantile, but with q in the range [0, 100].

Notes

For more information please see numpy.quantile

Examples

>>> a = np.array([[10., 7., 4.], [3., 2., 1.]])
>>> a[0][1] = np.nan
>>> a
array([[10.,  nan,   4.],
      [ 3.,   2.,   1.]])
>>> np.quantile(a, 0.5)
nan
>>> np.nanquantile(a, 0.5)
3.0
>>> np.nanquantile(a, 0.5, axis=0)
array([6.5, 2. , 2.5])
>>> np.nanquantile(a, 0.5, axis=1, keepdims=True)
array([[7.],
       [2.]])
>>> m = np.nanquantile(a, 0.5, axis=0)
>>> out = np.zeros_like(m)
>>> np.nanquantile(a, 0.5, axis=0, out=out)
array([6.5, 2. , 2.5])
>>> m
array([6.5,  2. ,  2.5])
>>> b = a.copy()
>>> np.nanquantile(b, 0.5, axis=1, overwrite_input=True)
array([7., 2.])
>>> assert not np.all(a==b)

References

mxnet.numpy.multiarray.nanstd(a, axis=None, dtype=None, out=None, ddof=0, keepdims=<no value>, *, where=<no value>)

Compute the standard deviation along the specified axis, while ignoring NaNs.

Returns the standard deviation, a measure of the spread of a distribution, of the non-NaN array elements. The standard deviation is computed for the flattened array by default, otherwise over the specified axis.

For all-NaN slices or slices with zero degrees of freedom, NaN is returned and a RuntimeWarning is raised.

Added in version 1.8.0.

Parameters:
  • a (array_like) – Calculate the standard deviation of the non-NaN values.

  • axis ({int, tuple of int, None}, optional) – Axis or axes along which the standard deviation is computed. The default is to compute the standard deviation of the flattened array.

  • dtype (dtype, optional) – Type to use in computing the standard deviation. For arrays of integer type the default is float64, for arrays of float types it is the same as the array type.

  • out (ndarray, optional) – Alternative output array in which to place the result. It must have the same shape as the expected output but the type (of the calculated values) will be cast if necessary.

  • ddof (int, optional) – Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of non-NaN elements. By default ddof is zero.

  • keepdims (bool, optional) –

    If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original a.

    If this value is anything but the default it is passed through as-is to the relevant functions of the sub-classes. If these functions do not have a keepdims kwarg, a RuntimeError will be raised.

  • where (array_like of bool, optional) –

    Elements to include in the standard deviation. See ~numpy.ufunc.reduce for details.

    Added in version 1.22.0.

Returns:

standard_deviation – If out is None, return a new array containing the standard deviation, otherwise return a reference to the output array. If ddof is >= the number of non-NaN elements in a slice or the slice contains only NaNs, then the result for that slice is NaN.

Return type:

ndarray, see dtype parameter above.

See also

var, mean, std, nanvar, nanmean, Output type determination

Notes

The standard deviation is the square root of the average of the squared deviations from the mean: std = sqrt(mean(abs(x - x.mean())**2)).

The average squared deviation is normally calculated as x.sum() / N, where N = len(x). If, however, ddof is specified, the divisor N - ddof is used instead. In standard statistical practice, ddof=1 provides an unbiased estimator of the variance of the infinite population. ddof=0 provides a maximum likelihood estimate of the variance for normally distributed variables. The standard deviation computed in this function is the square root of the estimated variance, so even with ddof=1, it will not be an unbiased estimate of the standard deviation per se.

Note that, for complex numbers, std takes the absolute value before squaring, so that the result is always real and nonnegative.

For floating-point input, the std is computed using the same precision the input has. Depending on the input data, this can cause the results to be inaccurate, especially for float32 (see example below). Specifying a higher-accuracy accumulator using the dtype keyword can alleviate this issue.

Examples

>>> a = np.array([[1, np.nan], [3, 4]])
>>> np.nanstd(a)
1.247219128924647
>>> np.nanstd(a, axis=0)
array([1., 0.])
>>> np.nanstd(a, axis=1)
array([0.,  0.5]) # may vary
mxnet.numpy.multiarray.nansum(a, axis=None, dtype=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)

Return the sum of array elements over a given axis treating Not a Numbers (NaNs) as zero.

In NumPy versions <= 1.9.0 Nan is returned for slices that are all-NaN or empty. In later versions zero is returned.

Parameters:
  • a (array_like) – Array containing numbers whose sum is desired. If a is not an array, a conversion is attempted.

  • axis ({int, tuple of int, None}, optional) – Axis or axes along which the sum is computed. The default is to compute the sum of the flattened array.

  • dtype (data-type, optional) –

    The type of the returned array and of the accumulator in which the elements are summed. By default, the dtype of a is used. An exception is when a has an integer type with less precision than the platform (u)intp. In that case, the default will be either (u)int32 or (u)int64 depending on whether the platform is 32 or 64 bits. For inexact inputs, dtype must be inexact.

    Added in version 1.8.0.

  • out (ndarray, optional) –

    Alternate output array in which to place the result. The default is None. If provided, it must have the same shape as the expected output, but the type will be cast if necessary. See Output type determination for more details. The casting of NaN to integer can yield unexpected results.

    Added in version 1.8.0.

  • keepdims (bool, optional) – If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original a.

initialscalar, optional

Starting value for the sum. See ~numpy.ufunc.reduce for details.

Added in version 1.22.0.

wherearray_like of bool, optional

Elements to include in the sum. See ~numpy.ufunc.reduce for details.

Added in version 1.22.0.

Returns:

nansum – A new array holding the result is returned unless out is specified, in which it is returned. The result has the same size as a, and the same shape as a if axis is not None or a is a 1-d array.

Return type:

ndarray.

See also

numpy.sum

Sum across array propagating NaNs.

isnan

Show which elements are NaN.

isfinite

Show which elements are not NaN or +/-inf.

Notes

If both positive and negative infinity are present, the sum will be Not A Number (NaN).

Examples

>>> np.nansum(1)
1
>>> np.nansum([1])
1
>>> np.nansum([1, np.nan])
1.0
>>> a = np.array([[1, 1], [1, np.nan]])
>>> np.nansum(a)
3.0
>>> np.nansum(a, axis=0)
array([2.,  1.])
>>> np.nansum([1, np.nan, np.inf])
inf
>>> np.nansum([1, np.nan, np.NINF])
-inf
>>> from numpy.testing import suppress_warnings
>>> with suppress_warnings() as sup:
...     sup.filter(RuntimeWarning)
...     np.nansum([1, np.nan, np.inf, -np.inf]) # both +/- infinity present
nan
mxnet.numpy.multiarray.nanvar(a, axis=None, dtype=None, out=None, ddof=0, keepdims=<no value>, *, where=<no value>)

Compute the variance along the specified axis, while ignoring NaNs.

Returns the variance of the array elements, a measure of the spread of a distribution. The variance is computed for the flattened array by default, otherwise over the specified axis.

For all-NaN slices or slices with zero degrees of freedom, NaN is returned and a RuntimeWarning is raised.

Added in version 1.8.0.

Parameters:
  • a (array_like) – Array containing numbers whose variance is desired. If a is not an array, a conversion is attempted.

  • axis ({int, tuple of int, None}, optional) – Axis or axes along which the variance is computed. The default is to compute the variance of the flattened array.

  • dtype (data-type, optional) – Type to use in computing the variance. For arrays of integer type the default is float64; for arrays of float types it is the same as the array type.

  • out (ndarray, optional) – Alternate output array in which to place the result. It must have the same shape as the expected output, but the type is cast if necessary.

  • ddof (int, optional) – “Delta Degrees of Freedom”: the divisor used in the calculation is N - ddof, where N represents the number of non-NaN elements. By default ddof is zero.

  • keepdims (bool, optional) – If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original a.

  • where (array_like of bool, optional) –

    Elements to include in the variance. See ~numpy.ufunc.reduce for details.

    Added in version 1.22.0.

Returns:

variance – If out is None, return a new array containing the variance, otherwise return a reference to the output array. If ddof is >= the number of non-NaN elements in a slice or the slice contains only NaNs, then the result for that slice is NaN.

Return type:

ndarray, see dtype parameter above

See also

std

Standard deviation

mean

Average

var

Variance while not ignoring NaNs

nanstd, nanmean, Output type determination

Notes

The variance is the average of the squared deviations from the mean, i.e., var = mean(abs(x - x.mean())**2).

The mean is normally calculated as x.sum() / N, where N = len(x). If, however, ddof is specified, the divisor N - ddof is used instead. In standard statistical practice, ddof=1 provides an unbiased estimator of the variance of a hypothetical infinite population. ddof=0 provides a maximum likelihood estimate of the variance for normally distributed variables.

Note that for complex numbers, the absolute value is taken before squaring, so that the result is always real and nonnegative.

For floating-point input, the variance is computed using the same precision the input has. Depending on the input data, this can cause the results to be inaccurate, especially for float32 (see example below). Specifying a higher-accuracy accumulator using the dtype keyword can alleviate this issue.

For this function to work on sub-classes of ndarray, they must define sum with the kwarg keepdims

Examples

>>> a = np.array([[1, np.nan], [3, 4]])
>>> np.nanvar(a)
1.5555555555555554
>>> np.nanvar(a, axis=0)
array([1.,  0.])
>>> np.nanvar(a, axis=1)
array([0.,  0.25])  # may vary
class mxnet.numpy.multiarray.ndarray

Bases: NDArray

ndarray(handle, writable=True):

An array object represents a multidimensional, homogeneous array of fixed-size items. An associated data-type object describes the format of each element in the array (its byte-order, how many bytes it occupies in memory, whether it is an integer, a floating point number, or something else, etc.). Arrays should be constructed using array, zeros or empty. Currently, only c-contiguous arrays are supported.

Arrays should be constructed using array, zeros or empty (refer to the See Also section below). The parameters given here refer to a low-level method (ndarray(…)) for instantiating an array.

For more information, refer to the mxnet.numpy module and examine the methods and attributes of an array.

Parameters:
  • handle (int) – The ndarray handle in backend (C++).

  • writable (bool) – Indicates whether inplace-assignment is allowed for the array.

T

Transpose of the array.

Type:

ndarray

dtype

Describes the format of the elements in the array.

Type:

dtype object

size

Number of elements in the array.

Type:

int

ndim

The array’s number of dimensions.

Type:

int

shape

Shape of the array.

Type:

tuple of ints

See also

array

Construct an array.

zeros

Create an array, each element of which is zero.

empty

Create an array, but leave its allocated memory unchanged (i.e., it contains “garbage”).

property T

Same as self.transpose(). This always returns a copy of self.

abs(*args, **kwargs)[source]

Convenience fluent method for abs().

The arguments are the same as for abs(), with this array as data.

arccos(*args, **kwargs)[source]

Convenience fluent method for arccos().

The arguments are the same as for arccos(), with this array as data.

arccosh(*args, **kwargs)[source]

Convenience fluent method for arccosh().

The arguments are the same as for arccosh(), with this array as data.

arcsin(*args, **kwargs)[source]

Convenience fluent method for arcsin().

The arguments are the same as for arcsin(), with this array as data.

arcsinh(*args, **kwargs)[source]

Convenience fluent method for arcsinh().

The arguments are the same as for arcsinh(), with this array as data.

arctan(*args, **kwargs)[source]

Convenience fluent method for arctan().

The arguments are the same as for arctan(), with this array as data.

arctanh(*args, **kwargs)[source]

Convenience fluent method for arctanh().

The arguments are the same as for arctanh(), with this array as data.

argmax(axis=None, out=None, keepdims=False)[source]

Return indices of the maximum values along the given axis. Refer to mxnet.numpy.argmax for full documentation.

argmax_channel(*args, **kwargs)[source]

Convenience fluent method for argmax_channel().

The arguments are the same as for argmax_channel(), with this array as data.

argmin(axis=None, out=None, keepdims=False)[source]

Return indices of the minium values along the given axis. Refer to mxnet.numpy.argmin for full documentation.

argsort(axis=-1, descending=False, stable=True)[source]

Convenience fluent method for argsort().

The arguments are the same as for argsort(), with this array as data.

as_in_context(context)[source]

This function has been deprecated. Please refer to ndarray.to_device.

as_in_ctx(ctx)[source]

This function has been deprecated. Please refer to ndarray.to_device.

as_nd_ndarray()[source]

Convert mxnet.numpy.ndarray to mxnet.ndarray.NDArray to use its fluent methods.

as_np_ndarray()[source]

A convenience function for creating a numpy ndarray from the current ndarray with zero copy. For this class, it just returns itself since it’s already a numpy ndarray.

asscalar()[source]

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, order='K', casting='unsafe', subok=True, copy=True)[source]

Copy of the array, cast to a specified type.

Parameters:
  • dtype (str or dtype) – Typecode or data-type to which the array is cast.

  • order ({'C', 'F', 'A', 'K'}, optional) – Controls the memory layout order of the result. ‘C’ means C order, ‘F’ means Fortran order, ‘A’ means ‘F’ order if all the arrays are Fortran contiguous, ‘C’ order otherwise, and ‘K’ means as close to the order the array elements appear in memory as possible. Default is ‘K’.

  • casting ({'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional) –

    Controls what kind of data casting may occur. Defaults to ‘unsafe’ for backwards compatibility.

    • ’no’ means the data types should not be cast at all.

    • ’equiv’ means only byte-order changes are allowed.

    • ’safe’ means only casts which can preserve values are allowed.

    • ’same_kind’ means only safe casts or casts within a kind, like float64 to float32, are allowed.

    • ’unsafe’ means any data conversions may be done.

  • subok (bool, optional) – If True, then sub-classes will be passed-through (default), otherwise the returned array will be forced to be a base-class array.

  • copy (bool, optional) – Default True. By default, astype always returns a newly allocated ndarray on the same device. If this is set to False, and the dtype requested is the same as the ndarray’s dtype, the ndarray is returned instead of a copy.

Returns:

arr_t – Unless copy is False and the other conditions for returning the input array are satisfied (see description for copy input parameter), arr_t is a new array of the same shape as the input array with dtype.

Return type:

ndarray

Notes

This function differs from the official ndarray’s astype function in the following aspects:

  • order only supports ‘C’ and ‘K’.

  • casting only supports ‘unsafe’.

  • subok only supports True.

attach_grad(grad_req='write')[source]

Attach a gradient buffer to this ndarray, so that backward can compute gradient with respect to it.

Parameters:

grad_req ({'write', 'add', 'null'}) – How gradient will be accumulated. * ‘write’: gradient will be overwritten on every backward. * ‘add’: gradient will be added to existing value on every backward. * ‘null’: do not compute gradient for this NDArray.

broadcast_axes(*args, **kwargs)[source]

Convenience fluent method for broadcast_axes().

The arguments are the same as for broadcast_axes(), with this array as data.

broadcast_like(other)[source]

Broadcasts the input array to the shape of other.

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:

other (NDArray) – Array with 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_like(mx.nd.ones((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)
broadcast_to(shape)[source]

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)
cbrt(*args, **kwargs)[source]

Convenience fluent method for cbrt().

The arguments are the same as for cbrt(), with this array as data.

ceil(*args, **kwargs)[source]

Convenience fluent method for ceil().

The arguments are the same as for ceil(), with this array as data.

clip(min=None, max=None, out=None)[source]

Return an array whose values are limited to [min, max]. One of max or min must be given.

property context

This function has been deprecated. Please refer to ndarray.ctx.

copy(order='C')[source]

Return a coyp of the array, keeping the same device.

Parameters:

order (str) – The memory layout of the copy. Currently, only c-contiguous memory layout is supported.

Examples

>>> x = np.ones((2, 3))
>>> y = x.copy()
>>> y
array([[ 1.,  1.,  1.],
       [ 1.,  1.,  1.]])
copyto(other)[source]

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 device, a new np.ndarray will be first created on the target device, and the value of self is copied.

Parameters:

other (ndarray or Device) – The destination array or device.

Returns:

out – 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 = np.ones((2, 3))
>>> y = np.zeros((2, 3), device=npx.gpu(0))
>>> z = x.copyto(y)
>>> z is y
True
>>> y
array([[ 1.,  1.,  1.],
       [ 1.,  1.,  1.]])
cos(*args, **kwargs)[source]

Convenience fluent method for cos().

The arguments are the same as for cos(), with this array as data.

cosh(*args, **kwargs)[source]

Convenience fluent method for cosh().

The arguments are the same as for cosh(), with this array as data.

property ctx

This property has been deprecated. Please refer to ndarray.device.

cumsum(axis=None, dtype=None, out=None)[source]

Return the cumulative sum of the elements along the given axis.

degrees(*args, **kwargs)[source]

Convenience fluent method for degrees().

The arguments are the same as for degrees(), with this array as data.

depth_to_space(*args, **kwargs)[source]

Convenience fluent method for depth_to_space().

The arguments are the same as for depth_to_space(), with this array as data.

detach()[source]

Returns a new ndarray, detached from the current graph.

property device

Hardware device the array data resides on.

Examples

>>> x = np.array([1, 2, 3, 4])
>>> x.device
cpu(0)
>>> type(x.device)
<class 'mxnet.device.Device'>
>>> y = np.zeros((2, 3), npx.gpu(0))
>>> y.device
gpu(0)
diag(k=0, **kwargs)[source]

Convenience fluent method for diag().

The arguments are the same as for diag(), with this array as data.

diagonal(offset=0, axis1=0, axis2=1)[source]

Return the diagonal with the given offset.

If array has more than two dimensions, then the axes specified by axis1 and axis2 are used to determine the 2-D sub-array whose diagonal is returned.

Refer to mxnet.numpy.diagonal for full documents.

dot(b, out=None)[source]

Dot product of two arrays. Refer to numpy.dot for full documentation.

drop_grad()[source]

Free the memory of the marked ndarray.

property dtype

Data-type of the array’s elements.

Returns:

This NDArray’s data type.

Return type:

numpy.dtype

Examples

>>> x = np.zeros((2,3))
>>> x.dtype
dtype('float32')
>>> y = np.zeros((2,3), dtype='int32')
>>> y.dtype
dtype('int32')
exp(*args, **kwargs)[source]

Convenience fluent method for exp().

The arguments are the same as for exp(), with this array as data.

expand_dims(*args, **kwargs)[source]

Convenience fluent method for expand_dims().

The arguments are the same as for expand_dims(), with this array as data.

expm1(*args, **kwargs)[source]

Convenience fluent method for expm1().

The arguments are the same as for expm1(), with this array as data.

fix(*args, **kwargs)[source]

Convenience fluent method for fix().

The arguments are the same as for fix(), with this array as data.

flatten(order='C')[source]

Return a copy of the array collapsed into one dimension.

flip(*args, **kwargs)[source]

Convenience fluent method for flip().

The arguments are the same as for flip(), with this array as data.

floor(*args, **kwargs)[source]

Convenience fluent method for floor().

The arguments are the same as for floor(), with this array as data.

property grad

Returns gradient buffer attached to this ndarray.

item(*args)[source]

Copy an element of an array to a standard Python scalar and return it.

Parameters:

*args (Arguments (variable number and type)) –

none: in this case, the method only works for arrays with one element (a.size == 1), which element is copied into a standard Python scalar object and returned.

int_type: this argument is interpreted as a flat index into the array, specifying which element to copy and return.

tuple of int_types: functions as does a single int_type argument, except that the argument is interpreted as an nd-index into the array.

Returns:

z – A copy of the specified element of the array as a suitable Python scalar.

Return type:

Standard Python scalar object

log(*args, **kwargs)[source]

Convenience fluent method for log().

The arguments are the same as for log(), with this array as data.

log10(*args, **kwargs)[source]

Convenience fluent method for log10().

The arguments are the same as for log10(), with this array as data.

log1p(*args, **kwargs)[source]

Convenience fluent method for log1p().

The arguments are the same as for log1p(), with this array as data.

log2(*args, **kwargs)[source]

Convenience fluent method for log2().

The arguments are the same as for log2(), with this array as data.

log_sigmoid(*args, **kwargs)[source]

Convenience fluent method for log_sigmoid().

The arguments are the same as for log_sigmoid(), with this array as data.

log_softmax(*args, **kwargs)[source]

Convenience fluent method for log_softmax().

The arguments are the same as for log_softmax(), with this array as data.

property mT

Same as self.transpose(). This always returns a copy of self.

max(axis=None, out=None, keepdims=False)[source]

Return the maximum along a given axis.

mean(axis=None, dtype=None, out=None, keepdims=False)[source]

Returns the average of the array elements along given axis.

min(axis=None, out=None, keepdims=False)[source]

Convenience fluent method for min().

The arguments are the same as for min(), with this array as data.

mish(*args, **kwargs)[source]

Convenience fluent method for mish().

The arguments are the same as for mish(), with this array as data.

nanprod(*args, **kwargs)[source]

Convenience fluent method for nanprod().

The arguments are the same as for nanprod(), with this array as data.

nansum(*args, **kwargs)[source]

Convenience fluent method for nansum().

The arguments are the same as for nansum(), with this array as data.

property ndim

Number of array dimensions.

nonzero()[source]

Return the indices of the elements that are non-zero.

Refer to numpy.nonzero for full documentation.

See also

numpy.nonzero

equivalent function

norm(*args, **kwargs)[source]

Convenience fluent method for norm().

The arguments are the same as for norm(), with this array as data.

one_hot(*args, **kwargs)[source]

Convenience fluent method for one_hot().

The arguments are the same as for one_hot(), with this array as data.

ones_like(*args, **kwargs)[source]

Convenience fluent method for ones_like().

The arguments are the same as for ones_like(), with this array as data.

pad(*args, **kwargs)[source]

Convenience fluent method for pad().

The arguments are the same as for pad(), with this array as data.

pick(*args, **kwargs)[source]

Convenience fluent method for pick().

The arguments are the same as for pick(), with this array as data.

prod(axis=None, dtype=None, out=None, keepdims=False)[source]

Return the product of the array elements over the given axis.

radians(*args, **kwargs)[source]

Convenience fluent method for radians().

The arguments are the same as for radians(), with this array as data.

ravel(order='C')[source]

Return a contiguous flattened array.

rcbrt(*args, **kwargs)[source]

Convenience fluent method for rcbrt().

The arguments are the same as for rcbrt(), with this array as data.

reciprocal(*args, **kwargs)[source]

Convenience fluent method for reciprocal().

The arguments are the same as for reciprocal(), with this array as data.

relu(*args, **kwargs)[source]

Convenience fluent method for relu().

The arguments are the same as for relu(), with this array as data.

repeat(repeats, axis=None)[source]

Repeat elements of an array.

reshape(*args, **kwargs)[source]

Returns a copy of the array with a new shape.

Notes

Unlike the free function numpy.reshape, this method on ndarray allows the elements of the shape parameter to be passed in as separate arguments. For example, a.reshape(10, 11) is equivalent to a.reshape((10, 11)).

reshape_like(*args, **kwargs)[source]

Convenience fluent method for reshape_like().

The arguments are the same as for reshape_like(), with this array as data.

reshape_view(*shape, **kwargs)[source]

Returns a view of this array with a new shape without altering any data. Inheritated from NDArray.reshape.

rint(*args, **kwargs)[source]

Convenience fluent method for rint().

The arguments are the same as for rint(), with this array as data.

round(decimals=0, out=None, **kwargs)[source]

Convenience fluent method for round().

The arguments are the same as for round(), with this array as data.

rsqrt(*args, **kwargs)[source]

Convenience fluent method for rsqrt().

The arguments are the same as for rsqrt(), with this array as data.

property shape

Tuple of array dimensions.

Examples

>>> x = mx.np.array([1, 2, 3, 4])
>>> x.shape
(4L,)
>>> y = mx.np.zeros((2, 3, 4))
>>> y.shape
(2L, 3L, 4L)
>>> z = mx.np.array(3)
>>> z.shape
()
shape_array(*args, **kwargs)[source]

Convenience fluent method for shape_array().

The arguments are the same as for shape_array(), with this array as data.

sigmoid(*args, **kwargs)[source]

Convenience fluent method for sigmoid().

The arguments are the same as for sigmoid(), with this array as data.

sign(*args, **kwargs)[source]

Convenience fluent method for sign().

The arguments are the same as for sign(), with this array as data.

sin(*args, **kwargs)[source]

Convenience fluent method for sin().

The arguments are the same as for sin(), with this array as data.

sinh(*args, **kwargs)[source]

Convenience fluent method for sinh().

The arguments are the same as for sinh(), with this array as data.

property size

Number of elements in the array.

size_array(*args, **kwargs)[source]

Convenience fluent method for size_array().

The arguments are the same as for size_array(), with this array as data.

slice(*args, **kwargs)[source]

Convenience fluent method for slice().

The arguments are the same as for slice(), with this array as data.

slice_assign(rhs, begin, end, step)[source]

Assign the rhs to a cropped subset of this ndarray in place. Returns the view of this ndarray.

Parameters:
  • rhs (ndarray.) – rhs and this NDArray should be of the same data type, and on the same device. The shape of rhs should be the same as the cropped shape of this ndarray.

  • begin (tuple of begin indices)

  • end (tuple of end indices)

  • step (tuple of step lenghths)

Returns:

out – This ndarray.

Return type:

ndarray

Examples

>>> x = np.ones((2, 2, 2))
>>> assigned = np.zeros((1, 1, 2))
>>> y = x.slice_assign(assigned, (0, 0, None), (1, 1, None), (None, None, None))
>>> y
array([[[0., 0.],
        [1., 1.]],
[[1., 1.],

[1., 1.]]])

>>> x
array([[[0., 0.],
        [1., 1.]],
[[1., 1.],

[1., 1.]]])

slice_assign_scalar(value, begin, end, step)[source]

Assign the scalar to a cropped subset of this ndarray. Value will broadcast to the shape of the cropped shape and will be cast to the same dtype of the ndarray.

Parameters:
  • value (numeric value) – Value and this ndarray should be of the same data type. The shape of rhs should be the same as the cropped shape of this ndarray.

  • begin (tuple of begin indices)

  • end (tuple of end indices)

  • step (tuple of step lenghths)

Return type:

This ndarray.

Examples

>>> x = np.ones((2, 2, 2))
>>> y = x.slice_assign_scalar(0, (0, 0, None), (1, 1, None), (None, None, None))
>>> y
array([[[0., 0.],
        [1., 1.]],
[[1., 1.],

[1., 1.]]])

>>> x
array([[[0., 0.],
        [1., 1.]],
[[1., 1.],

[1., 1.]]])

slice_axis(*args, **kwargs)[source]

Convenience fluent method for slice_axis().

The arguments are the same as for slice_axis(), with this array as data.

slice_like(*args, **kwargs)[source]

Convenience fluent method for slice_like().

The arguments are the same as for slice_like(), with this array as data.

softmax(*args, **kwargs)[source]

Convenience fluent method for softmax().

The arguments are the same as for softmax(), with this array as data.

softmin(*args, **kwargs)[source]

Convenience fluent method for softmin().

The arguments are the same as for softmin(), with this array as data.

sort(axis=-1, descending=False, stable=True)[source]

Convenience fluent method for sort().

The arguments are the same as for sort(), with this array as data.

space_to_depth(*args, **kwargs)[source]

Convenience fluent method for space_to_depth().

The arguments are the same as for space_to_depth(), with this array as data.

split(*args, **kwargs)[source]

Convenience fluent method for split().

The arguments are the same as for split(), with this array as data.

split_v2(*args, **kwargs)[source]

Convenience fluent method for split_v2().

The arguments are the same as for split_v2(), with this array as data.

sqrt(*args, **kwargs)[source]

Convenience fluent method for sqrt().

The arguments are the same as for sqrt(), with this array as data.

square(*args, **kwargs)[source]

Convenience fluent method for square().

The arguments are the same as for square(), with this array as data.

squeeze(axis=None)[source]

Remove single-dimensional entries from the shape of a.

std(axis=None, dtype=None, out=None, correction=0, keepdims=False)[source]

Returns the standard deviation of the array elements along given axis.

sum(axis=None, dtype=None, out=None, keepdims=False)[source]

Return the sum of the array elements over the given axis.

swapaxes(axis1, axis2)[source]

Return a copy of the array with axis1 and axis2 interchanged. Refer to mxnet.numpy.swapaxes for full documentation.

take(indices, axis=None, mode='raise')[source]

Convenience fluent method for take().

The arguments are the same as for take(), with this array as data.

tan(*args, **kwargs)[source]

Convenience fluent method for tan().

The arguments are the same as for tan(), with this array as data.

tanh(*args, **kwargs)[source]

Convenience fluent method for tanh().

The arguments are the same as for tanh(), with this array as data.

tile(reps)[source]

Construct an array by repeating A the number of times given by reps. Refer to mxnet.numpy.tile for full documentation.

to_device(device)[source]

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

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

Parameters:

device (Device) – The target device.

Returns:

The target array.

Return type:

ndarray

topk(*args, **kwargs)[source]

Convenience fluent method for topk().

The arguments are the same as for topk(), with this array as data.

tostype(stype)[source]

Return a copy of the array with chosen storage type.

Returns:

A copy of the array with the chosen storage stype

Return type:

NDArray, CSRNDArray or RowSparseNDArray

transpose(*axes)[source]

Permute the dimensions of an array.

trunc(*args, **kwargs)[source]

Convenience fluent method for trunc().

The arguments are the same as for trunc(), with this array as data.

var(axis=None, dtype=None, out=None, correction=0, keepdims=False)[source]

Returns the variance of the array elements, along given axis.

zeros_like(*args, **kwargs)[source]

Convenience fluent method for zeros_like().

The arguments are the same as for zeros_like(), with this array as data.

mxnet.numpy.multiarray.ndim(a)

Return the number of dimensions of an array.

Parameters:

a (array_like) – Input array. If it is not already an ndarray, a conversion is attempted.

Returns:

number_of_dimensions – The number of dimensions in a. Scalars are zero-dimensional.

Return type:

int

See also

ndarray.ndim

equivalent method

shape

dimensions of array

ndarray.shape

dimensions of array

Examples

>>> np.ndim([[1,2,3],[4,5,6]])
2
>>> np.ndim(np.array([[1,2,3],[4,5,6]]))
2
>>> np.ndim(1)
0
mxnet.numpy.multiarray.negative(x, out=None, **kwargs)

Numerical negative, element-wise.

Parameters:
  • x (ndarray or scalar) – Input array.

  • out (ndarray, None, or tuple of ndarray and None, optional) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.

Returns:

y – Returned array or scalar: y = -x. This is a scalar if x is a scalar.

Return type:

ndarray or scalar

Examples

>>> np.negative(1)
-1
mxnet.numpy.multiarray.nonzero(a)

Return the indices of the elements that are non-zero.

Returns a tuple of arrays, one for each dimension of a, containing the indices of the non-zero elements in that dimension. The values in a are always returned in row-major, C-style order.

To group the indices by element, rather than dimension, use argwhere, which returns a row for each non-zero element.

Parameters:

a (ndarray) – Input array.

Returns:

tuple_of_arrays – Indices of elements that are non-zero.

Return type:

tuple

See also

ndarray.nonzero

Equivalent ndarray method.

Notes

While the nonzero values can be obtained with a[nonzero(a)], it is recommended to use x[x.astype(bool)] or x[x != 0] instead, which will correctly handle 0-d arrays.

Examples

>>> x = np.array([[3, 0, 0], [0, 4, 0], [5, 6, 0]])
>>> x
array([[3, 0, 0],
       [0, 4, 0],
       [5, 6, 0]], dtype=int32)
>>> np.nonzero(x)
(array([0, 1, 2, 2], dtype=int64), array([0, 1, 0, 1], dtype=int64))
>>> x[np.nonzero(x)]
array([3, 4, 5, 6])
>>> np.transpose(np.stack(np.nonzero(x)))
array([[0, 0],
       [1, 1],
       [2, 0],
       [2, 1]], dtype=int64)

A common use for nonzero is to find the indices of an array, where a condition is True. Given an array a, the condition a > 3 is a boolean array and since False is interpreted as 0, np.nonzero(a > 3) yields the indices of the a where the condition is true.

>>> a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=np.int32)
>>> a > 3
array([[False, False, False],
       [ True,  True,  True],
       [ True,  True,  True]])
>>> np.nonzero(a > 3)
(array([1, 1, 1, 2, 2, 2], dtype=int64), array([0, 1, 2, 0, 1, 2], dtype=int64))

Using this result to index a is equivalent to using the mask directly:

>>> a[np.nonzero(a > 3)]
array([4, 5, 6, 7, 8, 9], dtype=int32)
>>> a[a > 3]
array([4, 5, 6, 7, 8, 9], dtype=int32)

nonzero can also be called as a method of the array.

>>> (a > 3).nonzero()
(array([1, 1, 1, 2, 2, 2], dtype=int64), array([0, 1, 2, 0, 1, 2], dtype=int64))
mxnet.numpy.multiarray.not_equal(x1, x2, out=None)

Return (x1 != x2) element-wise.

Parameters:
  • x1 (ndarrays or scalars) – Input arrays. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • x2 (ndarrays or scalars) – Input arrays. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • out (ndarray, None, or tuple of ndarray and None, optional) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned.

Returns:

out – Output array of type bool, element-wise comparison of x1 and x2. This is a scalar if both x1 and x2 are scalars.

Return type:

ndarray or scalar

Examples

>>> np.not_equal(np.ones(2, 1)), np.zeros(1, 3))
array([[ True,  True,  True],
       [ True,  True,  True]])
>>> np.not_equal(1, np.ones(1))
array([False])
mxnet.numpy.multiarray.ones(shape, dtype=None, order='C', device=None)

Return a new array of given shape and type, filled with ones. This function currently only supports storing multi-dimensional data in row-major (C-style).

Parameters:
  • shape (int or tuple of int) – The shape of the empty array.

  • dtype (str or numpy.dtype, optional) – An optional value type. Default is depend on your current default dtype. When npx.is_np_default_dtype() returns False, default dtype is float32; When npx.is_np_default_dtype() returns True, default dtype is float64. Note that this behavior is different from NumPy’s ones function where float64 is the default value.

  • order ({'C'}, optional, default: 'C') – How to store multi-dimensional data in memory, currently only row-major (C-style) is supported.

  • device (Device, optional) – Device context on which the memory is allocated. Default is mxnet.device.current_device().

Returns:

out – Array of ones with the given shape, dtype, and device.

Return type:

ndarray

Examples

>>> np.ones(5)
array([1., 1., 1., 1., 1.])
>>> np.ones((5,), dtype=int)
array([1, 1, 1, 1, 1], dtype=int64)
>>> np.ones((2, 1))
array([[1.],
       [1.]])
>>> s = (2,2)
>>> np.ones(s)
array([[1., 1.],
       [1., 1.]])
mxnet.numpy.multiarray.ones_like(a, dtype=None, order='C', device=None, out=None)

Return an array of ones with the same shape and type as a given array.

Parameters:
  • a (ndarray) – The shape and data-type of a define these same attributes of the returned array.

  • dtype (data-type, optional) – Overrides the data type of the result. Temporarily do not support boolean type.

  • order ({'C'}, optional) – Whether to store multidimensional data in C- or Fortran-contiguous (row- or column-wise) order in memory. Currently only supports C order.

  • device (Device, optional) – Device context on which the memory is allocated. Default is mxnet.device.current_device().

  • out (ndarray or None, optional) – A location into which the result is stored. If provided, it must have the same shape and dtype as input ndarray. If not provided or None, a freshly-allocated array is returned.

Returns:

out – Array of ones with the same shape and type as a.

Return type:

ndarray

See also

empty_like

Return an empty array with shape and type of input.

zeros_like

Return an array of zeros with shape and type of input.

full_like

Return a new array with shape of input filled with value.

ones

Return a new array setting values to one.

Examples

>>> x = np.arange(6)
>>> x = x.reshape((2, 3))
>>> x
array([[0., 1., 2.],
       [3., 4., 5.]])
>>> np.ones_like(x)
array([[1., 1., 1.],
       [1., 1., 1.]])
>>> np.ones_like(x, int)
array([[1, 1, 1],
       [1, 1, 1]], dtype=int64)
>>> y = np.arange(3, dtype=float)
>>> y
array([0., 1., 2.], dtype=float64)
>>> np.ones_like(y)
array([1., 1., 1.], dtype=float64)
mxnet.numpy.multiarray.outer(a, b)

Compute the outer product of two vectors. Given two vectors, a = [a0, a1, ..., aM] and b = [b0, b1, ..., bN], the outer product [1]_ is:: [[a0*b0 a0*b1 … a0*bN ] [a1*b0 . [ … . [aM*b0 aM*bN ]]

Parameters:
  • a ((M,) ndarray) – First input vector. Input is flattened if not already 1-dimensional.

  • b ((N,) ndarray) – Second input vector. Input is flattened if not already 1-dimensional.

Returns:

outout[i, j] = a[i] * b[j]

Return type:

(M, N) ndarray

See also

inner

einsum

einsum('i,j->ij', a.ravel(), b.ravel()) is the equivalent.

ufunc.outer

A generalization to N dimensions and other operations. np.multiply.outer(a.ravel(), b.ravel()) is the equivalent.

References

Examples

Make a (very coarse) grid for computing a Mandelbrot set:

>>> rl = np.outer(np.ones((5,)), np.linspace(-2, 2, 5))
>>> rl
array([[-2., -1.,  0.,  1.,  2.],
       [-2., -1.,  0.,  1.,  2.],
       [-2., -1.,  0.,  1.,  2.],
       [-2., -1.,  0.,  1.,  2.],
       [-2., -1.,  0.,  1.,  2.]])
mxnet.numpy.multiarray.packbits(a, /, axis=None, bitorder='big')

Packs the elements of a binary-valued array into bits in a uint8 array.

The result is padded to full bytes by inserting zero bits at the end.

Parameters:
  • a (array_like) – An array of integers or booleans whose elements should be packed to bits.

  • axis (int, optional) – The dimension over which bit-packing is done. None implies packing the flattened array.

  • bitorder ({'big', 'little'}, optional) –

    The order of the input bits. ‘big’ will mimic bin(val), [0, 0, 0, 0, 0, 0, 1, 1] => 3 = 0b00000011, ‘little’ will reverse the order so [1, 1, 0, 0, 0, 0, 0, 0] => 3. Defaults to ‘big’.

    Added in version 1.17.0.

Returns:

packed – Array of type uint8 whose elements represent bits corresponding to the logical (0 or nonzero) value of the input elements. The shape of packed has the same number of dimensions as the input (unless axis is None, in which case the output is 1-D).

Return type:

ndarray

See also

unpackbits

Unpacks elements of a uint8 array into a binary-valued output array.

Examples

>>> a = np.array([[[1,0,1],
...                [0,1,0]],
...               [[1,1,0],
...                [0,0,1]]])
>>> b = np.packbits(a, axis=-1)
>>> b
array([[[160],
        [ 64]],
       [[192],
        [ 32]]], dtype=uint8)

Note that in binary 160 = 1010 0000, 64 = 0100 0000, 192 = 1100 0000, and 32 = 0010 0000.

mxnet.numpy.multiarray.pad(x, pad_width=None, mode='constant', **kwargs)

Pad an array.

Parameters:
  • array (array_like of rank N) – The array to pad.

  • pad_width ({sequence, array_like, int}) – Number of values padded to the edges of each axis. ((before_1, after_1), … (before_N, after_N)) unique pad widths for each axis. ((before, after),) yields same before and after pad for each axis. (pad,) or int is a shortcut for before = after = pad width for all axes.

  • mode (str or function, optional) –

    One of the following string values or a user supplied function. ‘constant’ (default)

    Pads with a constant value.

    ’edge’

    Pads with the edge values of array.

    ’linear_ramp’

    not supported yet

    ’maximum’

    Pads with the maximum value of all of the vector along each axis.

    ’mean’

    not supported yet

    ’median’

    not supported yet

    ’minimum’

    Pads with the minimum value of all of the vector along each axis.

    ’reflect’

    Pads with the reflection of the vector mirrored on the first and last values of the vector along each axis.

    ’symmetric’

    Pads with the reflection of the vector mirrored along the edge of the array.

    ’wrap’

    not supported yet.

    ’empty’

    not supported yet.

    <function>

    not supported yet.

  • stat_length (not supported yet)

  • constant_values (scalar, optional) – Used in ‘constant’. The values to set the padded values for each axis. Default is 0.

  • end_values (not supported yet)

  • reflect_type ({'even', 'odd'}, optional) – only support even now

Returns:

pad – Padded array of rank equal to array with shape increased according to pad_width.

Return type:

ndarray

Examples

>>> a = [1, 2, 3, 4, 5]
>>> np.pad(a, (2, 3), 'edge')
array([1, 1, 1, ..., 5, 5, 5])
>>> np.pad(a, (2, 2), 'maximum')
array([5, 5, 1, 2, 3, 4, 5, 5, 5])
>>> np.pad(a, (2, 2), 'mean')
array([3, 3, 1, 2, 3, 4, 5, 3, 3])
>>> a = [[1, 2], [3, 4]]
>>> np.pad(a, ((3, 2), (2, 3)), 'minimum')
array([[1, 1, 1, 2, 1, 1, 1],
       [1, 1, 1, 2, 1, 1, 1],
       [1, 1, 1, 2, 1, 1, 1],
       [1, 1, 1, 2, 1, 1, 1],
       [3, 3, 3, 4, 3, 3, 3],
       [1, 1, 1, 2, 1, 1, 1],
       [1, 1, 1, 2, 1, 1, 1]])
>>> a = [1, 2, 3, 4, 5]
>>> np.pad(a, (2, 3), 'reflect')
array([3, 2, 1, 2, 3, 4, 5, 4, 3, 2])
>>> np.pad(a, (2, 3), 'symmetric')
array([2, 1, 1, 2, 3, 4, 5, 5, 4, 3])
>>> a = np.arange(6)
>>> a = a.reshape((2, 3))
>>> np.pad(a, ((2, 2), (2, 2)), pad_with)
array([[10, 10, 10, 10, 10, 10, 10],
       [10, 10, 10, 10, 10, 10, 10],
       [10, 10,  0,  1,  2, 10, 10],
       [10, 10,  3,  4,  5, 10, 10],
       [10, 10, 10, 10, 10, 10, 10],
       [10, 10, 10, 10, 10, 10, 10]])
mxnet.numpy.multiarray.partition(a, kth, axis=-1, kind='introselect', order=None)

Return a partitioned copy of an array.

Creates a copy of the array with its elements rearranged in such a way that the value of the element in k-th position is in the position the value would be in a sorted array. In the partitioned array, all elements before the k-th element are less than or equal to that element, and all the elements after the k-th element are greater than or equal to that element. The ordering of the elements in the two partitions is undefined.

Added in version 1.8.0.

Parameters:
  • a (array_like) – Array to be sorted.

  • kth (int or sequence of ints) –

    Element index to partition by. The k-th value of the element will be in its final sorted position and all smaller elements will be moved before it and all equal or greater elements behind it. The order of all elements in the partitions is undefined. If provided with a sequence of k-th it will partition all elements indexed by k-th of them into their sorted position at once.

    Deprecated since version 1.22.0: Passing booleans as index is deprecated.

  • axis (int or None, optional) – Axis along which to sort. If None, the array is flattened before sorting. The default is -1, which sorts along the last axis.

  • kind ({'introselect'}, optional) – Selection algorithm. Default is ‘introselect’.

  • order (str or list of str, optional) – When a is an array with fields defined, this argument specifies which fields to compare first, second, etc. A single field can be specified as a string. Not all fields need be specified, but unspecified fields will still be used, in the order in which they come up in the dtype, to break ties.

Returns:

partitioned_array – Array of the same type and shape as a.

Return type:

ndarray

See also

ndarray.partition

Method to sort an array in-place.

argpartition

Indirect partition.

sort

Full sorting

Notes

The various selection algorithms are characterized by their average speed, worst case performance, work space size, and whether they are stable. A stable sort keeps items with the same key in the same relative order. The available algorithms have the following properties:

kind

speed

worst case

work space

stable

‘introselect’

1

O(n)

0

no

All the partition algorithms make temporary copies of the data when partitioning along any but the last axis. Consequently, partitioning along the last axis is faster and uses less space than partitioning along any other axis.

The sort order for complex numbers is lexicographic. If both the real and imaginary parts are non-nan then the order is determined by the real parts except when they are equal, in which case the order is determined by the imaginary parts.

Examples

>>> a = np.array([7, 1, 7, 7, 1, 5, 7, 2, 3, 2, 6, 2, 3, 0])
>>> p = np.partition(a, 4)
>>> p
array([0, 1, 2, 1, 2, 5, 2, 3, 3, 6, 7, 7, 7, 7])

p[4] is 2; all elements in p[:4] are less than or equal to p[4], and all elements in p[5:] are greater than or equal to p[4]. The partition is:

[0, 1, 2, 1], [2], [5, 2, 3, 3, 6, 7, 7, 7, 7]

The next example shows the use of multiple values passed to kth.

>>> p2 = np.partition(a, (4, 8))
>>> p2
array([0, 1, 2, 1, 2, 3, 3, 2, 5, 6, 7, 7, 7, 7])

p2[4] is 2 and p2[8] is 5. All elements in p2[:4] are less than or equal to p2[4], all elements in p2[5:8] are greater than or equal to p2[4] and less than or equal to p2[8], and all elements in p2[9:] are greater than or equal to p2[8]. The partition is:

[0, 1, 2, 1], [2], [3, 3, 2], [5], [6, 7, 7, 7, 7]
mxnet.numpy.multiarray.percentile(a, q, axis=None, out=None, overwrite_input=None, interpolation='linear', keepdims=False)

Compute the q-th percentile of the data along the specified axis. Returns the q-th percentile(s) of the array elements.

Parameters:
  • a (array_like) – Input array

  • q (array_like) – Percentile or sequence of percentiles to compute.

  • axis ({int, tuple of int, None}, optional) – Axis or axes along which the percentiles are computed. The default is to compute the percentile(s) along a flattened version of the array.

  • out (ndarray, optional) – Alternative output array in which to place the result. It must have the same shape and buffer length as the expected output, but the type (of the output) will be cast if necessary.

  • overwrite_input (bool, optional (Not supported yet)) – If True, then allow the input array a to be modified by intermediate calculations, to save memory. In this case, the contents of the input a after this function completes is undefined.

  • interpolation ({'linear', 'lower', 'higher', 'midpoint', 'nearest'}) – This optional parameter specifies the interpolation method to use when the desired percentile lies between two data points i < j: ‘linear’: i + (j - i) * fraction, where fraction is the fractional part of the index surrounded by i and j. ‘lower’: i. ‘higher’: j. ‘nearest’: i or j, whichever is nearest. ‘midpoint’: (i + j) / 2.

  • keepdims (bool, optional) – If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original array a.

Returns:

percentile – Output array.

Return type:

scalar or ndarray

Examples

>>> a = np.array([[10, 7, 4], [3, 2, 1]])
>>> a
array([[10,  7,  4],
    [ 3,  2,  1]])
>>> np.percentile(a, np.array(50))
array(3.5)
>>> np.percentile(a, np.array(50), axis=0)
array([6.5, 4.5, 2.5])
>>> np.percentile(a, np.array(50), axis=1)
array([7.,  2.])
>>> np.percentile(a, np.array(50), axis=1, keepdims=True)
array([[7.],
    [2.]])
>>> m = np.percentile(a, np.array(50), axis=0)
>>> out = np.zeros_like(m)
>>> np.percentile(a, np.array(50), axis=0, out=out)
array([6.5, 4.5, 2.5])
>>> m
array([6.5, 4.5, 2.5])
mxnet.numpy.multiarray.permute_dims(a, axes=None)

Permute the dimensions of an array.

Parameters:
  • a (ndarray) – Input array.

  • axes (list of ints, optional) – By default, reverse the dimensions, otherwise permute the axes according to the values given.

Returns:

p – a with its axes permuted.

Return type:

ndarray

Note

permute_dims is a alias for transpose. It is a standard API in https://data-apis.org/array-api/latest/API_specification/manipulation_functions.html#permute-dims-x-axes instead of an official NumPy operator.

Examples

>>> x = np.arange(4).reshape((2,2))
>>> x
array([[0., 1.],
       [2., 3.]])
>>> np.permute_dims(x)
array([[0., 2.],
       [1., 3.]])
>>> x = np.ones((1, 2, 3))
>>> np.permute_dims(x, (1, 0, 2)).shape
(2, 1, 3)
mxnet.numpy.multiarray.piecewise(x, condlist, funclist, *args, **kw)

Evaluate a piecewise-defined function.

Given a set of conditions and corresponding functions, evaluate each function on the input data wherever its condition is true.

Parameters:
  • x (ndarray or scalar) – The input domain.

  • condlist (list of bool arrays or bool scalars) –

    Each boolean array corresponds to a function in funclist. Wherever condlist[i] is True, funclist[i](x) is used as the output value.

    Each boolean array in condlist selects a piece of x, and should therefore be of the same shape as x.

    The length of condlist must correspond to that of funclist. If one extra function is given, i.e. if len(funclist) == len(condlist) + 1, then that extra function is the default value, used wherever all conditions are false.

  • funclist (list of callables, f(x,*args,**kw), or scalars) – Each function is evaluated over x wherever its corresponding condition is True. It should take a 1d array as input and give an 1d array or a scalar value as output. If, instead of a callable, a scalar is provided then a constant function (lambda x: scalar) is assumed.

  • args (tuple, optional) – Any further arguments given to piecewise are passed to the functions upon execution, i.e., if called piecewise(..., ..., 1, 'a'), then each function is called as f(x, 1, 'a').

  • kw (dict, optional) – Keyword arguments used in calling piecewise are passed to the functions upon execution, i.e., if called piecewise(..., ..., alpha=1), then each function is called as f(x, alpha=1).

Returns:

out – The output is the same shape and type as x and is found by calling the functions in funclist on the appropriate portions of x, as defined by the boolean arrays in condlist. Portions not covered by any condition have a default value of 0.

Return type:

ndarray

See also

choose, select, where

Notes

This is similar to choose or select, except that functions are evaluated on elements of x that satisfy the corresponding condition from condlist.

The result is:

      |--
      |funclist[0](x[condlist[0]])
out = |funclist[1](x[condlist[1]])
      |...
      |funclist[n2](x[condlist[n2]])
      |--

Examples

Define the sigma function, which is -1 for x < 0 and +1 for x >= 0.

>>> x = np.linspace(-2.5, 2.5, 6)
>>> np.piecewise(x, [x < 0, x >= 0], [-1, 1])
array([-1., -1., -1.,  1.,  1.,  1.])

Define the absolute value, which is -x for x <0 and x for x >= 0.

>>> np.piecewise(x, [x < 0, x >= 0], [lambda x: -x, lambda x: x])
array([2.5,  1.5,  0.5,  0.5,  1.5,  2.5])

Apply the same function to a scalar value.

>>> y = -2
>>> np.piecewise(y, [y < 0, y >= 0], [lambda x: -x, lambda x: x])
array(2)
mxnet.numpy.multiarray.poly(seq_of_zeros)

Find the coefficients of a polynomial with the given sequence of roots.

Note

This forms part of the old polynomial API. Since version 1.4, the new polynomial API defined in numpy.polynomial is preferred. A summary of the differences can be found in the transition guide.

Returns the coefficients of the polynomial whose leading coefficient is one for the given sequence of zeros (multiple roots must be included in the sequence as many times as their multiplicity; see Examples). A square matrix (or array, which will be treated as a matrix) can also be given, in which case the coefficients of the characteristic polynomial of the matrix are returned.

Parameters:

seq_of_zeros (array_like, shape (N,) or (N, N)) – A sequence of polynomial roots, or a square array or matrix object.

Returns:

c – 1D array of polynomial coefficients from highest to lowest degree:

c[0] * x**(N) + c[1] * x**(N-1) + ... + c[N-1] * x + c[N] where c[0] always equals 1.

Return type:

ndarray

Raises:

ValueError – If input is the wrong shape (the input must be a 1-D or square 2-D array).

See also

polyval

Compute polynomial values.

roots

Return the roots of a polynomial.

polyfit

Least squares polynomial fit.

poly1d

A one-dimensional polynomial class.

Notes

Specifying the roots of a polynomial still leaves one degree of freedom, typically represented by an undetermined leading coefficient. [1]_ In the case of this function, that coefficient - the first one in the returned array - is always taken as one. (If for some reason you have one other point, the only automatic way presently to leverage that information is to use polyfit.)

The characteristic polynomial, \(p_a(t)\), of an n-by-n matrix A is given by

\(p_a(t) = \mathrm{det}(t\, \mathbf{I} - \mathbf{A})\),

where I is the n-by-n identity matrix. [2]_

References

Examples

Given a sequence of a polynomial’s zeros:

>>> np.poly((0, 0, 0)) # Multiple root example
array([1., 0., 0., 0.])

The line above represents z**3 + 0*z**2 + 0*z + 0.

>>> np.poly((-1./2, 0, 1./2))
array([ 1.  ,  0.  , -0.25,  0.  ])

The line above represents z**3 - z/4

>>> np.poly((np.random.random(1)[0], 0, np.random.random(1)[0]))
array([ 1.        , -0.77086955,  0.08618131,  0.        ]) # random

Given a square array object:

>>> P = np.array([[0, 1./3], [-1./2, 0]])
>>> np.poly(P)
array([1.        , 0.        , 0.16666667])

Note how in all cases the leading coefficient is always 1.

mxnet.numpy.multiarray.polyadd(a1, a2)

Find the sum of two polynomials.

Note

This forms part of the old polynomial API. Since version 1.4, the new polynomial API defined in numpy.polynomial is preferred. A summary of the differences can be found in the transition guide.

Returns the polynomial resulting from the sum of two input polynomials. Each input must be either a poly1d object or a 1D sequence of polynomial coefficients, from highest to lowest degree.

Parameters:
  • a1 (array_like or poly1d object) – Input polynomials.

  • a2 (array_like or poly1d object) – Input polynomials.

Returns:

out – The sum of the inputs. If either input is a poly1d object, then the output is also a poly1d object. Otherwise, it is a 1D array of polynomial coefficients from highest to lowest degree.

Return type:

ndarray or poly1d object

See also

poly1d

A one-dimensional polynomial class.

poly, polyadd, polyder, polydiv, polyfit, polyint, polysub, polyval

Examples

>>> np.polyadd([1, 2], [9, 5, 4])
array([9, 6, 6])

Using poly1d objects:

>>> p1 = np.poly1d([1, 2])
>>> p2 = np.poly1d([9, 5, 4])
>>> print(p1)
1 x + 2
>>> print(p2)
   2
9 x + 5 x + 4
>>> print(np.polyadd(p1, p2))
   2
9 x + 6 x + 6
mxnet.numpy.multiarray.polydiv(u, v)

Returns the quotient and remainder of polynomial division.

Note

This forms part of the old polynomial API. Since version 1.4, the new polynomial API defined in numpy.polynomial is preferred. A summary of the differences can be found in the transition guide.

The input arrays are the coefficients (including any coefficients equal to zero) of the “numerator” (dividend) and “denominator” (divisor) polynomials, respectively.

Parameters:
  • u (array_like or poly1d) – Dividend polynomial’s coefficients.

  • v (array_like or poly1d) – Divisor polynomial’s coefficients.

Returns:

  • q (ndarray) – Coefficients, including those equal to zero, of the quotient.

  • r (ndarray) – Coefficients, including those equal to zero, of the remainder.

Notes

Both u and v must be 0-d or 1-d (ndim = 0 or 1), but u.ndim need not equal v.ndim. In other words, all four possible combinations - u.ndim = v.ndim = 0, u.ndim = v.ndim = 1, u.ndim = 1, v.ndim = 0, and u.ndim = 0, v.ndim = 1 - work.

Examples

\[\frac{3x^2 + 5x + 2}{2x + 1} = 1.5x + 1.75, remainder 0.25\]
>>> x = np.array([3.0, 5.0, 2.0])
>>> y = np.array([2.0, 1.0])
>>> np.polydiv(x, y)
(array([1.5 , 1.75]), array([0.25]))
mxnet.numpy.multiarray.polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False)

Least squares polynomial fit.

Note

This forms part of the old polynomial API. Since version 1.4, the new polynomial API defined in numpy.polynomial is preferred. A summary of the differences can be found in the transition guide.

Fit a polynomial p(x) = p[0] * x**deg + ... + p[deg] of degree deg to points (x, y). Returns a vector of coefficients p that minimises the squared error in the order deg, deg-1, … 0.

The Polynomial.fit <numpy.polynomial.polynomial.Polynomial.fit> class method is recommended for new code as it is more stable numerically. See the documentation of the method for more information.

Parameters:
  • x (array_like, shape (M,)) – x-coordinates of the M sample points (x[i], y[i]).

  • y (array_like, shape (M,) or (M, K)) – y-coordinates of the sample points. Several data sets of sample points sharing the same x-coordinates can be fitted at once by passing in a 2D-array that contains one dataset per column.

  • deg (int) – Degree of the fitting polynomial

  • rcond (float, optional) – Relative condition number of the fit. Singular values smaller than this relative to the largest singular value will be ignored. The default value is len(x)*eps, where eps is the relative precision of the float type, about 2e-16 in most cases.

  • full (bool, optional) – Switch determining nature of return value. When it is False (the default) just the coefficients are returned, when True diagnostic information from the singular value decomposition is also returned.

  • w (array_like, shape (M,), optional) – Weights. If not None, the weight w[i] applies to the unsquared residual y[i] - y_hat[i] at x[i]. Ideally the weights are chosen so that the errors of the products w[i]*y[i] all have the same variance. When using inverse-variance weighting, use w[i] = 1/sigma(y[i]). The default value is None.

  • cov (bool or str, optional) – If given and not False, return not just the estimate but also its covariance matrix. By default, the covariance are scaled by chi2/dof, where dof = M - (deg + 1), i.e., the weights are presumed to be unreliable except in a relative sense and everything is scaled such that the reduced chi2 is unity. This scaling is omitted if cov='unscaled', as is relevant for the case that the weights are w = 1/sigma, with sigma known to be a reliable estimate of the uncertainty.

Returns:

  • p (ndarray, shape (deg + 1,) or (deg + 1, K)) – Polynomial coefficients, highest power first. If y was 2-D, the coefficients for k-th data set are in p[:,k].

  • residuals, rank, singular_values, rcond – These values are only returned if full == True

    • residuals – sum of squared residuals of the least squares fit

    • rank – the effective rank of the scaled Vandermonde

      coefficient matrix

    • singular_values – singular values of the scaled Vandermonde

      coefficient matrix

    • rcond – value of rcond.

    For more details, see numpy.linalg.lstsq.

  • V (ndarray, shape (M,M) or (M,M,K)) – Present only if full == False and cov == True. The covariance matrix of the polynomial coefficient estimates. The diagonal of this matrix are the variance estimates for each coefficient. If y is a 2-D array, then the covariance matrix for the k-th data set are in V[:,:,k]

Warns:

RankWarning – The rank of the coefficient matrix in the least-squares fit is deficient. The warning is only raised if full == False.

The warnings can be turned off by

>>> import warnings
>>> warnings.simplefilter('ignore', np.RankWarning)

See also

polyval

Compute polynomial values.

linalg.lstsq

Computes a least-squares fit.

scipy.interpolate.UnivariateSpline

Computes spline fits.

Notes

The solution minimizes the squared error

\[E = \sum_{j=0}^k |p(x_j) - y_j|^2\]

in the equations:

x[0]**n * p[0] + ... + x[0] * p[n-1] + p[n] = y[0]
x[1]**n * p[0] + ... + x[1] * p[n-1] + p[n] = y[1]
...
x[k]**n * p[0] + ... + x[k] * p[n-1] + p[n] = y[k]

The coefficient matrix of the coefficients p is a Vandermonde matrix.

polyfit issues a RankWarning when the least-squares fit is badly conditioned. This implies that the best fit is not well-defined due to numerical error. The results may be improved by lowering the polynomial degree or by replacing x by x - x.mean(). The rcond parameter can also be set to a value smaller than its default, but the resulting fit may be spurious: including contributions from the small singular values can add numerical noise to the result.

Note that fitting polynomial coefficients is inherently badly conditioned when the degree of the polynomial is large or the interval of sample points is badly centered. The quality of the fit should always be checked in these cases. When polynomial fits are not satisfactory, splines may be a good alternative.

References

Examples

>>> import warnings
>>> x = np.array([0.0, 1.0, 2.0, 3.0,  4.0,  5.0])
>>> y = np.array([0.0, 0.8, 0.9, 0.1, -0.8, -1.0])
>>> z = np.polyfit(x, y, 3)
>>> z
array([ 0.08703704, -0.81349206,  1.69312169, -0.03968254]) # may vary

It is convenient to use poly1d objects for dealing with polynomials:

>>> p = np.poly1d(z)
>>> p(0.5)
0.6143849206349179 # may vary
>>> p(3.5)
-0.34732142857143039 # may vary
>>> p(10)
22.579365079365115 # may vary

High-order polynomials may oscillate wildly:

>>> with warnings.catch_warnings():
...     warnings.simplefilter('ignore', np.RankWarning)
...     p30 = np.poly1d(np.polyfit(x, y, 30))
...
>>> p30(4)
-0.80000000000000204 # may vary
>>> p30(5)
-0.99999999999999445 # may vary
>>> p30(4.5)
-0.10547061179440398 # may vary

Illustration:

>>> import matplotlib.pyplot as plt
>>> xp = np.linspace(-2, 6, 100)
>>> _ = plt.plot(x, y, '.', xp, p(xp), '-', xp, p30(xp), '--')
>>> plt.ylim(-2,2)
(-2, 2)
>>> plt.show()
mxnet.numpy.multiarray.polyint(p, m=1, k=None)

Return an antiderivative (indefinite integral) of a polynomial.

Note

This forms part of the old polynomial API. Since version 1.4, the new polynomial API defined in numpy.polynomial is preferred. A summary of the differences can be found in the transition guide.

The returned order m antiderivative P of polynomial p satisfies \(\frac{d^m}{dx^m}P(x) = p(x)\) and is defined up to m - 1 integration constants k. The constants determine the low-order polynomial part

\[\frac{k_{m-1}}{0!} x^0 + \ldots + \frac{k_0}{(m-1)!}x^{m-1}\]

of P so that \(P^{(j)}(0) = k_{m-j-1}\).

Parameters:
  • p (array_like or poly1d) – Polynomial to integrate. A sequence is interpreted as polynomial coefficients, see poly1d.

  • m (int, optional) – Order of the antiderivative. (Default: 1)

  • k (list of m scalars or scalar, optional) –

    Integration constants. They are given in the order of integration: those corresponding to highest-order terms come first.

    If None (default), all constants are assumed to be zero. If m = 1, a single scalar can be given instead of a list.

See also

polyder

derivative of a polynomial

poly1d.integ

equivalent method

Examples

The defining property of the antiderivative:

>>> p = np.poly1d([1,1,1])
>>> P = np.polyint(p)
>>> P
 poly1d([ 0.33333333,  0.5       ,  1.        ,  0.        ]) # may vary
>>> np.polyder(P) == p
True

The integration constants default to zero, but can be specified:

>>> P = np.polyint(p, 3)
>>> P(0)
0.0
>>> np.polyder(P)(0)
0.0
>>> np.polyder(P, 2)(0)
0.0
>>> P = np.polyint(p, 3, k=[6,5,3])
>>> P
poly1d([ 0.01666667,  0.04166667,  0.16666667,  3. ,  5. ,  3. ]) # may vary

Note that 3 = 6 / 2!, and that the constants are given in the order of integrations. Constant of the highest-order polynomial term comes first:

>>> np.polyder(P, 2)(0)
6.0
>>> np.polyder(P, 1)(0)
5.0
>>> P(0)
3.0
mxnet.numpy.multiarray.polymul(a1, a2)

Find the product of two polynomials.

Note

This forms part of the old polynomial API. Since version 1.4, the new polynomial API defined in numpy.polynomial is preferred. A summary of the differences can be found in the transition guide.

Finds the polynomial resulting from the multiplication of the two input polynomials. Each input must be either a poly1d object or a 1D sequence of polynomial coefficients, from highest to lowest degree.

Parameters:
  • a1 (array_like or poly1d object) – Input polynomials.

  • a2 (array_like or poly1d object) – Input polynomials.

Returns:

out – The polynomial resulting from the multiplication of the inputs. If either inputs is a poly1d object, then the output is also a poly1d object. Otherwise, it is a 1D array of polynomial coefficients from highest to lowest degree.

Return type:

ndarray or poly1d object

See also

poly1d

A one-dimensional polynomial class.

poly, polyadd, polyder, polydiv, polyfit, polyint, polysub, polyval

convolve

Array convolution. Same output as polymul, but has parameter for overlap mode.

Examples

>>> np.polymul([1, 2, 3], [9, 5, 1])
array([ 9, 23, 38, 17,  3])

Using poly1d objects:

>>> p1 = np.poly1d([1, 2, 3])
>>> p2 = np.poly1d([9, 5, 1])
>>> print(p1)
   2
1 x + 2 x + 3
>>> print(p2)
   2
9 x + 5 x + 1
>>> print(np.polymul(p1, p2))
   4      3      2
9 x + 23 x + 38 x + 17 x + 3
mxnet.numpy.multiarray.polysub(a1, a2)

Difference (subtraction) of two polynomials.

Note

This forms part of the old polynomial API. Since version 1.4, the new polynomial API defined in numpy.polynomial is preferred. A summary of the differences can be found in the transition guide.

Given two polynomials a1 and a2, returns a1 - a2. a1 and a2 can be either array_like sequences of the polynomials’ coefficients (including coefficients equal to zero), or poly1d objects.

Parameters:
  • a1 (array_like or poly1d) – Minuend and subtrahend polynomials, respectively.

  • a2 (array_like or poly1d) – Minuend and subtrahend polynomials, respectively.

Returns:

out – Array or poly1d object of the difference polynomial’s coefficients.

Return type:

ndarray or poly1d

Examples

\[(2 x^2 + 10 x - 2) - (3 x^2 + 10 x -4) = (-x^2 + 2)\]
>>> np.polysub([2, 10, -2], [3, 10, -4])
array([-1,  0,  2])
mxnet.numpy.multiarray.polyval(p, x)

Evaluate a polynomial at specific values. If p is of length N, this function returns the value: p[0]*x**(N-1) + p[1]*x**(N-2) + … + p[N-2]*x + p[N-1] If x is a sequence, then p(x) is returned for each element of x. If x is another polynomial then the composite polynomial p(x(t)) is returned.

Parameters:
  • p (ndarray) – 1D array of polynomial coefficients (including coefficients equal to zero) from highest degree to the constant term.

  • x (ndarray) – An array of numbers, at which to evaluate p.

Returns:

  • values (ndarray) – Result array of polynomials

  • .. note:: – This function differs from the original numpy.polyval in the following way(s):

    • Does not support poly1d.

    • X should be ndarray type even if it contains only one element.

Examples

>>> p = np.array([3, 0, 1])
array([3., 0., 1.])
>>> x = np.array([5])
array([5.])
>>> np.polyval(p, x)  # 3 * 5**2 + 0 * 5**1 + 1
array([76.])
>>> x = np.array([5, 4])
array([5., 4.])
>>> np.polyval(p, x)
array([76., 49.])
mxnet.numpy.multiarray.positive(x, out=None, **kwargs)

Computes the numerical positive of each element x_i (i.e.,`y_i = +x_i`) of the input array x .

Parameters:

x (ndarray or scalar) – Input array.

Returns:

y – Returned array or scalar: y = +x. This is a scalar if x is a scalar.

Return type:

ndarray or scalar

Notes

Equivalent to x.copy(), but only defined for types that support arithmetic.

Examples

>>> x1 = np.array(([1., -1.]))
>>> np.positive(x1)
array([ 1., -1.])
>>> +x1
array([ 1., -1.])
mxnet.numpy.multiarray.pow(x1, x2, out=None, **kwargs)

First array elements raised to powers from second array, element-wise.

Parameters:
  • x1 (ndarray or scalar) – The bases.

  • x2 (ndarray or scalar) – The exponent.

  • out (ndarray) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned.

Returns:

out – The bases in x1 raised to the exponents in x2. This is a scalar if both x1 and x2 are scalars.

Return type:

ndarray or scalar

Examples

>>> x1 = np.arange(6)
>>> np.power(x1, 3)
array([  0.,   1.,   8.,  27.,  64., 125.])

Raise the bases to different exponents.

>>> x2 = np.array([1.0, 2.0, 3.0, 3.0, 2.0, 1.0])
>>> np.power(x1, x2)
array([ 0.,  1.,  8., 27., 16.,  5.])

The effect of broadcasting.

>>> x2 = np.array([[1, 2, 3, 3, 2, 1], [1, 2, 3, 3, 2, 1]])
>>> x2
array([[1., 2., 3., 3., 2., 1.],
       [1., 2., 3., 3., 2., 1.]])
>>> np.power(x1, x2)
array([[ 0.,  1.,  8., 27., 16.,  5.],
       [ 0.,  1.,  8., 27., 16.,  5.]])
mxnet.numpy.multiarray.power(x1, x2, out=None, **kwargs)

First array elements raised to powers from second array, element-wise.

Parameters:
  • x1 (ndarray or scalar) – The bases.

  • x2 (ndarray or scalar) – The exponent.

  • out (ndarray) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned.

Returns:

out – The bases in x1 raised to the exponents in x2. This is a scalar if both x1 and x2 are scalars.

Return type:

ndarray or scalar

Examples

>>> x1 = np.arange(6)
>>> np.power(x1, 3)
array([  0.,   1.,   8.,  27.,  64., 125.])

Raise the bases to different exponents.

>>> x2 = np.array([1.0, 2.0, 3.0, 3.0, 2.0, 1.0])
>>> np.power(x1, x2)
array([ 0.,  1.,  8., 27., 16.,  5.])

The effect of broadcasting.

>>> x2 = np.array([[1, 2, 3, 3, 2, 1], [1, 2, 3, 3, 2, 1]])
>>> x2
array([[1., 2., 3., 3., 2., 1.],
       [1., 2., 3., 3., 2., 1.]])
>>> np.power(x1, x2)
array([[ 0.,  1.,  8., 27., 16.,  5.],
       [ 0.,  1.,  8., 27., 16.,  5.]])
mxnet.numpy.multiarray.prod(a, axis=None, dtype=None, out=None, keepdims=False)

Return the product of array elements over a given axis.

Parameters:
  • a (array_like) – Input data.

  • axis (None or int or tuple of ints, optional) – Axis or axes along which a product is performed. The default, axis=None, will calculate the product of all the elements in the input array. If axis is negative it counts from the last to the first axis. .. versionadded:: 1.7.0 If axis is a tuple of ints, a product is performed on all of the axes specified in the tuple instead of a single axis or all the axes as before.

  • dtype (dtype, optional) – The type of the returned array, as well as of the accumulator in which the elements are multiplied. The dtype of a is used by default unless a has an integer dtype of less precision than the default platform integer. In that case, if a is signed then the platform integer is used while if a is unsigned then an unsigned integer of the same precision as the platform integer is used.

  • out (ndarray, optional) – Alternative output array in which to place the result. It must have the same shape as the expected output, but the type of the output values will be cast if necessary.

  • keepdims (bool, optional) – If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. If the default value is passed, then keepdims will not be passed through to the prod method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised.

  • initial (scalar, optional) – The starting value for this product. See ~numpy.ufunc.reduce for details.

  • where (not supported)

Returns:

product_along_axis – An array shaped as a but with the specified axis removed. Returns a reference to out if specified.

Return type:

ndarray, see dtype parameter above.

Examples

By default, calculate the product of all elements: >>> np.prod([1.,2.]) 2.0 Even when the input array is two-dimensional: >>> np.prod([[1.,2.],[3.,4.]]) 24.0 But we can also specify the axis over which to multiply: >>> np.prod([[1.,2.],[3.,4.]], axis=1) array([ 2., 12.]) Or select specific elements to include: >>> np.prod([1., np.nan, 3.], where=[True, False, True]) 3.0 If the type of x is unsigned, then the output type is the unsigned platform integer: >>> x = np.array([1, 2, 3], dtype=np.uint8) >>> np.prod(x).dtype == np.uint True If x is of a signed integer type, then the output type is the default platform integer: >>> x = np.array([1, 2, 3], dtype=np.int8) >>> np.prod(x).dtype == int True You can also start the product with a value other than one: >>> np.prod([1, 2], initial=5) 10

mxnet.numpy.multiarray.promote_types(type1, type2)

Returns the data type with the smallest size and smallest scalar kind to which both type1 and type2 may be safely cast. The returned data type is always considered “canonical”, this mainly means that the promoted dtype will always be in native byte order.

This function is symmetric, but rarely associative.

Parameters:
  • type1 (dtype or dtype specifier) – First data type.

  • type2 (dtype or dtype specifier) – Second data type.

Returns:

out – The promoted data type.

Return type:

dtype

Notes

Please see numpy.result_type for additional information about promotion.

Added in version 1.6.0.

Starting in NumPy 1.9, promote_types function now returns a valid string length when given an integer or float dtype as one argument and a string dtype as another argument. Previously it always returned the input string dtype, even if it wasn’t long enough to store the max integer/float value converted to a string.

Changed in version 1.23.0.

NumPy now supports promotion for more structured dtypes. It will now remove unnecessary padding from a structure dtype and promote included fields individually.

See also

result_type, dtype, can_cast

Examples

>>> np.promote_types('f4', 'f8')
dtype('float64')
>>> np.promote_types('i8', 'f4')
dtype('float64')
>>> np.promote_types('>i8', '<c8')
dtype('complex128')
>>> np.promote_types('i4', 'S8')
dtype('S11')

An example of a non-associative case:

>>> p = np.promote_types
>>> p('S', p('i1', 'u1'))
dtype('S6')
>>> p(p('S', 'i1'), 'u1')
dtype('S4')
mxnet.numpy.multiarray.ptp(a, axis=None, out=None, keepdims=<no value>)

Range of values (maximum - minimum) along an axis.

The name of the function comes from the acronym for ‘peak to peak’.

Warning

ptp preserves the data type of the array. This means the return value for an input of signed integers with n bits (e.g. np.int8, np.int16, etc) is also a signed integer with n bits. In that case, peak-to-peak values greater than 2**(n-1)-1 will be returned as negative values. An example with a work-around is shown below.

Parameters:
  • a (array_like) – Input values.

  • axis (None or int or tuple of ints, optional) –

    Axis along which to find the peaks. By default, flatten the array. axis may be negative, in which case it counts from the last to the first axis.

    Added in version 1.15.0.

    If this is a tuple of ints, a reduction is performed on multiple axes, instead of a single axis or all the axes as before.

  • out (array_like) – Alternative output array in which to place the result. It must have the same shape and buffer length as the expected output, but the type of the output values will be cast if necessary.

  • keepdims (bool, optional) –

    If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

    If the default value is passed, then keepdims will not be passed through to the ptp method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised.

Returns:

ptp – The range of a given array - scalar if array is one-dimensional or a new array holding the result along the given axis

Return type:

ndarray or scalar

Examples

>>> x = np.array([[4, 9, 2, 10],
...               [6, 9, 7, 12]])
>>> np.ptp(x, axis=1)
array([8, 6])
>>> np.ptp(x, axis=0)
array([2, 0, 5, 2])
>>> np.ptp(x)
10

This example shows that a negative value can be returned when the input is an array of signed integers.

>>> y = np.array([[1, 127],
...               [0, 127],
...               [-1, 127],
...               [-2, 127]], dtype=np.int8)
>>> np.ptp(y, axis=1)
array([ 126,  127, -128, -127], dtype=int8)

A work-around is to use the view() method to view the result as unsigned integers with the same bit width:

>>> np.ptp(y, axis=1).view(np.uint8)
array([126, 127, 128, 129], dtype=uint8)
mxnet.numpy.multiarray.quantile(a, q, axis=None, out=None, overwrite_input=None, interpolation='linear', keepdims=False)

Compute the q-th quantile of the data along the specified axis. New in version 1.15.0.

Parameters:
  • a (ndarray) – Input array or object that can be converted to an array.

  • q (ndarray) – Quantile or sequence of quantiles to compute, which must be between 0 and 1 inclusive.

  • axis ({int, tuple of int, None}, optional) – Axis or axes along which the quantiles are computed. The default is to compute the quantile(s) along a flattened version of the array.

  • out (ndarray, optional) – Alternative output array in which to place the result. It must have the same shape and buffer length as the expected output, but the type (of the output) will be cast if necessary.

  • interpolation ({'linear', 'lower', 'higher', 'midpoint', 'nearest'}) –

    This optional parameter specifies the interpolation method to use when the desired quantile lies between two data points i < j:

    • linear: i + (j - i) * fraction, where fraction is the fractional part of the index surrounded by i and j.

    • lower: i.

    • higher: j.

    • nearest: i or j, whichever is nearest.

    • midpoint: (i + j) / 2.

  • keepdims (bool, optional) – If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original array a.

Returns:

quantile – If q is a single quantile and axis=None, then the result is a scalar. If multiple quantiles are given, first axis of the result corresponds to the quantiles. The other axes are the axes that remain after the reduction of a. If out is specified, that array is returned instead.

Return type:

ndarray

See also

mean

Given a vector V of length N, the q-th quantile of V is the value q of the way from the minimum to the maximum in a sorted copy of V. The values and distances of the two nearest neighbors as well as the interpolation parameter will determine the quantile if the normalized ranking does not match the location of q exactly. This function is the same as the median if q=0.5, the same as the minimum if q=0.0 and the same as the maximum if q=1.0. This function differs from the original numpy.quantile in the following aspects: * q must be ndarray type even if it is a scalar * do not support overwrite_input

Examples

>>> a = np.array([[10, 7, 4], [3, 2, 1]])
>>> a
array([[10., 7., 4.],
       [3., 2., 1.]])
>>> q = np.array(0.5)
>>> q
array(0.5)
>>> np.quantile(a, q)
array(3.5)
>>> np.quantile(a, q, axis=0)
array([6.5, 4.5, 2.5])
>>> np.quantile(a, q, axis=1)
array([7., 2.])
>>> np.quantile(a, q, axis=1, keepdims=True)
array([[7.],
       [2.]])
>>> m = np.quantile(a, q, axis=0)
>>> out = np.zeros_like(m)
>>> np.quantile(a, q, axis=0, out=out)
array([6.5, 4.5, 2.5])
>>> out
array([6.5, 4.5, 2.5])
mxnet.numpy.multiarray.rad2deg(x, out=None, **kwargs)

Convert angles from radians to degrees.

Parameters:
  • x (ndarray or scalar) – Angles in degrees.

  • out (ndarray or None, optional) – A location into which the result is stored. If not provided or None, a freshly-allocated array is returned.

Returns:

  • y (ndarray or scalar) – The corresponding angle in radians. This is a scalar if x is a scalar.

  • .. note:: – “rad2deg(x)” is “x * 180 / pi”.

    This function differs from the original numpy.arange in the following aspects:

    • Only support float32 and float64.

    • out must be in the same size of input.

Examples

>>> np.rad2deg(np.pi/2)
90.0
mxnet.numpy.multiarray.radians(x, out=None, **kwargs)

Convert angles from degrees to radians.

Parameters:
  • x (ndarray or scalar) – Input array in degrees.

  • out (ndarray or None) – A location into which the result is stored. If provided, it must have the same shape and type as the input. If not provided or None, a freshly-allocated array is returned.

Returns:

  • y (ndarray) – The corresponding radian values. This is a scalar if x is a scalar.

  • .. note:: – This function differs from the original numpy.radians in the following way(s):

    • only ndarray or scalar is accpted as valid input, tuple of ndarray is not supported

    • broadcasting to out of different shape is currently not supported

    • when input is plain python numerics, the result will not be stored in the out param

Examples

>>> deg = np.arange(12.) * 30.
>>> np.radians(deg)
array([0.       , 0.5235988, 1.0471976, 1.5707964, 2.0943952, 2.6179938,
       3.1415927, 3.6651914, 4.1887903, 4.712389 , 5.2359877, 5.7595863],
       dtype=float32)
mxnet.numpy.multiarray.ravel(x)

Return a contiguous flattened array. A 1-D array, containing the elements of the input, is returned. A copy is made only if needed.

Parameters:
  • x (ndarray) – Input array. The elements in x are read in row-major, C-style order and packed as a 1-D array.

  • order (C, optional) – Only support row-major, C-style order.

Returns:

  • y (ndarray) – y is an array of the same subtype as x, with shape (x.size,). Note that matrices are special cased for backward compatibility, if x is a matrix, then y is a 1-D ndarray.

  • .. note:: – This function differs from the original numpy.arange in the following aspects:

    • Only support row-major, C-style order.

Examples

It is equivalent to reshape(x, -1).

>>> x = np.array([[1, 2, 3], [4, 5, 6]])
>>> print(np.ravel(x))
[1. 2. 3. 4. 5. 6.]
>>> print(x.reshape(-1))
[1. 2. 3. 4. 5. 6.]
>>> print(np.ravel(x.T))
[1. 4. 2. 5. 3. 6.]
mxnet.numpy.multiarray.real(val)

Return the real part of the complex argument.

Parameters:

val (array_like) – Input array.

Returns:

out – The real component of the complex argument. If val is real, the type of val is used for the output. If val has complex elements, the returned type is float.

Return type:

ndarray or scalar

See also

real_if_close, imag, angle

Examples

>>> a = np.array([1+2j, 3+4j, 5+6j])
>>> a.real
array([1.,  3.,  5.])
>>> a.real = 9
>>> a
array([9.+2.j,  9.+4.j,  9.+6.j])
>>> a.real = np.array([9, 8, 7])
>>> a
array([9.+2.j,  8.+4.j,  7.+6.j])
>>> np.real(1 + 1j)
1.0
mxnet.numpy.multiarray.reciprocal(x, out=None, **kwargs)

Return the reciprocal of the argument, element-wise. Calculates 1/x.

Parameters:
  • x (ndarray or scalar) – The values whose reciprocals are required.

  • out (ndarray or None, optional) – A location into which the result is stored. If provided, it must have the same shape as the input. If not provided or None, a freshly-allocated array is returned.

Returns:

y – Output array is same shape and type as x. This is a scalar if x is a scalar.

Return type:

ndarray or scalar

Examples

>>> np.reciprocal(2.)
0.5
>>> x = np.array([1, 2., 3.33])
>>> np.reciprocal(x)
array([1.       , 0.5      , 0.3003003])

Note

This function is not designed to work with integers. For integer arguments with absolute value larger than 1 the result is always zero because of the way Python handles integer division. For integer zero the result is an overflow. The output ndarray has the same device as the input ndarray. This function differs from the original numpy.reciprocal in the following aspects:

  • Only support ndarray and scalar now.

  • where argument is not supported.

mxnet.numpy.multiarray.remainder(x1, x2, out=None, **kwargs)

Return element-wise remainder of division.

Parameters:
  • x1 (ndarray or scalar) – Dividend array.

  • x2 (ndarray or scalar) – Divisor array.

  • out (ndarray) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned.

Returns:

out – This is a scalar if both x1 and x2 are scalars.

Return type:

ndarray or scalar

Examples

>>> np.remainder(np.arange(7), 5)
array([0., 1., 2., 3., 4., 0., 1.])
mxnet.numpy.multiarray.repeat(a, repeats, axis=None)

Repeat elements of an array.

Parameters:
  • a (array_like) – Input array.

  • repeats (int) – The number of repetitions for each element.

  • axis (int, optional) – The axis along which to repeat values. By default, use the flattened input array, and return a flat output array.

Returns:

repeated_array – Output array which has the same shape as a, except along the given axis.

Return type:

ndarray

See also

tile

Tile an array.

Examples

>>> np.repeat(3, 4)
array([3, 3, 3, 3])
>>> x = np.array([[1,2],[3,4]])
>>> np.repeat(x, 2)
array([1, 1, 2, 2, 3, 3, 4, 4])
>>> np.repeat(x, 3, axis=1)
array([[1, 1, 1, 2, 2, 2],
       [3, 3, 3, 4, 4, 4]])
>>> np.repeat(x, [1, 2], axis=0)
array([[1, 2],
       [3, 4],
       [3, 4]])
mxnet.numpy.multiarray.reshape(a, newshape, order='C', out=None)

Gives a new shape to an array without changing its data. This function always returns a copy of the input array if out is not provided.

Parameters:
  • a (ndarray) – Array to be reshaped.

  • newshape (int or tuple of ints) – The new shape should be compatible with the original shape. If an integer, then the result will be a 1-D array of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions.

  • order ({'C'}, optional) – Read the elements of a using this index order, and place the elements into the reshaped array using this index order. ‘C’ means to read / write the elements using C-like index order, with the last axis index changing fastest, back to the first axis index changing slowest. Other order types such as ‘F’/’A’ may be added in the future.

Returns:

reshaped_array – It will be always a copy of the original array. This behavior is different from the official NumPy reshape operator where views of the original array may be generated.

Return type:

ndarray

See also

ndarray.reshape

Equivalent method.

Examples

>>> a = np.arange(6).reshape((3, 2))
>>> a
array([[0., 1.],
       [2., 3.],
       [4., 5.]])
>>> np.reshape(a, (2, 3)) # C-like index ordering
array([[0., 1., 2.],
       [3., 4., 5.]])
>>> np.reshape(np.ravel(a), (2, 3)) # equivalent to C ravel then C reshape
array([[0., 1., 2.],
       [3., 4., 5.]])
>>> a = np.array([[1,2,3], [4,5,6]])
>>> np.reshape(a, 6)
array([1., 2., 3., 4., 5., 6.])
>>> np.reshape(a, (3,-1))       # the unspecified value is inferred to be 2
array([[1., 2.],
       [3., 4.],
       [5., 6.]])
mxnet.numpy.multiarray.resize(a, new_shape)

Return a new array with the specified shape. If the new array is larger than the original array, then the new array is filled with repeated copies of a. Note that this behavior is different from a.resize(new_shape) which fills with zeros instead of repeated copies of a.

Parameters:
  • a (ndarray) – Array to be resized.

  • new_shape (int or tuple of int) – Shape of resized array.

Returns:

reshaped_array – The new array is formed from the data in the old array, repeated if necessary to fill out the required number of elements. The data are repeated in the order that they are stored in memory.

Return type:

ndarray

See also

ndarray.resize

resize an array in-place.

Notes

Warning: This functionality does not consider axes separately, i.e. it does not apply interpolation/extrapolation. It fills the return array with the required number of elements, taken from a as they are laid out in memory, disregarding strides and axes. (This is in case the new shape is smaller. For larger, see above.) This functionality is therefore not suitable to resize images, or data where each axis represents a separate and distinct entity.

Examples

>>> a = np.array([[0, 1], [2, 3]])
>>> np.resize(a, (2, 3))
array([[0., 1., 2.],
       [3., 0., 1.]])
>>> np.resize(a, (1, 4))
array([[0., 1., 2., 3.]])
>>> np.resize(a,(2, 4))
array([[0., 1., 2., 3.],
       [0., 1., 2., 3.]])
mxnet.numpy.multiarray.rint(x, out=None, **kwargs)

Round elements of the array to the nearest integer.

Parameters:
  • x (ndarray or scalar) – Input array.

  • out (ndarray or None) – A location into which the result is stored. If provided, it must have the same shape and type as the input. If not provided or None, a freshly-allocated array is returned.

Returns:

  • out (ndarray or scalar) – Output array is same shape and type as x. This is a scalar if x is a scalar.

  • .. note:: – This function differs from the original numpy.rint in the following way(s):

    • only ndarray or scalar is accpted as valid input, tuple of ndarray is not supported

    • broadcasting to out of different shape is currently not supported

    • when input is plain python numerics, the result will not be stored in the out param

Examples

>>> a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0])
>>> np.rint(a)
array([-2., -2., -0.,  0.,  1.,  2.,  2.])
mxnet.numpy.multiarray.roll(a, shift, axis=None)

Roll array elements along a given axis.

Elements that roll beyond the last position are re-introduced at the first.

Parameters:
  • a (ndarray) – Input array.

  • shift (int or tuple of ints) – The number of places by which elements are shifted. If a tuple, then axis must be a tuple of the same size, and each of the given axes is shifted by the corresponding number. If an int while axis is a tuple of ints, then the same value is used for all given axes.

  • axis (int or tuple of ints, optional) – Axis or axes along which elements are shifted. By default, the array is flattened before shifting, after which the original shape is restored.

Returns:

res – Output array, with the same shape as a.

Return type:

ndarray

Notes

Supports rolling over multiple dimensions simultaneously.

Examples

>>> x = np.arange(10)
>>> np.roll(x, 2)
array([8., 9., 0., 1., 2., 3., 4., 5., 6., 7.])
>>> np.roll(x, -2)
array([2., 3., 4., 5., 6., 7., 8., 9., 0., 1.])
>>> x2 = np.reshape(x, (2,5))
>>> x2
array([[0., 1., 2., 3., 4.],
       [5., 6., 7., 8., 9.]])
>>> np.roll(x2, 1)
array([[9., 0., 1., 2., 3.],
       [4., 5., 6., 7., 8.]])
>>> np.roll(x2, -1)
array([[1., 2., 3., 4., 5.],
       [6., 7., 8., 9., 0.]])
>>> np.roll(x2, 1, axis=0)
array([[5., 6., 7., 8., 9.],
       [0., 1., 2., 3., 4.]])
>>> np.roll(x2, -1, axis=0)
array([[5., 6., 7., 8., 9.],
       [0., 1., 2., 3., 4.]])
>>> np.roll(x2, 1, axis=1)
array([[4., 0., 1., 2., 3.],
       [9., 5., 6., 7., 8.]])
>>> np.roll(x2, -1, axis=1)
array([[1., 2., 3., 4., 0.],
       [6., 7., 8., 9., 5.]])
mxnet.numpy.multiarray.rollaxis(a, axis, start=0)

Roll the specified axis backwards, until it lies in a given position.

Parameters:
  • a (ndarray) – Input array.

  • axis (integer) – The axis to roll backwards. The positions of the other axes do not change relative to one another.

  • start (int, optional) – The axis is rolled until it lies before this position. The default, 0, results in a “complete” roll.

Returns:

  • res (ndarray) – A view after applying rollaxis to a is returned.

  • —–

Examples

>>> a = np.ones((3,4,5,6))
>>> np.rollaxis(a, 3, 1).shape
(3, 6, 4, 5)
>>> np.rollaxis(a, 2).shape
(5, 3, 4, 6)
>>> np.rollaxis(a, 1, 4).shape
(3, 5, 6, 4)
mxnet.numpy.multiarray.roots(p)

Return the roots of a polynomial with coefficients given in p.

Note

This forms part of the old polynomial API. Since version 1.4, the new polynomial API defined in numpy.polynomial is preferred. A summary of the differences can be found in the transition guide.

The values in the rank-1 array p are coefficients of a polynomial. If the length of p is n+1 then the polynomial is described by:

p[0] * x**n + p[1] * x**(n-1) + ... + p[n-1]*x + p[n]
Parameters:

p (array_like) – Rank-1 array of polynomial coefficients.

Returns:

out – An array containing the roots of the polynomial.

Return type:

ndarray

Raises:

ValueError – When p cannot be converted to a rank-1 array.

See also

poly

Find the coefficients of a polynomial with a given sequence of roots.

polyval

Compute polynomial values.

polyfit

Least squares polynomial fit.

poly1d

A one-dimensional polynomial class.

Notes

The algorithm relies on computing the eigenvalues of the companion matrix [1]_.

References

Examples

>>> coeff = [3.2, 2, 1]
>>> np.roots(coeff)
array([-0.3125+0.46351241j, -0.3125-0.46351241j])
mxnet.numpy.multiarray.rot90(m, k=1, axes=(0, 1))

Rotate an array by 90 degrees in the plane specified by axes. Rotation direction is from the first towards the second axis.

Parameters:
  • m (ndarray) – Array of two or more dimensions.

  • k (integer) – Number of times the array is rotated by 90 degrees.

  • axes ((2,) array_like) – The array is rotated in the plane defined by the axes. Axes must be different.

Returns:

y – A rotated view of m.

Return type:

ndarray

Notes

rot90(m, k=1, axes=(1,0)) is the reverse of rot90(m, k=1, axes=(0,1)) rot90(m, k=1, axes=(1,0)) is equivalent to rot90(m, k=-1, axes=(0,1))

Examples

>>> m = np.array([[1,2],[3,4]], 'int')
>>> m
array([[1, 2],
       [3, 4]], dtype=int64)
>>> np.rot90(m)
array([[2, 4],
       [1, 3]], dtype=int64)
>>> np.rot90(m, 2)
array([[4, 3],
       [2, 1]], dtype=int64)
>>> m = np.arange(8).reshape((2,2,2))
>>> np.rot90(m, 1, (1,2))
array([[[1., 3.],
        [0., 2.]],
[[5., 7.],

[4., 6.]]])

mxnet.numpy.multiarray.round(a, decimals=0, out=None)

Round an array to the given number of decimals.

See also

around

equivalent function; see for details.

mxnet.numpy.multiarray.round_(a, decimals=0, out=None)

Round an array to the given number of decimals.

See also

around

equivalent function; see for details.

mxnet.numpy.multiarray.row_stack(arrays)

Stack arrays in sequence vertically (row wise). This is equivalent to concatenation along the first axis after 1-D arrays of shape (N,) have been reshaped to (1,N). Rebuilds arrays divided by vsplit. This function makes most sense for arrays with up to 3 dimensions. For instance, for pixel-data with a height (first axis), width (second axis), and r/g/b channels (third axis). The functions concatenate and stack provide more general stacking and concatenation operations.

Parameters:

tup (sequence of ndarrays) – The arrays must have the same shape along all but the first axis. 1-D arrays must have the same length.

Returns:

stacked – The array formed by stacking the given arrays, will be at least 2-D.

Return type:

ndarray

Examples

>>> a = np.array([1, 2, 3])
>>> b = np.array([2, 3, 4])
>>> np.vstack((a, b))
array([[1., 2., 3.],
       [2., 3., 4.]])
>>> a = np.array([[1], [2], [3]])
>>> b = np.array([[2], [3], [4]])
>>> np.vstack((a, b))
array([[1.],
       [2.],
       [3.],
       [2.],
       [3.],
       [4.]])
mxnet.numpy.multiarray.searchsorted(a, v, side='left', sorter=None)

Find indices where elements should be inserted to maintain order.

Find the indices into a sorted array a such that, if the corresponding elements in v were inserted before the indices, the order of a would be preserved.

Assuming that a is sorted:

side

returned index i satisfies

left

a[i-1] < v <= a[i]

right

a[i-1] <= v < a[i]

Parameters:
  • a (1-D array_like) – Input array. If sorter is None, then it must be sorted in ascending order, otherwise sorter must be an array of indices that sort it.

  • v (array_like) – Values to insert into a.

  • side ({'left', 'right'}, optional) – If ‘left’, the index of the first suitable location found is given. If ‘right’, return the last such index. If there is no suitable index, return either 0 or N (where N is the length of a).

  • sorter (1-D array_like, optional) –

    Optional array of integer indices that sort array a into ascending order. They are typically the result of argsort.

    Added in version 1.7.0.

Returns:

indices – Array of insertion points with the same shape as v, or an integer if v is a scalar.

Return type:

int or array of ints

See also

sort

Return a sorted copy of an array.

histogram

Produce histogram from 1-D data.

Notes

Binary search is used to find the required insertion points.

As of NumPy 1.4.0 searchsorted works with real/complex arrays containing nan values. The enhanced sort order is documented in sort.

This function uses the same algorithm as the builtin python bisect.bisect_left (side='left') and bisect.bisect_right (side='right') functions, which is also vectorized in the v argument.

Examples

>>> np.searchsorted([1,2,3,4,5], 3)
2
>>> np.searchsorted([1,2,3,4,5], 3, side='right')
3
>>> np.searchsorted([1,2,3,4,5], [-10, 10, 2, 3])
array([0, 5, 1, 2])
mxnet.numpy.multiarray.select(condlist, choicelist, default=0)

Return an array drawn from elements in choicelist, depending on conditions.

Parameters:
  • condlist (list of bool ndarrays) – The list of conditions which determine from which array in choicelist the output elements are taken. When multiple conditions are satisfied, the first one encountered in condlist is used.

  • choicelist (list of ndarrays) – The list of arrays from which the output elements are taken. It has to be of the same length as condlist.

  • default (scalar, optional) – The element inserted in output when all conditions evaluate to False.

Returns:

output – The output at position m is the m-th element of the array in choicelist where the m-th element of the corresponding array in condlist is True.

Return type:

ndarray

See also

where

Return elements from one of two arrays depending on condition.

take, choose, compress, diag, diagonal

Examples

>>> x = np.arange(6)
>>> condlist = [x<3, x>3]
>>> choicelist = [x, x**2]
>>> np.select(condlist, choicelist, 42)
array([ 0,  1,  2, 42, 16, 25])
>>> condlist = [x<=4, x>3]
>>> choicelist = [x, x**2]
>>> np.select(condlist, choicelist, 55)
array([ 0,  1,  2,  3,  4, 25])
mxnet.numpy.multiarray.setdiff1d(ar1, ar2, assume_unique=False)

Find the set difference of two arrays.

Return the unique values in ar1 that are not in ar2.

Parameters:
  • ar1 (array_like) – Input array.

  • ar2 (array_like) – Input comparison array.

  • assume_unique (bool) – If True, the input arrays are both assumed to be unique, which can speed up the calculation. Default is False.

Returns:

setdiff1d – 1D array of values in ar1 that are not in ar2. The result is sorted when assume_unique=False, but otherwise only sorted if the input is sorted.

Return type:

ndarray

See also

numpy.lib.arraysetops

Module with a number of other functions for performing set operations on arrays.

Examples

>>> a = np.array([1, 2, 3, 2, 4, 1])
>>> b = np.array([3, 4, 5, 6])
>>> np.setdiff1d(a, b)
array([1, 2])
mxnet.numpy.multiarray.setxor1d(ar1, ar2, assume_unique=False)

Find the set exclusive-or of two arrays.

Return the sorted, unique values that are in only one (not both) of the input arrays.

Parameters:
  • ar1 (array_like) – Input arrays.

  • ar2 (array_like) – Input arrays.

  • assume_unique (bool) – If True, the input arrays are both assumed to be unique, which can speed up the calculation. Default is False.

Returns:

setxor1d – Sorted 1D array of unique values that are in only one of the input arrays.

Return type:

ndarray

Examples

>>> a = np.array([1, 2, 3, 2, 4])
>>> b = np.array([2, 3, 5, 7, 5])
>>> np.setxor1d(a,b)
array([1, 4, 5, 7])
mxnet.numpy.multiarray.shape(a)

Return the shape of an array.

Parameters:

a (array_like) – Input array.

Returns:

shape – The elements of the shape tuple give the lengths of the corresponding array dimensions.

Return type:

tuple of ints

See also

ndarray.shape

Equivalent array method.

Examples

>>> np.shape(np.eye(3))
(3, 3)
>>> np.shape([[1, 2]])
(1, 2)
>>> np.shape([0])
(1,)
>>> np.shape(0)
()
mxnet.numpy.multiarray.shares_memory(a, b, max_work=None)

Determine if two arrays share memory

Parameters:
Returns:

out

Return type:

bool

See also

may_share_memory

Examples

>>> np.may_share_memory(np.array([1,2]), np.array([5,8,9]))
False

Note

This function differs from the original numpy.shares_memory in the following way(s):

  • Does not support max_work, it is a dummy argument

  • Actually it is same as may_share_memory in MXNet np

mxnet.numpy.multiarray.sign(x, out=None, **kwargs)

Returns an element-wise indication of the sign of a number. The sign function returns -1 if x < 0, 0 if x==0, 1 if x > 0. Only supports real number.

Parameters:
  • x (ndarray or a scalar) – Input values.

  • out (ndarray or None, optional) – A location into which the result is stored. If provided, it must have the same shape and dtype as input ndarray. If not provided or None, a freshly-allocated array is returned.

Returns:

  • y (ndarray) – The sign of x. This is a scalar if x is a scalar.

  • .. note::

    • Only supports real number as input elements.

    • Input type does not support Python native iterables(list, tuple, …).

    • out param: cannot perform auto broadcasting. out ndarray’s shape must be the same as the expected output.

    • out param: cannot perform auto type cast. out ndarray’s dtype must be the same as the expected output.

    • out param does not support scalar input case.

Examples

>>> a = np.array([-5., 4.5])
>>> np.sign(a)
array([-1.,  1.])
Scalars as input:
>>> np.sign(4.0)
1.0
>>> np.sign(0)
0
Use ``out`` parameter:
>>> b = np.zeros((2, ))
>>> np.sign(a, out=b)
array([-1.,  1.])
>>> b
array([-1.,  1.])
mxnet.numpy.multiarray.signbit(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])

Returns element-wise True where signbit is set (less than zero).

Parameters:
  • x (array_like) – The input value(s).

  • out (ndarray, None, or tuple of ndarray and None, optional) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.

  • where (array_like, optional) – This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.

Returns:

result – Output array, or reference to out if that was supplied. This is a scalar if x is a scalar.

Return type:

ndarray of bool

Examples

>>> np.signbit(-1.2)
True
>>> np.signbit(np.array([1, -2.3, 2.1]))
array([False,  True, False])
mxnet.numpy.multiarray.sin(x, out=None, **kwargs)

Trigonometric sine, element-wise.

Parameters:
  • x (ndarray or scalar) – Angle, in radians (\(2 \pi\) rad equals 360 degrees).

  • out (ndarray or None) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. The dtype of the output is the same as that of the input if the input is an ndarray.

Returns:

y – The sine of each element of x. This is a scalar if x is a scalar.

Return type:

ndarray or scalar

Notes

This function only supports input type of float.

Examples

>>> np.sin(np.pi/2.)
1.0
>>> np.sin(np.array((0., 30., 45., 60., 90.)) * np.pi / 180.)
array([0.        , 0.5       , 0.70710677, 0.86602545, 1.        ])
mxnet.numpy.multiarray.sinh(x, out=None, **kwargs)

Hyperbolic sine, element-wise. Equivalent to 1/2 * (np.exp(x) - np.exp(-x)) or -1j * np.sin(1j*x).

Parameters:
  • x (ndarray or scalar) – Input array or scalar.

  • out (ndarray or None) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. The dtype of the output is the same as that of the input if the input is an ndarray.

Returns:

y – The corresponding hyperbolic sine values. This is a scalar if x is a scalar.

Return type:

ndarray or scalar

Notes

This function only supports input type of float.

Examples

>>> np.sinh(0)
0.0
>>> # Example of providing the optional output parameter
>>> out1 = np.array([0], dtype='f')
>>> out2 = np.sinh(np.array([0.1]), out1)
>>> out2 is out1
True
mxnet.numpy.multiarray.size(a, axis=None)

Return the number of elements along a given axis.

Parameters:
  • a (array_like) – Input data.

  • axis (int, optional) – Axis along which the elements are counted. By default, give the total number of elements.

Returns:

element_count – Number of elements along the specified axis.

Return type:

int

See also

shape

dimensions of array

ndarray.shape

dimensions of array

ndarray.size

number of elements in array

Examples

>>> a = np.array([[1,2,3],[4,5,6]])
>>> np.size(a)
6
>>> np.size(a,1)
3
>>> np.size(a,0)
2
mxnet.numpy.multiarray.sort(a, axis=-1, descending=False, stable=True)

Return a sorted copy of an array.

Notes

sort is a standard API in https://data-apis.org/array-api/latest/API_specification/generated/signatures.sorting_functions.sort.html instead of an official NumPy operator.

Parameters:
  • a (ndarray) – Array to sort.

  • axis (int or None, optional) – Axis along which to sort. The default is -1 (the last axis). If None, the flattened array is used.

  • descending (bool, optional) – sort order. If True, the returned indices sort x in descending order (by value). If False, the returned indices sort x in ascending order (by value).Default: False.

  • stable (bool, optional) – sort stability. If True, the returned indices must maintain the relative order of x values which compare as equal. If False, the returned indices may or may not maintain the relative order of x values which compare as equal. Default: True.

Returns:

sorted_array – Array of the same type and shape as a.

Return type:

ndarray

Notes

This operator does not support different sorting algorithms.

Examples

>>> a = np.array([[1,4],[3,1]])
>>> np.sort(a)                # sort along the last axis
array([[1, 4],
       [1, 3]])
>>> np.sort(a, axis=None)     # sort the flattened array
array([1, 1, 3, 4])
>>> np.sort(a, axis=0)        # sort along the first axis
array([[1, 1],
       [3, 4]])
mxnet.numpy.multiarray.spacing(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])

Return the distance between x and the nearest adjacent number.

Parameters:
  • x (array_like) – Values to find the spacing of.

  • out (ndarray, None, or tuple of ndarray and None, optional) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.

  • where (array_like, optional) – This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.

Returns:

out – The spacing of values of x. This is a scalar if x is a scalar.

Return type:

ndarray or scalar

Notes

It can be considered as a generalization of EPS: spacing(np.float64(1)) == np.finfo(np.float64).eps, and there should not be any representable number between x + spacing(x) and x for any finite x.

Spacing of +- inf and NaN is NaN.

Examples

>>> np.spacing(1) == np.finfo(np.float64).eps
True
mxnet.numpy.multiarray.split(ary, indices_or_sections, axis=0)

Split an array into multiple sub-arrays.

Parameters:
  • ary (ndarray) – Array to be divided into sub-arrays.

  • indices_or_sections (int or 1-D Python tuple, list or set.) –

    If indices_or_sections is an integer, N, the array will be divided into N equal arrays along axis. If such a split is not possible, an error is raised. If indices_or_sections is a 1-D array of sorted integers, the entries indicate where along axis the array is split. For example, [2, 3] would, for axis=0, result in

    • ary[:2]

    • ary[2:3]

    • ary[3:]

    If an index exceeds the dimension of the array along axis, an empty sub-array is returned correspondingly.

  • axis (int, optional) – The axis along which to split, default is 0.

Returns:

sub-arrays – A list of sub-arrays.

Return type:

list of ndarrays

Raises:

ValueError – If indices_or_sections is given as an integer, but a split does not result in equal division.

See also

hsplit

Split array into multiple sub-arrays horizontally (column-wise).

vsplit

Split array into multiple sub-arrays vertically (row wise).

dsplit

Split array into multiple sub-arrays along the 3rd axis (depth).

concatenate

Join a sequence of arrays along an existing axis.

stack

Join a sequence of arrays along a new axis.

hstack

Stack arrays in sequence horizontally (column wise).

vstack

Stack arrays in sequence vertically (row wise).

dstack

Stack arrays in sequence depth wise (along third dimension).

Examples

>>> x = np.arange(9.0)
>>> np.split(x, 3)
[array([0., 1., 2.]), array([3., 4., 5.]), array([6., 7., 8.])]
>>> np.split(x, [3, 5, 6, 8])
[array([0., 1., 2.]), array([3., 4.]), array([5.]), array([6., 7.]), array([])]
mxnet.numpy.multiarray.sqrt(x, out=None, **kwargs)

Return the non-negative square-root of an array, element-wise.

Parameters:
  • x (ndarray or scalar) – The values whose square-roots are required.

  • out (ndarray, or None, optional) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned.

Returns:

y – An array of the same shape as x, containing the positive square-root of each element in x. This is a scalar if x is a scalar.

Return type:

ndarray or scalar

Notes

This function only supports input type of float.

Examples

>>> np.sqrt(np.array([1,4,9]))
array([1., 2., 3.])
>>> np.sqrt(np.array([4, -1, _np.inf]))
array([ 2., nan, inf])
mxnet.numpy.multiarray.square(x, out=None, **kwargs)

Return the element-wise square of the input.

Parameters:
  • x (ndarray or scalar) – The values whose squares are required.

  • out (ndarray or None, optional) – A location into which the result is stored. If provided, it must have the same shape as the input. If not provided or None, a freshly-allocated array is returned.

Returns:

y – Output array is same shape and type as x. This is a scalar if x is a scalar.

Return type:

ndarray or scalar

Examples

>>> np.square(2.)
4.0
>>> x = np.array([1, 2., -1])
>>> np.square(x)
array([1., 4., 1.])

Note

The output ndarray has the same device as the input ndarray. This function differs from the original numpy.square in the following aspects:

  • Only support ndarray and scalar now.

  • where argument is not supported.

  • Complex input is not supported.

mxnet.numpy.multiarray.squeeze(a, axis=None, out=None)

Remove single-dimensional entries from the shape of an array.

Parameters:
  • a (array_like) – Input data.

  • axis (None or int or tuple of ints, optional) – Selects a subset of the single-dimensional entries in the shape. If an axis is selected with shape entry greater than one, an error is raised.

Returns:

squeezed – The input array, but with all or a subset of the dimensions of length 1 removed. This is always a itself or a view into a.

Return type:

ndarray

Raises:

ValueError – If axis is not None, and an axis being squeezed is not of length 1

See also

expand_dims

The inverse operation, adding singleton dimensions

reshape

Insert, remove, and combine dimensions, and resize existing ones

Examples

>>> x = np.array([[[0], [1], [2]]])
>>> x.shape
(1, 3, 1)
>>> np.squeeze(x).shape
(3,)
>>> np.squeeze(x, axis=0).shape
(3, 1)
>>> np.squeeze(x, axis=1).shape
Traceback (most recent call last):
...
ValueError: cannot select an axis to squeeze out which has size not equal to one
>>> np.squeeze(x, axis=2).shape
(1, 3)
mxnet.numpy.multiarray.stack(arrays, axis=0, out=None)
Join a sequence of arrays along a new axis.

The axis parameter specifies the index of the new axis in the dimensions of the result. For example, if axis=0 it will be the first dimension and if axis=-1 it will be the last dimension.

Parameters:
  • arrays (sequence of array_like) – Each array must have the same shape.

  • axis (int, optional) – The axis in the result array along which the input arrays are stacked.

  • out (ndarray, optional) – If provided, the destination to place the result. The shape must be correct, matching that of what stack would have returned if no out argument were specified.

Returns:

stacked – The stacked array has one more dimension than the input arrays.

Return type:

ndarray

See also

concatenate

Join a sequence of arrays along an existing axis.

split

Split array into a list of multiple sub-arrays of equal size.

Examples

>>> arrays = [np.random.rand(3, 4) for _ in range(10)]
>>> np.stack(arrays, axis=0).shape
(10, 3, 4)
>>> np.stack(arrays, axis=1).shape
(3, 10, 4)
>>> np.stack(arrays, axis=2).shape
(3, 4, 10)
>>> a = np.array([1, 2, 3])
>>> b = np.array([2, 3, 4])
>>> np.stack((a, b))
array([[1., 2., 3.],
       [2., 3., 4.]])
>>> np.stack((a, b), axis=-1)
array([[1., 2.],
       [2., 3.],
       [3., 4.]])
mxnet.numpy.multiarray.std(a, axis=None, dtype=None, out=None, correction=0, keepdims=False)

Compute the standard deviation along the specified axis. Returns the standard deviation, a measure of the spread of a distribution, of the array elements. The standard deviation is computed for the flattened array by default, otherwise over the specified axis.

Parameters:
  • a (array_like) – Calculate the standard deviation of these values.

  • axis (None or int or tuple of ints, optional) – Axis or axes along which the standard deviation is computed. The default is to compute the standard deviation of the flattened array. .. versionadded:: 1.7.0 If this is a tuple of ints, a standard deviation is performed over multiple axes, instead of a single axis or all the axes as before.

  • dtype (dtype, optional) – Type to use in computing the standard deviation. For arrays of integer type the default is float64, for arrays of float types it is the same as the array type.

  • out (ndarray, optional) – Alternative output array in which to place the result. It must have the same shape as the expected output but the type (of the calculated values) will be cast if necessary.

  • correction (int, optional) – Means Delta Degrees of Freedom. The divisor used in calculations is N - correction, where N represents the number of elements. By default correction is zero.

  • keepdims (bool, optional) – If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. If the default value is passed, then keepdims will not be passed through to the std method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised.

Returns:

standard_deviation – If out is None, return a new array containing the standard deviation, otherwise return a reference to the output array.

Return type:

ndarray, see dtype parameter above.

Examples

>>> a = np.array([[1, 2], [3, 4]])
>>> np.std(a)
1.1180339887498949 # may vary
>>> np.std(a, axis=0)
array([1.,  1.])
>>> np.std(a, axis=1)
array([0.5,  0.5])
In single precision, std() can be inaccurate:
>>> a = np.zeros((2, 512*512), dtype=np.float32)
>>> a[0, :] = 1.0
>>> a[1, :] = 0.1
>>> np.std(a)
array(0.45)
>>> np.std(a, dtype=np.float64)
array(0.45, dtype=float64)
mxnet.numpy.multiarray.subtract(x1, x2, out=None, **kwargs)

Subtract arguments element-wise.

Parameters:
  • x1 (ndarrays or scalar values) – The arrays to be subtracted from each other. If x1.shape != x2.shape, they must be broadcastable to a common shape (which may be the shape of one or the other).

  • x2 (ndarrays or scalar values) – The arrays to be subtracted from each other. If x1.shape != x2.shape, they must be broadcastable to a common shape (which may be the shape of one or the other).

  • out (ndarray) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned.

Returns:

  • subtract (ndarray or scalar) – The difference of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars.

  • .. note:: – This operator now supports automatic type promotion. The resulting type will be determined according to the following rules: * If both inputs are of floating number types, the output is the more precise type. * If only one of the inputs is floating number type, the result is that type. * If both inputs are of integer types (including boolean), not supported yet.

Examples

>>> np.subtract(1.0, 4.0)
-3.0
>>> x1 = np.arange(9.0).reshape((3, 3))
>>> x2 = np.arange(3.0)
>>> np.subtract(x1, x2)
array([[0., 0., 0.],
       [3., 3., 3.],
       [6., 6., 6.]])
mxnet.numpy.multiarray.sum(a, axis=None, dtype=None, out=None, keepdims=None, initial=None, where=None)

Sum of array elements over a given axis.

Parameters:
  • a (ndarray) – Input data.

  • axis (None or int, optional) – Axis or axes along which a sum is performed. The default, axis=None, will sum all of the elements of the input array. If axis is negative it counts from the last to the first axis.

  • dtype (dtype, optional) – The type of the returned array and of the accumulator in which the elements are summed. The default type is float32.

  • keepdims (bool, optional) –

    If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

    If the default value is passed, then keepdims will not be passed through to the sum method of sub-classes of ndarray, however any non-default value will be. If the sub-classes sum method does not implement keepdims any exceptions will be raised.

  • initial (Currently only supports None as input, optional) – Starting value for the sum. Currently not implemented. Please use None as input or skip this argument.

  • out (ndarray or None, optional) – Alternative output array in which to place the result. It must have the same shape and dtype as the expected output.

Returns:

sum_along_axis – An ndarray with the same shape as a, with the specified axis removed. If an output array is specified, a reference to out is returned.

Return type:

ndarray

Notes

  • Input type does not support Python native iterables.

  • “out” param: cannot perform auto type change. out ndarray’s dtype must be the same as the expected output.

  • “initial” param is not supported yet. Please use None as input.

  • Arithmetic is modular when using integer types, and no error is raised on overflow.

  • The sum of an empty array is the neutral element 0:

>>> a = np.empty(1)
>>> np.sum(a)
array(0.)

This function differs from the original numpy.sum in the following aspects:

  • Input type does not support Python native iterables(list, tuple, …).

  • “out” param: cannot perform auto type cast. out ndarray’s dtype must be the same as the expected output.

  • “initial” param is not supported yet. Please use None as input or skip it.

  • The default type is float32.

Examples

>>> a = np.array([0.5, 1.5])
>>> np.sum(a)
array(2.)
>>> a = np.array([0.5, 0.7, 0.2, 1.5])
>>> np.sum(a, dtype=np.int32)
array(2, dtype=int32)
>>> a = np.array([[0, 1], [0, 5]])
>>> np.sum(a)
array(6.)
>>> np.sum(a, axis=0)
array([0., 6.])
>>> np.sum(a, axis=1)
array([1., 5.])

With output ndarray:

>>> a = np.array([[0, 1], [0, 5]])
>>> b = np.ones((2,), dtype=np.float32)
>>> np.sum(a, axis = 0, out=b)
array([0., 6.])
>>> b
array([0., 6.])

If the accumulator is too small, overflow occurs:

>>> np.ones(128, dtype=np.int8).sum(dtype=np.int8)
array(-128, dtype=int8)
mxnet.numpy.multiarray.swapaxes(a, axis1, axis2)

Interchange two axes of an array.

Parameters:
  • a (ndarray) – Input array.

  • axis1 (int) – First axis.

  • axis2 (int) – Second axis.

Returns:

a_swapped – Swapped array. This is always a copy of the input array.

Return type:

ndarray

Examples

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

[6., 7.]]])

>>> np.swapaxes(x,0,2)
array([[[0., 4.],
        [2., 6.]],
[[1., 5.],

[3., 7.]]])

mxnet.numpy.multiarray.take(a, indices, axis=None, mode='raise', out=None)

Take elements from an array along an axis.

When axis is not None, this function does the same thing as “fancy” indexing (indexing arrays using arrays); however, it can be easier to use if you need elements along a given axis. A call such as np.take(arr, indices, axis=3) is equivalent to arr[:,:,:,indices,...].

Explained without fancy indexing, this is equivalent to the following use of ndindex, which sets each of ii, jj, and kk to a tuple of indices:

Ni, Nk = a.shape[:axis], a.shape[axis+1:]
Nj = indices.shape
for ii in ndindex(Ni):
    for jj in ndindex(Nj):
        for kk in ndindex(Nk):
            out[ii + jj + kk] = a[ii + (indices[jj],) + kk]
Parameters:
  • a (ndarray) – The source array.

  • indices (ndarray) – The indices of the values to extract. Also allow scalars for indices.

  • axis (int, optional) – The axis over which to select values. By default, the flattened input array is used.

  • out (ndarray, optional) – If provided, the result will be placed in this array. It should be of the appropriate shape and dtype.

  • mode ({'clip', 'wrap'}, optional) –

    Specifies how out-of-bounds indices will behave.

    • ’clip’ – clip to the range (default)

    • ’wrap’ – wrap around

    ’clip’ mode means that all indices that are too large are replaced by the index that addresses the last element along that axis. Note that this disables indexing with negative numbers.

Returns:

  • out (ndarray) – The returned array has the same type as a.

  • .. note:: – This function differs from the original numpy.take in the following way(s):

    • Only ndarray or scalar ndarray is accepted as valid input.

Examples

>>> a = np.array([4, 3, 5, 7, 6, 8])
>>> indices = np.array([0, 1, 4])
>>> np.take(a, indices)
array([4., 3., 6.])

In this example for a is an ndarray, “fancy” indexing can be used.

>>> a[indices]
array([4., 3., 6.])

If indices is not one dimensional, the output also has these dimensions.

>>> np.take(a, np.array([[0, 1], [2, 3]]))
array([[4., 3.],
       [5., 7.]])
mxnet.numpy.multiarray.take_along_axis(arr, indices, axis)

Take values from the input array by matching 1d index and data slices.

This iterates over matching 1d slices oriented along the specified axis in the index and data arrays, and uses the former to look up values in the latter. These slices can be different lengths.

Functions returning an index along an axis, like argsort and argpartition, produce suitable indices for this function.

Added in version 1.15.0.

Parameters:
  • arr (ndarray (Ni..., M, Nk...)) – Source array

  • indices (ndarray (Ni..., J, Nk...)) – Indices to take along each 1d slice of arr. This must match the dimension of arr, but dimensions Ni and Nj only need to broadcast against arr.

  • axis (int) – The axis to take 1d slices along. If axis is None, the input array is treated as if it had first been flattened to 1d, for consistency with sort and argsort.

Returns:

out – The indexed result.

Return type:

ndarray (Ni…, J, Nk…)

Notes

This is equivalent to (but faster than) the following use of ndindex and s_, which sets each of ii and kk to a tuple of indices:

Ni, M, Nk = a.shape[:axis], a.shape[axis], a.shape[axis+1:]
J = indices.shape[axis]  # Need not equal M
out = np.empty(Ni + (J,) + Nk)

for ii in ndindex(Ni):
    for kk in ndindex(Nk):
        a_1d       = a      [ii + s_[:,] + kk]
        indices_1d = indices[ii + s_[:,] + kk]
        out_1d     = out    [ii + s_[:,] + kk]
        for j in range(J):
            out_1d[j] = a_1d[indices_1d[j]]

Equivalently, eliminating the inner loop, the last two lines would be:

out_1d[:] = a_1d[indices_1d]

See also

take

Take along an axis, using the same indices for every 1d slice

put_along_axis

Put values into the destination array by matching 1d index and data slices

Examples

For this sample array

>>> a = np.array([[10, 30, 20], [60, 40, 50]])

We can sort either by using sort directly, or argsort and this function

>>> np.sort(a, axis=1)
array([[10, 20, 30],
       [40, 50, 60]])
>>> ai = np.argsort(a, axis=1)
>>> ai
array([[0, 2, 1],
       [1, 2, 0]])
>>> np.take_along_axis(a, ai, axis=1)
array([[10, 20, 30],
       [40, 50, 60]])

The same works for max and min, if you maintain the trivial dimension with keepdims:

>>> np.max(a, axis=1, keepdims=True)
array([[30],
       [60]])
>>> ai = np.argmax(a, axis=1, keepdims=True)
>>> ai
array([[1],
       [0]])
>>> np.take_along_axis(a, ai, axis=1)
array([[30],
       [60]])

If we want to get the max and min at the same time, we can stack the indices first

>>> ai_min = np.argmin(a, axis=1, keepdims=True)
>>> ai_max = np.argmax(a, axis=1, keepdims=True)
>>> ai = np.concatenate([ai_min, ai_max], axis=1)
>>> ai
array([[0, 1],
       [1, 0]])
>>> np.take_along_axis(a, ai, axis=1)
array([[10, 30],
       [40, 60]])
mxnet.numpy.multiarray.tan(x, out=None, **kwargs)

Compute tangent element-wise. Equivalent to np.sin(x)/np.cos(x) element-wise.

Parameters:
  • x (ndarray) – Input array.

  • out (ndarray or none, optional) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.

Returns:

  • y (ndarray)

  • The corresponding tangent values. This is a scalar if x is a scalar.

Examples

>>> np.tan(np.array([-np.pi, np.pi/2, np.pi]))
array([-8.7422777e-08, -2.2877332e+07,  8.7422777e-08])
mxnet.numpy.multiarray.tanh(x, out=None, **kwargs)

Compute hyperbolic tangent element-wise. Equivalent to np.sinh(x)/np.cosh(x).

Parameters:
  • x (ndarray or scalar.) – Input array.

  • out (ndarray or None) – A location into which the result is stored. If provided, it must have a shape that the inputs fill into. If not provided or None, a freshly-allocated array is returned. The dtype of the output and input must be the same.

Returns:

  • y (ndarray or scalar) – The corresponding hyperbolic tangent values.

  • .. note:: – If out is provided, the function writes the result into it, and returns a reference to out. (See Examples)

    • input x does not support complex computation (like imaginary number)

    >>> np.tanh(np.pi*1j)
    TypeError: type <type 'complex'> not supported
    

Examples

>>> np.tanh(np.array[0, np.pi]))
array([0.       , 0.9962721])
>>> np.tanh(np.pi)
0.99627207622075
>>> # Example of providing the optional output parameter illustrating
>>> # that what is returned is a reference to said parameter
>>> out1 = np.array(1)
>>> out2 = np.tanh(np.array(0.1), out1)
>>> out2 is out1
True
mxnet.numpy.multiarray.tensordot(a, b, axes=2)

Compute tensor dot product along specified axes for arrays >= 1-D. Given two tensors (arrays of dimension greater than or equal to one), a and b, and an ndarray object containing two ndarray objects, (a_axes, b_axes), sum the products of a’s and b’s elements (components) over the axes specified by a_axes and b_axes. The third argument can be a single non-negative integer_like scalar, N; if it is such, then the last N dimensions of a and the first N dimensions of b are summed over.

Parameters:
  • a (ndarray, len(shape) >= 1) – Tensors to “dot”.

  • b (ndarray, len(shape) >= 1) – Tensors to “dot”.

  • axes (int or (2,) ndarray) –

    • integer_like If an int N, sum over the last N axes of a and the first N axes of b in order. The sizes of the corresponding axes must match.

    • (2,) ndarray Or, a list of axes to be summed over, first sequence applying to a, second to b. Both elements ndarray must be of the same length.

See also

dot, einsum

Three common use cases are: * axes = 0 : tensor product \(a\otimes b\) * axes = 1 : tensor dot product \(a\cdot b\) * axes = 2 : (default) tensor double contraction \(a:b\) When axes is integer_like, the sequence for evaluation will be: first the -Nth axis in a and 0th axis in b, and the -1th axis in a and Nth axis in b last. When there is more than one axis to sum over - and they are not the last (first) axes of a (b) - the argument axes should consist of two sequences of the same length, with the first axis to sum over given first in both sequences, the second axis second, and so forth.

Examples

>>> a = np.arange(60.).reshape(3,4,5)
>>> b = np.arange(24.).reshape(4,3,2)
>>> c = np.tensordot(a,b, axes=([1,0],[0,1]))
>>> c.shape
(5, 2)
>>> c
array([[ 4400.,  4730.],
       [ 4532.,  4874.],
       [ 4664.,  5018.],
       [ 4796.,  5162.],
       [ 4928.,  5306.]])
mxnet.numpy.multiarray.tile(A, reps)

Construct an array by repeating A the number of times given by reps.

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. So a shape (3,) array is promoted to (1, 3) for 2-D replication, or shape (1, 1, 3) for 3-D replication. If this is not the desired behavior, promote A to d-dimensions manually before calling this function.

If A.ndim > d, reps is promoted to A.ndim by pre-pending 1’s to it. Thus for an A of shape (2, 3, 4, 5), a reps of (2, 2) is treated as (1, 1, 2, 2).

Parameters:
  • A (ndarray or scalar) – An input array or a scalar to repeat.

  • reps (a single integer or tuple of integers) – The number of repetitions of A along each axis.

Returns:

c – The tiled output array.

Return type:

ndarray

Examples

>>> a = np.array([0, 1, 2])
>>> np.tile(a, 2)
array([0., 1., 2., 0., 1., 2.])
>>> np.tile(a, (2, 2))
array([[0., 1., 2., 0., 1., 2.],
       [0., 1., 2., 0., 1., 2.]])
>>> np.tile(a, (2, 1, 2))
array([[[0., 1., 2., 0., 1., 2.]],
       [[0., 1., 2., 0., 1., 2.]]])
>>> b = np.array([[1, 2], [3, 4]])
>>> np.tile(b, 2)
array([[1., 2., 1., 2.],
       [3., 4., 3., 4.]])
>>> np.tile(b, (2, 1))
array([[1., 2.],
       [3., 4.],
       [1., 2.],
       [3., 4.]])
>>> c = np.array([1,2,3,4])
>>> np.tile(c,(4,1))
array([[1., 2., 3., 4.],
       [1., 2., 3., 4.],
       [1., 2., 3., 4.],
       [1., 2., 3., 4.]])

Scalar as input:

>>> np.tile(2, 3)
array([2, 2, 2]) # repeating integer `2`
mxnet.numpy.multiarray.trace(a, offset=0, axis1=0, axis2=1, out=None)

Return the sum along diagonals of the array. If a is 2-D, the sum along its diagonal with the given offset is returned, i.e., the sum of elements a[i,i+offset] for all i. If a has more than two dimensions, then the axes specified by axis1 and axis2 are used to determine the 2-D sub-arrays whose traces are returned. The shape of the resulting array is the same as that of a with axis1 and axis2 removed.

Parameters:
  • a (ndarray) – Input array, from which the diagonals are taken.

  • offset (int, optional) – Offset of the diagonal from the main diagonal. Can be both positive and negative. Defaults to 0.

  • axis1 (int, optional) – Axes to be used as the first and second axis of the 2-D sub-arrays from which the diagonals should be taken. Defaults are the first two axes of a.

  • axis2 (int, optional) – Axes to be used as the first and second axis of the 2-D sub-arrays from which the diagonals should be taken. Defaults are the first two axes of a.

  • out (ndarray, optional) – Array into which the output is placed. It must be of the right shape and right type to hold the output.

Returns:

sum_along_diagonals – If a is 2-D, the sum along the diagonal is returned. If a has larger dimensions, then an array of sums along diagonals is returned.

Return type:

ndarray

Examples

>>> a = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
>>> np.trace(a)
array(3.)
>>> a = np.arange(8).reshape((2, 2, 2))
>>> np.trace(a)
array([6., 8.])
>>> a = np.arange(24).reshape((2, 2, 2, 3))
>>> np.trace(a).shape
(2, 3)
mxnet.numpy.multiarray.transpose(a, axes=None)

Permute the dimensions of an array.

Parameters:
  • a (ndarray) – Input array.

  • axes (list of ints, optional) – By default, reverse the dimensions, otherwise permute the axes according to the values given.

Returns:

  • p (ndarray) – a with its axes permuted.

  • .. note:: – This function differs from the original numpy.transpose in the following way(s):

    • only ndarray is accepted as valid input, python iterables are not supported

    • the operator always returns an ndarray that does not share the memory with the input

Examples

>>> x = np.arange(4).reshape((2,2))
>>> x
array([[0., 1.],
       [2., 3.]])
>>> np.transpose(x)
array([[0., 2.],
       [1., 3.]])
>>> x = np.ones((1, 2, 3))
>>> np.transpose(x, (1, 0, 2)).shape
(2, 1, 3)
mxnet.numpy.multiarray.trapz(y, x=None, dx=1.0, axis=-1)

Integrate along the given axis using the composite trapezoidal rule.

If x is provided, the integration happens in sequence along its elements - they are not sorted.

Integrate y (x) along each 1d slice on the given axis, compute \(\int y(x) dx\). When x is specified, this integrates along the parametric curve, computing \(\int_t y(t) dt = \int_t y(t) \left.\frac{dx}{dt}\right|_{x=x(t)} dt\).

Parameters:
  • y (array_like) – Input array to integrate.

  • x (array_like, optional) – The sample points corresponding to the y values. If x is None, the sample points are assumed to be evenly spaced dx apart. The default is None.

  • dx (scalar, optional) – The spacing between sample points when x is None. The default is 1.

  • axis (int, optional) – The axis along which to integrate.

Returns:

trapz – Definite integral of y = n-dimensional array as approximated along a single axis by the trapezoidal rule. If y is a 1-dimensional array, then the result is a float. If n is greater than 1, then the result is an n-1 dimensional array.

Return type:

float or ndarray

See also

sum, cumsum

Notes

Image [2]_ illustrates trapezoidal rule – y-axis locations of points will be taken from y array, by default x-axis distances between points will be 1.0, alternatively they can be provided with x array or with dx scalar. Return value will be equal to combined area under the red lines.

References

Examples

Use the trapezoidal rule on evenly spaced points:

>>> np.trapz([1, 2, 3])
4.0

The spacing between sample points can be selected by either the x or dx arguments:

>>> np.trapz([1, 2, 3], x=[4, 6, 8])
8.0
>>> np.trapz([1, 2, 3], dx=2)
8.0

Using a decreasing x corresponds to integrating in reverse:

>>> np.trapz([1, 2, 3], x=[8, 6, 4])
-8.0

More generally x is used to integrate along a parametric curve. We can estimate the integral \(\int_0^1 x^2 = 1/3\) using:

>>> x = np.linspace(0, 1, num=50)
>>> y = x**2
>>> np.trapz(y, x)
0.33340274885464394

Or estimate the area of a circle, noting we repeat the sample which closes the curve:

>>> theta = np.linspace(0, 2 * np.pi, num=1000, endpoint=True)
>>> np.trapz(np.cos(theta), x=np.sin(theta))
3.141571941375841

np.trapz can be applied along a specified axis to do multiple computations in one call:

>>> a = np.arange(6).reshape(2, 3)
>>> a
array([[0, 1, 2],
       [3, 4, 5]])
>>> np.trapz(a, axis=0)
array([1.5, 2.5, 3.5])
>>> np.trapz(a, axis=1)
array([2.,  8.])
mxnet.numpy.multiarray.tri(N, M=None, k=0, dtype=None, device=None)

An array with ones at and below the given diagonal and zeros elsewhere.

Parameters:
  • N (int) – Number of rows in the array.

  • M (int, optional) – Number of columns in the array. By default, M is taken equal to N.

  • k (int, optional) – The sub-diagonal at and below which the array is filled. k = 0 is the main diagonal, while k < 0 is below it, and k > 0 is above. The default is 0.

  • dtype (dtype, optional) – Data type of the returned array. The default is float.

Returns:

tri – Array with its lower triangle filled with ones and zero elsewhere; in other words T[i,j] == 1 for i <= j + k, 0 otherwise.

Return type:

ndarray of shape (N, M)

Examples

>>> np.tri(3, 5, 2, dtype=int)
array([[1, 1, 1, 0, 0],
       [1, 1, 1, 1, 0],
       [1, 1, 1, 1, 1]])
>>> np.tri(3, 5, -1)
array([[0.,  0.,  0.,  0.,  0.],
       [1.,  0.,  0.,  0.,  0.],
       [1.,  1.,  0.,  0.,  0.]])
mxnet.numpy.multiarray.tril(m, k=0)

Lower triangle of an array.

Return a copy of an array with elements above the k-th diagonal zeroed.

Parameters:
  • m (ndarray, shape (M, N)) – Input array.

  • k (int, optional) – Diagonal above which to zero elements. k = 0 (the default) is the main diagonal, k < 0 is below it and k > 0 is above.

Returns:

tril – Lower triangle of m, of same shape and data-type as m.

Return type:

ndarray, shape (M, N)

See also

triu

same thing, only for the upper triangle

Examples

>>> a = np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]])
>>> np.tril(a, -1)
array([[ 0.,  0.,  0.],
       [ 4.,  0.,  0.],
       [ 7.,  8.,  0.],
       [10., 11., 12.]])
mxnet.numpy.multiarray.tril_indices(n, k=0, m=None)

Return the indices for the lower-triangle of an (n, m) array.

Parameters:
  • n (int) – The row dimension of the arrays for which the returned indices will be valid.

  • k (int, optional) – Diagonal offset (see tril for details).

  • m (int, optional) –

    Added in version 1.9.0.

    The column dimension of the arrays for which the returned arrays will be valid. By default m is taken equal to n.

Returns:

inds – The indices for the triangle. The returned tuple contains two arrays, each with the indices along one dimension of the array.

Return type:

tuple of arrays

See also

triu_indices

similar function, for upper-triangular.

mask_indices

generic function accepting an arbitrary mask function.

tril, triu

Examples

Compute two different sets of indices to access 4x4 arrays, one for the lower triangular part starting at the main diagonal, and one starting two diagonals further right:

>>> il1 = np.tril_indices(4)
>>> il2 = np.tril_indices(4, 2)

Here is how they can be used with a sample array:

>>> a = np.arange(16).reshape(4, 4)
>>> a
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])

Both for indexing:

>>> a[il1]
array([ 0,  4,  5,  8,  9, 10, 12, 13, 14, 15])

And for assigning values:

>>> a[il1] = -1
>>> a
array([[-1,  1,  2,  3],
       [-1, -1,  6,  7],
       [-1, -1, -1, 11],
       [-1, -1, -1, -1]])

These cover almost the whole array (two diagonals right of the main one):

>>> a[il2] = -10
>>> a
array([[-10, -10, -10,   3],
       [-10, -10, -10, -10],
       [-10, -10, -10, -10],
       [-10, -10, -10, -10]])
mxnet.numpy.multiarray.tril_indices_from(arr, k=0)

Return the indices for the lower-triangle of arr.

See tril_indices for full details.

Parameters:
  • arr (array_like) – The indices will be valid for square arrays whose dimensions are the same as arr.

  • k (int, optional) – Diagonal offset (see tril for details).

Examples

Create a 4 by 4 array.

>>> a = np.arange(16).reshape(4, 4)
>>> a
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])

Pass the array to get the indices of the lower triangular elements.

>>> trili = np.tril_indices_from(a)
>>> trili
(array([0, 1, 1, 2, 2, 2, 3, 3, 3, 3]), array([0, 0, 1, 0, 1, 2, 0, 1, 2, 3]))
>>> a[trili]
array([ 0,  4,  5,  8,  9, 10, 12, 13, 14, 15])

This is syntactic sugar for tril_indices().

>>> np.tril_indices(a.shape[0])
(array([0, 1, 1, 2, 2, 2, 3, 3, 3, 3]), array([0, 0, 1, 0, 1, 2, 0, 1, 2, 3]))

Use the k parameter to return the indices for the lower triangular array up to the k-th diagonal.

>>> trili1 = np.tril_indices_from(a, k=1)
>>> a[trili1]
array([ 0,  1,  4,  5,  6,  8,  9, 10, 11, 12, 13, 14, 15])

Notes

Added in version 1.4.0.

mxnet.numpy.multiarray.trim_zeros(filt, trim='fb')

Trim the leading and/or trailing zeros from a 1-D array or sequence.

Parameters:
  • filt (1-D array or sequence) – Input array.

  • trim (str, optional) – A string with ‘f’ representing trim from front and ‘b’ to trim from back. Default is ‘fb’, trim zeros from both front and back of the array.

Returns:

trimmed – The result of trimming the input. The input data type is preserved.

Return type:

1-D array or sequence

Examples

>>> a = np.array((0, 0, 0, 1, 2, 3, 0, 2, 1, 0))
>>> np.trim_zeros(a)
array([1, 2, 3, 0, 2, 1])
>>> np.trim_zeros(a, 'b')
array([0, 0, 0, ..., 0, 2, 1])

The input data type is preserved, list/tuple in means list/tuple out.

>>> np.trim_zeros([0, 1, 2, 0])
[1, 2]
mxnet.numpy.multiarray.triu(m, k=0)

Upper triangle of an array.

Return a copy of a matrix with the elements below the k-th diagonal zeroed.

Please refer to the documentation for tril for further details.

See also

tril

lower triangle of an array

Examples

>>> np.triu(np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]]), -1)
array([[ 1,  2,  3],
       [ 4,  5,  6],
       [ 0,  8,  9],
       [ 0,  0, 12]])
mxnet.numpy.multiarray.triu_indices(n, k=0, m=None, device=None)

Return the indices for the upper-triangle of an (n, m) array.

Parameters:
  • n (int) – The size of the arrays for which the returned indices will be valid.

  • k (int, optional) – Diagonal offset (see triu for details).

  • m (int, optional) –

    Added in version 1.9.0.

    The column dimension of the arrays for which the returned arrays will be valid. By default m is taken equal to n.

Returns:

inds – The indices for the triangle. The returned tuple contains two arrays, each with the indices along one dimension of the array. Can be used to slice a ndarray of shape(n, n).

Return type:

tuple, shape(2) of ndarrays, shape(n)

See also

tril_indices

similar function, for lower-triangular.

mask_indices

generic function accepting an arbitrary mask function.

triu, tril

Examples

Compute two different sets of indices to access 4x4 arrays, one for the upper triangular part starting at the main diagonal, and one starting two diagonals further right: >>> iu1 = np.triu_indices(4) >>> iu2 = np.triu_indices(4, 2) Here is how they can be used with a sample array: >>> a = np.arange(16).reshape(4, 4) >>> a array([[ 0, 1, 2, 3],

[ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]])

Both for indexing: >>> a[iu1] array([ 0, 1, 2, …, 10, 11, 15]) And for assigning values: >>> a[iu1] = -1 >>> a array([[-1, -1, -1, -1],

[ 4, -1, -1, -1], [ 8, 9, -1, -1], [12, 13, 14, -1]])

These cover only a small part of the whole array (two diagonals right of the main one): >>> a[iu2] = -10 >>> a array([[ -1, -1, -10, -10],

[ 4, -1, -1, -10], [ 8, 9, -1, -1], [ 12, 13, 14, -1]])

mxnet.numpy.multiarray.triu_indices_from(arr, k=0)

Return the indices for the upper-triangle of arr. See triu_indices for full details.

Parameters:
  • arr (ndarray, shape(N, N)) – The indices will be valid for square arrays.

  • k (int, optional) – Diagonal offset (see triu for details).

Returns:

triu_indices_from – Indices for the upper-triangle of arr.

Return type:

tuple, shape(2) of ndarray, shape(N)

See also

triu_indices, triu

mxnet.numpy.multiarray.true_divide(x1, x2, out=None)

Returns a true division of the inputs, element-wise.

Instead of the Python traditional ‘floor division’, this returns a true division. True division adjusts the output type to present the best answer, regardless of input types.

Parameters:
  • x1 (ndarray or scalar) – Dividend array.

  • x2 (ndarray or scalar) – Divisor array.

  • out (ndarray) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned.

Returns:

  • out (ndarray or scalar) – This is a scalar if both x1 and x2 are scalars.

  • .. note:: – This operator now supports automatic type promotion. The resulting type will be determined according to the following rules:

    • If both inputs are of floating number types, the output is the more precise type.

    • If only one of the inputs is floating number type, the result is that type.

    • If both inputs are of integer types (including boolean), the output is of float32 or float64 type, which depends on your current default dtype. When npx.is_np_default_dtype() returns False, default dtype is float32; When npx.is_np_default_dtype() returns True, default dtype is float64.

Examples

>>> x = np.arange(5)
>>> np.true_divide(x, 4)
array([0.  , 0.25, 0.5 , 0.75, 1.  ])
mxnet.numpy.multiarray.trunc(x, out=None, **kwargs)

Return the truncated value of the input, element-wise. The truncated value of the scalar x is the nearest integer i which is closer to zero than x is. In short, the fractional part of the signed number x is discarded.

Parameters:
  • x (ndarray or scalar) – Input data.

  • out (ndarray or None, optional) – A location into which the result is stored.

Returns:

  • y (ndarray or scalar) – The truncated value of each element in x. This is a scalar if x is a scalar.

  • .. note:: – This function differs from the original numpy.trunc in the following aspects:

    • Do not support where, a parameter in numpy which indicates where to calculate.

    • Cannot cast type automatically. Dtype of out must be same as the expected one.

    • Cannot broadcast automatically. Shape of out must be same as the expected one.

    • If x is plain python numeric, the result won’t be stored in out.

Examples

>>> a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0])
>>> np.trunc(a)
array([-1., -1., -0.,  0.,  1.,  1.,  2.])
mxnet.numpy.multiarray.union1d(ar1, ar2)

Find the union of two arrays.

Return the unique, sorted array of values that are in either of the two input arrays.

Parameters:
  • ar1 (array_like) – Input arrays. They are flattened if they are not already 1D.

  • ar2 (array_like) – Input arrays. They are flattened if they are not already 1D.

Returns:

union1d – Unique, sorted union of the input arrays.

Return type:

ndarray

See also

numpy.lib.arraysetops

Module with a number of other functions for performing set operations on arrays.

Examples

>>> np.union1d([-1, 0, 1], [-2, 0, 2])
array([-2, -1,  0,  1,  2])

To find the union of more than two arrays, use functools.reduce:

>>> from functools import reduce
>>> reduce(np.union1d, ([1, 3, 4, 3], [3, 1, 2, 1], [6, 3, 4, 2]))
array([1, 2, 3, 4, 6])
mxnet.numpy.multiarray.unique(ar, return_index=False, return_inverse=False, return_counts=False, axis=None)

Find the unique elements of an array.

Returns the sorted unique elements of an array. There are three optional outputs in addition to the unique elements:

  • the indices of the input array that give the unique values

  • the indices of the unique array that reconstruct the input array

  • the number of times each unique value comes up in the input array

Parameters:
  • ar (ndarray) – Input array. Unless axis is specified, this will be flattened if it is not already 1-D.

  • return_index (bool, optional) – If True, also return the indices of ar (along the specified axis, if provided, or in the flattened array) that result in the unique array.

  • return_inverse (bool, optional) – If True, also return the indices of the unique array (for the specified axis, if provided) that can be used to reconstruct ar.

  • return_counts (bool, optional) – If True, also return the number of times each unique item appears in ar.

  • axis (int or None, optional) – The axis to operate on. If None, ar will be flattened. If an integer, the subarrays indexed by the given axis will be flattened and treated as the elements of a 1-D array with the dimension of the given axis, see the notes for more details. The default is None.

Returns:

  • unique (ndarray) – The sorted unique values.

  • unique_indices (ndarray, optional) – The indices of the first occurrences of the unique values in the original array. Only provided if return_index is True.

  • unique_inverse (ndarray, optional) – The indices to reconstruct the original array from the unique array. Only provided if return_inverse is True.

  • unique_counts (ndarray, optional) – The number of times each of the unique values comes up in the original array. Only provided if return_counts is True.

  • .. note:: – When an axis is specified the subarrays indexed by the axis are sorted. This is done by making the specified axis the first dimension of the array and then flattening the subarrays in C order. The flattened subarrays are then viewed as a structured type with each element given a label, with the effect that we end up with a 1-D array of structured types that can be treated in the same way as any other 1-D array. The result is that the flattened subarrays are sorted in lexicographic order starting with the first element.

    This function differs from the original numpy.unique in the following aspects:

    • Only support ndarray as input.

    • Object arrays or structured arrays are not supported.

Examples

>>> np.unique(np.array([1, 1, 2, 2, 3, 3]))
array([1., 2., 3.])
>>> a = np.array([[1, 1], [2, 3]])
>>> np.unique(a)
array([1., 2., 3.])

Return the unique rows of a 2D array

>>> a = np.array([[1, 0, 0], [1, 0, 0], [2, 3, 4]])
>>> np.unique(a, axis=0)
array([[1., 0., 0.],
       [2., 3., 4.]])

Return the indices of the original array that give the unique values:

>>> a = np.array([1, 2, 6, 4, 2, 3, 2])
>>> u, indices = np.unique(a, return_index=True)
>>> u
array([1., 2., 3., 4., 6.])
>>> indices
array([0, 1, 5, 3, 2], dtype=int64)
>>> a[indices]
array([1., 2., 3., 4., 6.])

Reconstruct the input array from the unique values:

>>> a = np.array([1, 2, 6, 4, 2, 3, 2])
>>> u, indices = np.unique(a, return_inverse=True)
>>> u
array([1., 2., 3., 4., 6.])
>>> indices
array([0, 1, 4, 3, 1, 2, 1], dtype=int64)
>>> u[indices]
array([1., 2., 6., 4., 2., 3., 2.])
mxnet.numpy.multiarray.unpackbits(a, /, axis=None, count=None, bitorder='big')

Unpacks elements of a uint8 array into a binary-valued output array.

Each element of a represents a bit-field that should be unpacked into a binary-valued output array. The shape of the output array is either 1-D (if axis is None) or the same shape as the input array with unpacking done along the axis specified.

Parameters:
  • a (ndarray, uint8 type) – Input array.

  • axis (int, optional) – The dimension over which bit-unpacking is done. None implies unpacking the flattened array.

  • count (int or None, optional) –

    The number of elements to unpack along axis, provided as a way of undoing the effect of packing a size that is not a multiple of eight. A non-negative number means to only unpack count bits. A negative number means to trim off that many bits from the end. None means to unpack the entire array (the default). Counts larger than the available number of bits will add zero padding to the output. Negative counts must not exceed the available number of bits.

    Added in version 1.17.0.

  • bitorder ({'big', 'little'}, optional) –

    The order of the returned bits. ‘big’ will mimic bin(val), 3 = 0b00000011 => [0, 0, 0, 0, 0, 0, 1, 1], ‘little’ will reverse the order to [1, 1, 0, 0, 0, 0, 0, 0]. Defaults to ‘big’.

    Added in version 1.17.0.

Returns:

unpacked – The elements are binary-valued (0 or 1).

Return type:

ndarray, uint8 type

See also

packbits

Packs the elements of a binary-valued array into bits in a uint8 array.

Examples

>>> a = np.array([[2], [7], [23]], dtype=np.uint8)
>>> a
array([[ 2],
       [ 7],
       [23]], dtype=uint8)
>>> b = np.unpackbits(a, axis=1)
>>> b
array([[0, 0, 0, 0, 0, 0, 1, 0],
       [0, 0, 0, 0, 0, 1, 1, 1],
       [0, 0, 0, 1, 0, 1, 1, 1]], dtype=uint8)
>>> c = np.unpackbits(a, axis=1, count=-3)
>>> c
array([[0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 1, 0]], dtype=uint8)
>>> p = np.packbits(b, axis=0)
>>> np.unpackbits(p, axis=0)
array([[0, 0, 0, 0, 0, 0, 1, 0],
       [0, 0, 0, 0, 0, 1, 1, 1],
       [0, 0, 0, 1, 0, 1, 1, 1],
       [0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8)
>>> np.array_equal(b, np.unpackbits(p, axis=0, count=b.shape[0]))
True
mxnet.numpy.multiarray.unravel_index(indices, shape, order='C')

Converts a flat index or array of flat indices into a tuple of coordinate arrays.

Parameters:
  • indices (array_like) – An integer array whose elements are indices into the flattened version of an array of dimensions shape. Before version 1.6.0, this function accepted just one index value.

  • shape (tuple of ints) – The shape of the array to use for unraveling indices.

  • order (Only row-major is supported currently.)

Returns:

  • unraveled_coords (ndarray) – Each row in the ndarray has the same shape as the indices array. Each column in the ndarray represents the unravelled index

  • Examples

  • ————-

  • >>> np.unravel_index([22, 41, 37], (7,6))

  • [[3. 6. 6.] – [4. 5. 1.]]

  • >>> np.unravel_index(1621, (6,7,8,9))

  • [3, 1, 4, 1]

mxnet.numpy.multiarray.unwrap(p, discont=None, axis=-1, *, period=6.283185307179586)

Unwrap by taking the complement of large deltas with respect to the period.

This unwraps a signal p by changing elements which have an absolute difference from their predecessor of more than max(discont, period/2) to their period-complementary values.

For the default case where period is \(2\pi\) and discont is \(\pi\), this unwraps a radian phase p such that adjacent differences are never greater than \(\pi\) by adding \(2k\pi\) for some integer \(k\).

Parameters:
  • p (array_like) – Input array.

  • discont (float, optional) – Maximum discontinuity between values, default is period/2. Values below period/2 are treated as if they were period/2. To have an effect different from the default, discont should be larger than period/2.

  • axis (int, optional) – Axis along which unwrap will operate, default is the last axis.

  • period (float, optional) –

    Size of the range over which the input wraps. By default, it is 2 pi.

    Added in version 1.21.0.

Returns:

out – Output array.

Return type:

ndarray

See also

rad2deg, deg2rad

Notes

If the discontinuity in p is smaller than period/2, but larger than discont, no unwrapping is done because taking the complement would only make the discontinuity larger.

Examples

>>> phase = np.linspace(0, np.pi, num=5)
>>> phase[3:] += np.pi
>>> phase
array([ 0.        ,  0.78539816,  1.57079633,  5.49778714,  6.28318531]) # may vary
>>> np.unwrap(phase)
array([ 0.        ,  0.78539816,  1.57079633, -0.78539816,  0.        ]) # may vary
>>> np.unwrap([0, 1, 2, -1, 0], period=4)
array([0, 1, 2, 3, 4])
>>> np.unwrap([ 1, 2, 3, 4, 5, 6, 1, 2, 3], period=6)
array([1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> np.unwrap([2, 3, 4, 5, 2, 3, 4, 5], period=4)
array([2, 3, 4, 5, 6, 7, 8, 9])
>>> phase_deg = np.mod(np.linspace(0 ,720, 19), 360) - 180
>>> np.unwrap(phase_deg, period=360)
array([-180., -140., -100.,  -60.,  -20.,   20.,   60.,  100.,  140.,
        180.,  220.,  260.,  300.,  340.,  380.,  420.,  460.,  500.,
        540.])
mxnet.numpy.multiarray.vander(x, N=None, increasing=False)

Generate a Vandermonde matrix.

The columns of the output matrix are powers of the input vector. The order of the powers is determined by the increasing boolean argument. Specifically, when increasing is False, the i-th output column is the input vector raised element-wise to the power of N - i - 1. Such a matrix with a geometric progression in each row is named for Alexandre- Theophile Vandermonde.

Parameters:
  • x (array_like) – 1-D input array.

  • N (int, optional) – Number of columns in the output. If N is not specified, a square array is returned (N = len(x)).

  • increasing (bool, optional) –

    Order of the powers of the columns. If True, the powers increase from left to right, if False (the default) they are reversed.

    Added in version 1.9.0.

Returns:

out – Vandermonde matrix. If increasing is False, the first column is x^(N-1), the second x^(N-2) and so forth. If increasing is True, the columns are x^0, x^1, ..., x^(N-1).

Return type:

ndarray

See also

polynomial.polynomial.polyvander

Examples

>>> x = np.array([1, 2, 3, 5])
>>> N = 3
>>> np.vander(x, N)
array([[ 1,  1,  1],
       [ 4,  2,  1],
       [ 9,  3,  1],
       [25,  5,  1]])
>>> np.column_stack([x**(N-1-i) for i in range(N)])
array([[ 1,  1,  1],
       [ 4,  2,  1],
       [ 9,  3,  1],
       [25,  5,  1]])
>>> x = np.array([1, 2, 3, 5])
>>> np.vander(x)
array([[  1,   1,   1,   1],
       [  8,   4,   2,   1],
       [ 27,   9,   3,   1],
       [125,  25,   5,   1]])
>>> np.vander(x, increasing=True)
array([[  1,   1,   1,   1],
       [  1,   2,   4,   8],
       [  1,   3,   9,  27],
       [  1,   5,  25, 125]])

The determinant of a square Vandermonde matrix is the product of the differences between the values of the input vector:

>>> np.linalg.det(np.vander(x))
48.000000000000043 # may vary
>>> (5-3)*(5-2)*(5-1)*(3-2)*(3-1)*(2-1)
48
mxnet.numpy.multiarray.var(a, axis=None, dtype=None, out=None, correction=0, keepdims=False)

Compute the variance along the specified axis. Returns the variance of the array elements, a measure of the spread of a distribution. The variance is computed for the flattened array by default, otherwise over the specified axis.

Parameters:
  • a (array_like) – Array containing numbers whose variance is desired. If a is not an array, a conversion is attempted.

  • axis (None or int or tuple of ints, optional) – Axis or axes along which the variance is computed. The default is to compute the variance of the flattened array. .. versionadded:: 1.7.0 If this is a tuple of ints, a variance is performed over multiple axes, instead of a single axis or all the axes as before.

  • dtype (data-type, optional) – Type to use in computing the variance. For arrays of integer type, the default is of your current default dtype, When npx.is_np_default_dtype() returns False, default dtype is float32, When npx.is_np_default_dtype() returns True, default dtype is float64. For arrays of float types it is the same as the array type.

  • out (ndarray, optional) – Alternate output array in which to place the result. It must have the same shape as the expected output, but the type is cast if necessary.

  • correction (int, optional) – “Delta Degrees of Freedom”: the divisor used in the calculation is N - correction, where N represents the number of elements. By default correction is zero.

  • keepdims (bool, optional) – If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. If the default value is passed, then keepdims will not be passed through to the var method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised.

Returns:

variance – If out=None, returns a new array containing the variance; otherwise, a reference to the output array is returned.

Return type:

ndarray, see dtype parameter above

Examples

>>> a = np.array([[1, 2], [3, 4]])
>>> np.var(a)
array(1.25)
>>> np.var(a, axis=0)
array([1.,  1.])
>>> np.var(a, axis=1)
array([0.25,  0.25])
>>> a = np.zeros((2, 512*512), dtype=np.float32)
>>> a[0, :] = 1.0
>>> a[1, :] = 0.1
>>> np.var(a)
array(0.2025)
>>> np.var(a, dtype=np.float64)
array(0.2025, dtype=float64)
>>> ((1-0.55)**2 + (0.1-0.55)**2)/2
0.2025
mxnet.numpy.multiarray.vdot(a, b)

Return the dot product of two vectors. Note that vdot handles multidimensional arrays differently than dot: it does not perform a matrix product, but flattens input arguments to 1-D vectors first. Consequently, it should only be used for vectors.

Parameters:
  • a (ndarray) – First argument to the dot product.

  • b (ndarray) – Second argument to the dot product.

Returns:

output – Dot product of a and b.

Return type:

ndarray

See also

dot

Return the dot product without using the complex conjugate of the first argument.

Examples

Note that higher-dimensional arrays are flattened!

>>> a = np.array([[1, 4], [5, 6]])
>>> b = np.array([[4, 1], [2, 2]])
>>> np.vdot(a, b)
array(30.)
>>> np.vdot(b, a)
array(30.)
>>> 1*4 + 4*1 + 5*2 + 6*2
30
mxnet.numpy.multiarray.vsplit(ary, indices_or_sections)

Split an array into multiple sub-arrays vertically (row-wise).

vsplit is equivalent to split with axis=0 (default): the array is always split along the first axis regardless of the array dimension.

Parameters:
  • ary (ndarray) – Array to be divided into sub-arrays.

  • indices_or_sections (int or 1 - D Python tuple, list or set.) –

    If indices_or_sections is an integer, N, the array will be divided into N equal arrays along axis 0. If such a split is not possible, an error is raised.

    If indices_or_sections is a 1-D array of sorted integers, the entries indicate where along axis 0 the array is split. For example, [2, 3] would result in

    • ary[:2]

    • ary[2:3]

    • ary[3:]

    If an index exceeds the dimension of the array along axis 0, an error will be thrown.

Returns:

sub-arrays – A list of sub-arrays.

Return type:

list of ndarrays

See also

split

Split an array into multiple sub-arrays of equal size.

This function differs from the original numpy.vsplit in the following aspects: * Currently parameter indices_or_sections does not support ndarray, but supports scalar, tuple and list. * In indices_or_sections, if an index exceeds the dimension of the array along axis 0, an error will be thrown.

Examples

>>> x = np.arange(16.0).reshape(4, 4)
>>> x
array([[  0.,   1.,   2.,   3.],
       [  4.,   5.,   6.,   7.],
       [  8.,   9.,  10.,  11.],
       [ 12.,  13.,  14.,  15.]])
>>> np.vsplit(x, 2)
[array([[0., 1., 2., 3.],
        [4., 5., 6., 7.]]), array([[ 8.,  9., 10., 11.],
        [12., 13., 14., 15.]])]
>>> # With a higher dimensional array the split is still along the first axis.
>>> x = np.arange(8.0).reshape(2, 2, 2)
>>> x
array([[[ 0.,  1.],
        [ 2.,  3.]],
       [[ 4.,  5.],
        [ 6.,  7.]]])
>>> np.vsplit(x, 2)
[array([[[0., 1.],
        [2., 3.]]]), array([[[4., 5.],
        [6., 7.]]])]
mxnet.numpy.multiarray.vstack(arrays, out=None)

Stack arrays in sequence vertically (row wise).

This is equivalent to concatenation along the first axis after 1-D arrays of shape (N,) have been reshaped to (1,N). Rebuilds arrays divided by vsplit.

This function makes most sense for arrays with up to 3 dimensions. For instance, for pixel-data with a height (first axis), width (second axis), and r/g/b channels (third axis). The functions concatenate and stack provide more general stacking and concatenation operations.

Parameters:

tup (sequence of ndarrays) – The arrays must have the same shape along all but the first axis. 1-D arrays must have the same length.

Returns:

stacked – The array formed by stacking the given arrays, will be at least 2-D.

Return type:

ndarray

Examples

>>> a = np.array([1, 2, 3])
>>> b = np.array([2, 3, 4])
>>> np.vstack((a, b))
array([[1., 2., 3.],
       [2., 3., 4.]])
>>> a = np.array([[1], [2], [3]])
>>> b = np.array([[2], [3], [4]])
>>> np.vstack((a, b))
array([[1.],
       [2.],
       [3.],
       [2.],
       [3.],
       [4.]])
mxnet.numpy.multiarray.where(condition[, x, y])

Return elements chosen from x or y depending on condition.

Note

When only condition is provided, this function is a shorthand for np.asarray(condition).nonzero(). The rest of this documentation covers only the case where all three arguments are provided.

Parameters:
  • condition (ndarray) – Where True, yield x, otherwise yield y.

  • x (ndarray) – Values from which to choose. x, y and condition need to be broadcastable to some shape. x and y must have the same dtype.

  • y (ndarray) – Values from which to choose. x, y and condition need to be broadcastable to some shape. x and y must have the same dtype.

Returns:

out – An array with elements from x where condition is True, and elements from y elsewhere.

Return type:

ndarray

Notes

If all the arrays are 1-D, where is equivalent to:

[xv if c else yv
for c, xv, yv in zip(condition, x, y)]

Examples

>>> a = np.arange(10)
>>> a
array([0., 1., 2., 3., 4., 5., 6., 7., 8., 9.])
>>> np.where(a < 5, a, 10*a)
array([ 0.,  1.,  2.,  3.,  4., 50., 60., 70., 80., 90.])

This can be used on multidimensional arrays too:

>>> cond = np.array([[True, False], [True, True]])
>>> x = np.array([[1, 2], [3, 4]])
>>> y = np.array([[9, 8], [7, 6]])
>>> np.where(cond, x, y)
array([[1., 8.],
       [3., 4.]])

The shapes of x, y, and the condition are broadcast together:

>>> x, y = onp.ogrid[:3, :4]
>>> x = np.array(x)
>>> y = np.array(y)
>>> np.where(x < y, x, 10 + y)  # both x and 10+y are broadcast
array([[10,  0,  0,  0],
       [10, 11,  1,  1],
       [10, 11, 12,  2]], dtype=int64)
>>> a = np.array([[0, 1, 2],
...               [0, 2, 4],
...               [0, 3, 6]])
>>> np.where(a < 4, a, -1)  # -1 is broadcast
array([[ 0.,  1.,  2.],
       [ 0.,  2., -1.],
       [ 0.,  3., -1.]])
mxnet.numpy.multiarray.zeros(shape, dtype=None, order='C', device=None)

Return a new array of given shape and type, filled with zeros. This function currently only supports storing multi-dimensional data in row-major (C-style).

Parameters:
  • shape (int or tuple of int) – The shape of the empty array.

  • dtype (str or numpy.dtype, optional) – An optional value type, When npx.is_np_default_dtype() returns False, default dtype is float32, When npx.is_np_default_dtype() returns True, default dtype is float64. Note that this behavior is different from NumPy’s zeros function where float64 is the default value, here we can set ‘float32’ or ‘float64’ as your default dtype, because float32 is considered as the default data type in deep learning.

  • order ({'C'}, optional, default: 'C') – How to store multi-dimensional data in memory, currently only row-major (C-style) is supported.

  • device (Device, optional) – Device context on which the memory is allocated. Default is mxnet.device.current_device().

Returns:

out – Array of zeros with the given shape, dtype, and device.

Return type:

ndarray

Examples

>>> np.zeros(5)
array([0., 0., 0., 0., 0.])
>>> np.zeros((5,), dtype=int)
array([0, 0, 0, 0, 0], dtype=int64)
>>> np.zeros((2, 1))
array([[0.],
       [0.]])
mxnet.numpy.multiarray.zeros_like(a, dtype=None, order='C', device=None, out=None)

Return an array of zeros with the same shape and type as a given array.

Parameters:
  • a (ndarray) – The shape and data-type of a define these same attributes of the returned array.

  • dtype (data-type, optional) – Overrides the data type of the result. Temporarily do not support boolean type.

  • order ({'C'}, optional) – Whether to store multidimensional data in C- or Fortran-contiguous (row- or column-wise) order in memory. Currently only supports C order.

  • device (Device, optional) – Device context on which the memory is allocated. Default is mxnet.device.current_device().

  • out (ndarray or None, optional) – A location into which the result is stored. If provided, it must have the same shape and dtype as input ndarray. If not provided or None, a freshly-allocated array is returned.

Returns:

out – Array of zeros with the same shape and type as a.

Return type:

ndarray

See also

empty_like

Return an empty array with shape and type of input.

ones_like

Return an array of ones with shape and type of input.

zeros_like

Return an array of zeros with shape and type of input.

full

Return a new array of given shape filled with value.

Examples

>>> x = np.arange(6)
>>> x = x.reshape((2, 3))
>>> x
array([[0., 1., 2.],
       [3., 4., 5.]])
>>> np.zeros_like(x)
array([[0., 0., 0.],
       [0., 0., 0.]])
>>> np.zeros_like(x, int)
array([[0, 0, 0],
       [0, 0, 0]], dtype=int64)
>>> y = np.arange(3, dtype=float)
>>> y
array([0., 1., 2.], dtype=float64)
>>> np.zeros_like(y)
array([0., 0., 0.], dtype=float64)