mindspore.Tensor

class mindspore.Tensor(input_data=None, dtype=None, shape=None, init=None, internal=False)[source]

Tensor is a data structure that stores an n-dimensional array.

Parameters
  • input_data (Union[Tensor, float, int, bool, tuple, list, numpy.ndarray]) – The data to be stored. It can be another Tensor, Python number or NumPy ndarray. Default: None.

  • dtype (mindspore.dtype) – Used to indicate the data type of the output Tensor. The argument should be defined in mindspore.dtype. If it is None, the data type of the output Tensor will be the same as the input_data. Default: None.

  • shape (Union[tuple, list, int]) – Used to indicate the shape of the output Tensor. The argument should be a list of integers, a tuple of integers or an integer. If input_data is available, shape doesn’t need to be set. Default: None.

  • init (Initializer) – The information of init data. ‘init’ is used for delayed initialization in parallel mode. Usually, it is not recommended to use ‘init’ interface to initialize Tensor in the other conditions. If ‘init’ interface is used to initialize Tensor, the Tensor.init_data API needs to be called to convert Tensor to the actual data. Default: None.

  • internal (bool) – Whether it is created by the framework. ‘True’ means that the tensor is created by framework. ‘False’ means that the tensor is created by user. Default: False

Outputs:

Tensor.

Examples

>>> import numpy as np
>>> import mindspore as ms
>>> from mindspore import Tensor
>>> from mindspore.common.initializer import One
>>> # initialize a tensor with numpy.ndarray
>>> t1 = Tensor(np.zeros([1, 2, 3]), ms.float32)
>>> print(t1)
[[[0. 0. 0.]
[0. 0. 0.]]]
>>> print(type(t1))
<class 'mindspore.common.tensor.Tensor'>
>>> print(t1.shape)
(1, 2, 3)
>>> print(t1.dtype)
Float32
>>>
>>> # initialize a tensor with a float scalar
>>> t2 = Tensor(0.1)
>>> print(t2)
0.1
>>> print(type(t2))
<class 'mindspore.common.tensor.Tensor'>
>>> print(t2.shape)
()
>>> print(t2.dtype)
Float32
>>>
>>> # initialize a tensor with a tuple
>>> t3 = Tensor((1, 2))
>>> print(t3)
[1 2]
>>> print(type(t3))
<class 'mindspore.common.tensor.Tensor'>
>>> print(t3.shape)
(2,)
>>> print(t3.dtype)
Int64
...
>>> # initialize a tensor with init
>>> t4 = Tensor(shape = (1, 3), dtype=ms.float32, init=One())
>>> print(t4)
[[1. 1. 1.]]
>>> print(type(t4))
<class 'mindspore.common.tensor.Tensor'>
>>> print(t4.shape)
(1, 3)
>>> print(t4.dtype)
Float32
property T

Return the transposed tensor.

abs()[source]

Return absolute value element-wisely.

Returns

Tensor.

Supported Platforms:

Ascend GPU CPU

Examples

>>> from mindspore import Tensor
>>> a = Tensor([1.1, -2.1]).astype("float32")
>>> output = a.abs()
>>> print(output)
[1.1 2.1]
all(axis=(), keep_dims=False)[source]

Check all tensor elements along a given axis evaluate to True.

Parameters
  • axis (Union[None, int, tuple(int)]) – Dimensions of reduction. When the axis is None or empty tuple, reduce all dimensions. When the axis is int or tuple(int), if the dimension of Tensor is dim, the value range is [-dim, dim). Default: ().

  • keep_dims (bool) – Whether to keep the reduced dimensions. Default: False.

Returns

Tensor, if all tensor elements along the given axis evaluate to True, its value is True, otherwise its value is False. If the axis is None or empty tuple, reduce all dimensions.

Supported Platforms:

Ascend GPU CPU

See also

mindspore.Tensor.any(): Check any tensor element along a given axis evaluate to True.

Examples

>>> from mindspore import Tensor
>>> a = Tensor([True, True, False])
>>> output = a.all()
>>> print(output)
False
amax(axis=(), keep_dims=False)[source]

Reduces a dimension of a tensor by the maximum value in the dimension, by default. And also can reduce a dimension of x along the axis. Determine whether the dimensions of the output and input are the same by controlling keep_dims.

Parameters
  • axis (Union[None, int, tuple(int), list(int)]) – Dimensions of reduction. When the axis is None or empty tuple, reduce all dimensions. When the axis is int, tuple(int) or list(int), if the dimension of Tensor is dim, the value range is [-dim, dim). Default: ().

  • keep_dims (bool) – Whether to keep the reduced dimensions. Default: False.

Returns

Tensor, has the same data type as input tensor.

  • If axis is () and keep_dims is False, output a 0-dimensional Tensor representing the maximum value of all elements in the input Tensor.

  • If axis is int, takes the value 1, and keep_dims is False, the shape of the output is \((x_0, x_2, ..., x_R)\) .

  • If axis is tuple(int) or list(int), the value is (1, 2), and keep_dims is False, the shape of the output Tensor is: math:(x_0, x_3, … , x_R) .

Raises
  • TypeError – If axis is not one of the following: int, tuple or list.

  • TypeError – If keep_dims is not a bool.

  • ValueError – If axis is out of range.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> input_x = Tensor(np.array([1, 2, 3], dtype=np.float32))
>>> output = input_x.amax()
>>> print(output)
3.0
amin(axis=(), keep_dims=False)[source]

Reduces a dimension of a tensor by the minimum value in the dimension, by default. And also can reduce a dimension of x along the axis. Determine whether the dimensions of the output and input are the same by controlling keep_dims.

Parameters
  • axis (Union[None, int, tuple(int), list(int)]) – Dimensions of reduction. When the axis is None or empty tuple, reduce all dimensions. When the axis is int, tuple(int) or list(int), if the dimension of Tensor is dim, the value range is [-dim, dim). Default: ().

  • keep_dims (bool) – Whether to keep the reduced dimensions. Default: False.

Returns

Tensor, has the same data type as input tensor.

  • If axis is () and keep_dims is False, output a 0-dimensional Tensor representing the minimum value of all elements in the input Tensor.

  • If axis is int, takes the value 1, and keep_dims is False, the shape of the output is \((x_0, x_2, ..., x_R)\) .

  • If axis is tuple(int) or list(int), the value is (1, 2), and keep_dims is False, the shape of the output Tensor is: math:(x_0, x_3, … , x_R) .

Raises
  • TypeError – If axis is not one of the following: int, tuple or list.

  • TypeError – If keep_dims is not a bool.

  • ValueError – If axis is out of range.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> input_x = Tensor(np.array([1, 2, 3], dtype=np.float32))
>>> output = input_x.amin()
>>> print(output)
1.0
any(axis=(), keep_dims=False)[source]

Check any tensor element along a given axis evaluate to True.

Parameters
  • axis (Union[None, int, tuple(int)]) – Dimensions of reduction. When the axis is None or empty tuple, reduce all dimensions. When the axis is int or tuple(int), if the dimension of Tensor is dim, the value range is [-dim, dim). Default: ().

  • keep_dims (bool) – Whether to keep the reduced dimensions. Default: False.

Returns

Tensor, if any tensor element along the given axis evaluates to True, its value is True, otherwise its value is False. If the axis is None or empty tuple, reduce all dimensions.

Supported Platforms:

Ascend GPU CPU

See also

mindspore.Tensor.all(): Check all tensor elements along a given axis evaluate to True.

Examples

>>> from mindspore import Tensor
>>> a = Tensor([True, True, False])
>>> output = a.any()
>>> print(output)
True
argmax(axis=None)[source]

Return the indices of the maximum values along an axis.

Parameters

axis (int, optional) – By default, the index is into the flattened tensor, otherwise along the specified axis. Default: None.

Returns

Tensor, indices into the input tensor. It has the same shape as self.shape with the dimension along axis removed.

Raises

ValueError – If the axis is out of range.

Supported Platforms:

Ascend GPU CPU

See also

mindspore.Tensor.argmin(): Return the indices of the minimum values along an axis.

mindspore.Tensor.min(): Return the minimum of a tensor or minimum along an axis.

mindspore.Tensor.max(): Return the maximum of a tensor or maximum along an axis.

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> a = Tensor(np.arange(10, 16).reshape(2, 3).astype("float32"))
>>> print(a.argmax())
5
argmin(axis=None)[source]

Return the indices of the minimum values along an axis.

Parameters

axis (int, optional) – By default, the index is into the flattened tensor, otherwise along the specified axis. Default: None.

Returns

Tensor, indices into the input tensor. It has the same shape as self.shape with the dimension along axis removed.

Raises

ValueError – If the axis is out of range.

Supported Platforms:

Ascend GPU CPU

See also

mindspore.Tensor.argmax(): Return the indices of the maximum values along an axis.

mindspore.Tensor.min(): Return the minimum of a tensor or minimum along an axis.

mindspore.Tensor.max(): Return the maximum of a tensor or maximum along an axis.

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> a = Tensor(np.arange(10, 16).reshape(2, 3).astype("float32"))
>>> print(a.argmin())
0
asnumpy()[source]

Convert tensor to numpy array. Returns self tensor as a NumPy ndarray. This tensor and the returned ndarray share the same underlying storage. Changes to self tensor will be reflected in the ndarray.

Returns

A numpy ndarray which shares the same underlying storage with the tensor.

Examples

>>> from mindspore import Tensor
>>> import numpy as np
>>> x = Tensor(np.array([1, 2], dtype=np.float32))
>>> y = x.asnumpy()
>>> y[0] = 11
>>> print(x)
[11.  2.]
>>> print(y)
[11.  2.]
assign_value(value)[source]

Assign another tensor value to this tensor.

Parameters

value (Tensor) – Tensor for assignment.

Returns

Tensor, Tensor that’s been assigned.

astype(dtype, copy=True)[source]

Return a copy of the tensor, cast to a specified type.

Parameters
  • dtype (Union[mindspore.dtype, numpy.dtype, str]) – Designated tensor dtype, can be in format of mindspore.dtype.float32 or numpy.float32 or float32.

  • copy (bool, optional) – By default, astype always returns a newly allocated tensor. If this is set to false, the input tensor is returned instead of a copy. Default: True.

Returns

Tensor, with the designated dtype.

Raises

TypeError – If the specified dtype cannot be understood.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> x = Tensor(np.ones((1,2,2,1), dtype=np.float32))
>>> x = x.astype("int32")
>>> print(x.dtype)
Int32
atan2(y)[source]

Returns arctangent of x/y element-wise.

x refer to self tensor.

It returns \(\theta\ \in\ [-\pi, \pi]\) such that \(x = r*\sin(\theta), y = r*\cos(\theta)\), where \(r = \sqrt{x^2 + y^2}\).

Args of x and y comply with the implicit type conversion rules to make the data types consistent. If they have different data types, the lower precision data type will be converted to the relatively highest precision data type.

Parameters

y (Tensor) – The input tensor. It has the same shape with x.

Returns

Tensor, the shape is the same as the one after broadcasting,and the data type is same as x.

Raises
  • TypeError – If x or y is not a Tensor.

  • RuntimeError – If the data type of x and y conversion of Parameter is required when data type conversion of Parameter is not supported.

Supported Platforms:

Ascend CPU GPU

Examples

>>> x = Tensor(np.array([0, 1]), mindspore.float32)
>>> y = Tensor(np.array([1, 1]), mindspore.float32)
>>> output = x.atan2(y)
>>> print(output)
[0.        0.7853982]
bernoulli(p=0.5, seed=- 1)[source]

Randomly set the elements of output to 0 or 1 with the probability of P which follows the Bernoulli distribution.

\[out_{i} \sim Bernoulli(p_{i})\]
Parameters
  • p (Union[Tensor, float], optional) – The shape of p need to be broadcast. Data type must be float32 or float64. The elements of p represent the probability of setting 1 for the corresponding broadcast position of the current Tensor. The value of p must be in the range [0, 1]. Default: 0.5.

  • seed (int, optional) – The seed value for random generating. The value of seed must be -1 or a positive integer. Default: -1, which means using the current timestamp.

Returns

output (Tensor), with the same shape and type as x.

Raises
  • TypeError – If dtype of Tensor is not one of: int8, uint8, int16, int32, int64, bool, float32, float64.

  • TypeError – If dtype of p is not one of: float32, float64.

  • TypeError – If dtype of seed is not int.

  • ValueError – If p is not in range [0, 1].

  • ValueError – If seed is less than 0 and not -1.

