PyTorch torch.trace function
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:
input: The input tensor (at least 2D)
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
)
(
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
)
(
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
)
(
y.
shape
)
The output is:
torch.Size([3, 5])