Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PyTorch torch.trace function

PyTorch torch.trace function


PyTorch torch reference manual PyTorch torch reference manual

torch.trace is a function in PyTorch used to compute the trace of a matrix. The trace is the sum of the elements on the main diagonal of the matrix.

Function definition

torch.trace(input)

Parameter Description:


Usage examples

Example

import

torch

Create a matrix

a

=

torch.

tensor

(

[

[

1

,

2

,

3

]

,

[

4

,

5

,

6

]

,

[

7

,

8

,

9

]

]

)

Compute the trace (sum of the main diagonal elements)

y

=

torch.

trace

(

a

)

print

(

y

)

The output is:

tensor(15)

Example

import

torch

Create a non-square matrix

a

=

torch.

tensor

(

[

[

1

,

2

,

3

]

,

[

4

,

5

,

6

]

]

)

Compute the trace

y

=

torch.

trace

(

a

)

print

(

y

)

The output is:

tensor(6)

Example

import

torch

Create a multi-dimensional tensor, considering only the first two dimensions

a

=

torch.

randn

(

3

,

4

,

4

,

5

)

y

=

torch.

trace

(

a

)

print

(

y.

shape

)

The output is:

torch.Size([3, 5])


PyTorch torch reference manual PyTorch torch reference manual