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

PyTorch torch.diagonal function

PyTorch torch.diagonal function


PyTorch torch reference manual PyTorch torch reference manual

torch.diagonal is a PyTorch function for extracting the diagonal elements of a tensor. It returns a view of the specified diagonal of the input tensor.

Function definition

torch.diagonal(input, diagonal=0, dim1=0, dim2=1)

Parameter Description:


Usage examples

Example

import

torch

Create a 3x3 matrix

x

=

torch.

tensor

(

[

[

1

,

2

,

3

]

,

[

4

,

5

,

6

]

,

[

7

,

8

,

9

]

]

)

Extract the main diagonal

y

=

torch.

diagonal

(

x

)

print

(

y

)

The output is:

tensor([1, 5, 9])

Example

import

torch

Create a 3x3 matrix

x

=

torch.

tensor

(

[

[

1

,

2

,

3

]

,

[

4

,

5

,

6

]

,

[

7

,

8

,

9

]

]

)

Extract the diagonal above the main diagonal

y

=

torch.

diagonal

(

x

,

offset

=

1

)

print

(

y

)

The output is:

tensor([2, 6])

Example

import

torch

Create a 3D tensor

x

=

torch.

arange

(

12

)

.

reshape

(

2

,

3

,

4

)

Extract the diagonal along specified dimensions

y

=

torch.

diagonal

(

x

,

offset

=

0

,

dim1

=

1

,

dim2

=

2

)

print

(

y.

shape

)

print

(

y

)

The output is:

torch.Size([2, 3])

tensor([[ 0,  5, 10],

        [12, 17, 22]])


PyTorch torch reference manual PyTorch torch reference manual