PyTorch torch.tril function
PyTorch torch reference manual
torch.tril is a function in PyTorch used to extract the lower triangular part of a matrix (including the main diagonal). The upper triangular part is set to 0.
Function definition
torch.tril(input, diagonal=0, out=None)
Parameter Description:
input: the input tensordiagonal: Diagonal index; 0 means the main diagonalout: Output tensor
Usage examples
Example
import
torch
Create a matrix
a
=
torch.
tensor
(
[
[
1
,
2
,
3
]
,
[
4
,
5
,
6
]
,
[
7
,
8
,
9
]
]
)
Extract the lower triangular part
y
=
torch.
tril
(
a
)
(
y
)
The output is:
tensor([[1, 0, 0],
[4, 5, 0],
[7, 8, 9]])
Example
import
torch
Create a matrix
a
=
torch.
tensor
(
[
[
1
,
2
,
3
]
,
[
4
,
5
,
6
]
,
[
7
,
8
,
9
]
]
)
Extract the lower triangle below the first diagonal under the main diagonal
y
=
torch.
tril
(
a
,
diagonal
=
1
)
(
y
)
The output is:
tensor([[1, 2, 0],
[4, 5, 6],
[7, 8, 9]])
Example
import
torch
Create a non-square matrix
a
=
torch.
tensor
(
[
[
1
,
2
,
3
]
,
[
4
,
5
,
6
]
]
)
Extract the lower triangular part
y
=
torch.
tril
(
a
)
(
y
)
The output is:
tensor([[1, 0, 0],
[4, 5, 0]])