diff --git a/mindspore/numpy/array_creations.py b/mindspore/numpy/array_creations.py index 25e997deb34..fb704e799cb 100644 --- a/mindspore/numpy/array_creations.py +++ b/mindspore/numpy/array_creations.py @@ -491,9 +491,9 @@ def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis dtype (Union[:class:`mindspore.dtype`, str], optional): Designated tensor dtype, If `dtype` is None, infer the data type from other input arguments. Default is None. axis (int, optional): The axis in the result to store the samples. Relevant - only if start or stop are array-like. By default :math:`(0)`, the samples will - be along a new axis inserted at the beginning. Use :math:`-1` to get an axis at the end. - Default is :math:`0`. + only if start or stop are array-like. By default, the samples will + be along a new axis inserted at the beginning. Use -1 to get an axis at the end. + Default is 0. Returns: Tensor, with `num` equally spaced samples in the closed interval @@ -564,13 +564,13 @@ def logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None, axis=0): not included. Default is True. base (Union[int, float], optional): The base of the log space. The step size between the elements in :math:`ln(samples) / ln(base)` (or :math:`log_{base}(samples)`) - is uniform. Default is :math:`10.0`. + is uniform. Default is 10.0. dtype (Union[:class:`mindspore.dtype`, str], optional): Designated tensor dtype. If `dtype` is None, infer the data type from other input arguments. Default is None. axis (int, optional): The axis in the result to store the samples. Relevant - only if start or stop is array-like. By default (:math:`0`), the samples will - be along a new axis inserted at the beginning. Use :math:`-1` to get an axis at the end. - Default is :math:`0`. + only if start or stop is array-like. By default, the samples will + be along a new axis inserted at the beginning. Use -1 to get an axis at the end. + Default is 0. Returns: Tensor, equally spaced on a log scale. @@ -657,7 +657,7 @@ def geomspace(start, stop, num=50, endpoint=True, dtype=None, axis=0): def eye(N, M=None, k=0, dtype=mstype.float32): """ - Returns a 2-D tensor with ones on the diagnoal and zeros elsewhere. + Returns a 2-D tensor with ones on the diagonal and zeros elsewhere. Args: N (int): Number of rows in the output, must be larger than 0. @@ -984,12 +984,12 @@ def tri(N, M=None, k=0, dtype=mstype.float32): :math:`k = 0` is the main diagonal, while :math:`k < 0` is below it, and :math:`k > 0` is above. The default is 0. dtype(:class:`mindspore.dtype`, optional): Data type of the returned array. The default - is :class:`mindspore.dtype`. + is mstype.float32. Returns: Tensor with shape `(N, M)`, with its lower triangle filled with ones and zeros elsewhere; in other words :math:`T[i,j] = 1` for :math:`j <= i + k`, - :math:`0` otherwise. + 0 otherwise. Raises: TypeError: If input arguments have types not specified above. @@ -1936,7 +1936,7 @@ def triu_indices(n, k=0, m=None): Args: n (int): The size of the arrays for which the returned indices will be valid. - k (int, optional): Diagonal offset. + k (int, optional): Diagonal offset, default is 0. m (int, optional): The column dimension of the arrays for which the returned arrays will be valid. By default `m` is taken equal to `n`. @@ -1965,7 +1965,7 @@ def tril_indices(n, k=0, m=None): Args: n (int): The size of the arrays for which the returned indices will be valid. - k (int, optional): Diagonal offset. + k (int, optional): Diagonal offset, default is 0. m (int, optional): The column dimension of the arrays for which the returned arrays will be valid. By default `m` is taken equal to `n`. @@ -1994,7 +1994,7 @@ def triu_indices_from(arr, k=0): Args: arr (Union[Tensor, list, tuple]): 2-dimensional array. - k (int, optional): Diagonal offset. + k (int, optional): Diagonal offset, default is 0. Returns: triu_indices_from, tuple of 2 tensor, shape(N) @@ -2026,7 +2026,7 @@ def tril_indices_from(arr, k=0): Args: arr (Union[Tensor, list, tuple]): 2-dimensional array. - k (int, optional): Diagonal offset. + k (int, optional): Diagonal offset, default is 0. Returns: triu_indices_from, tuple of 2 tensor, shape(N) diff --git a/mindspore/numpy/array_ops.py b/mindspore/numpy/array_ops.py index 92189ae52c0..a4a70595353 100644 --- a/mindspore/numpy/array_ops.py +++ b/mindspore/numpy/array_ops.py @@ -79,11 +79,12 @@ def expand_dims(a, axis): def squeeze(a, axis=None): """ - Removes single-dimensional entries from the shape of an tensor. + Removes single-dimensional entries from the shape of a tensor. Args: a (Tensor): Input tensor array. - axis (Union[None, int, list(int), tuple(list)]): Default is None. + axis (Union[None, int, list(int), tuple(list)]): The axis(axes) to squeeze, + default is None. Returns: Tensor, with all or a subset of the dimensions of length :math:`1` removed. @@ -886,7 +887,7 @@ def stack(arrays, axis=0): Args: arrays (sequence of Tensor): Each array must have the same shape. axis (int, optional): The axis in the result array along which the - input arrays are stacked. + input arrays are stacked. Default: 0. Returns: Tensor, The stacked array has one more dimension than the input @@ -1045,7 +1046,7 @@ def roll(a, shift, axis=None): shift (Union[int, tuple(int)]: The number of places by which elements are shifted. If a tuple, then axis must be a tuple of the same size, and each of the given axes is shifted by the corresponding number. If shift - is an int while axis is a tuple of ints, then the same value is used + is an int while axis is a tuple of integers, then the same value is used for all given axes. axis (Union[int, tuple(int)], optional): Axis or axes along which elements are shifted. By default, the array is flattened before shifting, after @@ -1630,15 +1631,12 @@ def flip(m, axis=None): The shape of the array is preserved, but the elements are reordered. - Note: - On CPU, the supported dtypes are np.float16, np.float32, and np.float64. - Args: m (Tensor): Input array. - axis (None or int or tuple of ints, optional): Axis or axes along which + axis (None or int or tuple of integers, optional): Axis or axes along which to flip over. The default, ``axis=None``, will flip over all of the axes of the input array. If `axis` is negative it counts from the last to - the first axis. If `axis` is a tuple of ints, flipping is performed on + the first axis. If `axis` is a tuple of integers, flipping is performed on all of the axes specified in the tuple. Returns: @@ -1648,7 +1646,7 @@ def flip(m, axis=None): TypeError: if the input is not a tensor. Supported Platforms: - ``GPU`` + ``GPU`` ``CPU`` Example: >>> import mindspore.numpy as np @@ -1689,9 +1687,6 @@ def flipud(m): Flips the entries in each column in the up/down direction. Rows are preserved, but appear in a different order than before. - Note: - On CPU, the supported dtypes are np.float16, np.float32, and np.float64. - Args: m (Tensor): Input array. @@ -1702,7 +1697,7 @@ def flipud(m): TypeError: if the input is not a tensor. Supported Platforms: - ``GPU`` + ``GPU`` ``CPU`` Example: >>> import mindspore.numpy as np @@ -1722,9 +1717,6 @@ def fliplr(m): Flips the entries in each row in the left/right direction. Columns are preserved, but appear in a different order than before. - Note: - On CPU, the supported dtypes are np.float16, np.float32, and np.float64. - Args: m (Tensor): Input array. @@ -1735,7 +1727,7 @@ def fliplr(m): TypeError: if the input is not a tensor. Supported Platforms: - ``GPU`` + ``GPU`` ``CPU`` Example: >>> import mindspore.numpy as np @@ -1954,7 +1946,7 @@ def rot90(a, k=1, axes=(0, 1)): Raises: TypeError: if input `a` is not a Tensor or the argument `k` is not integer or - the argument `axes` is not tuple of ints or list of ints. + the argument `axes` is not tuple of integers or list of ints. ValueError: if any axis is out of range or the length of `axes` is not `2`. @@ -2241,7 +2233,7 @@ def array_str(a): Note: Numpy argument `max_line_width`, `precision` and `suppress_small` are not supported. - Graph mode dose not support the function. + Graph mode does not support the function. Args: a (Tensor): Input data. @@ -2412,7 +2404,7 @@ def unravel_index(indices, shape, order='C'): Args: indices (Union[int, float, bool, list, tuple, Tensor]): An integer array whose elements are indices into the flattened version of an array of dimensions shape. - shape (tuple of ints): The shape of the array to use for unraveling indices. + shape (tuple of integers): The shape of the array to use for unraveling indices. order (Union['C', 'F'], optional): Determines whether the indices should be viewed as indexing in row-major (C-style) or column-major (Fortran-style) order. diff --git a/mindspore/numpy/logic_ops.py b/mindspore/numpy/logic_ops.py index 8d00660737d..88c312e9dc4 100644 --- a/mindspore/numpy/logic_ops.py +++ b/mindspore/numpy/logic_ops.py @@ -872,7 +872,7 @@ def sometrue(a, axis=None, keepdims=False): performed. Default: None. If None, perform a logical OR over all the dimensions of the input array. If negative, it counts from the last to the first axis. - If tuple of ints, a reduction is performed on multiple axes, instead of a single axis or + If tuple of integers, a reduction is performed on multiple axes, instead of a single axis or all the axes as before. keepdims (bool): Default: False. If True, the axes which are reduced are left in the result as dimensions with size one. @@ -885,7 +885,7 @@ def sometrue(a, axis=None, keepdims=False): Returns single boolean unless axis is not None Raises: - TypeError: If input is not array_like or `axis` is not int or tuple of ints or + TypeError: If input is not array_like or `axis` is not int or tuple of integers or `keepdims` is not integer or `initial` is not scalar. ValueError: If any axis is out of range or duplicate axes exist. diff --git a/mindspore/numpy/math_ops.py b/mindspore/numpy/math_ops.py index 6576e52589b..591f7b21f48 100644 --- a/mindspore/numpy/math_ops.py +++ b/mindspore/numpy/math_ops.py @@ -594,7 +594,7 @@ def mean(a, axis=None, keepdims=False, dtype=None): Args: a (Tensor): input tensor containing numbers whose mean is desired. If a is not an array, a conversion is attempted. - axis (None or int or tuple of ints, optional): Axis or axes along + axis (None or int or tuple of integers, optional): Axis or axes along which the means are computed. The default is to compute the mean of the flattened array. If this is a tuple of ints, a mean is performed over multiple axes. @@ -890,7 +890,11 @@ def std(x, axis=None, ddof=0, keepdims=False): If `None`, compute the standard deviation of the flattened array. ddof (int): Means Delta Degrees of Freedom. The divisor used in calculations is :math:`N - ddof`, where :math:`N` represents the number of elements. Default: 0. - keepdims: Default: `False`. + keepdims: 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 tensor. + If the default value is passed, then keepdims will not be passed through to the std method of + sub-classes of tensor, however any non-default value will be. If the sub-class’ method does not + implement keepdims any exceptions will be raised. Default: `False`. Returns: Standard deviation tensor. @@ -928,7 +932,7 @@ def var(x, axis=None, ddof=0, keepdims=False): ddof (int): Means Delta Degrees of Freedom. Default: 0. The divisor used in calculations is :math:`N - ddof`, where :math:`N` represents the number of elements. keepdims (bool): 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. + dimensions with size one. With this option, the result will broadcast correctly against the input tensor. If the default value is passed, then keepdims will not be passed through to the var method of sub-classes of tensor, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised. Default: `False`. @@ -1385,15 +1389,15 @@ def amax(a, axis=None, keepdims=False, initial=None, where=True): Args: a (Tensor): Input data. - axis (None or int or tuple of ints, optional): defaults to None. Axis or + axis (None or int or tuple of integers, optional): defaults to None. Axis or axes along which to operate. By default, flattened input is used. If - this is a tuple of ints, the maximum is selected over multiple axes, + this is a tuple of integers, the maximum is selected over multiple axes, instead of a single axis or all the axes as before. keepdims (boolean, optional): defaults to False. 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. - initial (scalar, optional): + initial (scalar, optional): defaults to None. The minimum value of an output element. Must be present to allow computation on empty slice. where (boolean Tensor, optional): defaults to True. @@ -1440,15 +1444,15 @@ def amin(a, axis=None, keepdims=False, initial=None, where=True): Args: a (Tensor): Input data. - axis (None or int or tuple of ints, optional): defaults to None. Axis or + axis (None or int or tuple of integers, optional): defaults to None. Axis or axes along which to operate. By default, flattened input is used. If - this is a tuple of ints, the minimum is selected over multiple axes, + this is a tuple of integers, the minimum is selected over multiple axes, instead of a single axis or all the axes as before. keepdims (bool, optional): defaults to False. 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. - initial (Number, optional): + initial (Number, optional): defaults to None. The maximum value of an output element. Must be present to allow computation on empty slice. where (bool Tensor, optional): defaults to True. @@ -2029,8 +2033,8 @@ def trapz(y, x=None, dx=1.0, axis=-1): corresponding to the `y` values. If `x` is None, the sample points are assumed to be evenly spaced `dx` apart. The default is None. dx (scalar, optional): The spacing between sample points when `x` is None. The - default is 1. - axis (int, optional): The axis along which to integrate. + default is 1.0. + axis (int, optional): The axis along which to integrate. Defaults to -1. Returns: Tensor of float, definite integral as approximated by trapezoidal rule. @@ -2300,7 +2304,7 @@ def cov(m, y=None, rowvar=True, bias=False, ddof=None, fweights=None, aweights=N and observations. Each row of `m` represents a variable, and each column represents a single observation of all those variables. Also see `rowvar` below. y (Union[Tensor, list, tuple], optional): An additional set of variables - and observations. `y` has the same form as that of `m`. + and observations. `y` has the same form as that of `m`, default is ``None``. rowvar(bool, optional): If `rowvar` is ``True`` (default), then each row represents a variable, with observations in the columns. Otherwise, the relationship is transposed: each column represents a variable, while the rows contain @@ -2316,12 +2320,12 @@ def cov(m, y=None, rowvar=True, bias=False, ddof=None, fweights=None, aweights=N is ``None``. fweights (Union[Tensor, list, tuple], optional): 1-D tensor of integer frequency weights; the number of times each observation vector should - be repeated. + be repeated. The default value is ``None``. aweights (Union[Tensor, list, tuple], optional): 1-D tensor of observation vector weights. These relative weights are typically larger for observations considered more important and smaller for observations considered less important. If :math:`ddof=0` the tensor of weights can be used to assign probabilities - to observation vectors. + to observation vectors. The default value is ``None``. dtype (Union[:class:`mindspore.dtype`, str], optional): Data-type of the result. By default, the return data-type will have mstype.float32 precision. @@ -4036,7 +4040,7 @@ def sum_(a, axis=None, dtype=None, keepdims=False, initial=None): axis (Union[None, int, tuple(int)]): Axis or axes along which a sum is performed. Default: None. If None, sum all of the elements of the input array. If axis is negative it counts from the last to the first axis. - If axis is a tuple of ints, a sum is performed on all of the axes specified in the tuple + If axis is a tuple of integers, a sum is performed on all of the axes specified in the tuple instead of a single axis or all the axes as before. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the output Tensor. @@ -4045,7 +4049,8 @@ def sum_(a, axis=None, dtype=None, keepdims=False, initial=None): If the default value is passed, then keepdims will not be passed through to the sum method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised. Default: `False`. - initial (scalar): Starting value for the sum. + initial (scalar): Starting value for the sum, if `None`, which refers to the first element of the reduction. + Default: `None`. Returns: Tensor. An array with the same shape as a, with the specified axis removed. @@ -4053,7 +4058,7 @@ def sum_(a, axis=None, dtype=None, keepdims=False, initial=None): If an output array is specified, a reference to out is returned. Raises: - TypeError: If input is not array_like or `axis` is not int or tuple of ints or + TypeError: If input is not array_like or `axis` is not int or tuple of integers or `keepdims` is not integer or `initial` is not scalar. ValueError: If any axis is out of range or duplicate axes exist. @@ -4597,9 +4602,10 @@ def bincount(x, weights=None, minlength=0, length=None): Args: x (Union[list, tuple, Tensor]): 1-d input array. weights (Union[int, float, bool, list, tuple, Tensor], optional): Weights, - array of the same shape as `x`. + array of the same shape as `x`. Defaults to None. minlength (int, optional): A minimum number of bins for the output array. - length (int, optional): Number of bins. + Defaults to 0. + length (int, optional): Number of bins. Defaults to None. Returns: Tensor, the result of binning the input array. The length of out is equal to @@ -4664,7 +4670,7 @@ def histogram(a, bins=10, range=None, weights=None, density=False): # pylint: di the range are ignored. The first element of the range must be less than or equal to the second. weights (Union[int, float, bool, list, tuple, Tensor], optional): An array - of weights, of the same shape as `a`. Each value in a only contributes + of weights, of the same shape as `a`. Each value in `a` only contributes its associated weight towards the bin count (instead of 1). If density is True, the weights are normalized, so that the integral of the density over the range remains 1. @@ -5446,7 +5452,7 @@ def ravel_multi_index(multi_index, dims, mode='clip', order='C'): Args: multi_index (tuple of array_like): A tuple of integer arrays, one array for each dimension. - dims (Union[int, tuple of ints]): The shape of array into which the indices from multi_index apply. + dims (Union[int, tuple of integers]): The shape of array into which the indices from multi_index apply. mode ({`wrap`, `clip`}): Specifies how out-of-bounds indices are handled. Default: `clip`. - `wrap`: wrap around @@ -5555,7 +5561,7 @@ def norm(x, ord=None, axis=None, keepdims=False): # pylint: disable=redefined-bu the 2-norm of ``x.ravel`` will be returned. ord (Union[None, 'fro', 'nuc', inf, -inf, int, float], optional): Order of the norm. inf means numpy’s inf object. The default is None. - axis (Union[None, int, 2-tuple of ints], optional): If `axis` is an integer, it + axis (Union[None, int, 2-tuple of integers], optional): If `axis` is an integer, it specifies the axis of `x` along which to compute the vector norms. If `axis` is a 2-tuple, it specifies the axes that hold 2-D matrices, and the matrix norms of these matrices are computed. If `axis` is None then either a vector norm (when x diff --git a/mindspore/numpy/utils_const.py b/mindspore/numpy/utils_const.py index dbb5edd91b3..bb2f51bad5b 100644 --- a/mindspore/numpy/utils_const.py +++ b/mindspore/numpy/utils_const.py @@ -25,10 +25,14 @@ from ..common import dtype as mstype from ..common import Tensor from .._c_expression import Tensor as Tensor_ from .._c_expression import typing +from .._checkparam import Validator as validator from .dtypes import promotion_rule, dtype_tuple, all_types, dtype_map, rule_for_trigonometric +_check_axis_type = constexpr(validator.check_axis_type) + + @constexpr def _check_shape(shape): """check the shape param to match the numpy style""" @@ -303,27 +307,6 @@ def _check_is_int(dtype): return isinstance(dtype, typing.Int) -@constexpr -def _check_axis_type(axis, type_int=True, type_tuple=True, type_list=True): - """Check axis argument type.""" - if type_int and isinstance(axis, int): - return True - if (type_tuple and isinstance(axis, tuple)) or (type_list and isinstance(axis, list)): - for ax in axis: - if not isinstance(ax, int): - raise TypeError(f"Each axis should be integer, but got {type(ax)} in {axis}.") - return True - - type_str = "" - if type_int: - type_str += "int, " - if type_tuple: - type_str += "tuple, " - if type_list: - type_str += "list, " - raise TypeError(f"Axis should be {type_str}but got {type(axis)}.") - - @constexpr def _canonicalize_axis(axis, ndim): """