篩選出前k個最小的數:
Microsoft Windows [版本 10.0.18363.1256]
(c) 2019 Microsoft Corporation,保留所有權利,
C:\Users\chenxuqi>conda activate ssd4pytorch1_2_0
(ssd4pytorch1_2_0) C:\Users\chenxuqi>python
Python 3.7.7 (default, May 6 2020, 11:45:54) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import torch
>>> torch.manual_seed(seed=20200910)
<torch._C.Generator object at 0x0000026DB7CFD330>
>>>
>>> data = torch.randint(100,(15,))
>>> data
tensor([63, 48, 14, 47, 28, 5, 80, 68, 88, 61, 6, 84, 82, 87, 59])
>>> # 篩選出前k個最小的數
>>> k = 7
>>> a, idx1 = torch.sort(data)
>>> b, idx2 = torch.sort(idx1)
>>> a
tensor([ 5, 6, 14, 28, 47, 48, 59, 61, 63, 68, 80, 82, 84, 87, 88])
>>> data
tensor([63, 48, 14, 47, 28, 5, 80, 68, 88, 61, 6, 84, 82, 87, 59])
>>> data[idx2<k]
tensor([48, 14, 47, 28, 5, 6, 59])
>>>
>>>
>>>
篩選出前k個最大的數:
Microsoft Windows [版本 10.0.18363.1256]
(c) 2019 Microsoft Corporation,保留所有權利,
C:\Users\chenxuqi>conda activate ssd4pytorch1_2_0
(ssd4pytorch1_2_0) C:\Users\chenxuqi>python
Python 3.7.7 (default, May 6 2020, 11:45:54) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import torch
>>> torch.manual_seed(seed=20200910)
<torch._C.Generator object at 0x000001846D60D330>
>>>
>>>
>>> data = torch.randint(100,(15,))
>>> data
tensor([63, 48, 14, 47, 28, 5, 80, 68, 88, 61, 6, 84, 82, 87, 59])
>>> # 篩選出前k個最大的數
>>>
>>> k = 7
>>> a, idx1 = torch.sort(data, descending=True)
>>> b, idx2 = torch.sort(idx1)
>>>
>>> a
tensor([88, 87, 84, 82, 80, 68, 63, 61, 59, 48, 47, 28, 14, 6, 5])
>>> data
tensor([63, 48, 14, 47, 28, 5, 80, 68, 88, 61, 6, 84, 82, 87, 59])
>>> data[idx2<k]
tensor([63, 80, 68, 88, 84, 82, 87])
>>>
>>>
>>>
簡單證明:

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/241335.html
標籤:python
