mindspore.numpy.trace

View Source On Gitee
mindspore.numpy.trace(a, offset=0, axis1=0, axis2=1, dtype=None)[source]

Return the sum along diagonals of the tensor.

Note

  • trace is currently only used in mindscience scientific computing scenarios and dose not support other usage scenarios.

  • trace is not supported on Windows platform yet.

Parameters
  • a (Tensor) – A matrix to be calculated.

  • offset (int, optional) – Offset of the diagonal from the main diagonal. Can be positive or negative. Default: 0.

  • axis1 (int, optional) – Axis to be used as the first axis of the 2-D sub-arrays from which the diagonals should be taken. Default: 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. Default: 1.

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

Returns

Tensor, the sum along diagonals. If a is 2-D, the sum along the diagonal is returned. If a has more than two dimensions, then the axes specified by axis1 and axis2 are used to determine the 2-D sub-arrays whose traces are returned. The shape of the resulting array is the same as that of a with axis1 and axis2 removed.

Raises
  • ValueError – If a has less than two dimensions.

  • ValueError – If axis1 or axis2 is not in [-dims, dims), which dims is dimension of a.

  • ValueError – If axes specified by axis1 and axis2 are same.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> from mindspore.numpy import trace
>>> x = Tensor(np.eye(3, dtype=np.float32))
>>> print(trace(x))
3.0