mindspore.Tensor

class mindspore.Tensor(input_data=None, dtype=None, shape=None, init=None, internal=False, const_arg=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

  • const_arg (bool) – Whether the tensor is a constant when it is used for the argument of a network. 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

Neural Network Layer Methods

Neural Network

API Name

Description

Supported Platforms

mindspore.Tensor.flatten

Return a copy of the tensor collapsed into one dimension.

Ascend GPU CPU

Activation Function

API Name

Description

Supported Platforms

mindspore.Tensor.hardshrink

Apply the Hard Shrink function for tensor.

Ascend GPU CPU

mindspore.Tensor.soft_shrink

Apply the soft shrink function for a tensor.

Ascend GPU CPU

Element-wise Methods

API Name

Description

Supported Platforms

mindspore.Tensor.abs

Return absolute value element-wisely.

Ascend GPU CPU

mindspore.Tensor.addcdiv

Performs the element-wise division of tensor x1 by tensor x2, multiply the result by the scalar value and add it to input_data.

Ascend GPU CPU

mindspore.Tensor.addcmul

Performs the element-wise product of tensor x1 and tensor x2, multiply the result by the scalar value and add it to input_data.

Ascend GPU CPU

mindspore.Tensor.atan2

Returns arctangent of x/y element-wise.

Ascend CPU GPU

mindspore.Tensor.bernoulli

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

GPU

mindspore.Tensor.bitwise_and

Returns bitwise and of two tensors element-wise.

Ascend GPU CPU

mindspore.Tensor.bitwise_or

Returns bitwise or of two tensors element-wise.

Ascend GPU CPU

mindspore.Tensor.bitwise_xor

Returns bitwise xor of two tensors element-wise.

Ascend GPU CPU

mindspore.Tensor.ceil

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

Ascend GPU CPU

mindspore.Tensor.cosh

Computes hyperbolic cosine of x element-wise.

Ascend GPU CPU

mindspore.Tensor.erf

Computes the Gauss error function of self tensor element-wise.

Ascend GPU CPU

mindspore.Tensor.erfc

Computes the complementary error function of self tensor element-wise.

Ascend GPU CPU

mindspore.Tensor.exp

Returns exponential of a tensor element-wise.

Ascend GPU CPU

mindspore.Tensor.inv

Computes Reciprocal of this Tensor element-wise.

Ascend GPU CPU

mindspore.Tensor.invert

Flips all bits of this Tensor element-wise.

Ascend GPU CPU

mindspore.Tensor.lerp

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

Ascend GPU CPU

mindspore.Tensor.log

Returns the natural logarithm of self Tensor element-wise.

Ascend GPU CPU

mindspore.Tensor.log1p

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

Ascend GPU CPU

mindspore.Tensor.logit

Calculate the logit of a tensor element-wise.

GPU

mindspore.Tensor.pow

Calculate the power of Tensor.

Ascend GPU CPU

mindspore.Tensor.round

Returns half to even of the tensor element-wise.

Ascend GPU CPU

mindspore.Tensor.sigmoid

Sigmoid activation function.

Ascend GPU CPU

mindspore.Tensor.sqrt

Returns sqrt of a tensor element-wise.

Ascend GPU CPU

mindspore.Tensor.square

Returns square of a tensor element-wise.

Ascend GPU CPU

mindspore.Tensor.std

Compute the standard deviation along the specified axis.

Ascend GPU CPU

mindspore.Tensor.sub

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

Ascend GPU CPU

mindspore.Tensor.svd

Computes the singular value decompositions of one or more matrices.

GPU CPU

mindspore.Tensor.tan

Computes tangent of x element-wise.

Ascend GPU CPU

mindspore.Tensor.tanh

Tanh activation function.

Ascend GPU CPU

mindspore.Tensor.var

Compute the variance along the specified axis.

Ascend GPU CPU

mindspore.Tensor.xdivy

Divides self tensor by the input tensor element-wise.

Ascend GPU CPU

mindspore.Tensor.xlogy

Computes the self tensor multiplied by the logarithm of input tensor element-wise.

Ascend GPU CPU

Reduction Methods

API Name

Description

Supported Platforms

mindspore.Tensor.amax

Reduces a dimension of a tensor by the maximum value in the dimension, by default.

Ascend GPU CPU

mindspore.Tensor.amin

Reduces a dimension of a tensor by the minimum value in the dimension, by default.

Ascend GPU CPU

mindspore.Tensor.argmax

Return the indices of the maximum values along an axis.

Ascend GPU CPU

mindspore.Tensor.argmin

Return the indices of the minimum values along an axis.

Ascend GPU CPU

mindspore.Tensor.argmax_with_value

Returns the maximum value with corresponding index.

Ascend GPU CPU

mindspore.Tensor.argmin_with_value

Returns the minimum value with corresponding index.

Ascend GPU CPU

mindspore.Tensor.max

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

Ascend GPU CPU

mindspore.Tensor.mean

Reduces a dimension of a tensor by averaging all elements in the dimension, by default.

Ascend GPU CPU

mindspore.Tensor.median

Computes the median of input tensor.

GPU CPU

mindspore.Tensor.min

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

Ascend GPU CPU

mindspore.Tensor.norm

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

Ascend GPU CPU

mindspore.Tensor.prod

Reduces a dimension of a tensor by product all elements in the dimension, by default.

Ascend GPU CPU

mindspore.Tensor.renorm

Renormalizes the sub-tensors along dimension dim, and each sub-tensor's p-norm should not exceed the 'maxnorm'.

Ascend CPU GPU

Comparison Methods

API Name

Description

Supported Platforms

mindspore.Tensor.all

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

Ascend GPU CPU

mindspore.Tensor.any

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

Ascend GPU CPU

mindspore.Tensor.approximate_equal

Returns True if abs(x-y) is smaller than tolerance element-wise, otherwise False.

Ascend GPU CPU

mindspore.Tensor.has_init

Whether tensor is initialized.

Ascend GPU CPU

mindspore.Tensor.isclose

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

Ascend GPU CPU

mindspore.Tensor.isfinite

Determines which elements are finite for each position.

Ascend GPU CPU

mindspore.Tensor.top_k

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

Ascend GPU CPU

Linear Algebraic Methods

API Name

Description

Supported Platforms

mindspore.Tensor.ger

Ger product of self and x.

Ascend GPU CPU

mindspore.Tensor.log_matrix_determinant

Computes the sign and the log of the absolute value of the determinant of one or more square matrices.

GPU CPU

mindspore.Tensor.matrix_determinant

Computes the determinant of one or more square matrices.

Ascend GPU CPU

Tensor Operation Methods

Tensor Construction

API Name

Description

Supported Platforms

mindspore.Tensor.choose

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

Ascend GPU CPU

mindspore.Tensor.fill

Fill the tensor with a scalar value.

Ascend GPU CPU

mindspore.Tensor.fills

Create a tensor of the same shape and type as the input tensor and fill it with specified value.

GPU

mindspore.Tensor.view

Reshape the tensor according to the input shape.

Ascend GPU CPU

Random Generation Methods

API Name

Description

Supported Platforms

mindspore.Tensor.random_categorical

Generates random samples from a given categorical distribution tensor.

Ascend GPU CPU

Array Methods

API Name

Description

Supported Platforms

mindspore.Tensor.broadcast_to

Broadcasts input tensor to a given shape.

Ascend GPU CPU

mindspore.Tensor.col2im

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

GPU

mindspore.Tensor.copy

Return a copy of the tensor.

Ascend GPU CPU

mindspore.Tensor.cummax

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.

GPU CPU

mindspore.Tensor.cummin

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.

Ascend GPU CPU

mindspore.Tensor.cumsum

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

Ascend GPU CPU

mindspore.Tensor.diag

Constructs a diagonal tensor with a given diagonal values.

Ascend GPU

mindspore.Tensor.diagonal

Return specified diagonals.

Ascend GPU CPU

mindspore.Tensor.dtype

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

Ascend GPU CPU

mindspore.Tensor.expand_as

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

Ascend GPU CPU

mindspore.Tensor.expand_dims

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

Ascend GPU CPU

mindspore.Tensor.gather

Returns the slice of the input tensor corresponding to the elements of input_indices on the specified axis.

Ascend GPU CPU

mindspore.Tensor.gather_elements

Gathers elements along an axis specified by dim.

Ascend GPU CPU

mindspore.Tensor.gather_nd

Gathers slices from a input tensor by indices.

Ascend GPU CPU

mindspore.Tensor.index_fill

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.

GPU

mindspore.Tensor.init_data

Get the tensor format data of this Tensor.

Ascend GPU CPU

mindspore.Tensor.inplace_update

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

Ascend GPU CPU

mindspore.Tensor.item

Get the item at the specified index of the tensor.

Ascend GPU CPU

mindspore.Tensor.itemset

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

Ascend GPU CPU

mindspore.Tensor.itemsize

Return the length of one tensor element in bytes.

Ascend GPU CPU

mindspore.Tensor.masked_fill

Fills elements of self tensor with value where mask is True.

Ascend GPU CPU

mindspore.Tensor.masked_select

Returns a new 1-D Tensor which indexes the self tensor according to the boolean mask.

Ascend GPU CPU

mindspore.Tensor.minimum

Computes the minimum of self and input tensor element-wise.

Ascend GPU CPU

mindspore.Tensor.nbytes

Return the total number of bytes taken by the tensor.

Ascend GPU CPU

mindspore.Tensor.ndim

Return the number of tensor dimensions.

Ascend GPU CPU

mindspore.Tensor.nonzero

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

GPU

mindspore.Tensor.narrow

Returns a narrowed tensor from input tensor.

Ascend GPU CPU

mindspore.Tensor.ptp

The name of the function comes from the acronym for "peak to peak".

Ascend GPU CPU

mindspore.Tensor.ravel

Return a contiguous flattened tensor.

Ascend GPU CPU

mindspore.Tensor.repeat

Repeat elements of a tensor.

Ascend GPU CPU

mindspore.Tensor.reshape

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

Ascend GPU CPU

mindspore.Tensor.resize

Changes shape and size of tensor in-place.

Ascend GPU CPU

mindspore.Tensor.scatter_add

Creates a new tensor by adding the values from the positions in self tensor indicated by indices, with values from updates.

Ascend GPU CPU

mindspore.Tensor.scatter_div

Creates a new tensor by dividing the values from the positions in self tensor indicated by indices, with values from updates.

GPU CPU

mindspore.Tensor.scatter_max

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.

GPU CPU

mindspore.Tensor.scatter_min

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.

Ascend GPU CPU

mindspore.Tensor.scatter_mul

Creates a new tensor by multiplying the values from the positions in self tensor indicated by indices, with values from updates.

GPU CPU

mindspore.Tensor.scatter_sub

Creates a new tensor by subtracting the values from the positions in self tensor indicated by indices, with values from updates.

Ascend GPU CPU

mindspore.Tensor.searchsorted

Finds indices where elements should be inserted to maintain order.

Ascend GPU CPU

mindspore.Tensor.select

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.

Ascend GPU CPU

mindspore.Tensor.shape

Returns the shape of the tensor as a tuple.

Ascend GPU CPU

mindspore.Tensor.size

Returns the total number of elements in tensor.

Ascend GPU CPU

mindspore.Tensor.split

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

Ascend GPU CPU

mindspore.Tensor.squeeze

Remove the dimension of shape 1 from the Tensor

Ascend GPU CPU

mindspore.Tensor.strides

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

Ascend GPU CPU

mindspore.Tensor.sum

Return sum of tensor elements over a given axis.

Ascend GPU CPU

mindspore.Tensor.swapaxes

Interchange two axes of a tensor.

Ascend GPU CPU

mindspore.Tensor.T

Return the transposed tensor.

Ascend GPU CPU

mindspore.Tensor.take

Takes elements from a tensor along an axis.

Ascend GPU CPU

mindspore.Tensor.to_tensor

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

Ascend GPU CPU

mindspore.Tensor.trace

Return the sum along diagonals of the tensor.

Ascend GPU CPU

mindspore.Tensor.transpose

Return a tensor with axes transposed.

Ascend GPU CPU

mindspore.Tensor.unique_consecutive

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

Ascend GPU

mindspore.Tensor.unique_with_pad

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

Ascend GPU CPU

mindspore.Tensor.unsorted_segment_max

Computes the maximum along segments of a tensor.

Ascend GPU CPU

mindspore.Tensor.unsorted_segment_min

Computes the minimum of a tensor along segments.

Ascend GPU CPU

mindspore.Tensor.unsorted_segment_prod

Computes the product of a tensor along segments.

Ascend GPU

Type Conversion

API Name

Description

Supported Platforms

mindspore.Tensor.asnumpy

Convert tensor to numpy array.

Ascend GPU CPU

mindspore.Tensor.astype

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

Ascend GPU CPU

mindspore.Tensor.from_numpy

Convert numpy array to Tensor.

Ascend GPU CPU

mindspore.Tensor.to_coo

Convert a Tensor to COOTensor.

GPU

mindspore.Tensor.to_csr

Convert a Tensor to CSRTensor.

GPU

Gradient Clipping

API Name

Description

Supported Platforms

mindspore.Tensor.clip

Clips (limits) the values in a Tensor.

Ascend GPU CPU

Parameter Operation Methods

API Name

Description

Supported Platforms

mindspore.Tensor.assign_value

Assign another tensor value to this tensor.

Ascend GPU CPU

Other Methods

API Name

Description

Supported Platforms

mindspore.Tensor.flush_from_cache

Flush cache data to host if tensor is cache enable.

Ascend GPU CPU

mindspore.Tensor.set_const_arg

Specify whether the tensor is a constant when it is used for the argument of a network.

Ascend GPU CPU