PyTorch torch.diag function
PyTorch torch reference manual
torch.diag is a PyTorch function for creating a diagonal matrix or extracting the diagonal elements of a tensor.
Function definition
torch.diag(input, diagonal=0, out=None)
Parameter Description:
input: the input tensordiagonal: Diagonal index; 0 means the main diagonal, positive values mean upper diagonals, negative values mean lower diagonals
Usage examples
Example
import
torch
Create a 1D tensor
x
=
torch.
tensor
(
[
1
,
2
,
3
]
)
Create a diagonal matrix
y
=
torch.
diag
(
x
)
(
y
)
The output is:
tensor([[1, 0, 0],
[0, 2, 0],
[0, 0, 3]])
Example
import
torch
Extract diagonal elements from a matrix
x
=
torch.
tensor
(
[
[
1
,
2
,
3
]
,
[
4
,
5
,
6
]
,
[
7
,
8
,
9
]
]
)
Extract the main diagonal
y
=
torch.
diag
(
x
)
(
y
)
The output is:
tensor([1, 5, 9])