【问题标题】:How to get topk's values with its indices (2D)?如何使用其索引(2D)获取 topk 的值?
【发布时间】:2021-03-11 16:00:37
【问题描述】:

我有两个 3D 张量,我想使用一个前 k 个索引获得另一个前 k 个。

例如对于以下张量

a = torch.tensor([[[1], [2], [3]],
                  [[4], [5], [6]]])

b = torch.tensor([[[7,1], [8,2], [9,3]],
                  [[10,4],[11,5],[12,6]]])

pytorch 的 topk 函数会给我以下。

top_tensor, indices = torch.topk(a, 2, dim=1)

# top_tensor: tensor([[[3], [2]],
#                    [[6],  [5]]])

# indices: tensor([[[2], [1]],
#                 [[2],  [1]]])

但是我想使用a的结果,映射到b。

# use indices to do something for b, get torch.tensor([[[8,2], [9,3]],
#                                                      [[11,5],[12,6]]])

在这种情况下,我不知道b的真实值,所以我不能使用topk来b。

另一方面,我想得到一个函数 foo_slice,如下所示:

top_tensor, indices = torch.topk(a, 2, dim=1)
# top_tensor == foo_slice(a, indices)

有什么方法可以使用 pytorch 实现这一点吗?

谢谢!

【问题讨论】:

    标签: python pytorch torch


    【解决方案1】:

    您正在寻找的解决方案是here

    所以你的问题的基于代码的解决方案如下

    #inputs are changed in order from the above ques
    
    a = torch.tensor([[[1], [2], [3]],
                      [[5], [6], [4]]])
    
    b = torch.tensor([[[7,1], [8,2], [9,3]],
                      [[11,5],[12,6],[10,4]]])
    
    top_tensor, indices = torch.topk(a, 2, dim=1)
    
    v = [indices.view(-1,2)[i] for i in range(0,indices.shape[1])]
    
    
    new_tensor = []
    for i,f in enumerate(v):
          new_tensor.append(torch.index_select(b[i], 0, f))
    print(new_tensor ) #[tensor([[9, 3],
                       #         [8, 2]]),
                       #tensor([[12,  6],
                       #        [11,  5]])]
    

    【讨论】:

    • 我测试了一下,如果索引是tensor([[[1], [2]], [[0], [1]]]),这个解决方案会得到错误的答案。
    • 根据你的想法,我这样做:new_tensor = []; for batch in range(2):new_tensor.append(torch.index_select(q, 1, indices.view(-1,2)[batch])[batch]); final_tensor = torch.stack(new_tensor);
    • 糟糕...我不知道如何正确地用代码响应。
    • 嗨@Sam,你太有礼貌了!我已经进行了更改,现在它工作得非常好...为 3D 形状提供它
    猜你喜欢
    • 2020-03-17
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 2011-04-14
    • 2018-12-10
    • 2021-02-17
    • 1970-01-01
    相关资源
    最近更新 更多