Supported Platforms:

GPU

Examples

>>> import mindspore
>>> import numpy as np
>>> from mindspore import Tensor
>>> input_x = Tensor(np.array([1, 2, 3]), mindspore.int8)
>>> output = input_x.bernoulli(p=1.0)
>>> print(output)
[1 1 1]
>>> input_p = Tensor(np.array([0.0, 1.0, 1.0]), mindspore.float32)
>>> output = input_x.bernoulli(input_p)
>>> print(output)
[0 1 1]
bitwise_and(x)[source]

Returns bitwise and of two tensors element-wise.

Refer to mindspore.ops.bitwise_and() for more detail.

Parameters

x (Tensor) – The input tensor with int16, int32 or uint16 data type.

Returns

Tensor, has the same type as the x.

Supported Platforms:

Ascend CPU

Examples

>>> from mindspore import Tensor
>>> import numpy as np
>>> a = Tensor(np.array([0, 0, 1, -1, 1, 1, 1]), mindspore.int16)
>>> b = Tensor(np.array([0, 1, 1, -1, -1, 2, 3]), mindspore.int16)
>>> output = a.bitwise_and(b)
>>> print(output)
[ 0  0  1 -1  1  0  1]
bitwise_or(x)[source]

Returns bitwise or of two tensors element-wise.

Refer to mindspore.ops.bitwise_or() for more detail.

Parameters

x (Tensor) – The input tensor with int16, int32 or uint16 data type.

Returns

Tensor, has the same type as the x.

Supported Platforms:

Ascend CPU

Examples

>>> from mindspore import Tensor
>>> import numpy as np
>>> a = Tensor(np.array([0, 0, 1, -1, 1, 1, 1]), mindspore.int16)
>>> b = Tensor(np.array([0, 1, 1, -1, -1, 2, 3]), mindspore.int16)
>>> output = a.bitwise_or(b)
>>> print(output)
[ 0  1  1 -1 -1  3  3]
bitwise_xor(x)[source]

Returns bitwise xor of two tensors element-wise.

Refer to mindspore.ops.bitwise_xor() for more detail.

Parameters

x (Tensor) – The input tensor with int16, int32 or uint16 data type.

Returns

Tensor, has the same type as the x.

Supported Platforms:

Ascend CPU

Examples

>>> from mindspore import Tensor
>>> import numpy as np
>>> a = Tensor(np.array([0, 0, 1, -1, 1, 1, 1]), mindspore.int16)
>>> b = Tensor(np.array([0, 1, 1, -1, -1, 2, 3]), mindspore.int16)
>>> output = a.bitwise_xor(b)
>>> print(output)
[ 0  1  0  0 -2  3  2]
broadcast_to(shape)[source]

Broadcasts input tensor to a given shape.

Refer to mindspore.ops.broadcast_to() for more detail.

Parameters

shape (tuple) – The target shape to broadcast. Can be fully specified, or have -1 in one position where it will be substituted by the input tensor’s shape in that position, see example.

Returns

Tensor, with the given shape and the same data type as self.

Raises
  • TypeError – If shape is not a tuple.

  • ValueError – If the target and input shapes are incompatible, or if a - 1 in the target shape is in an invalid location.

Supported Platforms:

Ascend GPU CPU

Examples

>>> from mindspore import Tensor
>>> from mindspore import dtype as mstype
>>> shape = (2, 3)
>>> x = Tensor(np.array([1, 2, 3]).astype(np.float32))
>>> output = x.broadcast_to(shape)
>>> print(output)
[[1. 2. 3.]
 [1. 2. 3.]]
>>> shape = (-1, 2)
>>> x = Tensor(np.array([[1], [2]]).astype(np.float32))
>>> output = x.broadcast_to(shape)
>>> print(output)
[[1. 1.]
 [2. 2.]]
ceil()[source]

Rounds a tensor up to the closest integer element-wise.

Returns

Tensor.

Raises

TypeError – If dtype of self tensor is not float16 or float32.

Supported Platforms:

Ascend GPU CPU

Examples

>>> from mindspore import Tensor
>>> a = Tensor([1.1, 2.5, -1.5]).astype("float32")
>>> output = a.ceil()
>>> print(output)
[ 2.  3. -1.]
choose(choices, mode='clip')[source]

Construct a tensor from an index tensor and a list of tensors to choose from.

Parameters
  • choices (Union[tuple, list, Tensor]) – Choice tensors. The input tensor and all of the choices must be broadcasted to the same shape. If choices is itself a tensor, then its outermost dimension (i.e., the one corresponding to choices.shape[0]) is taken as defining the “sequence”.

  • mode ('raise', 'wrap', 'clip', optional) –

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

    ’raise’ – Raises an error;

    ’wrap’ – Wraps around;

    ’clip’ – Clips to the range. ‘clip’ mode means that values greater than n-1 are mapped to n-1. Note that this disables indexing with negative numbers.

    Default: ‘clip’.

Returns

Tensor, the merged result.

Supported Platforms:

Ascend GPU CPU

Raises

ValueError – If the input tensor and any of the choices cannot be broadcast.

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> choices = [[0, 1, 2, 3], [10, 11, 12, 13], [20, 21, 22, 23], [30, 31, 32, 33]]
>>> x = Tensor(np.array([2, 3, 1, 0]))
>>> print(x.choose(choices))
[20 31 12  3]
clip(xmin, xmax, dtype=None)[source]

Clips (limits) the values in a Tensor.

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

Note

Currently, clip with xmin=nan or xmax=nan is not supported.

Parameters
  • xmin (Tensor, scalar, None) – Minimum value. If None, clipping is not performed on the lower interval edge. Not more than one of xmin and xmax may be None.

  • xmax (Tensor, scalar, None) – Maximum value. If None, clipping is not performed on the upper interval edge. Not more than one of xmin and xmax may be None. If xmin or xmax are tensors, then xmin, xmax and the given tensor will be broadcasted to match their shapes.

  • dtype (mindspore.dtype, optional) – Overrides the dtype of the output Tensor. Default is None.

Returns

Tensor, a tensor with the elements of the input tensor, but where values < xmin are replaced with xmin, and those > xmax with xmax.

Raises
  • TypeError – If inputs have types not specified above.

  • ValueError – If the shapes of x1 and x2 cannot broadcast, or both xmin and xmax are None.

Supported Platforms:

Ascend GPU CPU

Examples

>>> from mindspore import Tensor
>>> x = Tensor([1, 2, 3, -4, 0, 3, 2, 0]).astype("float32")
>>> y = x.clip(0, 2)
>>> print(y)
[1. 2. 2. 0. 0. 2. 2. 0.]
>>> t = Tensor([1, 1, 1, 1, 1, 1, 1, 1])
>>> y = x.clip(t, 2)
>>> print(y)
[1. 2. 2. 1. 1. 2. 2. 1.]
col2im(output_size, kernel_size, dilation, padding_value, stride)[source]

Combines an array of sliding local blocks into a large containing tensor.

Parameters
  • output_size (Tensor) – 1D tensor with 2 elements of data type int.

  • kernel_size (Union[int, tuple[int], list[int]]) – The size of the kernel, should be two int for height and width. If type is int, it means that height equal with width. Must be specified.

  • dilation (Union[int, tuple[int], list[int]]) – The size of the dilation, should be two int for height and width. If type is int, it means that height equal with width. Default: 1.

  • padding_value (Union[int, tuple[int], list[int]]) – The size of the padding, should be two int for height and width. If type is int, it means that height equal with width. Default: 1.

  • stride (Union[int, tuple[int], list[int]]) – The size of the stride, should be two int for height and width. If type is int, it means that height equal with width. Default: 0.

Returns

A 4D Tensor, with same type as input ‘x’.

Raises
  • TypeError – If kernel_size, dilation, padding_value, stride data type is not in Union[int, tuple[int], list[int]].

  • ValueError – If kernel_size, dilation, stride value is less than zero or elements number more than 2.

  • ValueError – If padding_value value is not greater than zero or elements number more than 2.

Supported Platforms:

GPU

Examples

>>> x = Tensor(input_data=np.random.rand(16, 16, 4, 25), dtype=mstype.float32)
>>> output_size = Tensor(input_data=[8, 8], dtype=mstype.int32)
>>> y = x.col2im(output_size, kernel_size=[2, 2], dilation=[2, 2], padding_value=[2, 2], stride=[2, 2])
>>> print(y.shape)
(16, 16, 8, 8)
copy()[source]

Return a copy of the tensor.

Note

The current implementation does not support order argument.

Returns

Copied tensor.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> a = Tensor(np.ones((3,3)).astype("float32"))
>>> output = a.copy()
>>> print(output)
[[1. 1. 1.]
[1. 1. 1.]
[1. 1. 1.]]
cosh()[source]

Computes hyperbolic cosine of x element-wise.

\[out_i = \cosh(x_i)\]
Returns

Tensor, has the same shape as x.

Supported Platforms:

Ascend GPU CPU

Examples

>>> from mindspore import Tensor
>>> a = Tensor(np.array([0.24, 0.83, 0.31, 0.09]), mindspore.float32)
>>> output = a.cosh()
>>> print(output)
[1.0289385 1.364684 1.048436 1.0040528]
cummax(axis)[source]

Returns a tuple (values,indices) where ‘values’ is the cumulative maximum value of self Tensor along the dimension axis, and indices is the index location of each maximum value.

\[\begin{split}\begin{array}{ll} \\ y{i} = max(x{1}, x{2}, ... , x{i}) \end{array}\end{split}\]
Parameters

axis (int) – The dimension to do the operation over. The value of axis must be in the range [-x.ndim, x.ndim - 1].

Returns

tuple [Tensor], tuple of 2 Tensors, containing the cumulative maximum of elements and the index, The shape of each output tensor is the same as self Tensor.

Raises
  • TypeError – If axis is not an int.

  • ValueError – If axis is out the range of [-x.ndim, x.ndim - 1].

Supported Platforms:

GPU CPU

Examples

>>> import mindspore
>>> import numpy as np
>>> from mindspore import Tensor
>>> import mindspore.ops as ops
>>> x = Tensor(np.array([[3, 4, 6, 10], [1, 6, 7, 9], [4, 3, 8, 7], [1, 3, 7, 9]]).astype(np.float32))
>>> output = x.cummax(axis=0)
>>> print(output[0])
[[ 3.  4.  6. 10.]
 [ 3.  6.  7. 10.]
 [ 4.  6.  8. 10.]
 [ 4.  6.  8. 10.]]
>>> print(output[1])
[[0 0 0 0]
 [0 1 1 0]
 [2 1 2 0]
 [2 1 2 0]]
cummin(axis)[source]

Returns a tuple (values,indices) where ‘values’ is the cumulative minimum value of self Tensor along the dimension axis, and indices is the index location of each minimum value.

\[\begin{split}\begin{array}{ll} \\ y{i} = min(x{1}, x{2}, ... , x{i}) \end{array}\end{split}\]
Parameters

axis (int) – The dimension to do the operation over. The value of axis must be in the range [-x.ndim, x.ndim - 1].

Returns

tuple [Tensor], tuple of 2 Tensors, containing the cumulative minimum of elements and the index, The shape of each output tensor is the same as self Tensor.

Raises
  • TypeError – If axis is not an int.

  • ValueError – If axis is out the range of [-x.ndim, x.ndim - 1].

Supported Platforms:

Ascend GPU CPU

Examples

>>> from mindspore import Tensor, ops
>>> import mindspore
>>> a = Tensor([-0.2284, -0.6628,  0.0975,  0.2680, -1.3298, -0.4220], mindspore.float32)
>>> output = a.cummin(axis=0)
>>> print(output[0])
[-0.2284 -0.6628 -0.6628 -0.6628 -1.3298 -1.3298]
>>> print(output[1])
[0 1 1 1 4 4]
cumsum(axis=None, dtype=None)[source]

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

Note

If self.dtype is int8, int16 or bool, the result dtype will be elevated to int32, int64 is not supported.

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

  • dtype (mindspore.dtype, optional) – If not specified, stay the same as original tensor, unless it has an integer dtype with a precision less than float32. In that case, float32 is used. Default: None.

Raises

ValueError – If the axis is out of range.

Returns

Tensor.

Supported Platforms:

Ascend GPU CPU

See also

mindspore.Tensor.sum(): Return sum of tensor elements over a given axis.

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> a = Tensor(np.ones((3,3)).astype("float32"))
>>> output = a.cumsum(axis=0)
>>> print(output)
[[1. 1. 1.]
[2. 2. 2.]
[3. 3. 3.]]
diag()[source]

