简体   繁体   English

如何将 PyTorch 张量与另一个张量切片?

[英]How can I slice a PyTorch tensor with another tensor?

I have:我有:

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

and I have another tensor called indices with values:我有另一个张量,称为带有值的indices

tensor([[124, 583, 158, 529],
        [172, 631, 206, 577]], device='cuda:0')

I want the equivalent of:我想要相当于:

inp0 = inp[:,124:172,:]
inp1 = inp[:,583:631,:]
inp2 = inp[:,158:206,:]
inp3 = inp[:,529:577,:]

Except all added together, to have a.size of [4, 48, 161] .除了全部加在一起,a.size 为[4, 48, 161] How can I accomplish this?我怎样才能做到这一点?

Currently, my solution is a for loop:目前,我的解决方案是一个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()]

Here you go (EDIT: you probably need to copy tensors to cpu using tensor=tensor.cpu() before doing following operations):在这里你 go (编辑:在执行以下操作之前,您可能需要使用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, :]

Here is how it works:下面是它的工作原理:

np.s_[i:j] creates a slice object (simply a range) of indices from start= i to end= j . np.s_[i:j]创建从 start= i到 end= j的索引切片 object (只是一个范围)。

np.r_[i:j, k:m] creates a list ALL indices in slices (i,j) and (k,m) (You can pass more slices to np.r_ to concatenate them all together at once. This is an example of concatenating only two slices.) np.r_[i:j, k:m]在切片(i,j)(k,m)中创建一个列表所有索引(您可以将更多切片传递给np.r_以一次将它们连接在一起。这是仅连接两个切片的示例。)

Therefore, indexer creates a list of ALL indices by concatenating a list of slices (each slice is a range of indices).因此, indexer通过连接切片列表(每个切片是一个索引范围)来创建所有索引的列表。

UPDATE: If you need to remove interval overlaps and sort intervals:更新:如果您需要删除间隔重叠和排序间隔:

indexer = np.unique(indexer)

if you want to remove interval overlaps but not sort and keep original order (and first occurrences of overlaps)如果要删除间隔重叠但不排序并保持原始顺序(以及第一次出现的重叠)

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,:])

You can implement it like this... zip function helps to convert your indices tensor to list of tuples which you can use directly via for loop您可以像这样实现它... zip function 有助于将您的索引张量转换为您可以通过 for 循环直接使用的元组列表

Hope it helps you out....希望对你有所帮助......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM