| # pylint: disable=C0302 |
| # Licensed to the Apache Software Foundation (ASF) under one |
| # or more contributor license agreements. See the NOTICE file |
| # distributed with this work for additional information |
| # regarding copyright ownership. The ASF licenses this file |
| # to you under the Apache License, Version 2.0 (the |
| # "License"); you may not use this file except in compliance |
| # with the License. You may obtain a copy of the License at |
| # |
| # http://www.apache.org/licenses/LICENSE-2.0 |
| # |
| # Unless required by applicable law or agreed to in writing, |
| # software distributed under the License is distributed on an |
| # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| # KIND, either express or implied. See the License for the |
| # specific language governing permissions and limitations |
| # under the License. |
| |
| # pylint: disable=unused-argument |
| """Namespace for numpy operators used in Gluon dispatched by F=ndarray.""" |
| |
| import numpy as _np |
| from ...base import numeric_types, integer_types |
| from ...util import _sanity_check_params, set_module |
| from ...util import wrap_np_unary_func, wrap_np_binary_func |
| from ...util import is_np_default_dtype, dtype_from_number |
| from ...device import current_device |
| from . import _internal as _npi |
| from . import _api_internal |
| from ..ndarray import NDArray, get_dtype_name |
| |
| |
| __all__ = ['shape', 'zeros', 'zeros_like', 'ones', 'ones_like', 'full', 'full_like', 'empty_like', 'invert', 'delete', |
| 'add', 'broadcast_to', 'subtract', 'multiply', 'divide', 'mod', 'remainder', 'fmod', |
| 'power', 'bitwise_not', 'trace', 'transpose', 'copy', 'moveaxis', 'reshape', 'dot', |
| 'arctan2', 'sin', 'cos', 'tan', 'sinh', 'cosh', 'tanh', 'log10', 'sqrt', 'cbrt', 'abs', 'insert', 'fabs', |
| 'absolute', 'exp', 'expm1', 'arcsin', 'arccos', 'arctan', 'sign', 'log', 'degrees', 'log2', 'matmul', |
| 'log1p', 'rint', 'radians', 'reciprocal', 'square', 'negative', 'fix', 'ceil', 'floor', 'histogram', |
| 'trunc', 'logical_not', 'arcsinh', 'arccosh', 'arctanh', 'argsort', 'all', 'any', 'sort', |
| 'tensordot', 'eye', 'linspace', 'median', 'tril_indices', 'triu_indices_from', 'triu_indices', |
| 'logspace', 'expand_dims', 'tile', 'arange', 'array_split', 'split', 'hsplit', 'vsplit', 'dsplit', |
| 'concatenate', 'append', 'stack', 'vstack', 'row_stack', 'column_stack', 'hstack', 'dstack', |
| 'average', 'mean', 'maximum', 'fmax', 'minimum', 'fmin', 'around', 'round', 'round_', 'flatnonzero', |
| 'max', 'min', 'amax', 'amin', 'logical_and', 'logical_or', 'logical_xor', |
| 'swapaxes', 'clip', 'argmax', 'argmin', 'std', 'var', 'indices', 'copysign', 'ravel', 'unravel_index', |
| 'diag_indices_from', 'hanning', 'hamming', 'blackman', 'flip', 'flipud', 'fliplr', |
| 'hypot', 'bitwise_and', 'bitwise_xor', 'bitwise_or', 'rad2deg', 'deg2rad', 'unique', 'lcm', 'gcd', |
| 'tril', 'triu', 'tri', 'identity', 'take', 'ldexp', 'vdot', 'inner', 'outer', 'cross', 'kron', |
| 'equal', 'not_equal', 'greater', 'less', 'greater_equal', 'less_equal', 'roll', 'rot90', 'einsum', |
| 'true_divide', 'nonzero', 'quantile', 'percentile', 'shares_memory', 'may_share_memory', 'interp', |
| 'diff', 'ediff1d', 'resize', 'polyval', 'nan_to_num', 'isnan', 'isinf', 'isposinf', 'isneginf', 'isfinite', |
| 'atleast_1d', 'atleast_2d', 'atleast_3d', 'fill_diagonal', 'squeeze', |
| 'where', 'bincount', 'rollaxis', 'diagflat', 'repeat', 'prod', 'pad', 'cumsum', 'sum', 'diag', 'diagonal', |
| 'positive', 'logaddexp', 'floor_divide', 'bitwise_left_shift', 'bitwise_right_shift'] |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| def shape(a): |
| """ |
| Return the shape of an array. |
| |
| Parameters |
| ---------- |
| a : array_like |
| Input array. |
| |
| Returns |
| ------- |
| shape : tuple of ints |
| The elements of the shape tuple give the lengths of the |
| corresponding array dimensions. |
| |
| 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) |
| () |
| """ |
| return a.shape |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| def zeros(shape, dtype=None, order='C', device=None): # pylint: disable=redefined-outer-name |
| """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 : ndarray |
| Array of zeros with the given shape, dtype, and device. |
| """ |
| if order != 'C': |
| raise NotImplementedError |
| # If the following code (4 lines) regarding device is removed |
| # np.zeros((3, 4)) can be as fast as 4.96 us |
| if device is None: |
| device = str(current_device()) |
| else: |
| device = str(device) |
| if dtype is not None and not isinstance(dtype, str): |
| dtype = get_dtype_name(dtype) |
| return _api_internal.zeros(shape, dtype, device) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| def ones(shape, dtype=None, order='C', device=None): # pylint: disable=redefined-outer-name |
| """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. |
| - 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 : ndarray |
| Array of ones with the given shape, dtype, and device. |
| """ |
| if order != 'C': |
| raise NotImplementedError |
| if device is None: |
| device = str(current_device()) |
| else: |
| device = str(device) |
| if dtype is not None and not isinstance(dtype, str): |
| dtype = get_dtype_name(dtype) |
| return _api_internal.ones(shape, dtype, device) |
| |
| |
| # pylint: disable=too-many-arguments, redefined-outer-name |
| @set_module('mxnet.ndarray.numpy') |
| def 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 : ndarray |
| Array of zeros with the same shape and type as a. |
| |
| 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) |
| """ |
| if order != 'C': |
| raise NotImplementedError |
| return full_like(a, 0, dtype=dtype, order=order, device=device, out=out) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| def 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 : ndarray |
| Array of ones with the same shape and type as a. |
| |
| 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) |
| """ |
| return full_like(a, 1, dtype=dtype, order=order, device=device, out=out) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| def 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 : array |
| 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. |
| |
| Raises |
| ------ |
| MXNetError |
| If the array is not compatible with the new shape according to NumPy's |
| broadcasting rules. |
| """ |
| if _np.isscalar(array): |
| return full(shape, array) |
| return _api_internal.broadcast_to(array, shape) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| def full(shape, fill_value, dtype=None, order='C', device=None, out=None): # pylint: disable=too-many-arguments |
| """ |
| 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`. |
| |
| Notes |
| ----- |
| This function differs from the original `numpy.full |
| https://docs.scipy.org/doc/numpy/reference/generated/numpy.full.html`_ in |
| the following way(s): |
| - Have an additional `device` argument to specify the device |
| - Have 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) |
| |
| """ |
| if order != 'C': |
| raise NotImplementedError |
| if isinstance(fill_value, NDArray): |
| if dtype is None: |
| ret = broadcast_to(fill_value, shape) |
| else: |
| ret = broadcast_to(fill_value, shape).astype(dtype) |
| return ret |
| if device is None: |
| device = str(current_device()) |
| else: |
| device = str(device) |
| if isinstance(fill_value, bool): |
| fill_value = int(fill_value) |
| dtype = _np.bool if dtype is None else dtype |
| elif isinstance(fill_value, numeric_types): |
| if dtype is None or dtype is float: |
| dtype = dtype_from_number(fill_value) |
| if dtype is not None and not isinstance(dtype, str): |
| dtype = get_dtype_name(dtype) |
| return _api_internal.full(shape, dtype, fill_value, device, out) |
| # pylint: enable=too-many-arguments, redefined-outer-name |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| def full_like(a, fill_value, dtype=None, order='C', device=None, out=None): # pylint: disable=too-many-arguments |
| """ |
| 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 : ndarray |
| Array of `fill_value` with the same shape and type as `a`. |
| |
| 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.double) |
| 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]) |
| """ |
| if order != 'C': |
| raise NotImplementedError |
| if isinstance(fill_value, bool): |
| fill_value = int(fill_value) |
| if device is None: |
| device = str(current_device()) |
| else: |
| device = str(device) |
| if dtype is not None and not isinstance(dtype, str): |
| dtype = get_dtype_name(dtype) |
| return _api_internal.full_like(a, fill_value, dtype, device, out) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| def empty_like(prototype, dtype=None, order='C', subok=False, shape=None): # pylint: disable=W0621 |
| """ |
| 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. |
| 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 : ndarray |
| Array of uninitialized (arbitrary) data with the same |
| shape and type as `prototype`. |
| |
| 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]]) |
| """ |
| dtype_list = {_np.float16: 'float16', _np.float32: 'float32', _np.float64: 'float64', |
| float: 'float64', _np.int8: 'int8', _np.int16: 'int16', _np.int32: 'int32', |
| _np.int64: 'int64', int:'int64', _np.uint8: 'uint8', _np.uint16: 'uint16', |
| _np.uint32: 'uint32', _np.uint64: 'uint64', _np.bool: 'bool', |
| _np.bool_: 'bool_', bool: 'bool', None: 'None'} |
| if order != 'C': |
| raise NotImplementedError("Only support C-order at this moment") |
| if subok: |
| raise NotImplementedError("Creating array by using sub-class is not supported at this moment") |
| if shape is not None: |
| raise NotImplementedError("Assigning new shape is not supported at this moment") |
| try: |
| dtype = dtype if isinstance(dtype, str) else dtype_list[dtype] |
| except: |
| raise NotImplementedError("Do not support this dtype at this moment") |
| return _npi.empty_like_fallback(prototype, dtype=dtype, order=order, subok=subok, shape=shape) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| def 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. |
| - When npx.is_np_default_dtype() returns False, default dtype is float32; |
| - When npx.is_np_default_dtype() returns True, default dtype is float64. |
| |
| Returns |
| ------- |
| arange : ndarray |
| 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`. |
| """ |
| if dtype is not None and not isinstance(dtype, str): |
| dtype = get_dtype_name(dtype) |
| if device is None: |
| device = str(current_device()) |
| else: |
| device = str(device) |
| if stop is None: |
| stop = start |
| start = 0 |
| if step is None: |
| step = 1 |
| if start is None and stop is None: |
| raise ValueError('start and stop cannot be both None') |
| if step == 0: |
| raise ZeroDivisionError('step cannot be 0') |
| return _api_internal.arange(start, stop, step, dtype, device) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| def 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 |
| ------- |
| out : ndarray |
| `n` x `n` array with its main diagonal set to one, |
| and all other elements 0. |
| |
| Examples |
| -------- |
| >>> np.identity(3) |
| array([[1., 0., 0.], |
| [0., 1., 0.], |
| [0., 0., 1.]]) |
| """ |
| if not isinstance(n, int): |
| raise TypeError("Input 'n' should be an integer") |
| if n < 0: |
| raise ValueError("Input 'n' cannot be negative") |
| if device is None: |
| device = str(current_device()) |
| else: |
| device = str(device) |
| shape = (n, n) # pylint: disable=redefined-outer-name |
| if dtype is not None and not isinstance(dtype, str): |
| dtype = get_dtype_name(dtype) |
| return _api_internal.identity(shape, dtype, device) |
| |
| |
| # pylint: disable=redefined-outer-name |
| @set_module('mxnet.ndarray.numpy') |
| def take(a, indices, axis=None, mode='raise', out=None): |
| r""" |
| 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`. |
| |
| Notes |
| ----- |
| |
| This function differs from the original `numpy.take |
| <https://docs.scipy.org/doc/numpy/reference/generated/numpy.take.html>`_ 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.]]) |
| """ |
| if mode not in ('wrap', 'clip', 'raise'): |
| raise NotImplementedError( |
| "function take does not support mode '{}'".format(mode)) |
| if axis is None: |
| return _api_internal.take(reshape(a, -1), indices, 0, mode, out) |
| else: |
| return _api_internal.take(a, indices, axis, mode, out) |
| # pylint: enable=redefined-outer-name |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| def 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. |
| |
| Notes |
| ----- |
| - 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.]]) |
| """ |
| if isinstance(values, numeric_types): |
| if isinstance(obj, slice): |
| start = obj.start |
| stop = obj.stop |
| step = 1 if obj.step is None else obj.step |
| return _api_internal.insert_slice(arr, values, start, stop, step, axis) |
| elif isinstance(obj, integer_types): |
| return _api_internal.insert_scalar(arr, values, obj, axis) |
| elif isinstance(obj, NDArray): |
| return _api_internal.insert_tensor(arr, obj, values, axis) |
| |
| if not isinstance(arr, NDArray): |
| raise TypeError("'arr' can not support type {}".format(str(type(arr)))) |
| if not isinstance(values, NDArray): |
| raise TypeError("'values' can not support type {}".format(str(type(values)))) |
| if isinstance(obj, slice): |
| start = obj.start |
| stop = obj.stop |
| step = 1 if obj.step is None else obj.step |
| return _api_internal.insert_slice(arr, values, start, stop, step, axis) |
| elif isinstance(obj, integer_types): |
| return _api_internal.insert_scalar(arr, values, obj, axis) |
| elif isinstance(obj, NDArray): |
| return _api_internal.insert_tensor(arr, values, obj, axis) |
| else: |
| raise TypeError("'obj' can not support type {}".format(str(type(obj)))) |
| |
| |
| #pylint: disable= too-many-arguments, no-member, protected-access |
| def _ufunc_helper(lhs, rhs, fn_array, fn_scalar, lfn_scalar, rfn_scalar=None, out=None): |
| """ Helper function for element-wise operation. |
| The function will perform numpy-like broadcasting if needed and call different functions. |
| |
| Parameters |
| -------- |
| lhs : ndarray or numeric value |
| Left-hand side operand. |
| |
| rhs : ndarray or numeric value |
| Right-hand operand, |
| |
| fn_array : function |
| Function to be called if both lhs and rhs are of ``ndarray`` type. |
| |
| fn_scalar : function |
| Function to be called if both lhs and rhs are numeric values. |
| |
| lfn_scalar : function |
| Function to be called if lhs is ``ndarray`` while rhs is numeric value |
| |
| rfn_scalar : function |
| Function to be called if lhs is numeric value while rhs is ``ndarray``; |
| if none is provided, then the function is commutative, so rfn_scalar is equal to lfn_scalar |
| |
| Returns |
| -------- |
| mxnet.numpy.ndarray or scalar |
| result array or scalar |
| """ |
| from ...numpy import ndarray |
| from ...numpy_extension import from_numpy # pylint: disable=unused-import |
| if isinstance(lhs, numeric_types): |
| if isinstance(rhs, numeric_types): |
| return fn_scalar(lhs, rhs, out=out) |
| else: |
| if rfn_scalar is None: |
| # commutative function |
| return lfn_scalar(rhs, float(lhs), out=out) |
| else: |
| return rfn_scalar(rhs, float(lhs), out=out) |
| elif isinstance(rhs, numeric_types): |
| return lfn_scalar(lhs, float(rhs), out=out) |
| elif isinstance(lhs, ndarray) and isinstance(rhs, ndarray): |
| return fn_array(lhs, rhs, out=out) |
| else: |
| raise TypeError('type {} not supported'.format(str(type(rhs)))) |
| #pylint: enable= too-many-arguments, no-member, protected-access |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| def 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. |
| |
| Notes |
| ----- |
| 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 |
| <https://docs.scipy.org/doc/numpy/reference/generated/numpy.unique.html>`_ 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.]) |
| """ |
| ret = list(_api_internal.unique(ar, return_index, return_inverse, return_counts, axis)) |
| return ret[0] if len(ret) == 1 else tuple(ret) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| @wrap_np_binary_func |
| def add(x1, x2, out=None, **kwargs): |
| """ |
| Add arguments element-wise. |
| |
| Parameters |
| ---------- |
| x1, 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 |
| ------- |
| add : ndarray or scalar |
| The sum of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars. |
| |
| Notes |
| ----- |
| 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. |
| """ |
| if isinstance(x1, numeric_types) and isinstance(x2, numeric_types): |
| return _np.add(x1, x2, out=out) |
| return _api_internal.add(x1, x2, out) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| @wrap_np_binary_func |
| def subtract(x1, x2, out=None, **kwargs): |
| """ |
| Subtract arguments element-wise. |
| |
| Parameters |
| ---------- |
| x1, 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. |
| |
| Notes |
| ----- |
| 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. |
| """ |
| if isinstance(x1, numeric_types) and isinstance(x2, numeric_types): |
| return _np.subtract(x1, x2, out=out) |
| return _api_internal.subtract(x1, x2, out) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| @wrap_np_binary_func |
| def multiply(x1, x2, out=None, **kwargs): |
| """ |
| Multiply arguments element-wise. |
| |
| Parameters |
| ---------- |
| x1, 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 multiplication of x1 and x2, element-wise. This is a scalar if both x1 and x2 |
| are scalars. |
| |
| Notes |
| ----- |
| 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. |
| """ |
| if isinstance(x1, numeric_types) and isinstance(x2, numeric_types): |
| return _np.multiply(x1, x2, out=out) |
| return _api_internal.multiply(x1, x2, out) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| @wrap_np_binary_func |
| def divide(x1, x2, out=None, **kwargs): |
| """ |
| Returns a true division of the inputs, element-wise. |
| |
| 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. |
| |
| Notes |
| ----- |
| 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 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. |
| """ |
| if isinstance(x1, numeric_types) and isinstance(x2, numeric_types): |
| return _np.divide(x1, x2, out=out) |
| return _api_internal.true_divide(x1, x2, out) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| def 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. |
| |
| Notes |
| ----- |
| 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 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. |
| """ |
| if isinstance(x1, numeric_types) and isinstance(x2, numeric_types): |
| return _np.true_divide(x1, x2, out=out) |
| return _api_internal.true_divide(x1, x2, out) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| @wrap_np_binary_func |
| def 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 |
| |
| """ |
| if isinstance(x1, numeric_types) and isinstance(x2, numeric_types): |
| return _np.floor_divide(x1, x2, out=out) |
| return _api_internal.floor_divide(x1, x2, out) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| @wrap_np_binary_func |
| def 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 : ndarray or scalar |
| This is a scalar if both x1 and x2 are scalars. |
| """ |
| if isinstance(x1, numeric_types) and isinstance(x2, numeric_types): |
| return _np.mod(x1, x2, out=out) |
| return _api_internal.mod(x1, x2, out) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| @wrap_np_binary_func |
| def 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 : ndarray or scalar |
| This is a scalar if both x1 and x2 are scalars. |
| """ |
| if isinstance(x1, numeric_types) and isinstance(x2, numeric_types): |
| _np.fmod(x1, x2, out=out) |
| return _api_internal.fmod(x1, x2, out) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| def 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 : ndarray |
| 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. |
| |
| 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.]) |
| """ |
| if not isinstance(arr, NDArray): |
| raise TypeError("'arr' can not support type {}".format(str(type(arr)))) |
| if isinstance(obj, slice): |
| start = obj.start |
| stop = obj.stop |
| step = 1 if obj.step is None else obj.step |
| return _api_internal.delete(arr, start, stop, step, axis) |
| elif isinstance(obj, integer_types): |
| return _api_internal.delete(arr, obj, axis) |
| elif isinstance(obj, NDArray): |
| return _api_internal.delete(arr, obj, axis) |
| else: |
| raise TypeError("'obj' can not support type {}".format(str(type(obj)))) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| @wrap_np_binary_func |
| def matmul(a, b, out=None): |
| """ |
| Matrix product of two arrays. |
| |
| Parameters |
| ---------- |
| a, 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 : ndarray |
| The matrix product of the inputs. |
| This is a scalar only when both x1, x2 are 1-d vectors. |
| |
| 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. |
| |
| Notes |
| ----- |
| 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. |
| """ |
| return _api_internal.matmul(a, b, out) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| @wrap_np_binary_func |
| def remainder(x1, x2, out=None): |
| """ |
| 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 : ndarray or scalar |
| This is a scalar if both x1 and x2 are scalars. |
| """ |
| if isinstance(x1, numeric_types) and isinstance(x2, numeric_types): |
| _np.mod(x1, x2, out=out) |
| return _api_internal.mod(x1, x2, out) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| @wrap_np_binary_func |
| def 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 : ndarray or scalar |
| The bases in x1 raised to the exponents in x2. |
| This is a scalar if both x1 and x2 are scalars. |
| """ |
| if isinstance(x1, numeric_types) and isinstance(x2, numeric_types): |
| return _np.power(x1, x2, out=out) |
| return _api_internal.power(x1, x2, out) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| def 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 |
| """ |
| return _api_internal.all(a, axis, keepdims, out) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| def 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) |
| """ |
| return _api_internal.any(a, axis, keepdims, out) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| def 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 : ndarray, int |
| 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. |
| |
| 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]) |
| """ |
| return _api_internal.argsort(a, axis, not descending, 'int64') |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| def 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 : ndarray |
| Array of the same type and shape as `a`. |
| |
| 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]]) |
| """ |
| return _api_internal.sort(a, axis, not descending) |
| |
| @set_module('mxnet.ndarray.numpy') |
| def 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 :func:`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 : ndarray |
| 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 |
| |
| 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.) |
| """ |
| return _api_internal.dot(a, b, out) |
| |
| @set_module('mxnet.ndarray.numpy') |
| def tensordot(a, b, axes=2): |
| r""" |
| 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, 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 |
| Notes |
| ----- |
| Three common use cases are: |
| * ``axes = 0`` : tensor product :math:`a\otimes b` |
| * ``axes = 1`` : tensor dot product :math:`a\cdot b` |
| * ``axes = 2`` : (default) tensor double contraction :math:`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.]]) |
| """ |
| return _api_internal.tensordot(a, b, axes) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| def histogram(a, bins=10, range=None, normed=None, weights=None, density=None): # pylint: disable=too-many-arguments |
| """ |
| 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. |
| """ |
| if normed is True: |
| raise NotImplementedError("normed is not supported yet...") |
| if weights is not None: |
| raise NotImplementedError("weights is not supported yet...") |
| if density is True: |
| raise NotImplementedError("density is not supported yet...") |
| if isinstance(bins, numeric_types): |
| if range is None: |
| raise NotImplementedError("automatic range is not supported yet...") |
| return tuple(_api_internal.histogram(a, None, bins, range)) |
| if isinstance(bins, (list, tuple)): |
| raise NotImplementedError("array_like bins is not supported yet...") |
| if isinstance(bins, str): |
| raise NotImplementedError("string bins is not supported yet...") |
| if isinstance(bins, NDArray): |
| return tuple(_api_internal.histogram(a, bins, None, None)) |
| raise ValueError("np.histogram fails with", locals()) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| def eye(N, M=None, k=0, dtype=float, **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. |
| |
| Returns |
| ------- |
| I : ndarray of shape (N,M) |
| An array where all elements are equal to zero, |
| except for the k-th diagonal, whose values are equal to one. |
| """ |
| _sanity_check_params('eye', ['order'], kwargs) |
| device = kwargs.pop('device', current_device()) |
| if device is None: |
| device = str(current_device()) |
| else: |
| device = str(device) |
| if dtype is None or dtype is float: |
| dtype = _np.float64 if is_np_default_dtype() else _np.float32 |
| if dtype is not None and not isinstance(dtype, str): |
| dtype = get_dtype_name(dtype) |
| |
| # To avoid overflow errors, map large positive k values to the just-out-of-range "num_columns" value |
| k = minimum(k, M if M is not None else N) |
| # Similarly, map large negative k values to the just-out-of-range "-num_rows" value |
| k = maximum(k, -N) |
| return _api_internal.eye(N, M, int(k), device, dtype) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0, device=None): # pylint: disable=too-many-arguments |
| r""" |
| 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. |
| |
| 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() |
| |
| Notes |
| ----- |
| |
| This function differs from the original `numpy.linspace |
| <https://docs.scipy.org/doc/numpy/reference/generated/numpy.linspace.html>`_ 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. |
| """ |
| if isinstance(start, (list, _np.ndarray, NDArray)) or \ |
| isinstance(stop, (list, _np.ndarray, NDArray)): |
| raise NotImplementedError('start and stop only support int') |
| if axis != 0: |
| raise NotImplementedError("the function only support axis 0") |
| if device is None: |
| device = str(current_device()) |
| else: |
| device = str(device) |
| if dtype is not None and not isinstance(dtype, str): |
| dtype = get_dtype_name(dtype) |
| if dtype is None: |
| dtype = _np.float64 if is_np_default_dtype() else _np.float32 |
| if retstep: |
| step = (stop - start) / (num - int(endpoint)) |
| return _api_internal.linspace(start, stop, num, endpoint, device, dtype), step |
| else: |
| return _api_internal.linspace(start, stop, num, endpoint, device, dtype) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| def logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None, axis=0, device=None): # pylint: disable=too-many-arguments |
| r"""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 |
| ------- |
| samples : ndarray |
| `num` samples, equally spaced on a log scale. |
| |
| 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. Now wo only support axis = 0. |
| |
| >>> 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)) |
| """ |
| if isinstance(start, (list, tuple, _np.ndarray, NDArray)) or \ |
| isinstance(stop, (list, tuple, _np.ndarray, NDArray)): |
| raise NotImplementedError('start and stop only support int and float') |
| if axis != 0: |
| raise NotImplementedError("the function only support axis 0") |
| if device is None: |
| device = str(current_device()) |
| else: |
| device = str(device) |
| if dtype is not None and not isinstance(dtype, str): |
| dtype = get_dtype_name(dtype) |
| return _api_internal.logspace(start, stop, num, endpoint, base, device, dtype) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| def expand_dims(a, axis): |
| """Expand the shape of an array. |
| |
| Insert a new axis that will appear at the `axis` position in the expanded |
| |
| Parameters |
| ---------- |
| a : ndarray |
| Input array. |
| axis : int |
| Position in the expanded axes where the new axis is placed. |
| |
| Returns |
| ------- |
| res : ndarray |
| Output array. The number of dimensions is one greater than that of |
| the input array. |
| """ |
| return _api_internal.expand_dims(a, axis) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| @wrap_np_binary_func |
| def gcd(x1, x2, out=None, **kwargs): |
| """ |
| Returns the greatest common divisor of ``|x1|`` and ``|x2|`` |
| |
| Parameters |
| ---------- |
| x1, 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 : ndarray or scalar |
| The greatest common divisor of the absolute value of the inputs |
| This is a scalar if both `x1` and `x2` are scalars. |
| |
| See Also |
| -------- |
| lcm : 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) |
| """ |
| if isinstance(x1, numeric_types) and isinstance(x2, numeric_types): |
| return _np.gcd(x1, x2, out=out) |
| return _api_internal.gcd(x1, x2, out) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| @wrap_np_binary_func |
| def lcm(x1, x2, out=None, **kwargs): |
| """ |
| Returns the lowest common multiple of ``|x1|`` and ``|x2|`` |
| |
| Parameters |
| ---------- |
| x1, 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 : ndarray or scalar |
| The lowest common multiple of the absolute value of the inputs |
| This is a scalar if both `x1` and `x2` are scalars. |
| |
| 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) |
| """ |
| if isinstance(x1, numeric_types) and isinstance(x2, numeric_types): |
| return _np.lcm(x1, x2, out=out) |
| return _api_internal.lcm(x1, x2, out) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| def tril(m, k=0): |
| r""" |
| 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 : ndarray, shape (M, N) |
| Lower triangle of `m`, of same shape and data-type as `m`. |
| |
| 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.]]) |
| """ |
| return _api_internal.tril(m, k) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| def triu(m, k=0): |
| r""" |
| 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]]) |
| """ |
| return _api_internal.triu(m, k) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| def 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, 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 : ndarray |
| 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. |
| |
| 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) |
| """ |
| return _api_internal.trace(a, offset, axis1, axis2, out) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| def tri(N, M=None, k=0, dtype=None, device=None): |
| r""" |
| 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 : ndarray of shape (N, M) |
| Array with its lower triangle filled with ones and zero elsewhere; |
| in other words ``T[i,j] == 1`` for ``i <= j + k``, 0 otherwise. |
| |
| 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.]]) |
| """ |
| if device is None: |
| device = str(current_device()) |
| return _api_internal.tri(N, M, k, dtype, device) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| def triu_indices(n, k=0, m=None, device=None): |
| r""" |
| 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 |
| .. versionadded:: 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 : tuple, shape(2) of ndarrays, shape(`n`) |
| 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`). |
| |
| 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]]) |
| """ |
| return nonzero(~tri(N=n, M=m, k=k-1, dtype=bool, device=device)) |
| |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| def 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 : tuple, shape(2) of ndarray, shape(N) |
| Indices for the upper-triangle of `arr`. |
| See Also |
| -------- |
| triu_indices, triu |
| """ |
| if arr.ndim != 2: |
| raise ValueError("input array must be 2-d") |
| return triu_indices(arr.shape[-2], k=k, m=arr.shape[-1]) |
| |
| |
| def _unary_func_helper(x, fn_array, fn_scalar, out=None, **kwargs): |
| """Helper function for unary operators with kwargs. |
| |
| Parameters |
| ---------- |
| x : ndarray or scalar |
| Input of the unary operator. |
| fn_array : function |
| Function to be called if x is of ``ndarray`` type. |
| fn_scalar : function |
| Function to be called if x is a Python scalar. |
| out : ndarray |
| The buffer ndarray for storing the result of the unary function. |
| |
| Returns |
| ------- |
| out : mxnet.numpy.ndarray or scalar |
| Result array or scalar. |
| """ |
| if isinstance(x, numeric_types): |
| return fn_scalar(x, **kwargs) |
| elif isinstance(x, NDArray): |
| return fn_array(x, out=out, **kwargs) |
| else: |
| raise TypeError('type {} not supported'.format(str(type(x)))) |
| |
| |
| def _pure_unary_func_helper(x, fn_array, fn_scalar, out=None, **kwargs): |
| """Helper function for unary operators without support for kwargs. |
| |
| Parameters |
| ---------- |
| x : ndarray or scalar |
| Input of the unary operator. |
| fn_array : function |
| Function to be called if x is of ``ndarray`` type. |
| fn_scalar : function |
| Function to be called if x is a Python scalar. |
| out : ndarray |
| The buffer ndarray for storing the result of the unary function. |
| |
| Returns |
| ------- |
| out : mxnet.numpy.ndarray or scalar |
| Result array or scalar. |
| """ |
| if isinstance(x, numeric_types): |
| return fn_scalar(x, **kwargs) |
| elif isinstance(x, NDArray): |
| return fn_array(x, out) |
| else: |
| raise TypeError('type {} not supported'.format(str(type(x)))) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| @wrap_np_unary_func |
| def sin(x, out=None, **kwargs): |
| r""" |
| Trigonometric sine, element-wise. |
| |
| Parameters |
| ---------- |
| x : ndarray or scalar |
| Angle, in radians (:math:`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 : ndarray or scalar |
| The sine of each element of x. This is a scalar if `x` is a 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. ]) |
| """ |
| return _pure_unary_func_helper(x, _api_internal.sin, _np.sin, out=out, **kwargs) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| @wrap_np_unary_func |
| def cos(x, out=None, **kwargs): |
| r""" |
| Cosine, element-wise. |
| |
| Parameters |
| ---------- |
| x : ndarray or scalar |
| Angle, in radians (:math:`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 : ndarray or scalar |
| The corresponding cosine values. This is a scalar if x is a 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 |
| """ |
| return _pure_unary_func_helper(x, _api_internal.cos, _np.cos, out=out, **kwargs) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| @wrap_np_unary_func |
| def 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 : ndarray or scalar |
| The corresponding hyperbolic sine values. This is a scalar if `x` is a 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 |
| """ |
| return _pure_unary_func_helper(x, _api_internal.sinh, _np.sinh, out=out, **kwargs) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| @wrap_np_unary_func |
| def 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 : ndarray or scalar |
| The corresponding hyperbolic cosine values. This is a scalar if `x` is a scalar. |
| |
| Notes |
| ---- |
| This function only supports input type of float. |
| |
| Examples |
| -------- |
| >>> np.cosh(0) |
| 1.0 |
| """ |
| return _pure_unary_func_helper(x, _api_internal.cosh, _np.cosh, out=out, **kwargs) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| @wrap_np_unary_func |
| def 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. |
| |
| Notes |
| ----- |
| 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 |
| """ |
| return _pure_unary_func_helper(x, _api_internal.tanh, _np.tanh, out=out, **kwargs) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| @wrap_np_unary_func |
| def 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 t'absolute', he 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 : ndarray or scalar |
| 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. |
| |
| Notes |
| ---- |
| This function only supports input type of float. |
| |
| Examples |
| -------- |
| >>> np.log10(np.array([1e-15, -3.])) |
| array([-15., nan]) |
| """ |
| return _pure_unary_func_helper(x, _api_internal.log10, _np.log10, out=out, **kwargs) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| @wrap_np_unary_func |
| def 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 : ndarray or scalar |
| 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. |
| |
| 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]) |
| """ |
| return _pure_unary_func_helper(x, _api_internal.sqrt, _np.sqrt, out=out, **kwargs) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| @wrap_np_unary_func |
| def cbrt(x, out=None, **kwargs): |
| r""" |
| 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 : ndarray |
| 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. |
| |
| Examples |
| ---------- |
| >>> np.cbrt([1,8,27]) |
| array([ 1., 2., 3.]) |
| """ |
| return _pure_unary_func_helper(x, _api_internal.cbrt, _np.cbrt, out=out, **kwargs) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| @wrap_np_unary_func |
| def abs(x, out=None, **kwargs): |
| r""" |
| 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 : ndarray |
| An ndarray containing the absolute value of |
| each element in `x`. This is a scalar if `x` is a scalar. |
| |
| Examples |
| -------- |
| >>> x = np.array([-1.2, 1.2]) |
| >>> np.abs(x) |
| array([1.2, 1.2]) |
| """ |
| return _pure_unary_func_helper(x, _api_internal.abs, _np.abs, out=out, **kwargs) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| @wrap_np_unary_func |
| def fabs(x, out=None, **kwargs): |
| r""" |
| 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 : ndarray |
| An ndarray containing the absolute value of |
| each element in `x`. This is a scalar if `x` is a scalar. |
| |
| Examples |
| -------- |
| >>> np.fabs(-1) |
| 1.0 |
| >>> np.fabs(np.array([-1.2, 1.2]))s |
| array([ 1.2, 1.2]) |
| """ |
| return _pure_unary_func_helper(x, _api_internal.abs, _np.abs, out=out, **kwargs) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| @wrap_np_unary_func |
| def absolute(x, out=None, **kwargs): |
| r""" |
| 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 : ndarray |
| An ndarray containing the absolute value of each element in x. |
| |
| Examples |
| ---------- |
| >>> x = np.array([-1.2, 1.2]) |
| >>> np.absolute(x) |
| array([ 1.2, 1.2]) |
| """ |
| return _pure_unary_func_helper(x, _api_internal.abs, _np.abs, out=out, **kwargs) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| @wrap_np_unary_func |
| def sign(x, out=None, **kwargs): |
| r""" |
| 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.]) |
| >>> # Use scalars as inputs: |
| >>> 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.]) |
| """ |
| return _pure_unary_func_helper(x, _api_internal.sign, _np.sign, out=out, **kwargs) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| @wrap_np_unary_func |
| def exp(x, out=None, **kwargs): |
| r""" |
| 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 : ndarray or scalar |
| Output array, element-wise exponential of `x`. |
| This is a scalar if `x` is a 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 ]) |
| """ |
| return _pure_unary_func_helper(x, _api_internal.exp, _np.exp, out=out, **kwargs) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| @wrap_np_unary_func |
| def expm1(x, out=None, **kwargs): |
| r""" |
| Calculate `exp(x) - 1` 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 : ndarray or scalar |
| Output array, element-wise exponential minus one: `out = exp(x) - 1`. |
| This is a scalar if `x` is a scalar. |
| |
| Examples |
| -------- |
| >>> np.expm1(1) |
| 1.718281828459045 |
| >>> x = np.array([-1, 1, -2, 2]) |
| >>> np.expm1(x) |
| array([-0.63212056, 1.71828183, -0.86466472, 6.3890561]) |
| """ |
| return _pure_unary_func_helper(x, _api_internal.expm1, _np.expm1, out=out, **kwargs) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| @wrap_np_unary_func |
| def arcsin(x, out=None, **kwargs): |
| r""" |
| Inverse sine, element-wise. |
| |
| 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 : ndarray or scalar |
| 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]``. |
| |
| Examples |
| -------- |
| >>> np.arcsin(1) # pi/2 |
| 1.5707963267948966 |
| >>> np.arcsin(-1) # -pi/2 |
| -1.5707963267948966 |
| >>> np.arcsin(0) |
| 0.0 |
| |
| Notes |
| ----- |
| `arcsin` is a multivalued function: for each `x` there are infinitely |
| many numbers `z` such that :math:`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, *arcsin* 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 `device` as the input `ndarray`. |
| This function differs from the original `numpy.arcsin |
| <https://numpy.org/doc/stable/reference/generated/numpy.arcsin.html>`_ 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/ |
| """ |
| return _pure_unary_func_helper(x, _api_internal.arcsin, _np.arcsin, out=out, **kwargs) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| @wrap_np_unary_func |
| def arccos(x, out=None, **kwargs): |
| r""" |
| Trigonometric inverse cosine, element-wise. |
| The inverse of cos so that, if y = cos(x), then x = arccos(y). |
| |
| 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 : ndarray |
| 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. |
| |
| See also |
| ---------- |
| cos, arctan, arcsin |
| |
| Notes |
| ---------- |
| arccos 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, arccos 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.arccos([1, -1]) |
| array([ 0. , 3.14159265]) |
| """ |
| return _pure_unary_func_helper(x, _api_internal.arccos, _np.arccos, out=out, **kwargs) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| @wrap_np_unary_func |
| def arctan(x, out=None, **kwargs): |
| r""" |
| Trigonometric inverse tangent, element-wise. |
| The inverse of tan, so that if ``y = tan(x)`` then ``x = arctan(y)``. |
| |
| 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 : ndarray or scalar |
| Out has the same shape as `x`. It lies is in |
| ``[-pi/2, pi/2]`` (``arctan(+/-inf)`` returns ``+/-pi/2``). |
| This is a scalar if `x` is a scalar. |
| |
| Notes |
| ----- |
| `arctan` 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, `arctan` 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.arctan(x) |
| array([0. , 0.7853982]) |
| >>> np.pi/4 |
| 0.7853981633974483 |
| """ |
| return _pure_unary_func_helper(x, _api_internal.arctan, _np.arctan, out=out, **kwargs) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| @wrap_np_unary_func |
| def 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. |
| |
| Notes |
| ----- |
| 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 |
| <https://docs.scipy.org/doc/numpy/reference/generated/numpy.log.html>`_ 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 default float32 dtype may lead to slightly different behavior: |
| >>> a = np.array([1, np.exp(1), np.exp(2), 0], dtype=np.float32) |
| >>> np.log(a) |
| array([ 0., 0.99999994, 2., -inf]) |
| >>> np.log(1) |
| 0.0 |
| """ |
| return _pure_unary_func_helper(x, _api_internal.log, _np.log, out=out, **kwargs) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| @wrap_np_unary_func |
| def 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. |
| |
| Notes |
| ------- |
| This function differs from the original `numpy.degrees |
| <https://docs.scipy.org/doc/numpy/reference/generated/numpy.degrees.html>`_ 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.]) |
| """ |
| return _pure_unary_func_helper(x, _api_internal.degrees, _np.degrees, out=out, **kwargs) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| @wrap_np_unary_func |
| def rad2deg(x, out=None, **kwargs): |
| r""" |
| 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. |
| |
| Notes |
| ----- |
| "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 |
| """ |
| return _pure_unary_func_helper(x, _api_internal.rad2deg, _np.rad2deg, out=out) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| @wrap_np_unary_func |
| def 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. |
| |
| Notes |
| ----- |
| This function differs from the original `numpy.rint |
| <https://docs.scipy.org/doc/numpy/reference/generated/numpy.rint.html>`_ 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.]) |
| """ |
| return _pure_unary_func_helper(x, _api_internal.rint, _np.rint, out=out, **kwargs) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| @wrap_np_unary_func |
| def 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. |
| |
| Notes |
| ----- |
| This function differs from the original `numpy.log2 |
| <https://www.google.com/search?q=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.]) |
| """ |
| return _pure_unary_func_helper(x, _api_internal.log2, _np.log2, out=out, **kwargs) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| @wrap_np_unary_func |
| def 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 : ndarray or scalar |
| Natural logarithm of 1 + x, element-wise. This is a scalar |
| if x is a 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]) |
| """ |
| return _pure_unary_func_helper(x, _api_internal.log1p, _np.log1p, out=out, **kwargs) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| @wrap_np_unary_func |
| def 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. |
| |
| Notes |
| ----- |
| This function differs from the original `numpy.radians |
| <https://docs.scipy.org/doc/numpy/reference/generated/numpy.radians.html>`_ 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) |
| """ |
| return _pure_unary_func_helper(x, _api_internal.radians, _np.radians, out=out, **kwargs) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| @wrap_np_unary_func |
| def deg2rad(x, out=None, **kwargs): |
| r""" |
| 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. |
| |
| Notes |
| ----- |
| "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 |
| """ |
| return _pure_unary_func_helper(x, _api_internal.deg2rad, _np.deg2rad, out=out) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| @wrap_np_unary_func |
| def reciprocal(x, out=None, **kwargs): |
| r""" |
| 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 : ndarray or scalar |
| Output array is same shape and type as x. This is a scalar if x is a scalar. |
| |
| Examples |
| -------- |
| >>> np.reciprocal(2.) |
| 0.5 |
| >>> x = np.array([1, 2., 3.33]) |
| >>> np.reciprocal(x) |
| array([1. , 0.5 , 0.3003003]) |
| |
| Notes |
| ----- |
| .. 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 |
| <https://docs.scipy.org/doc/numpy/reference/generated/numpy.reciprocal.html>`_ in |
| the following aspects: |
| - Only support ndarray and scalar now. |
| - `where` argument is not supported. |
| """ |
| return _pure_unary_func_helper(x, _api_internal.reciprocal, _np.reciprocal, out=out, **kwargs) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| @wrap_np_unary_func |
| def square(x, out=None, **kwargs): |
| r""" |
| 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 : ndarray or scalar |
| Output array is same shape and type as x. This is a scalar if x is a scalar. |
| |
| Examples |
| -------- |
| >>> np.square(2.) |
| 4.0 |
| >>> x = np.array([1, 2., -1]) |
| >>> np.square(x) |
| array([1., 4., 1.]) |
| |
| Notes |
| ----- |
| The output `ndarray` has the same `device` as the input `ndarray`. |
| This function differs from the original `numpy.square |
| <https://docs.scipy.org/doc/numpy/reference/generated/numpy.square.html>`_ in |
| the following aspects: |
| - Only support ndarray and scalar now. |
| - `where` argument is not supported. |
| - Complex input is not supported. |
| """ |
| return _pure_unary_func_helper(x, _api_internal.square, _np.square, out=out, **kwargs) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| @wrap_np_unary_func |
| def negative(x, out=None, **kwargs): |
| r""" |
| 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. |
| |
| Returns: |
| --------- |
| y : ndarray or scalar |
| Returned array or scalar: y = -x. This is a scalar if x is a scalar. |
| |
| Examples: |
| --------- |
| >>> np.negative(1) |
| -1 |
| """ |
| return _pure_unary_func_helper(x, _api_internal.negative, _np.negative, out=out) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| @wrap_np_unary_func |
| def positive(x, out=None, **kwargs): |
| r""" |
| 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 : ndarray or scalar |
| Returned array or scalar: y = +x. This is a scalar if x is a 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.]) |
| """ |
| if out is x: |
| return x |
| return _pure_unary_func_helper(x, _api_internal.copy, _np.positive, out=out) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| @wrap_np_unary_func |
| def fix(x, out=None, **kwargs): |
| r""" |
| 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 of floats |
| |
| Examples |
| --------- |
| >>> np.fix(3.14) |
| 3 |
| """ |
| return _pure_unary_func_helper(x, _api_internal.fix, _np.fix, out=out) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| @wrap_np_unary_func |
| def tan(x, out=None, **kwargs): |
| r""" |
| Compute tangent element-wise. |
| Equivalent to np.sin(x)/np.cos(x) element-wise. |
| |
| Parameters: |
| ---------- |
| x : ndarray |
| 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 : ndarray, optional |
| Values of True indicate to calculate the ufunc at that position, |
| values of False indicate to leave the value in the output alone. |
| |
| Returns: |
| ------- |
| y : ndarray |
| The corresponding tangent values. This is a scalar if x is a scalar. |
| |
| Examples: |
| --------- |
| >>> np.tan(0.5) |
| 0.5463024898437905 |
| """ |
| |
| return _pure_unary_func_helper(x, _api_internal.tan, _np.tan, out=out, **kwargs) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| @wrap_np_unary_func |
| def ceil(x, out=None, **kwargs): |
| r""" |
| 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 :math:`\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 same 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 ceiling of each element in `x`, with `float` dtype. |
| This is a scalar if `x` is a 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.) |
| """ |
| if isinstance(x, NDArray) and _np.issubdtype(x.dtype, _np.integer): |
| return x |
| return _pure_unary_func_helper(x, _api_internal.ceil, _np.ceil, out=out, **kwargs) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| @wrap_np_unary_func |
| def floor(x, out=None, **kwargs): |
| r""" |
| Return the floor of the input, element-wise. |
| The floor of the ndarray `x` is the largest integer `i`, such that |
| `i <= x`. It is often denoted as :math:`\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 same 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 floor of each element in `x`, with `float` dtype. |
| This is a scalar if `x` is a 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.) |
| """ |
| if isinstance(x, NDArray) and _np.issubdtype(x.dtype, _np.integer): |
| return x |
| return _pure_unary_func_helper(x, _api_internal.floor, _np.floor, out=out, **kwargs) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| @wrap_np_unary_func |
| def bitwise_not(x, out=None, **kwargs): |
| r""" |
| 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 : ndarray or scalar |
| Result. |
| This is a scalar if `x` is a 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 |
| """ |
| return _pure_unary_func_helper(x, _api_internal.bitwise_not, _np.bitwise_not, out=out, **kwargs) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| @wrap_np_unary_func |
| def invert(x, out=None, **kwargs): |
| r""" |
| 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 : ndarray or scalar |
| Result. |
| This is a scalar if `x` is a 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 |
| """ |
| return _pure_unary_func_helper(x, _api_internal.bitwise_not, _np.bitwise_not, out=out, **kwargs) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| @wrap_np_unary_func |
| def trunc(x, out=None, **kwargs): |
| r""" |
| 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. |
| |
| Notes |
| ----- |
| 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.]) |
| """ |
| if isinstance(x, NDArray) and _np.issubdtype(x.dtype, _np.integer): |
| return x |
| return _pure_unary_func_helper(x, _api_internal.trunc, _np.trunc, out=out, **kwargs) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| @wrap_np_unary_func |
| def logical_not(x, out=None, **kwargs): |
| r""" |
| 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. |
| |
| Notes |
| ----- |
| 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]) |
| """ |
| return _pure_unary_func_helper(x, _api_internal.logical_not, _np.logical_not, out=out, **kwargs) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| @wrap_np_unary_func |
| def arcsinh(x, out=None, **kwargs): |
| r""" |
| Inverse hyperbolic sine, element-wise. |
| |
| Parameters |
| ---------- |
| x : ndarray or scalar |
| Input array. |
| out : ndarray or None, optional |
| A location into which the result is stored. |
| |
| Returns |
| ------- |
| arcsinh : ndarray |
| Array of the same shape as `x`. |
| This is a scalar if `x` is a scalar. |
| |
| Notes |
| ----- |
| `arcsinh` is a multivalued function: for each `x` there are infinitely |
| many numbers `z` such that `sinh(z) = x`. |
| |
| For real-valued input data types, `arcsinh` 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.arcsinh(a) |
| array([1.8309381, 2.2924316]) |
| >>> np.arcsinh(1) |
| 0.0 |
| """ |
| return _pure_unary_func_helper(x, _api_internal.arcsinh, _np.arcsinh, out=out, **kwargs) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| @wrap_np_unary_func |
| def arccosh(x, out=None, **kwargs): |
| r""" |
| Inverse hyperbolic cosine, element-wise. |
| |
| Parameters |
| ---------- |
| x : ndarray or scalar |
| Input array. |
| out : ndarray or None, optional |
| A location into which the result is stored. |
| |
| Returns |
| ------- |
| arccosh : ndarray |
| Array of the same shape as `x`. |
| This is a scalar if `x` is a scalar. |
| |
| Notes |
| ----- |
| `arccosh` is a multivalued function: for each `x` there are infinitely |
| many numbers `z` such that `cosh(z) = x`. |
| |
| For real-valued input data types, `arccosh` 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.arccosh(a) |
| array([1.8309381, 2.2924316]) |
| >>> np.arccosh(1) |
| 0.0 |
| """ |
| return _pure_unary_func_helper(x, _api_internal.arccosh, _np.arccosh, out=out, **kwargs) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| @wrap_np_unary_func |
| def arctanh(x, out=None, **kwargs): |
| r""" |
| Inverse hyperbolic tangent, element-wise. |
| |
| Parameters |
| ---------- |
| x : ndarray or scalar |
| Input array. |
| out : ndarray or None, optional |
| A location into which the result is stored. |
| |
| Returns |
| ------- |
| arctanh : ndarray |
| Array of the same shape as `x`. |
| This is a scalar if `x` is a scalar. |
| |
| Notes |
| ----- |
| `arctanh` is a multivalued function: for each `x` there are infinitely |
| many numbers `z` such that `tanh(z) = x`. |
| |
| For real-valued input data types, `arctanh` 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.arctanh(a) |
| array([0., -0.54930615]) |
| >>> np.arctanh(0.0) |
| 0.0 |
| """ |
| return _pure_unary_func_helper(x, _api_internal.arctanh, _np.arctanh, out=out, **kwargs) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| def tile(A, reps): |
| r""" |
| 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 : ndarray |
| The tiled output array. |
| |
| 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` |
| |
| """ |
| if isinstance(A, numeric_types): |
| return _np.tile(A, reps) |
| elif isinstance(A, NDArray): |
| return _api_internal.tile(A, reps) |
| else: |
| raise TypeError('type {} not supported'.format(str(type(A)))) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| def 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. |
| |
| Notes |
| ----- |
| This function differs from the original `numpy.transpose |
| <https://docs.scipy.org/doc/numpy/reference/generated/numpy.transpose.html>`_ 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) |
| """ |
| return _api_internal.transpose(a, axes) |
| |
| |
| @set_module('mxnet.ndarray.numpy') |
| def 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 : ndarray |
| Output array which has the same shape as `a`, except along |
| the given axis. |
| |
| 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) |
|