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

PyTorch torch.topk function

PyTorch torch.topk function


PyTorch torch reference manual 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

)

print

(

"The 2 largest values:"

)

print

(

values

)

print

(

"Corresponding indices:"

)

print

(

indices

)

The output is:

最大的 2 个值:

tensor([[3, 2],

        [6, 5]])

Corresponding index:

tensor([[0, 2],

        [0, 2]])


PyTorch torch reference manual PyTorch torch reference manual