Constructs a diagonal tensor with a given diagonal values.

Assume self tensor has dimensions \([D_1,... D_k]\), the output is a tensor of rank 2k with dimensions \([D_1,..., D_k, D_1,..., D_k]\) where: \(output[i_1,..., i_k, i_1,..., i_k] = self[i_1,..., i_k]\) and 0 everywhere else.

Returns

Tensor, has the same dtype as self tensor.

Raises

ValueError – If rank of self tensor is less than 1.

Supported Platforms:

Ascend GPU

Examples

>>> from mindspore import Tensor
>>> x = Tensor([1, 2, 3, 4]).astype('int32')
>>> output = x.diag()
>>> print(output)
[[1, 0, 0, 0]
 [0, 2, 0, 0]
 [0, 0, 3, 0]
 [0, 0, 0, 4]]
diagonal(offset=0, axis1=0, axis2=1)[source]

Return specified diagonals.

Parameters
  • offset (int, optional) – Offset of the diagonal from the main diagonal. Can be positive or negative. Defaults to main diagonal.

  • axis1 (int, optional) – Axis to be used as the first axis of the 2-D sub-arrays from which the diagonals should be taken. Defaults to first axis (0).

  • axis2 (int, optional) – Axis to be used as the second axis of the 2-D sub-arrays from which the diagonals should be taken. Defaults to second axis.

Returns

Tensor, if Tensor is 2-D, return a 1-D Tensor containing the diagonal.

Raises

ValueError – If the input tensor has less than two dimensions.

Supported Platforms:

Ascend GPU CPU

See also

mindspore.Tensor.trace(): Return the sum along diagonals of the tensor.

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> a = Tensor(np.arange(4).reshape(2, 2))
>>> print(a)
[[0 1]
[2 3]]
>>> output = a.diagonal()
>>> print(output)
[0 3]
property dtype

Return the dtype of the tensor (mindspore.dtype).

erf()[source]

Computes the Gauss error function of self tensor element-wise. Refer to mindspore.ops.erf() for more details.

Returns

Tensor, has the same shap dtype as the self Tensor.

Raises

TypeError – If dtype of self tensor is not float16 or float32.

Supported Platforms:

Ascend GPU CPU

Examples

>>> x = Tensor(np.array([-1, 0, 1, 2, 3]), mindspore.float32)
>>> output = x.erf()
>>> print(output)
[-0.8427168   0.          0.8427168   0.99530876  0.99997765]
erfc()[source]

Computes the complementary error function of self tensor element-wise. Refer to mindspore.ops.erfc() for more details.

Returns

Tensor, has the same shap dtype as the self tensor.

Raises

TypeError – If dtype of self tensor is not float16 or float32.

Supported Platforms:

Ascend GPU CPU

Examples

>>> x = Tensor(np.array([-1, 0, 1, 2, 3]), mindspore.float32)
>>> output = x.erfc()
>>> print(output)
[1.8427168e+00 1.0000000e+00 1.5728319e-01 4.6912432e-03 2.2351742e-05]
expand_as(x)[source]

Expand the dimension of target tensor to the dimension of input tensor.

Parameters

x (Tensor) – The input tensor. The shape of the input tensor must obey the broadcasting rule.

Returns

Tensor, has the same dimension as input tensor.

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> from mindspore import dtype as mstype
>>> x = Tensor([1, 2, 3], dtype=mstype.float32)
>>> y = Tensor(np.ones((2, 3)), dtype=mstype.float32)
>>> output = x.expand_as(y)
>>> print(output)
[[1. 2. 3.]
[1. 2. 3.]]
expand_dims(axis)[source]

Insert a dimension of shape 1 at the specified axis of Tensor

Parameters

axis (int) – the axis at which to insert the singleton dimension.

Returns

Tensor, with inserted dimension of length 1.

Raises
  • TypeError – If axis is not an int.

  • ValueError – If axis is not in range [-self.ndim - 1, self.ndim + 1).

Supported Platforms:

Ascend GPU CPU

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> x = Tensor(np.ones((2,2), dtype=np.float32))
>>> print(x)
[[1. 1.]
[1. 1.]]
>>> print(x.shape)
(2, 2)
>>> y = x.expand_dims(axis=0)
>>> print(y)
[[[1. 1.]
[1. 1.]]]
>>> print(y.shape)
(1, 2, 2)
fill(value)[source]

Fill the tensor with a scalar value.

Note

Unlike Numpy, tensor.fill() will always return a new tensor, instead of filling the original tensor.

Parameters

value (Union[None, int, float, bool]) – All elements of a will be assigned this value.

Returns

Tensor, with the original dtype and shape.

Raises

TypeError – If input arguments have types not specified above.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> a = Tensor(np.arange(4).reshape((2,2)).astype('float32'))
>>> print(a.fill(1.0))
[[1. 1.]
[1. 1.]]
flatten(order='C')[source]

Return a copy of the tensor collapsed into one dimension.

Parameters

order (str, optional) – Can choose between ‘C’ and ‘F’. ‘C’ means to flatten in row-major (C-style) order. ‘F’ means to flatten in column-major (Fortran-style) order. Default: ‘C’.

Returns

Tensor, has the same data type as input.

Supported Platforms:

Ascend GPU CPU

Raises
  • TypeError – If order is not string type.

  • ValueError – If order is string type, but not ‘C’ or ‘F’.

See also

mindspore.Tensor.reshape(): Give a new shape to a tensor without changing its data.

mindspore.Tensor.ravel(): Return a contiguous flattened tensor.

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> x = Tensor(np.ones((2,3,4), dtype=np.float32))
>>> output = x.flatten()
>>> print(output.shape)
(24,)
flush_from_cache()[source]

Flush cache data to host if tensor is cache enable.

Examples

>>> from mindspore import Tensor
>>> import numpy as np
>>> x = Tensor(np.array([1, 2], dtype=np.float32))
>>> y = x.flush_from_cache()
>>> print(y)
None
static from_numpy(array)[source]

Convert numpy array to Tensor without copy data.

Parameters

array (numpy.array) – The input array.

Returns

Tensor, has the same data type as input array.

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> x = np.array([1, 2])
>>> output = Tensor.from_numpy(x)
>>> print(output)
[1 2]
gather(input_indices, axis)[source]

Returns the slice of the input tensor corresponding to the elements of input_indices on the specified axis. The shape of input tensor is \((x_1, x_2, ..., x_R)\). For convenience, define it as input_params, the variable input_params refers to input tensor.

Note

  1. The value of input_indices must be in the range of [0, input_param.shape[axis]), the result is undefined out of range.

  2. The data type of input_params cannot be bool_ on Ascend platform currently.

Parameters
  • input_indices (Tensor) – Index tensor to be sliced, the shape of tensor is \((y_1, y_2, ..., y_S)\). Specifies the indices of elements of the original Tensor. The data type can be int32 or int64.

  • axis (int) – Specifies the dimension index to gather indices.

Returns

Tensor, the shape of tensor is \(input\_params.shape[:axis] + input\_indices.shape + input\_params.shape[axis + 1:]\).

Raises
  • TypeError – If axis is not an int.

  • TypeError – If input_indices is not a tensor of type int.

Supported Platforms:

Ascend GPU CPU

Examples

>>> # case1: input_indices is a Tensor with shape (5, ).
>>> input_params = Tensor(np.array([1, 2, 3, 4, 5, 6, 7]), mindspore.float32)
>>> input_indices = Tensor(np.array([0, 2, 4, 2, 6]), mindspore.int32)
>>> axis = 0
>>> output = input_params.gather(input_indices, axis)
>>> print(output)
[1. 3. 5. 3. 7.]
>>> # case2: input_indices is a Tensor with shape (2, 2). When the input_params has one dimension,
>>> # the output shape is equal to the input_indices shape.
>>> input_indices = Tensor(np.array([[0, 2], [2, 6]]), mindspore.int32)
>>> axis = 0
>>> output = input_params.gather(input_indices, axis)
>>> print(output)
[[ 1. 3.]
 [ 3. 7.]]
>>> # case3: input_indices is a Tensor with shape (2, ) and
>>> # input_params is a Tensor with shape (3, 4) and axis is 0.
>>> input_params = Tensor(np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]), mindspore.float32)
>>> input_indices = Tensor(np.array([0, 2]), mindspore.int32)
>>> axis = 0
>>> output = input_params.gather(input_indices, axis)
>>> print(output)
[[1.  2.  3.  4.]
 [9. 10. 11. 12.]]
>>> # case4: input_indices is a Tensor with shape (2, ) and
>>> # input_params is a Tensor with shape (3, 4) and axis is 1.
>>> input_params = Tensor(np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]), mindspore.float32)
>>> input_indices = Tensor(np.array([0, 2]), mindspore.int32)
>>> axis = 1
>>> output = input_params.gather(input_indices, axis)
>>> print(output)
[[1.  3.]
 [5.  7.]
 [9. 11.]]
gather_elements(dim, index)[source]

Gathers elements along an axis specified by dim.

For a 3-D tensor, the output is:

output[i][j][k] = x[index[i][j][k]][j][k]  # if dim == 0

output[i][j][k] = x[i][index[i][j][k]][k]  # if dim == 1

output[i][j][k] = x[i][j][index[i][j][k]]  # if dim == 2

x and index have the same length of dimensions, and all dimensions except dim have the same size. If dim = i, x is an n-D tensor with shape \((z_0, z_1, ..., z_i, ..., z_{n-1})\), the index must be an n-D tensor with shape \((z_0, z_1, ..., y, ..., z_{n-1})\) where y>=1 and the output will have the same shape with index.

Parameters
  • dim (int) – The axis along which to index. It must be int32 or int64. The value range is [-self.ndim, self.ndim).

  • index (Tensor) – The indices of elements to gather. It can be one of the following data types: int32, int64. The value range of each index element is [-self.shape(dim), self.shape(dim)).

Returns

Tensor, has the same shape as index tensor, the shape of tensor is \((z_1, z_2, ..., z_{n-1})\), and has the same data type with self.dtype.

Raises
  • TypeError – If dtype of dim or index is neither int32 nor int64.

  • ValueError – If length of shape of self is not equal to length of shape of index.

  • ValueError – If the size of the dimension except dim is not equal between self and index.

  • ValueError – If the value of dim is not in the expected range.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import numpy as np
>>> import mindspore
>>> from mindspore import Tensor
>>> x = Tensor(np.array([[1, 2], [3, 4]]), mindspore.int32)
>>> index = Tensor(np.array([[0, 0], [1, 0]]), mindspore.int32)
>>> dim = 1
>>> output = x.gather_elements(dim, index)
>>> print(output)
[[1 1]
 [4 3]]
gather_nd(indices)[source]

Gathers slices from a input tensor by indices. Using given indices to gather slices from a input tensor with a specified shape. input tensor’s shape is \((N,*)\) where \(*\) means any number of additional dimensions. For convenience define it as input_x, the variable input_x refers to input tensor. indices is an K-dimensional integer tensor. Suppose that it is a (K-1)-dimensional tensor and each element of it defines a slice of input tensor:

\[output[(i_0, ..., i_{K-2})] = input\_x[indices[(i_0, ..., i_{K-2})]]\]

The last dimension of indices can not more than the rank of input tensor: \(indices.shape[-1] <= input\_x.rank\).

Parameters

indices (Tensor) – The index tensor that gets the collected elements, with int32 or int64 data type.

Returns

Tensor, has the same type as input tensor and the shape is \(indices\_shape[:-1] + input\_x\_shape[indices\_shape[-1]:]\).

Raises

ValueError – If length of shape of input tensor is less than the last dimension of indices.

Supported Platforms:

Ascend GPU CPU

Examples

>>> input_x = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]), mindspore.float32)
>>> indices = Tensor(np.array([[0, 0], [1, 1]]), mindspore.int32)
>>> output = input_x.gather_nd(indices)
>>> print(output)
[-0.1  0.5]
ger(x)[source]

Ger product of self and x. Calculate the outer product of two arrays. If self is a 1D Tensor of shape \((m,)\) and x is a 1D Tensor of shape \((n,)\), then output must be a Tensor of shape \((m, n)\).

Note

Currently Ascend does not support float64 data input.

Refer to mindspore.ops.ger() for more detail.

Parameters

x (Tensor) – input Tensor, with dtype of float16, float32 or float64.

Returns

