【问题标题】:Extracting the top-k value-indices from a 1-D Tensor从一维张量中提取前 k 个值索引
【发布时间】:2016-04-17 10:59:35
【问题描述】:

给定 Torch (torch.Tensor) 中的一维张量,其中包含可以比较的值(比如浮点),我们如何提取其中的 top-k 值的索引张量?

除了蛮力方法之外,我正在寻找一些 API 调用,由 Torch/lua 提供,它可以有效地执行此任务。

【问题讨论】:

    标签: python lua pytorch torch


    【解决方案1】:

    从拉取请求 #496 开始,Torch 现在包含一个名为 torch.topk 的内置 API。示例:

    > t = torch.Tensor{9, 1, 8, 2, 7, 3, 6, 4, 5}
    
    -- obtain the 3 smallest elements
    > res = t:topk(3)
    > print(res)
     1
     2
     3
    [torch.DoubleTensor of size 3]
    
    -- you can also get the indices in addition
    > res, ind = t:topk(3)
    > print(ind)
     2
     4
     6
    [torch.LongTensor of size 3]
    
    -- alternatively you can obtain the k largest elements as follow
    -- (see the API documentation for more details)
    > res = t:topk(3, true)
    > print(res)
     9
     8
     7
    [torch.DoubleTensor of size 3]
    

    在撰写本文时,CPU 实现遵循sort and narrow approach(未来计划对其进行改进)。话虽如此,目前为 cutorch 优化的 GPU 实现是reviewed

    【讨论】:

    • deltheil,我正在尝试按照您的建议进行操作,但遇到以下错误:res = t:topk(3) [string "res = t:topk(3)"]:1: attempt to call method 'topk' (a nil value);你能告诉我发生了什么吗?
    • 您的torch7安装太旧:尝试安装最新版本(最近添加了topk)。
    • deltheil,我也这么认为。现在可以工作了。谢谢。
    • 有人可以解释一下t:topk(3) 中的列 (:) 语法,它给了我NameError,而torch.topk(t, k=3),按预期工作?
    【解决方案2】:

    你可以使用topk函数。

    例如:

    import torch
    
    t = torch.tensor([5.7, 1.4, 9.5, 1.6, 6.1, 4.3])
    
    values,indices = t.topk(2)
    
    print(values)
    print(indices)
    

    结果:

    tensor([9.5000, 6.1000])
    tensor([2, 4])
    

    【讨论】:

      【解决方案3】:

      只需遍历张量并运行比较:

      require 'torch'
      
      data = torch.Tensor({1,2,3,4,505,6,7,8,9,10,11,12})
      idx  = 1
      max  = data[1]
      
      for i=1,data:size()[1] do
         if data[i]>max then
            max=data[i]
            idx=i
         end
      end
      
      print(idx,max)
      

      --编辑-- 响应您的编辑:使用此处记录的 torch.max 操作:https://github.com/torch/torch7/blob/master/doc/maths.md#torchmaxresval-resind-x-dim ...

      y, i = torch.max(x, 1) returns the largest element in each column (across rows) of x, and a Tensor i of their corresponding indices in x
      

      【讨论】:

      • binarymax,你知道如何像这样直接提取任何一般的top-k值吗?
      • 如果您需要索引而不是值,那么不需要。如果您只需要这些值,则对张量进行排序,然后对其进行切片。
      猜你喜欢
      • 2021-01-22
      • 2020-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多