PyTorch torch.diagflat function
PyTorch torch reference manual
torch.diagflat is a PyTorch function for creating a diagonal flat matrix. Whether the input is 1D or multi-dimensional, it is flattened and used as the diagonal elements.
Function definition
torch.diagflat(input, diagonal=0)
Parameter Description:
input: Input tensor, which will be flatteneddiagonal: Diagonal index
Usage examples
Example
import
torch
Create a 1D tensor
x
=
torch.
tensor
(
[
1
,
2
,
3
]
)
Create a diagonal flat matrix
y
=
torch.
diagflat
(
x
)
(
y
)
The output is:
tensor([[1, 0, 0],
[0, 2, 0],
[0, 0, 3]])
Example
import
torch
Create a 2D tensor
x
=
torch.
tensor
(
[
[
1
,
2
]
,
[
3
,
4
]
]
)
It will be flattened to [1,2,3,4], creating a 4x4 diagonal matrix
y
=
torch.
diagflat
(
x
)
(
y
)
The output is:
tensor([[1, 0, 0, 0],
[0, 2, 0, 0],
[0, 0, 3, 0],
[0, 0, 0, 4]])