Tensor, output matrix with the same dtype as inputs.With self shape \((m,)\) and x shape of \((n,)\), the output has shape \((m, n)\).

Supported Platforms:

Ascend GPU CPU

Examples

>>> x1 = Tensor([1., 2., 3., 4.], mindspore.float32)
>>> x2 = Tensor([1., 2., 3.], mindspore.float32)
>>> output = x1.ger(x2)
>>> print(output)
[[ 1.  2.  3.]
 [ 2.  4.  6.]
 [ 3.  6.  9.]
 [ 4.  8. 12.]]
hardshrink(lambd=0.5)[source]

Apply the Hard Shrink function for tensor. Calculates the output according to the input elements.

The formula is defined as follows:

\[\begin{split}\text{HardShrink}(x) = \begin{cases} x, & \text{ if } x > \lambda \\ x, & \text{ if } x < -\lambda \\ 0, & \text{ otherwise } \end{cases}\end{split}\]
Parameters

lambd (float) – The threshold \(\lambda\) defined by the Hard Shrink formula. Default: 0.5.

Returns

Tensor, has the same shape and data type as self.

Raises
  • TypeError – If lambd is not a float.

  • TypeError – If dtype of the input tensor is neither float16 nor float32.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import numpy as np
>>> import mindspore as ms
>>> from mindspore import Tensor
>>> x = Tensor(np.array([[0.5,  1,  2.0], [0.0533, 0.0776, -2.1233]]), ms.float32)
>>> print(x.hardshrink())
[[ 0.      1.      2.    ]
[ 0.      0.     -2.1233]]
property has_init

Whether tensor is initialized.

index_fill(dim, index, value)[source]

Fills the elements under the dim dimension of the self Tensor with the input value by selecting the indices in the order given in index.

Parameters
  • dim (Union[int, Tensor]) – Dimension along which to fill the input Tensor. Only supports an int number or a 0-dimensional Tensor, whose data type is int32 or int64.

  • index (Tensor) – Indices of the input Tensor to fill in. The dtype must be int32.

  • value (Union[bool, int, float, Tensor]) – Value to fill the returned Tensor. If value is a Tensor, it must be a 0-dimensional Tensor and has the same dtype as self Tensor. Otherwise, the value will be cast to a 0-dimensional Tensor with the same data type as self Tensor.

Outputs:

Tensor, has the same dtype and shape as self Tensor.

Raises
  • TypeError – If dim is neither int number nor Tensor.

  • TypeError – When dim is a Tensor and its dtype is not int32 or int64.

  • TypeError – If index is not a Tensor.

  • TypeError – If dtype of index is not int32.

  • TypeError – If value is not a bool, int, float, or Tensor.

  • TypeError – If dtype of self Tensor and value are not the same.

  • ValueError – When dim is a Tensor and its rank is not equal to 0.

  • ValueError – If the rank of index is greater than 1D.

  • ValueError – When value is a Tensor and its rank is not equal to 0.

  • RuntimeError – If the value of dim is out the range of [-self.ndim, self.ndim - 1].

  • RuntimeError – If the values of index are out the range of [-self.shape[dim], self.shape[dim] - 1].

Supported Platforms:

GPU

Examples

>>> import mindspore
>>> import mindspore.ops as ops
>>> from mindspore import Tensor
>>> x = Tensor(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]).astype(np.float32))
>>> index = Tensor([0, 2], mindspore.int32)
>>> value = Tensor(-2.0, mindspore.float32)
>>> y = x.index_fill(1, index, value)
>>> print(y)
[[-2. 2. -2.]
 [-2. 5. -2.]
 [-2. 8. -2.]]
init_data(slice_index=None, shape=None, opt_shard_group=None)[source]

Get the tensor format data of this Tensor.

Note

The init_data function can be called once for the same tensor.

Parameters
  • slice_index (int) – Slice index of a parameter’s slices. It is used when initialize a slice of a parameter, it guarantees that devices using the same slice can generate the same tensor. Default: None.

  • shape (list[int]) – Shape of the slice, it is used when initialize a slice of the parameter. Default: None.

  • opt_shard_group (str) – Optimizer shard group which is used in auto or semi auto parallel mode to get one shard of a parameter’s slice. Default: None.

Returns

Initialized Tensor.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore as ms
>>> from mindspore.common.initializer import initializer, Constant
>>> x = initializer(Constant(1), [2, 2], ms.float32)
>>> out = x.init_data()
>>> print(out)
[[1. 1.]
 [1. 1.]]
inplace_update(v, indices)[source]

Update some rows of a tensor with values of v according to the specified indices.

Note

indices refers to the left-most dimension.

Parameters
  • v (Tensor) – A tensor with the same type and same dimension size except the first dimension, which must be the same as the size of indices.

  • indices (Union[int, tuple]) – Indices into the left-most dimension determining which rows to be updated.

Returns

Tensor, with updated values.

Raises
  • TypeError – if indices is not int or tuple.

  • TypeError – if indices is tuple but any of its element is not int.

  • ValueError – the Tensor shape is different from that of v.

Supported Platforms:

Ascend CPU

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> import mindspore
>>> x = Tensor(np.array([[1, 2], [3, 4], [5, 6]]), mindspore.float32)
>>> v = Tensor(np.array([[0.1, 0.2], [0.3, 0.4]]), mindspore.float32)
>>> indices = (0, 1)
>>> output = x.inplace_update(v, indices)
>>> print(output)
[[0.1 0.2]
 [0.3 0.4]
 [5.  6. ]]
inv()[source]

Computes Reciprocal of this Tensor element-wise.

\[out_i = \frac{1}{x_{i} }\]
Returns

Tensor, has the same type and shape as self Tensor.

Raises

TypeError – If dtype of this Tensor is not one of float16, float32, int32.

Supported Platforms:

Ascend GPU CPU

Examples

>>> x = Tensor(np.array([0.25, 0.4, 0.31, 0.52]), mindspore.float32)
>>> output = x.inv()
>>> print(output)
[4.        2.5       3.2258065 1.923077 ]
invert()[source]

Flips all bits of this Tensor element-wise.

\[out_i = \sim x_{i}\]
Returns

Tensor, has the same shape as as self Tensor.

Raises

TypeError – If dtype of this Tensor is neither int16 nor uint16.

Supported Platforms:

Ascend GPU CPU

Examples

>>> x = Tensor(np.array([25, 4, 13, 9]), mindspore.int16)
>>> output = x.invert()
>>> print(output)
[-26 -5 -14 -10]
isclose(x2, rtol=1e-05, atol=1e-08, equal_nan=False)[source]

Returns a boolean Tensor where two Tensors are element-wise equal within a tolerance.

Parameters
  • x2 (Tensor) – Second Tensor to compare, with data type belongs to float32, float16, int32.

  • rtol (float, optional) – Relative tolerance. Default: 1e-05.

  • atol (float, optional) – Absolute tolerance. Default: 1e-08.

  • equal_nan (bool, optional) – If True, then two NaNs will be considered equal. Default: False.

Returns

A bool Tensor, with the shape as broadcasted result of the input Tensor and x2.

Raises
  • TypeError – If either of self Tensor and x2 is not Tensor.

  • TypeError – If either of self Tensor and x2 is not float16, float32 or int32.

  • TypeError – If either of atol and rtol is not float.

  • TypeError – If equal_nan is not bool.

  • TypeError – If the dtype of self Tensor is not same as the x2.

  • ValueError – If self Tensor and x2 can not be broadcast.

  • ValueError – If either of atol and rtol is less than zero.

Supported Platforms:

CPU

Examples

>>> input = Tensor(np.array([1.3, 2.1, 3.2, 4.1, 5.1]), mindspore.float16)
>>> other = Tensor(np.array([1.3, 3.3, 2.3, 3.1, 5.1]), mindspore.float16)
>>> output = input.isclose(other)
>>> print(output)
[ True False False False  True]
isfinite()[source]

Determines which elements are finite for each position.

Returns

Tensor, has the same shape of input, and the dtype is bool.

Raises

TypeError – If self Tensor is not Tensor.

Supported Platforms:

Ascend GPU CPU

Examples

>>> from mindspore import Tensor
>>> a = Tensor(np.array([np.log(-1), 1, np.log(0)]), mindspore.float32)
>>> output = a.isfinite()
>>> print(output)
[False True False]
item(index=None)[source]

Get the item at the specified index of the tensor.

Note

Tensor.item returns a Tensor scalar instead of a Python scalar.

Parameters

index (Union[None, int, tuple(int)]) – The index in Tensor. Default: None.

Returns

A Tensor scalar, dtype is the same with the original Tensor.

Raises

ValueError – If the length of the index is not equal to self.ndim.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> x = Tensor(np.array([[1,2,3],[4,5,6]], dtype=np.float32))
>>> x = x.item((0,1))
>>> print(x)
2.0
itemset(*args)[source]

Insert scalar into a tensor (scalar is cast to tensor’s dtype, if possible).

There must be at least 1 argument, and define the last argument as item. Then, tensor.itemset(*args) is equivalent to \(tensor[args] = item\).

Parameters

args (Union[(numbers.Number), (int/tuple(int), numbers.Number)]) – The arguments that specify the index and value. If args contain one argument (a scalar), it is only used in case tensor is of size 1. If args contain two arguments, the last argument is the value to be set and must be a scalar, the first argument specifies a single tensor element location. It is either an int or a tuple.

Returns

A new tensor that doesn’t affect the original tensor, with value set by \(tensor[args] = item\).

Raises
  • ValueError – If the length of the first argument is not equal to self.ndim.

  • IndexError – If only one argument is provided, and the original Tensor is not scalar.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> x = Tensor(np.array([[1,2,3],[4,5,6]], dtype=np.float32))
>>> print(x.itemset((0,1), 4))
[[1. 4. 3.]
[4. 5. 6.]]
>>> print(x)
[[1. 2. 3.]
[4. 5. 6.]]
property itemsize

Return the length of one tensor element in bytes.

lerp(end, weight)[source]

Does a linear interpolation of two tensors start and end based on a float or tensor weight.

If weight is a tensor, the shapes of two inputs need to be broadcast; If weight is a float, the shapes of end need to be broadcast.

Parameters
  • end (Tensor) – The tensor with the ending points. Data type must be float16 or float32.

  • weight (Union[float, Tensor]) – The weight for the interpolation formula. Must be a float or a scalar tensor with float16 or float32 data type.

Returns

Tensor, has the same type and shape as self tensor.

Raises
  • TypeError – If end is not a tensor.

  • TypeError – If weight is neither scalar(float) nor tensor.

  • TypeError – If dtype of end is neither float16 nor float32.

  • TypeError – If dtype of weight is neither float16 nor float32 when it is a tensor.

  • TypeError – If self tensor and end have different data types.

  • TypeError – If self tensor, end and weight have different data types when weight is a tensor.

  • ValueError – If end could not be broadcast to tensor with shape of self tensor.

  • ValueError – If weight could not be broadcast to tensor with shapes of end when it is a tensor.

Supported Platforms:

Ascend CPU

Examples

>>> start = Tensor(np.array([1., 2., 3., 4.]), mindspore.float32)
>>> end = Tensor(np.array([10., 10., 10., 10.]), mindspore.float32)
>>> output = start.lerp( end, 0.5)
>>> print(output)
[5.5 6. 6.5 7. ]
log1p()[source]

Returns the natural logarithm of one plus the input tensor element-wise.

x refer to self tensor.

\[out_i = {log_e}(x_i + 1)\]
Returns

Tensor, has the same shape as the x.

Raises
  • TypeError – If x is not a Tensor.

  • TypeError – If dtype of x is neither float16 nor float32.

Supported Platforms:

Ascend GPU CPU

Examples

>>> x = Tensor(np.array([1.0, 2.0, 4.0]), mindspore.float32)
>>> output = x.log1p()
>>> print(output)
[0.6931472 1.0986123 1.609438 ]
masked_fill(mask, value)[source]

Fills elements of self tensor with value where mask is True. The shapes of self tensor and mask need to be the same or broadcastable.

Parameters
  • mask (Tensor[bool]) – The boolean mask.

  • value (Union[float, Tensor]) – The value to fill in with, which dtype is the same as self.

Returns

Tensor, has the same type and shape as self.

Raises
  • TypeError – If mask is not a Tensor.

  • TypeError – If dtype of mask is not bool.

  • ValueError – If the shapes of self tensor and mask could not be broadcast.

  • TypeError – If dtype of self tensor or value is not one of float16, float32, int8, int32.

  • TypeError – If dtype of value is different from that of self.

  • TypeError – If value is neither float number nor Tensor.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> a = Tensor(np.arange(4)).astype('float32')
