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

PyTorch torch.triu_indices function

PyTorch torch.triu_indices function


PyTorch torch reference manual PyTorch torch reference manual

torch.triu_indices is a function in PyTorch used to generate indices for an upper triangular matrix. It returns the row and column indices of the upper triangular part (including the diagonal).

Function definition

torch.triu_indices(row, column, offset=0, dtype=torch.long, device='cpu')

Parameter Description:


Usage examples

Example

import

torch

Generate upper triangular indices for a 3x3 matrix

row

,

col

=

torch.

triu_indices

(

3

,

3

)

print

(

"row:"

,

row

)

print

(

"col:"

,

col

)

The output is:

row: tensor([0, 0, 0, 1, 1, 2])

col: tensor([0, 1, 2, 1, 2, 2])

Example

import

torch

Generate indices and use them in an indexing operation

row

,

col

=

torch.

triu_indices

(

3

,

3

,

offset

=

1

)

Create a 3x3 matrix

a

=

torch.

ones

(

3

,

3

)

Use the indices to set the upper triangular part

a

[

row

,

col

]

=

0

print

(

a

)

The output is:

tensor([[1., 1., 1.],

        [0., 1., 1.],

        [0., 0., 1.]])

Example

import

torch

Non-square matrix case

row

,

col

=

torch.

triu_indices

(

3

,

4

)

print

(

"row:"

,

row

)

print

(

"col:"

,

col

)

The output is:

row: tensor([0, 0, 0, 1, 1, 2])

col: tensor([0, 1, 2, 1, 2, 2])


PyTorch torch reference manual PyTorch torch reference manual