PyTorch torch.tril_indices function
PyTorch torch reference manual
torch.tril_indices is a function in PyTorch used to generate indices for a lower triangular matrix. It returns the row and column indices of the lower triangular part (including the diagonal).
Function definition
torch.tril_indices(row, column, offset=0, dtype=torch.long, device='cpu')
Parameter Description:
row: Number of rowscolumn: Number of columnsoffset: Diagonal offsetdtype: The data type of the returned indicesdevice: Device
Usage examples
Example
import
torch
Generate lower triangular indices for a 3x3 matrix
row
,
col
=
torch.
tril_indices
(
3
,
3
)
(
"row:"
,
row
)
(
"col:"
,
col
)
The output is:
row: tensor([0, 1, 1, 2, 2, 2])
col: tensor([0, 0, 1, 0, 1, 2])
Example
import
torch
Generate indices and use them in an indexing operation
row
,
col
=
torch.
tril_indices
(
3
,
3
,
offset
=
1
)
Create a 3x3 matrix
a
=
torch.
ones
(
3
,
3
)
Use the indices to set the lower triangular part
a
[
row
,
col
]
=
0
(
a
)
The output is:
tensor([[1., 0., 0.],
[1., 1., 0.],
[1., 1., 1.]])
Example
import
torch
Non-square matrix case
row
,
col
=
torch.
tril_indices
(
3
,
4
)
(
"row:"
,
row
)
(
"col:"
,
col
)
The output is:
row: tensor([0, 1, 1, 2, 2, 2])
col: tensor([0, 0, 1, 0, 1, 2])