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

PyTorch torch.triu function

PyTorch torch.triu function


PyTorch torch reference manual PyTorch torch reference manual

torch.triu is a function in PyTorch used to extract the upper triangular part of a matrix (including the main diagonal). The lower triangular part is set to 0.

Function definition

torch.triu(input, diagonal=0, out=None)

Parameter Description:


Usage examples

Example

import

torch

Create a matrix

a

=

torch.

tensor

(

[

[

1

,

2

,

3

]

,

[

4

,

5

,

6

]

,

[

7

,

8

,

9

]

]

)

Extract the upper triangular part

y

=

torch.

triu

(

a

)

print

(

y

)

The output is:

tensor([[1, 2, 3],

        [0, 5, 6],

        [0, 0, 9]])

Example

import

torch

Create a matrix

a

=

torch.

tensor

(

[

[

1

,

2

,

3

]

,

[

4

,

5

,

6

]

,

[

7

,

8

,

9

]

]

)

Extract the upper triangle above the first diagonal over the main diagonal

y

=

torch.

triu

(

a

,

diagonal

=

1

)

print

(

y

)

The output is:

tensor([[0, 2, 3],

        [0, 0, 6],

        [0, 0, 0]])

Example

import

torch

Create a non-square matrix

a

=

torch.

tensor

(

[

[

1

,

2

,

3

]

,

[

4

,

5

,

6

]

]

)

Extract the upper triangular part

y

=

torch.

triu

(

a

)

print

(

y

)

The output is:

tensor([[1, 2, 3],

        [0, 5, 6]])


PyTorch torch reference manual PyTorch torch reference manual