PyTorch torch.topk function
PyTorch torch reference manual
torch.topk is a function in PyTorch used to return the k largest elements and their indices.
Function definition
torch.topk(input, k, dim, largest, sorted, out)
Usage examples
Example
import
torch
x
=
torch.
tensor
(
[
[
3
,
1
,
2
]
,
[
6
,
4
,
5
]
]
)
Return the 2 largest elements
values
,
indices
=
torch.
topk
(
x
,
k
=
2
)
(
"The 2 largest values:"
)
(
values
)
(
"Corresponding indices:"
)
(
indices
)
The output is:
最大的 2 个值:
tensor([[3, 2],
[6, 5]])
Corresponding index:
tensor([[0, 2],
[0, 2]])