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

PyTorch torch.diagflat function

PyTorch torch.diagflat function


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


Usage examples

Example

import

torch

Create a 1D tensor

x

=

torch.

tensor

(

[

1

,

2

,

3

]

)

Create a diagonal flat matrix

y

=

torch.

diagflat

(

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

]

]

)

It will be flattened to [1,2,3,4], creating a 4x4 diagonal matrix

y

=

torch.

diagflat

(

x

)

print

(

y

)

The output is:

tensor([[1, 0, 0, 0],

        [0, 2, 0, 0],

        [0, 0, 3, 0],

        [0, 0, 0, 4]])


PyTorch torch reference manual PyTorch torch reference manual