gpt4 book ai didi

python - 如何用另一个张量切片 PyTorch 张量?

转载 作者:行者123 更新时间:2023-12-03 23:48:07 28 4
gpt4 key购买 nike

我有:

inp =  torch.randn(4, 1040, 161)

我还有另一个名为 indices 的张量值:
tensor([[124, 583, 158, 529],
[172, 631, 206, 577]], device='cuda:0')

我想要相当于:
inp0 = inp[:,124:172,:]
inp1 = inp[:,583:631,:]
inp2 = inp[:,158:206,:]
inp3 = inp[:,529:577,:]

除了所有加在一起之外,要具有 [4, 48, 161] 的 .size| .我怎样才能做到这一点?

目前,我的解决方案是 for环形:
            left_indices = torch.empty(inp.size(0), self.side_length, inp.size(2))
for batch_index in range(len(inp)):
print(left_indices_start[batch_index].item())
left_indices[batch_index] = inp[batch_index, left_indices_start[batch_index].item():left_indices_end[batch_index].item()]

最佳答案

在这里(编辑:在执行以下操作之前,您可能需要使用 tensor=tensor.cpu() 将张量复制到 cpu):

index = tensor([[124, 583, 158, 529],
[172, 631, 206, 577]], device='cuda:0')
#create a concatenated list of ranges of indices you desire to slice
indexer = np.r_[tuple([np.s_[i:j] for (i,j) in zip(index[0,:],index[1,:])])]
#slice using numpy indexing
sliced_inp = inp[:, indexer, :]

下面是它的工作原理:
np.s_[i:j]从 start= i 创建索引的切片对象(只是一个范围)结束= j .
np.r_[i:j, k:m]创建切片中的所有索引列表 (i,j)(k,m) (您可以将更多切片传递给 np.r_ 以将它们一次连接在一起。这是仅连接两个切片的示例。)

因此, indexer通过连接切片列表(每个切片是一个索引范围)来创建所有索引的列表。

更新:如果您需要删除间隔重叠和排序间隔:
indexer = np.unique(indexer)

如果要删除间隔重叠但不排序并保持原始顺序(以及第一次出现的重叠)
uni = np.unique(indexer, return_index=True)[1]
indexer = [indexer[index] for index in sorted(uni)]

关于python - 如何用另一个张量切片 PyTorch 张量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61290287/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com