PyTorch torch.diag_embed function
PyTorch torch reference manual
torch.diag_embed is a PyTorch function for embedding an input tensor as diagonal elements into a new tensor. It creates a diagonal along the last dimension of the input.
Function definition
torch.diag_embed(input, diagonal=0, offset=0)
Parameter Description:
input: the input tensordiagonal/offset: Diagonal index
Usage examples
Example
import
torch
Create a 1D tensor
x
=
torch.
tensor
(
[
1
,
2
,
3
]
)
Create a diagonal embedding
y
=
torch.
diag_embed
(
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
]
]
)
Create a diagonal embedding
y
=
torch.
diag_embed
(
x
)
(
y.
shape
)
(
y
)
The output is:
torch.Size([2, 2, 2])
tensor([[[1, 0],
[0, 2]],
[[3, 0],
[0, 4]]])