>>> print(a)
[0. 1. 2. 3.]
>>> mask = Tensor([False, False, True, True])
>>> print(a.masked_fill(mask, 0.0))
[0. 1. 0. 0.]
masked_select(mask)[source]

Returns a new 1-D Tensor which indexes the self tensor according to the boolean mask. The shapes of the mask tensor and the self tensor don’t need to match, but they must be broadcastable.

Parameters

mask (Tensor[bool]) – The boolean Tensor.

Returns

A 1-D Tensor, with the same type as self.

Raises

TypeError – If mask is not a bool Tensor.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> x = Tensor(np.array([1, 2, 3, 4]), mindspore.int64)
>>> mask = Tensor(np.array([1, 0, 1, 0]), mindspore.bool_)
>>> output = x.masked_select(mask)
>>> print(output)
[1 3]
max(axis=None, keepdims=False, initial=None, where=True)[source]

Return the maximum of a tensor or maximum along an axis.

Parameters
  • axis (Union[None, int, list, tuple of ints], optional) – 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, instead of a single axis or all the axes as before. Default: None.

  • 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. Default: False.

  • initial (scalar, optional) – The minimum value of an output element. Must be present to allow computation on empty slice. Default: None.

  • where (bool Tensor, optional) – A boolean tensor which is broadcasted to match the dimensions of array, and selects elements to include in the reduction. If non-default value is passed, initial must also be provided. Default: True.

Returns

Tensor or scalar, maximum of input tensor. If axis is None, the result is a scalar value. If axis is given, the result is a tensor of dimension self.ndim - 1.

Raises

TypeError – If arguments have types not specified above.

Supported Platforms:

Ascend GPU CPU

See also

mindspore.Tensor.argmin(): Return the indices of the minimum values along an axis.

mindspore.Tensor.argmax(): Return the indices of the maximum values along an axis.

mindspore.Tensor.min(): Return the minimum of a tensor or minimum along an axis.

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> a = Tensor(np.arange(4).reshape((2, 2)).astype('float32'))
>>> output = a.max()
>>> print(output)
3.0
mean(axis=(), keep_dims=False)[source]

Reduce a dimension of a tensor by averaging all elements in the dimension.

Parameters
  • axis (Union[None, int, tuple(int), list(int)]) – Dimensions of reduction. When the axis is None or empty tuple, reduce all dimensions. When the axis is int, tuple(int) or list(int), if the dimension of Tensor is dim, the value range is [-dim, dim). Default: ().

  • keep_dims (bool) – Whether to keep the reduced dimensions. Default: False.

Returns

Tensor, has the same data type as input tensor.

  • If axis is () and keep_dims is False, output a 0-dimensional Tensor representing the average of all elements in the input Tensor.

  • If axis is int, takes the value 1, and keep_dims is False, the shape of the output is \((x_0, x_2, ..., x_R)\) .

  • If axis is tuple(int) or list(int), the value is (1, 2), and keep_dims is False, the shape of the output Tensor is: math:(x_0, x_3, … , x_R) .

Raises
  • TypeError – If axis is not one of the following: int, tuple or list.

  • TypeError – If keep_dims is not a bool.

  • ValueError – If axis is out of range.

Supported Platforms:

Ascend GPU CPU

See also

mindspore.Tensor.std(): Compute the standard deviation along the specified axis.

mindspore.Tensor.var(): Compute the variance along the specified axis.

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> input_x = Tensor(np.array([1, 2, 3], dtype=np.float32))
>>> output = input_x.mean()
>>> print(output)
2.0
min(axis=None, keepdims=False, initial=None, where=True)[source]

Return the minimum of a tensor or minimum along an axis.

Parameters
  • axis (Union[None, int, list, tuple of ints], optional) – 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, instead of a single axis or all the axes as before. Default: None.

  • 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 tensor. Default: False.

  • initial (scalar, optional) – The maximum value of an output element. Must be present to allow computation on empty slice. Default: None.

  • where (bool Tensor, optional) – A boolean tensor which is broadcasted to match the dimensions of tensor, and selects elements to include in the reduction. If non-default value is passed, initial must also be provided. Default: True.

Returns

Tensor or scalar, minimum of input tensor. If the axis is None, the result is a scalar value. If axis is given, the result is a tensor of dimension self.ndim - 1.

Raises

TypeError – If arguments have types not specified above.

Supported Platforms:

Ascend GPU CPU

See also

mindspore.Tensor.argmin(): Return the indices of the minimum values along an axis.

mindspore.Tensor.argmax(): Return the indices of the maximum values along an axis.

mindspore.Tensor.max(): Return the maximum of a tensor or maximum along an axis.

Examples

>>> from mindspore import Tensor
>>> import mindspore.numpy as np
>>> a = Tensor(np.arange(4).reshape((2,2)).astype('float32'))
>>> output = a.min()
>>> print(output)
0.0
narrow(axis, start, length)[source]

Returns a narrowed tensor from input tensor. The dimension axis is input from start to start + length.

Parameters
  • axis (int) – the axis along which to narrow.

  • start (int) – the starting dimension.

  • length (int) – the distance to the ending dimension.

Returns

Tensor.

  • output (Tensors) - The narrowed tensor.

Raises
  • TypeError – axis is not integer.

  • TypeError – start is not integer.

  • TypeError – length is not integer.

  • ValueError – axis is not in the range of [0, ndim-1].

  • ValueError – start is not in the range of [0, shape[axis]-1].

  • ValueError – start+length is greater than shape[axis]-1.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore
>>> from mindspore import Tensor
>>> x = Tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], mindspore.int32)
>>> output = x.narrow(0, 0, 2)
>>> print(output)
[[ 1 2 3]
 [ 4 5 6]]
>>> output = x.narrow(1, 1, 2)
>>> print(output)
[[ 2 3]
 [ 5 6]
 [ 8 9]]
property nbytes

Return the total number of bytes taken by the tensor.

property ndim

Return the number of tensor dimensions.

nonzero()[source]

Return a Tensor of the positions of all non-zero values.

Returns

Tensor, a 2-D Tensor whose data type is int64, containing the positions of all non-zero values of the input.

Supported Platforms:

GPU

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> x = Tensor(np.array([[[1,  0], [-5, 0]]]), mindspore.int32)
>>> output = x.nonzero()
>>> print(output)
[[0 0 0]
 [0 1 0]]
norm(axis, p=2, keep_dims=False, epsilon=1e-12)[source]

Returns the matrix norm or vector norm of a given tensor.

Parameters
  • axis (Union[int,list,tuple]) – Specifies which dimension or dimensions of input to calculate the norm across.

  • p (int) – The order of norm. Default: 2. p is greater than or equal to 0.

  • keep_dims (bool) – Whether the output tensors have dim retained or not. Default: False.

  • epsilon (float) – A value added to the denominator for numerical stability. Default: 1e-12.

Returns

Tensor, has the same dtype as self tensor, which shape depends on the args axis. For example, if the size of input is (2, 3, 4), axis is [0, 1], Outputs’ shape will be (4,).

Raises
  • TypeError – If dtype of self tensor is not one of: float16, float32.

  • TypeError – If p is not an int.

  • TypeError – If axis is not an int, a tuple or a list.

  • TypeError – If axis is a tuple or a list, but the element of axis is not an int.

  • TypeError – If keep_dims is not a bool.

  • TypeError – If epsilon is not a float.

  • ValueError – If the element of axis is out of the range [-len(input_x.shape), len(input_x.shape)). input_x refers to self tensor.

  • ValueError – If the length of shape of axis is bigger than the length of shape of self tensor.

Supported Platforms:

Ascend GPU CPU

Examples

>>> input_x = Tensor(np.array([[[1.0, 2.0], [3.0, 4.0]], [[5.0, 6.0], [7.0, 8.0]]]).astype(np.float32))
>>> output = input_x.norm([0, 1], p=2)
>>> print(output)
[ 9.165152 10.954452]
pow(power)[source]

Calculate the power of Tensor.

\[out_{i} = x_{i} ^{ y_{i}}\]

Note

  • The current Tensor and power comply with the implicit type conversion rules to make the data types consistent.

  • Dtypes of the current Tensor and power cannot be bool at the same time, and the shapes of them can be broadcast.

Parameters

power (Union[Tensor, number.Number, bool]) – The power value, should be a number.Number or bool value, or a Tensor whose data type is number or bool_.

Returns

Tensor, the shape is the same as the one after broadcasting, and the data type is the one with higher precision or higher digits among Tensor and power.

Raises
  • TypeError – If power is not one of the following: Tensor, number.Number or bool.

  • ValueError – If the shape of the current Tensor and power are different.

Supported Platforms:

Ascend GPU CPU

Examples

>>> x = Tensor(np.array([1.0, 2.0, 4.0]), mindspore.float32)
>>> y = 3.0
>>> output = x.pow(y)
>>> print(output)
[ 1.  8. 64.]
>>>
>>> x = Tensor(np.array([1.0, 2.0, 4.0]), mindspore.float32)
>>> y = Tensor(np.array([2.0, 4.0, 3.0]), mindspore.float32)
>>> output = x.pow(y)
>>> print(output)
[ 1. 16. 64.]
prod(axis=(), keep_dims=False)[source]

Reduces a dimension of a tensor by multiplying all elements in the dimension, by default. And also can reduce a dimension of x along the axis. Determine whether the dimensions of the output and input are the same by controlling keep_dims.

Parameters
  • axis (Union[None, int, tuple(int), list(int)]) – Dimensions of reduction. When the axis is None or empty tuple, reduce all dimensions. When the axis is int, tuple(int) or list(int), if the dimension of Tensor is dim, the value range is [-dim, dim). Default: ().

  • keep_dims (bool) – Whether to keep the reduced dimensions. Default: False.

Returns

Tensor, has the same data type as input tensor.

  • If axis is () and keep_dims is False, output a 0-dimensional Tensor representing the product of all elements in the input Tensor.

  • If axis is int, takes the value 1, and keep_dims is False, the shape of the output is \((x_0, x_2, ..., x_R)\) .

  • If axis is tuple(int) or list(int), the value is (1, 2), and keep_dims is False, the shape of the output Tensor is: math:(x_0, x_3, … , x_R) .

Raises
  • TypeError – If axis is not one of the following: int, tuple or list.

  • TypeError – If keep_dims is not a bool.

  • ValueError – If axis is out of range.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> input_x = Tensor(np.array([1, 2, 3], dtype=np.float32))
>>> output = input_x.prod()
>>> print(output)
6.0
ptp(axis=None, keepdims=False)[source]

The name of the function comes from the acronym for “peak to peak”. Calculate the difference between the maximum value and the minimum value along the axis.

Note

Numpy argument out is not supported.

Parameters
  • axis (Union[None, int, tuple(int)]) – Axis or axes along which the range is computed. The default is to compute the variance of the flattened tensor. Default: None.

  • 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 tensor. Default is False.

Returns

Tensor.

Raises

TypeError – If self is not a tensor, or axis and keepdims have types not specified above.

Supported Platforms:

Ascend GPU CPU

Examples

>>> from mindspore import Tensor
>>> x = Tensor([[4.0, 9.0, 2.0, 10.0], [6.0, 9.0, 7.0, 12.0]]).astype("float32")
>>> print(x.ptp(axis=1))
[8. 6.]
>>> print(x.ptp(axis=0))
[2. 0. 5. 2.]
ravel()[source]

Return a contiguous flattened tensor.

Returns

Tensor, a 1-D tensor, containing the same elements of the input.

Supported Platforms:

Ascend GPU CPU

See also

mindspore.Tensor.reshape(): Give a new shape to a tensor without changing its data.

mindspore.Tensor.flatten(): Return a copy of the tensor collapsed into one dimension.

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> x = Tensor(np.ones((2,3,4), dtype=np.float32))
>>> output = x.ravel()
>>> print(output.shape)
(24,)
renorm(p, dim, maxnorm)[source]

Renormalizes the sub-tensors along dimension dim, and each sub-tensor’s p-norm should not exceed the ‘maxnorm’. The values of current sub-tensor don’t need change if the p-norm of the sub-tensor is less than maxnorm. Otherwise the sub-tensor needs to be modified to the original value of the corresponding position divided by the p-norm of the substensor and then multiplied by maxnorm.

Parameters
  • p (float) – Power of norm calculation.

  • dim (int) – The dimension that expected to get the slice-tensor.

  • maxnorm (float) – Max norm.

