使用Torch7 Tensor进行非连续索引(类似于Numpy)

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

谢谢!

点赞
用户2267681
用户2267681

我找不到确切的解决方案,但我找到了我想要做的近似解决方案,我分享一下,以防有人觉得有用:

array = torch.zeros(5) -- array = [0 0 0 0 0]
indices = torch.LongTensor({1, 3, 5}) -- 重要的是要使用 LongTensor
array:indexAdd(1, indices, torch.Tensor({1, 2, 3})) -- array = [1 0 2 0 3]
2015-11-29 19:38:43
用户4850610
用户4850610

torch.IndexCopy 正是你所需要的:

array:indexCopy(1, indices, torch.Tensor({1, 2, 3}))
2015-12-08 21:31:29
用户6262499
用户6262499

如果你是 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)

# 在这里放入你的 Torch 代码

# 将 tensor 转换回 numpy 数组
array = tensor.asNumpyArray()
# 现在 array 与 tensor 共享内存
2016-04-27 17:36:32