mindspore.Tensor

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

Tensor is used for data storage.

Tensor inherits tensor object in C++. Some functions are implemented in C++ and some functions are implemented in Python.

Parameters
  • input_data (Union[Tensor, float, int, bool, tuple, list, numpy.ndarray]) – Input data of the tensor.

  • dtype (mindspore.dtype) – Input data should be None, bool or numeric type defined in mindspore.dtype. The argument is used to define the data type of the output tensor. 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]) – A list of integers, a tuple of integers or an integer as the shape of output. 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 parameters in other conditions. If ‘init’ interface is used to initialize parameters, the Tensor.init_data API needs to be called to convert Tensor to the actual data.

Outputs:

Tensor. If dtype and shape are not set, return a tensor with the same dtype and shape as input_data. If dtype or shape is set, the dtype or shape of the output Tensor is consistent with the setting.

Examples

>>> import numpy as np
>>> import mindspore as ms
>>> from mindspore import Tensor
>>> from mindspore.common.initializer import One
>>> # initialize a tensor with input data
>>> t1 = Tensor(np.zeros([1, 2, 3]), ms.float32)
>>> assert isinstance(t1, Tensor)
>>> assert t1.shape == (1, 2, 3)
>>> assert t1.dtype == ms.float32
>>>
>>> # initialize a tensor with a float scalar
>>> t2 = Tensor(0.1)
>>> assert isinstance(t2, Tensor)
>>> assert t2.dtype == ms.float64
...
>>> # initialize a tensor with init
>>> t3 = Tensor(shape = (1, 3), dtype=ms.float32, init=One())
>>> assert isinstance(t3, Tensor)
>>> assert t3.shape == (1, 3)
>>> assert t3.dtype == ms.float32
property T

Return the transposed tensor.

abs()[source]

Return absolute value element-wisely.

Returns

Tensor, with absolute value element-wisely.

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 array 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. Default: ().

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

Returns

Tensor, if all array 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

Examples

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

Check any array 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. Default: ().

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

Returns

Tensor, if any array 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

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.

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

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.

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

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.

astype(dtype, copy=True)[source]

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

Parameters
  • dtype (Union[mindspore.dtype, str]) – Designated tensor dtype, can be in format of mindspore.dtype.float32 or float32. Default: mindspore.dtype.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 if possible. Default: True.

Returns

Tensor, with the designated dtype.

Raises

TypeError – If dtype has types not specified above, or values 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 an array from an index array and a list of arrays to choose from.

Parameters
  • choices (Union[tuple, list, Tensor]) – Choice arrays. a and all of the choices must be broadcasted to the same shape. If choices is itself an array, 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’ – raise an error (default);

    ‘wrap’ – wrap around;

    ‘clip’ – clip 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.

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 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 upper interval edge. Not more than one of xmin and xmax may be None. If xmin or xmax are tensors, then the three tensors 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 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")
>>> output = x.clip(0, 2)
>>> print(output)
[1. 2. 2. 0. 0. 2. 2. 0.]
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

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 a is 2-D, then a 1-D array containing the diagonal.

Raises

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

Supported Platforms:

Ascend GPU CPU

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 input tensor must obey the broadcasting rule.

Returns

Tensor, has the same dimension as input tensor.

fill(value)[source]

Fill the array with a scalar value.

Note

Unlike Numpy, tensor.fill() will always returns 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 as input tensor.

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. Only ‘C’ and ‘F’ are supported. 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’.

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.

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.

property has_init

tensor is inited.

init_data(slice_index=None, shape=None, opt_shard_group=None)[source]

Get the tensor format data of this Tensor. 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]

Getitem from the Tensor with the index.

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 euqal to self.ndim.

Supported Platforms:

Ascend GPU

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, with value set by \(tensor[args] = item\).

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

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

Supported Platforms:

Ascend GPU

Examples

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

Return the length of one tensor element in bytes.

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 array 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 an array of dimension self.ndim - 1.

Raises

TypeError – if 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'))
>>> 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. 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

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 array. 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 array 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, minimum of input tensor. If the axis is None, the result is a scalar value. If axis is given, the result is an array of dimension self.ndim - 1.

Raises

TypeError – if arguments have types not specified above.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import numpy as np
>>> 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
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’.

Note

Numpy arguments dtype and out are 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 array. 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 array. 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

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 an array.

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.

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

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 array of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions.

Returns

Tensor, with new specified shape.

Raises
  • TypeError – If new_shape is not integer, list or tuple, or x is not tensor.

  • 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 array in-place.

Note

Instead of changing the size of the input array 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 array.

Returns

Tensor.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> x = Tensor(np.array([[0, 1], [2, 3]]))
>>> x = x.resize(2, 3)
>>> print(x)
[[0 1 2]
[3 0 0]]
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 a.

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

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

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 single-dimensional entries from the shape of a 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 specified axis has shape entry \(> 1\).

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.squeeze()
>>> print(x.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

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 array 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 of the elements of the input array. 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 of 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 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

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 an array 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 array is used. Default: None.

  • mode (‘raise’, ‘wrap’, ‘clip’, optional) –

    • edge: Pads with the edge values of arr.

    • 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 array.

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

Raises

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

Supported Platforms:

Ascend GPU CPU

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 view of the 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 euqal to a.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.

Supported Platforms:

Ascend GPU CPU

Returns

Standard deviation tensor.

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.

Parameters

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

Returns

Tensor, has the same dimension as the input shape.

property virtual_flag

Used to mark whether the tensor is virtual. If the tensor is virtual, return True.