Returns

Tensor, has the same dtype and shape as itself.

Raises
Supported Platforms:

Ascend CPU GPU

Examples

>>> x = Tensor(np.array([[1, 1, 1], [2, 2, 2], [3, 3, 3]]), mindspore.float32)
>>> y = x.renorm(p=1, dim=0, maxnorm=5.)
>>> print(y)
[[1.       1.        1.        ]
[1.6666666 1.6666666 1.6666666 ]
[1.6666667 1.6666667 1.6666667 ]]
repeat(repeats, axis=None)[source]

Repeat elements of a tensor.

Parameters
  • repeats (Union[int, tuple, list]) – The number of repetitions for each element. repeats is broadcasted to fit the shape of the given axis.

  • axis (int, optional) – The axis along which to repeat values. By default, use the flattened input tensor, and return a flat output tensor. Default: None.

Returns

Tensor, has the same shape as input tensor except along the given axis.

Raises
  • ValueError – If the axis is out of range.

  • TypeError – If arguments have types not specified above.

Supported Platforms:

Ascend GPU CPU

See also

mindspore.Tensor.reshape(): Give a new shape to a tensor without changing its data.

mindspore.Tensor.resize(): Changes shape and size of tensor in-place.

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> x = Tensor(np.array(3))
>>> print(x.repeat(4))
[3 3 3 3]
>>> x = Tensor(np.array([[1, 2],[3, 4]]))
>>> print(x.repeat(2))
[1 1 2 2 3 3 4 4]
>>> print(x.repeat(3, axis=1))
[[1 1 1 2 2 2]
[3 3 3 4 4 4]]
>>> print(x.repeat([1,2], axis=0))
[[1 2]
[3 4]
[3 4]]
reshape(*shape)[source]

Give a new shape to a tensor without changing its data.

Parameters

shape (Union[int, tuple(int), list(int)]) – The new shape should be compatible with the original shape. If an integer, then the result will be a 1-D tensor of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the tensor and remaining dimensions.

Returns

Tensor, with new specified shape.

Raises
  • TypeError – If new shape is not integer, list or tuple.

  • ValueError – If new shape is not compatible with the original shape.

Supported Platforms:

Ascend GPU CPU

Examples

>>> from mindspore import Tensor
>>> from mindspore import dtype as mstype
>>> x = Tensor([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]], dtype=mstype.float32)
>>> output = x.reshape((3, 2))
>>> print(output)
[[-0.1  0.3]
[ 3.6  0.4]
[ 0.5 -3.2]]
resize(*new_shape)[source]

Changes shape and size of tensor in-place.

If the shape of the new tensor is larger than the shape of the original tensor, the new tensor will be filled with 0. And if the shape of the new tensor is smaller than the shape of the original tensor, the new tensor is filled with the elements of the original tensor in order.

Note

Instead of changing the size of the input tensor and returns nothing as in numpy, this method returns a new Tensor with the input size. Numpy argument refcheck is not supported.

Parameters

new_shape (Union[ints, tuple of ints]) – Shape of resized tensor.

Returns

Tensor.

Supported Platforms:

Ascend GPU CPU

See also

mindspore.Tensor.reshape(): Give a new shape to a tensor without changing its data.

mindspore.Tensor.repeat(): Repeat elements of a tensor.

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> x = Tensor(np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float32))
>>> y = x.resize(3, 3)
>>> print(y)
[[1. 2. 3.]
[4. 5. 6.]
[0. 0. 0.]]
>>> y = x.resize(2, 2)
>>> print(y)
[[1. 2.]
[3. 4.]]
round()[source]

Returns half to even of the tensor element-wise.

Returns

Tensor, has the same shape and type as the Tensor.

Supported Platforms:

Ascend GPU CPU

Examples

>>> x = Tensor(np.array([0.8, 1.5, 2.3, 2.5, -4.5]), mindspore.float32)
>>> output = x.round()
>>> print(output)
[ 1.  2.  2.  2. -4.]
scatter_add(indices, updates)[source]

Creates a new tensor by adding the values from the positions in self tensor indicated by indices, with values from updates. When multiple values are given for the same index, the updated result will be the sum of all values. This operation is almost equivalent to using ScatterNdAdd, except that the updates are applied on output Tensor instead of input Parameter.

The last axis of indices is the depth of each index vectors. For each index vector, there must be a corresponding value in updates. The shape of updates should be equal to the shape of self[indices]. For more details, see use cases.

Note

On GPU, if some values of the indices are out of bound, instead of raising an index error, the corresponding updates will not be updated to self tensor. On CPU, if some values of the indices are out of bound, raising an index error. On Ascend, out of bound checking is not supported, if some values of the indices are out of bound, unknown errors may be caused.

Parameters
  • indices (Tensor) – The index of input tensor whose data type is int32 or int64. The rank must be at least 2.

  • updates (Tensor) – The tensor to update the input tensor, has the same type as self tensor, and updates. Shape should be equal to indices.shape[:-1] + self.shape[indices.shape[-1]:].

Returns

Tensor, has the same shape and type as self tensor.

Raises
  • TypeError – If dtype of indices is neither int32 nor int64.

  • ValueError – If length of shape of self tensor is less than the last dimension of shape of indices.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> x = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]).astype('float32'))
>>> indices = Tensor(np.array([[0, 0], [0, 0]]).astype('int32'))
>>> updates = Tensor(np.array([1.0, 2.2]).astype('float32'))
>>> output = x.scatter_add(indices, updates)
>>> print(output)
[[ 3.1  0.3  3.6]
[ 0.4  0.5 -3.2]]
scatter_div(indices, updates)[source]

Creates a new tensor by dividing the values from the positions in self tensor indicated by indices, with values from updates. When divided values are provided for the same index, the result of the update will be to divided these values respectively. Except that the updates are applied on output Tensor instead of input Parameter.

The last axis of indices is the depth of each index vectors. For each index vector, there must be a corresponding value in updates. The shape of updates should be equal to the shape of input_x[indices], the variable input_x refers to self tensor. For more details, see use cases.

Note

  • If some values of the indices are out of bound, instead of raising an index error, the corresponding updates will not be updated to input_x.

  • The operator can’t handle division by 0 exceptions, so the user needs to make sure there is no 0 value in updates.

Parameters
  • indices (Tensor) – The index of input tensor whose data type is int32 or int64. The rank must be at least 2.

  • updates (Tensor) – The tensor to update the input tensor, has the same type as input, and updates.shape should be equal to indices.shape[:-1] + input_x.shape[indices.shape[-1]:].

Returns

Tensor, has the same shape and type as self tensor.

Raises
  • TypeError – If dtype of indices is neither int32 nor int64.

  • ValueError – If length of shape of self tensor is less than the last dimension of shape of indices.

Supported Platforms:

GPU CPU

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> input_x = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]).astype('float32'))
>>> indices = Tensor(np.array([[0, 0], [0, 0]]).astype('int32'))
>>> updates = Tensor(np.array([1.0, 2.0]).astype('float32'))
>>> output = input_x.scatter_div(indices, updates)
>>> print(output)
[[-0.05  0.3  3.6  ]
 [ 0.4   0.5  -3.2 ]]
scatter_max(indices, updates)[source]

By comparing the value at the position indicated by indices in x with the value in the updates, the value at the index will eventually be equal to the largest one to create a new tensor.

The last axis of the index is the depth of each index vector. For each index vector, there must be a corresponding value in updates. The shape of updates should be equal to the shape of input_x[indices]. For more details, see case below.

Note

If some values of the indices are out of bound, instead of raising an index error, the corresponding updates will not be updated to input_x.

Parameters
  • indices (Tensor) – The index of input tensor whose data type is int32 or int64. The rank must be at least 2.

  • updates (Tensor) – The tensor to update the input tensor, has the same type as input, and updates.shape should be equal to indices.shape[:-1] + input_x.shape[indices.shape[-1]:].

Returns

Tensor, has the same shape and type as input_x.

Raises
  • TypeError – If dtype of indices is neither int32 nor int64.

  • ValueError – If length of shape of input_x is less than the last dimension of shape of indices.

Supported Platforms:

GPU

Examples

>>> input_x = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]), mindspore.float32)
>>> indices = Tensor(np.array([[0, 0], [0, 0]]), mindspore.int32)
>>> updates = Tensor(np.array([1.0, 2.2]), mindspore.float32)
>>> # Next, demonstrate the approximate operation process of this operator:
>>> # 1, indices[0] = [0, 0], indices[1] = [0, 0]
>>> # 2, And input_x[0, 0] = -0.1
>>> # 3, So input_x[indices] = [-0.1, -0.1]
>>> # 4, Satisfy the above formula: input_x[indices].shape=(2) == updates.shape=(2)
>>> op = ops.TensorScatterMax()
>>> # 5, Perform the max operation for the first time:
>>> #      first_input_x = Max(input_x[0][0], updates[0]) = [[1.0, 0.3, 3.6], [0.4, 0.5, -3.2]]
>>> # 6, Perform the max operation for the second time:
>>> #      second_input_x = Max(input_x[0][0], updates[1]) = [[2.2, 0.3, 3.6], [0.4, 0.5, -3.2]]
>>> output = op(input_x, indices, updates)
>>> print(output)
[[ 2.2  0.3  3.6]
[ 0.4  0.5 -3.2]]
scatter_min(indices, updates)[source]

By comparing the value at the position indicated by indices in self tensor with the value in the updates, the value at the index will eventually be equal to the smallest one to create a new tensor.

The last axis of the index is the depth of each index vector. For each index vector, there must be a corresponding value in updates. The shape of updates should be equal to the shape of input_x[indices]. For more details, see case below.

Note

If some values of the indices are out of range, instead of raising an index error, the corresponding updates will not be updated to input_x.

Parameters
  • indices (Tensor) – The index of input tensor whose data type is int32 or int64. The rank must be at least 2.

  • updates (Tensor) – The tensor to update the input tensor, has the same type as input, and updates.shape should be equal to indices.shape[:-1] + input_x.shape[indices.shape[-1]:].

Returns

Tensor, has the same shape and type as input_x.

Raises
  • TypeError – If dtype of indices is neither int32 nor int64.

  • ValueError – If length of shape of input_x is less than the last dimension of shape of indices.

Supported Platforms:

GPU

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> x = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]).astype('float32'))
>>> indices = Tensor(np.array([[0, 0], [0, 0]]).astype('int32'))
>>> updates = Tensor(np.array([1.0, 2.2]).astype('float32'))
>>> output = x.scatter_min(indices, updates)
>>> print(output)
[[ -0.1  0.3  3.6]
[ 0.4  0.5 -3.2]]
scatter_mul(indices, updates)[source]

Creates a new tensor by multiplying the values from the positions in self tensor indicated by indices, with values from updates. When divided values are provided for the same index, the result of the update will be to divided these values respectively. Except that the updates are applied on output Tensor instead of input Parameter. The variable input_x refers to self tensor.

The last axis of indices is the depth of each index vectors. For each index vector, there must be a corresponding value in updates. The shape of updates should be equal to the shape of input_x[indices]. For more details, see use cases.

Note

  • If some values of the indices are out of bound, instead of raising an index error, the corresponding updates will not be updated to input_x.

Parameters
  • indices (Tensor) – The index of input tensor whose data type is int32 or int64. The rank must be at least 2.

  • updates (Tensor) – The tensor to update the input tensor, has the same type as input, and updates shape should be equal to indices.shape[:-1] + input_x.shape[indices.shape[-1]:].

Returns

Tensor, has the same shape and type as self tensor.

Raises
  • TypeError – If dtype of indices is neither int32 nor int64.

  • ValueError – If length of shape of self tensor is less than the last dimension of shape of indices.

Supported Platforms:

GPU CPU

Examples

>>> input_x = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]), mindspore.float32)
>>> indices = Tensor(np.array([[0, 0], [0, 0]]), mindspore.int32)
>>> updates = Tensor(np.array([1.0, 2.2]), mindspore.float32)
>>> # Next, demonstrate the approximate operation process of this operator:
>>> # 1, indices[0] = [0, 0], indices[1] = [0, 0]
>>> # 2, And input_x[0, 0] = -0.1
>>> # 3, So input_x[indices] = [-0.1, -0.1]
>>> # 4, Satisfy the above formula: input_x[indices].shape=(2) == updates.shape=(2)
>>> # 5, Perform the multiply operation for the first time:
>>> #      first_input_x = input_x[0][0] * updates[0] = [[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]
>>> # 6, Perform the multiply operation for the second time:
>>> #      second_input_x = input_x[0][0] * updates[1] = [[-0.22, 0.3, 3.6], [0.4, 0.5, -3.2]]
>>> output = input_x.scatter_mul(indices, updates)
>>> print(output)
[[-0.22  0.3   3.6  ]
 [ 0.4   0.5   -3.2 ]]
