如何用另一个张量对 PyTorch 张量进行切片?

How can I slice a PyTorch tensor with another tensor?

我有:

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 到 end=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)]
inp =  torch.randn(4, 1040, 161)   
indices = torch.tensor([[124, 583, 158, 529],
            [172, 631, 206, 577]])
k = zip(indices[0], indices[1])
for i,j in k:
    print(inp[:,i:j,:])

您可以像这样实现它...zip 函数有助于将您的索引张量转换为您可以通过 for 循环直接使用的元组列表

希望对您有所帮助....