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

PyTorch torch.diag_embed function

PyTorch torch.diag_embed function


PyTorch torch reference manual 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:


Usage examples

Example

import

torch

Create a 1D tensor

x

=

torch.

tensor

(

[

1

,

2

,

3

]

)

Create a diagonal embedding

y

=

torch.

diag_embed

(

x

)

print

(

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

)

print

(

y.

shape

)

print

(

y

)

The output is:

torch.Size([2, 2, 2])

tensor([[[1, 0],

         [0, 2]],



        [[3, 0],

         [0, 4]]])


PyTorch torch reference manual PyTorch torch reference manual