scatter_sub(indices, updates)[source]

Creates a new tensor by subtracting the values from the positions in self tensor indicated by indices, with values from updates. When multiple values are provided for the same index, the result of the update will be to subtract these values respectively. This operation is almost equivalent to using mindspore.ops.ScatterNdSub , except that the updates are applied on output Tensor instead of input Parameter.

The last axis of indices is the depth of each index vectors. For each index vector, there must be a corresponding value in updates. The shape of updates should be equal to the shape of self[indices]. For more details, see use cases.

Note

On GPU, if some values of the indices are out of bound, instead of raising an index error, the corresponding updates will not be updated to self tensor. On CPU, if some values of the indices are out of bound, raising an index error. On Ascend, out of bound checking is not supported, if some values of the indices are out of bound, unknown errors may be caused.

Parameters
  • indices (Tensor) – The index of input tensor whose data type is int32 or int64. The rank must be at least 2.

  • updates (Tensor) – The tensor to update the input tensor, has the same type as input, and updates.shape should be equal to indices.shape[:-1] + self.shape[indices.shape[-1]:].

Returns

Tensor, has the same shape and type as self tensor.

Raises
  • TypeError – If dtype of indices is neither int32 nor int64.

  • ValueError – If length of shape of self tensor is less than the last dimension of shape of indices.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> x = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]).astype('float32'))
>>> indices = Tensor(np.array([[0, 0], [0, 0]]).astype('int32'))
>>> updates = Tensor(np.array([1.0, 2.2]).astype('float32'))
>>> output = x.scatter_sub(indices, updates)
>>> print(output)
[[-3.3000002  0.3        3.6      ]
[ 0.4        0.5       -3.2      ]]
select(condition, y)[source]

The conditional tensor determines whether the corresponding element in the output must be selected from the current Tensor (if true) or \(y\) (if false) based on the value of each element.

It can be defined as:

\[\begin{split}out_i = \begin{cases} tensor_i, & \text{if } condition_i \\ y_i, & \text{otherwise} \end{cases}\end{split}\]
Parameters
  • condition (Tensor[bool]) – The condition tensor, decides which element is chosen. The shape is the same as the current Tensor.

  • y (Union[Tensor, int, float]) – If y is Tensor, the shape is the same as the current Tensor. If y is an int or a float, it will be cast to the type of int32 or float32, and broadcast to the same shape as the Tensor.

Returns

Tensor, has the same shape as the current Tensor.

Raises
  • TypeError – If y is not a Tensor, an int or a float.

  • ValueError – The shapes of inputs are different.

Supported Platforms:

Ascend GPU CPU

Examples

>>> # 1) y is Tensor
>>>
>>> cond = Tensor([True, False])
>>> x = Tensor([2,3], mindspore.float32)
>>> y = Tensor([1,2], mindspore.float32)
>>> output = x.select(cond, y)
>>> print(output)
[2. 2.]
>>> # 2) y is a float
>>> cond = Tensor([True, False])
>>> x = Tensor([2,3], mindspore.float32)
>>> y = 2.0
>>> output = x.select(cond, y)
>>> print(output)
[2. 2.]
property shape

Returns the shape of the tensor as a tuple.

property size

Returns the total number of elements in tensor.

soft_shrink(lambd=0.5)[source]

Apply the soft shrink function for a tensor. Calculates the output according to the input elements.

The formula is defined as follows:

\[\begin{split}\text{SoftShrink}(x) = \begin{cases} x - \lambda, & \text{ if } x > \lambda \\ x + \lambda, & \text{ if } x < -\lambda \\ 0, & \text{ otherwise } \end{cases}\end{split}\]
Parameters

lambd (float) – the \(\lambda\) must be no less than zero. Default: 0.5.

Returns

Tensor, has the same shape and data type as self.

Raises
  • TypeError – If lambd is not a float.

  • TypeError – If input_x is not a Tensor.

  • TypeError – If dtype of input_x is neither float16 nor float32.

  • ValueError – If lambd is less than 0.

Supported Platforms:

Ascend GPU CPU

Examples

>>> from mindspore import Tensor
>>> a = Tensor([[ 0.5297,  0.7871,  1.1754], [ 0.7836,  0.6218, -1.1542]]).astype("float32")
>>> output = a.soft_shrink()
>>> print(output)
[[ 0.02979  0.287    0.676  ]
 [ 0.2837   0.1216  -0.6543 ]]
split(axis=0, output_num=1)[source]

Splits a tensor into output_num of tensors along the given axis and output numbers.

The tensor will be split into equally sized sub-tensors. This requires that self.shape(axis) is divisible by output_num.

Parameters
  • axis (int) – Index of the split position. Default: 0.

  • output_num (int) – The number of output tensors. Must be positive int. Default: 1.

Returns

tuple[Tensor], the shape of each output tensor is the same, which is \((y_1, y_2, ..., y_S)\). And the data type is the same with the tensor.

Raises
  • TypeError – If axis or output_num is not an int.

  • ValueError – If axis is out of the range [-len(self.shape), len(self.shape)), or if the output_num is less than or equal to 0.

  • ValueError – If self.shape(axis) is not divisible by output_num.

Supported Platforms:

Ascend GPU CPU

Examples

>>> x = Tensor(np.array([[1, 1, 1, 1], [2, 2, 2, 2]]), mindspore.int32)
>>> print(x)
[[1 1 1 1]
 [2 2 2 2]]
>>> output = x.split(1, 2)
>>> print(output)
(Tensor(shape=[2, 2], dtype=Int32, value=
[[1, 1],
 [2, 2]]), Tensor(shape=[2, 2], dtype=Int32, value=
[[1, 1],
 [2, 2]]))
squeeze(axis=None)[source]

Remove the dimension of shape 1 from the Tensor

Parameters

axis (Union[None, int, list(int), tuple(int)], optional) – Selects a subset of the entries of length one in the shape. If an axis is selected with shape entry greater than one, an error is raised. Default is None.

Returns

Tensor, with all or a subset of the dimensions of length 1 removed.

Raises
  • TypeError – If input arguments have types not specified above.

  • ValueError – If axis is greater than one.

Supported Platforms:

Ascend GPU CPU

See also

mindspore.Tensor.expand_as(): Expand the dimension of target tensor to the dimension of input tensor.

mindspore.Tensor.reshape(): Give a new shape to a tensor without changing its data.

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> x = Tensor(np.ones((1,2,2), dtype=np.float32))
>>> print(x)
[[[1. 1.]
[1. 1.]]]
>>> print(x.shape)
(1, 2, 2)
>>> y = x.squeeze()
>>> print(y)
[[1. 1.]
[1. 1.]]
>>> print(y.shape)
(2, 2)
>>> y = x.squeeze(axis=0)
>>> print(y)
[[1. 1.]
[1. 1.]]
>>> print(y.shape)
(2, 2)
std(axis=None, ddof=0, keepdims=False)[source]

Compute the standard deviation along the specified axis.

The standard deviation is the square root of the average of the squared deviations from the mean, i.e., \(std = sqrt(mean(abs(x - x.mean())**2))\).

Return the standard deviation, which is computed for the flattened array by default, otherwise over the specified axis.

Note

Numpy arguments dtype, out and where are not supported.

Parameters
  • axis (Union[None, int, tuple(int)]) –

    Axis or axes along which the standard deviation is computed. Default: None.

    If None, compute the standard deviation of the flattened array.

  • ddof (int) – Means Delta Degrees of Freedom. The divisor used in calculations is \(N - ddof\), where \(N\) represents the number of elements. Default: 0.

  • keepdims – Default: False.

Returns

Standard deviation tensor.

Supported Platforms:

Ascend GPU CPU

See also

mindspore.Tensor.mean(): Reduce a dimension of a tensor by averaging all elements in the dimension.

mindspore.Tensor.var(): Compute the variance along the specified axis.

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> input_x = Tensor(np.array([1, 2, 3, 4], dtype=np.float32))
>>> output = input_x.std()
>>> print(output)
1.118034
property strides

Return the tuple of bytes to step in each dimension when traversing a tensor.

sum(axis=None, dtype=None, keepdims=False, initial=None)[source]

Return sum of tensor elements over a given axis.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported.

Parameters
  • axis (Union[None, int, tuple(int)]) – Axis or axes along which a sum is performed. Default: None. If None, sum all the elements of the input tensor. If the axis is negative, it counts from the last to the first axis. If the axis is a tuple of ints, a sum is performed on all the axes specified in the tuple instead of a single axis or all the axes as before.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

  • 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. 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. Default: None.

Returns

Tensor. A tensor with the same shape as input, with the specified axis removed. If the input tensor is a 0-d array, or if the axis is None, a scalar is returned.

Raises
  • TypeError – If input is not array_like, or axis is not int or tuple of ints, or keepdims is not integer, or initial is not scalar.

  • ValueError – If any axis is out of range or duplicate axes exist.

Supported Platforms:

Ascend GPU CPU

See also

mindspore.Tensor.cumsum(): Return the cumulative sum of the elements along a given axis.

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> input_x = Tensor(np.array([-1, 0, 1]).astype(np.float32))
>>> print(input_x.sum())
0.0
>>> input_x = Tensor(np.arange(10).reshape(2, 5).astype(np.float32))
>>> print(input_x.sum(axis=1))
[10. 35.]
swapaxes(axis1, axis2)[source]

Interchange two axes of a tensor.

Parameters
  • axis1 (int) – First axis.

  • axis2 (int) – Second axis.

Returns

Transposed tensor, has the same data type as the input.

Raises
  • TypeError – If axis1 or axis2 is not integer.

  • ValueError – If axis1 or axis2 is not in the range of \([-ndim, ndim-1]\).

Supported Platforms:

Ascend GPU CPU

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> x = Tensor(np.ones((2,3,4), dtype=np.float32))
>>> output = x.swapaxes(0, 2)
>>> print(output.shape)
(4,3,2)
take(indices, axis=None, mode='clip')[source]

Takes elements from a tensor along an axis.

Parameters
  • indices (Tensor) – The indices with shape (Nj…) of the values to extract.

  • axis (int, optional) – The axis over which to select values. By default, the flattened input tensor is used. Default: None.

  • mode ('raise', 'wrap', 'clip', optional) –

    Default: “clip”.

    ’raise’ – Raises an error;

    ’wrap’ – Wraps around;

    ’clip’ – Clips to the range. ‘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.

    Default: ‘clip’.

Returns

Tensor, the indexed result.

Raises

ValueError – If axis is out of range, or mode has values other than (‘raise’, ‘wrap’, ‘clip’)

Supported Platforms:

Ascend GPU CPU

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> a = Tensor(np.array([4, 3, 5, 7, 6, 8]))
>>> indices = Tensor(np.array([0, 1, 4]))
>>> output = a.take(indices)
>>> print(output)
[4 3 6]
tan()[source]

Computes tangent of x element-wise.

\[out_i = tan(x_i)\]
Returns

Tensor, has the same shape as self.

Raises

TypeError – If self is not a Tensor.

Supported Platforms:

Ascend GPU CPU

Examples

>>> from mindspore import Tensor
>>> a = Tensor([-1.0, 0.0, 1.0]).astype("float32")
>>> output = a.tan()
>>> print(output)
[-1.5574081 0. 1.5574081]
to_coo()[source]

Convert a Tensor to COOTensor.

Note

Only 2-D tensor is supported for now.

Returns

indices: the positions of all non-zero values of the input. values: the non-zero values of the dense tensor. shape: the shape of the coo_tensor.

Return type

COOTensor, a 2-D coo_tensor, containing

Raises

ValueError – If input tensor is not 2-D.

Supported Platforms:

GPU

Examples

>>> import numpy as np
>>> import mindspore
>>> from mindspore import Tensor
>>> x = Tensor(np.array([[1,  0], [-5, 0]]), mindspore.float32)
>>> output = x.to_coo()
>>> print(output.indices, output.values, output.shape)
[[0 0]
 [1 0]] [ 1. -5.] (2, 2)
to_csr()[source]

Convert a Tensor to CSRTensor.

Note

Only 2-D tensor is supported for now.

Returns

