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

PyTorch torch.diag function

PyTorch torch.diag function


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


Usage examples

Example

import

torch

Create a 1D tensor

x

=

torch.

tensor

(

[

1

,

2

,

3

]

)

Create a diagonal matrix

y

=

torch.

diag

(

x

)

print

(

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

)

print

(

y

)

The output is:

tensor([1, 5, 9])


PyTorch torch reference manual PyTorch torch reference manual