Pytorch 在张量列表中查找n个最小值

Pytorch 在张量列表中查找n个最小值,pytorch,tensor,Pytorch,Tensor,我试图找到pytorch中张量列表中n个最小值的索引。由于这些张量可能包含许多非唯一值,我不能简单地计算百分位数来获得指数。然而,非唯一值的顺序并不重要 我提出了以下解决方案,但我想知道是否有更优雅的方法: 导入火炬 n=10 张量列表=[torch.randn(10,10),torch.zero(20,20),torch.one(30,10)] all_sorted,all_sorted_idx=torch.sort(torch.cat([t.view(-1)表示张量列表中的t])) cum_

我试图找到pytorch中张量列表中n个最小值的索引。由于这些张量可能包含许多非唯一值,我不能简单地计算百分位数来获得指数。然而,非唯一值的顺序并不重要

我提出了以下解决方案,但我想知道是否有更优雅的方法:

导入火炬
n=10
张量列表=[torch.randn(10,10),torch.zero(20,20),torch.one(30,10)]
all_sorted,all_sorted_idx=torch.sort(torch.cat([t.view(-1)表示张量列表中的t]))
cum_num_elements=torch.cumsum(torch.tensor([t.numel()表示张量列表中的t]),dim=0)
cum_num_elements=torch.cat([torch.tensor([0]),cum_num_elements])
拆分索引\u lt=[所有排序的\u idx[:n]=cum_num_elements[i]for i,在枚举中(cum_num_elements[:-1])]
拆分索引=[所有排序的索引idx[:n][torch.logical\u and(lt,ge)]-c表示lt,ge,zip中的c(拆分索引\u lt,拆分索引\u ge,cum\u num元素[:-1])]
n_minimate=[t.view(-1)[idx]表示t,idx在zip中(张量列表,拆分索引)]

编辑:理想情况下,解决方案会选择非唯一值的随机子集,而不是选择列表中第一个张量的条目。

Pytorch确实提供了一种更优雅(我认为)的方法,使用
torch.unique\u continuoused
(请参阅)

我将研究一个张量,而不是张量列表,因为正如你自己所做的,只有一个
cat
要做。之后解开这些指数也不难

# We want to find the n=3 min values and positions in t 
n = 3
t = torch.tensor([1,2,3,2,0,1,4,3,2])
# To get a random occurrence, we create a random permutation
randomizer = torch.randperm(len(t))
# first, we sort t, and get the indices
sorted_t, idx_t = t[randomizer].sort()
# small util function to extract only the n smallest values and positions
head = lambda v,w : (v[:n], w[:n])
# use unique_consecutive to remove duplicates
uniques_t, counts_t = head(*torch.unique_consecutive(sorted_t, return_counts=True))
# counts_t.cumsum gives us the position of the unique values in sorted_t
uniq_idx_t = torch.cat([torch.tensor([0]), counts_t.cumsum(0)[:-1]], 0)
# And now, we have the positions of uniques_t values in t : 
final_idx_t = randomizer[idx_t[uniq_idx_t]]
print(uniques_t, final_idx_t)

>>> tensor([0,1,2]), tensor([4,0,1])
>>> tensor([0,1,2]), tensor([4,5,8])
>>> tensor([0,1,2]), tensor([4,0,8])

编辑:我认为添加的排列解决了您需要的随机出现问题

您好,我不太理解您的编辑。你想要n个最小的张量值,它是通过连接整个张量列表产生的,是吗?您的意思是,您不希望获取第一次出现的最小值,而是随机出现的值?@TrialError是的。如果由于多个相同的值导致排序不确定,我需要一个随机排序。这是找到n个最小唯一值的好方法,谢谢!不幸的是,这并不能回答我的问题,因为我要的是n个最小值,因为有许多相同(非唯一)的值,这些值不允许严格的单调排序,但应该包括在内。@smonsays我在pytorch中找不到可靠的非确定性排序,所以我事先添加了一个置换。这对你有用吗?