indptr: indicates the start and end point for values in each row. indices: the column positions of all non-zero values of the input. values: the non-zero values of the dense tensor. shape: the shape of the csr_tensor.

Return type

CSRTensor, a 2-D csr_tensor, containing

Raises

ValueError – If input tensor is not 2-D.

Supported Platforms:

GPU

Examples

>>> import numpy as np
>>> import mindspore
>>> from mindspore import Tensor
>>> x = Tensor(np.array([[1,  0], [-5, 0]]), mindspore.float32)
>>> output = x.to_csr()
>>> print(output.indptr, output.indices, output.values, output.shape)
[0 1 2] [0 0] [ 1. -5.] (2, 2)
to_tensor(slice_index=None, shape=None, opt_shard_group=None)[source]

Return init_data() and get the tensor format data of this Tensor.

Note

The usage of to_tensor is deprecated. Please use init_data.

Parameters
  • slice_index (int) – Slice index of a parameter’s slices. It is used when initialize a slice of a parameter, it guarantees that devices using the same slice can generate the same tensor. Default: None.

  • shape (list[int]) – Shape of the slice, it is used when initialize a slice of the parameter. Default: None.

  • opt_shard_group (str) – Optimizer shard group which is used in auto or semi auto parallel mode to get one shard of a parameter’s slice. Default: None.

Returns

Initialized Tensor.

Raises
  • TypeErrorindices is neither int32 nor int64.

  • ValueError – The length of the shape of the tensor is less than the last dimension of indices.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore as ms
>>> from mindspore.common.initializer import initializer, Constant
>>> x = initializer(Constant(1), [2, 2], ms.float32)
>>> out = x.to_tensor()
>>> print(out)
[[1. 1.]
 [1. 1.]]
top_k(k, sorted=True)[source]

Finds values and indices of the k largest entries along the last dimension.

Warning

  • If sorted is set to ‘False’, it will use the aicpu operator, the performance may be reduced.

input_x refer to self tensor.

If the input_x is a one-dimensional Tensor, finds the k largest entries in the Tensor, and outputs its value and index as a Tensor. Therefore, values[k] is the k largest item in input_x, and its index is indices [k].

For a multi-dimensional matrix, calculates the first k entries in each row (corresponding vector along the last dimension), therefore:

\[values.shape = indices.shape = input\_x.shape[:-1] + [k].\]

If the two compared elements are the same, the one with the smaller index value is returned first.

Parameters
  • k (int) – The number of top elements to be computed along the last dimension, constant input is needed.

  • sorted (bool, optional) – If true, the obtained elements will be sorted by the values in descending order. Default: True.

Returns

Tuple of 2 tensors, the values and the indices.

  • values (Tensor): The k largest elements in each slice of the last dimension.

  • indices (Tensor): The indices of values within the last dimension of input.

Raises
Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore as ms
>>> from mindspore import Tensor
>>> input_x = Tensor([1, 2, 3, 4, 5], ms.float16)
>>> k = 3
>>> values, indices = input_x.top_k(k, sorted=True)
>>> print((values, indices))
(Tensor(shape=[3], dtype=Float16, value= [ 5.0000e+00,  4.0000e+00,  3.0000e+00]), Tensor(shape=[3],
  dtype=Int32, value= [4, 3, 2]))
trace(offset=0, axis1=0, axis2=1, dtype=None)[source]

Return the sum along diagonals of the tensor.

Parameters
  • offset (int, optional) – Offset of the diagonal from the main diagonal. Can be positive or negative. Defaults to main diagonal.

  • axis1 (int, optional) – Axis to be used as the first axis of the 2-D sub-arrays from which the diagonals should be taken. Defaults to first axis (0).

  • axis2 (int, optional) – Axis to be used as the second axis of the 2-D sub-arrays from which the diagonals should be taken. Defaults to second axis.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor, the sum along diagonals.

Raises

ValueError – If the input tensor has less than two dimensions.

Supported Platforms:

Ascend GPU CPU

See also

mindspore.Tensor.diagonal(): Return specified diagonals.

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> x = Tensor(np.eye(3, dtype=np.float32))
>>> print(x.trace())
3.0
transpose(*axes)[source]

Return a tensor with axes transposed.

  • For a 1-D tensor, this has no effect, as a transposed vector is simply the same vector.

  • For a 2-D tensor, this is a standard matrix transpose.

  • For an n-D tensor, if axes are given, their order indicates how the axes are permuted.

If axes are not provided and tensor.shape = (i[0], i[1],...i[n-2], i[n-1]), then tensor.transpose().shape = (i[n-1], i[n-2], ... i[1], i[0]).

Parameters

axes (Union[None, tuple(int), list(int), int], optional) – If axes is None or blank, the method will reverse the order of the axes. If axes is tuple(int) or list(int), tensor.transpose() will transpose the tensor to the new axes order. If axes is int, this form is simply intended as a convenience alternative to the tuple/list form.

Returns

Tensor, has the same dimension as input tensor, with axes suitably permuted.

Raises
  • TypeError – If input arguments have types not specified above.

  • ValueError – If the number of axes is not equal to Tensor’s ndim.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> x = Tensor(np.ones((1,2,3), dtype=np.float32))
>>> x = x.transpose()
>>> print(x.shape)
(3, 2, 1)
unique_consecutive(return_idx=False, return_counts=False, axis=None)[source]

Returns the elements that are unique in each consecutive group of equivalent elements in the input tensor.

Parameters
  • return_idx (bool, optional) – Whether to return the indices of the end position of each element in the original input list in the returned unique list. Default: False.

  • return_counts (bool, optional) – Whether to return the counts of each unique element. Default: False.

  • axis (int, optional) – The dimension to apply unique. If None, the unique of the flattened input is returned. If specified, it must be int32 or int64. Default: None.

Returns

A tensor or a tuple of tensors containing tensor objects (output, idx, counts). output has the same type as the input tensor and is used to represent the output list of unique scalar elements. If return_idx is True, there will be an additional returned tensor, idx, which has the same shape as the inupt tensor and represents the index of where the element in the original input maps to the position in the output. If return_counts is True, there will be an additional returned tensor, counts, which represents the number of occurrences for each unique value or tensor.

Raises

RuntimeError – If axis is not in the range of \([-ndim, ndim-1]\).

Supported Platforms:

Ascend GPU

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> from mindspore import dtype as mstype
>>> x = Tensor(np.array([1, 1, 2, 2, 3, 1, 1, 2]), mstype.int32)
>>> output, idx, counts = x.unique_consecutive(return_idx=True, return_counts=True, axis=None)
>>> print(output)
[1 2 3 1 2]
>>> print(idx)
[0 0 1 1 2 3 3 4]
>>> print(counts)
[2 2 1 2 1]
unique_with_pad(pad_num)[source]

Returns unique elements and relative indexes in 1-D tensor, filled with padding num.

The basic function is the same as the Unique operator, but the UniqueWithPad operator adds a Pad function. The returned tuple(y, idx) after the self tensor is processed by the unique operator, in which the shapes of y and idx are mostly not equal. Therefore, in order to solve the above situation, the UniqueWithPad operator will fill the y Tensor with the pad_num specified by the user to make it have the same shape as the Tensor idx.

Parameters

pad_num (int) – Pad num. The data type is an int.

Returns

tuple(Tensor), tuple of 2 tensors, y and idx.

  • y (Tensor) - The unique elements filled with pad_num, the shape and data type same as self tensor.

  • idx (Tensor) - The index of each value of self tensor in the unique output y, the shape and data type same as self tensor.

Raises
  • TypeError – If dtype of self tensor is neither int32 nor int64.

  • ValueError – If length of shape of self tensor is not equal to 1.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> from mindspore import dtype as mstype
>>> x = Tensor(np.array([1, 1, 2, 2, 3, 1]), mstype.int32)
>>> output, idx = x.unique_with_pad(pad_num=0)
>>> print(output)
[1 2 3 0 0 0]
>>> print(idx)
[0 0 1 1 2 0]
var(axis=None, ddof=0, keepdims=False)[source]

Compute the variance along the specified axis.

The variance is the average of the squared deviations from the mean, i.e., \(var = mean(abs(x - x.mean())**2)\).

Return the variance, which is computed for the flattened array by default, otherwise over the specified axis.

Note

Numpy arguments dtype, out and where are not supported.

Parameters
  • axis (Union[None, int, tuple(int)]) – Axis or axes along which the variance is computed. The default is to compute the variance of the flattened array. Default: None.

  • ddof (int) – Means Delta Degrees of Freedom. Default: 0. The divisor used in calculations is \(N - ddof\), where \(N\) represents the number of elements.

  • keepdims (bool) – Default: False.

Returns

Variance tensor.

Supported Platforms:

Ascend GPU CPU

See also

mindspore.Tensor.mean(): Reduce a dimension of a tensor by averaging all elements in the dimension.

mindspore.Tensor.std(): Compute the standard deviation along the specified axis.

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> input_x = Tensor(np.array([1., 2., 3., 4.], np.float32))
>>> output = input_x.var()
>>> print(output)
1.25
view(*shape)[source]

Reshape the tensor according to the input shape. It’s the same as mindspore.Tensor.reshape(), implemented by the underlying reshape operator.

Parameters

shape (Union[tuple(int), int]) – Dimension of the output tensor.

Returns

Tensor, which dimension is the input shape’s value.

Examples

>>> from mindspore import Tensor
>>> import numpy as np
>>> a = Tensor(np.array([[1, 2, 3], [2, 3, 4]], dtype=np.float32))
>>> output = a.view((3, 2))
>>> print(output)
[[1. 2.]
[3. 2.]
[3. 4.]]
xdivy(y)[source]

Divides self tensor by the input tensor element-wise. Returns zero when self is zero. The dtype of original Tensor must be one of float, complex or bool. For simplicity, denote the original Tensor as x.

\[out_i = x_{i} / {y_{i}}\]

x and y comply with the implicit type conversion rules to make the data types consistent. ‘y’ must be tensor or scalar, when y is tensor, dtypes of self and y cannot be bool at the same time, and the shapes of them could be broadcast. When y is scalar, the scalar can only be a constant.

Parameters

y (-) – or a bool when the first input x is a tensor, or a tensor whose data type is float16, float32, float64, complex64, complex128 or bool.

Returns

Tensor, the shape is the same as the one after broadcasting, and the data type is the one with higher precision or higher digits among the two inputs.

Raises
  • TypeError – If y is not one of the following: Tensor, Number, bool.

  • TypeError – If dtype of self and ‘y’ is not in [float16, float32, float64, complex64, complex128, bool].

  • ValueError – If self could not be broadcast to a tensor with shape of y.

  • RuntimeError – If the data type of y conversion of Parameter is given but data type conversion of Parameter is not supported.

Supported Platforms:

Ascend GPU CPU

Examples

>>> x = Tensor(np.array([2, 4, -1]), mindspore.float32)
>>> y = Tensor(np.array([2, 2, 2]), mindspore.float32)
>>> output = x.xdivy(y)
>>> print(output)
[ 1.   2.  -0.5]
xlogy(y)[source]

Computes the self tensor multiplied by the logarithm of input tensor element-wise. Returns zero when self tensor is zero. The data type of the self tensor should be number or bool_. To make it clear, the following content will use x to represent the self tensor.

\[out_i = x_{i}\ln{y_{i}}\]

Inputs of x and y comply with the implicit type conversion rules to make the data types consistent. The inputs must be two tensors or one tensor and one scalar. When the inputs are two tensors, dtypes of them cannot be bool at the same time, and the shapes of them could be broadcast. When the inputs are one tensor and one scalar, the scalar could only be a constant.

Warning

  • On Ascend, the data type of x and y must be float16 or float32.

Parameters

y (Union[Tensor, number.Number, bool]) – The y input is a number.Number or a bool or a tensor whose data type is number or bool.

Returns

Tensor, the shape is the same as the one after broadcasting, and the data type is the one with higher precision or higher digits among the two inputs.

Raises
  • TypeError – If y is not a number.Number or a bool or a Tensor.

  • TypeError – If dtype of x and ‘y’ is not in [float16, float32, float64, complex64, complex128] .

  • ValueError – If x could not be broadcast to a tensor with shape of y.

Supported Platforms:

Ascend CPU

Examples

>>> x = Tensor(np.array([-5, 0, 4]), mindspore.float32)
>>> y = Tensor(np.array([2, 2, 2]), mindspore.float32)
>>> print(x.xlogy(y))
[-3.465736   0.        2.7725887]