【问题标题】:Torch7 Tensor Non-Contiguos Index (Similar to Numpy)Torch 张量非连续索引(类似于 Numpy)
【发布时间】:2016-03-03 05:01:08
【问题描述】:

我是torch7的新手,我找不到基于另一个张量获取张量的一些非连续索引的方法。在 numpy 中,我所做的如下:

array = np.zeros(5) # array = [0 0 0 0 0]
indices = np.array([0, 2, 4])
array[indices] = np.array([1, 2, 3]) # array = [1 0 2 0 3]

有没有办法在torch7中做类似的事情?比如:

array = torch.zeros(5) -- array = [0 0 0 0 0]
indices = torch.Tensor({1, 3, 5})
array[indices] = torch.Tensor({1, 2, 3}) -- array = [1 0 2 0 3]

谢谢!

【问题讨论】:

    标签: python numpy lua torch


    【解决方案1】:

    好的,环顾四周,我找不到确切的解决方案,但我找到了我想做的近似值,我分享它以防其他人发现它有用:

    array = torch.zeros(5) -- array = [0 0 0 0 0]
    indices = torch.LongTensor({1, 3, 5}) -- Is important that this is a LongTensor
    array:indexAdd(1, indices, torch.Tensor({1, 2, 3})) -- array = [1 0 2 0 3]
    

    【讨论】:

      【解决方案2】:

      torch.IndexCopy 完全满足您的需求:

      array:indexCopy(1, indices, torch.Tensor({1, 2, 3}))
      

      【讨论】:

        【解决方案3】:

        如果你是 python 用户,也许你也可以试试 https://github.com/imodpasteur/lutorpy 。例如,您可以在 python 中处理您的数组,然后将其转换为 Torch 张量。如果你想转换回numpy数组,转换是即时的,因为它只传递指针,并且python和lua中的两个对象共享相同的内存。

        array = np.zeros(5) # array = [0 0 0 0 0]
        indices = np.array([0, 2, 4])
        array[indices] = np.array([1, 2, 3]) # array = [1 0 2 0 3]
        
        require("torch")
        # convert numpy array to torch tensor
        tensor = torch.fromNumpyArray(array) 
        
        # put your torch code here
        
        #convert back to numpy array
        array = tensor.asNumpyArray()
        # now array is sharing memory with tensor 
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-10-31
          • 2017-09-11
          • 2021-08-12
          • 1970-01-01
          • 2020-04-13
          • 2016-05-15
          • 1970-01-01
          相关资源
          最近更新 更多