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
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
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.]
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.]]
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.]]
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).

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]
property has_init

Whether tensor is initialized.

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
>>> import mindspore.common.initializer as init
>>> x = init.initializer(init.Constant(1), [2, 2], ms.float32)
>>> out = x.init_data()
>>> print(out)
[[1. 1.]
 [1. 1.]]
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.

masked_fill(mask, value)[source]

Fills elements of self tensor with value where mask is True. The shape of mask must be equal to the shape of the underlying tensor.

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

  • value (Union[int, float]) – The value to fill in with, which only supports a float or an int number.

Returns

Tensor, has the same type and shape as self.

Raises
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.]
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, 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.

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, 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.

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,)
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.]]
searchsorted(v, side='left', sorter=None)[source]

Finds indices where elements should be inserted to maintain order.

Parameters
  • v (Union[int, float, bool, list, tuple, Tensor]) – Values to insert into the tensor.

  • side ('left', 'right', optional) – If ‘left’, the index of the first suitable location found is given. If ‘right’, return the last such index. If there is no suitable index, return either 0 or N (where N is the length of the tensor). Default: ‘left’.

  • sorter (Union[int, float, bool, list, tuple, Tensor]) – 1-D optional tensor of integer indices that sort the tensor into ascending order. They are typically the result of argsort. Default: None.

Returns

Tensor, array of insertion points with the same shape as v.

Raises

ValueError – If argument for side or sorter is invalid.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> x = Tensor(np.array([1, 2, 3, 4, 5]))
>>> print(x.searchsorted(3))
2
property shape

Returns the shape of the tensor as a tuple.

property size

Returns the total number of elements in tensor.

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]
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.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore as ms
>>> import mindspore.common.initializer as init
>>> x = init.initializer(init.Constant(1), [2, 2], ms.float32)
>>> out = x.to_tensor()
>>> print(out)
[[1. 1.]
 [1. 1.]]
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)
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.]]