Torch 张量非连续索引(类似于 Numpy)
Torch7 Tensor Non-Contiguos Index (Similar to 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]
谢谢!
好的,环顾四周,我找不到确切的解决方案,但我找到了我想做的事情的近似值,我分享它以防其他人发现它有用:
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]
torch.IndexCopy
正是您所需要的:
array:indexCopy(1, indices, torch.Tensor({1, 2, 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
我是 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]
torch.IndexCopy
正是您所需要的:
array:indexCopy(1, indices, torch.Tensor({1, 2, 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