Skip to main content
 首页 » 编程设计

python之Torch 张量非连续索引(类似于 Numpy)

2024年10月24日13langtianya

我是 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] 

谢谢!

请您参考如下方法:

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

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]