从张量数组中切出不均匀的列

Slicing uneven columns from tensor array

我有一个这样的数组:

([[[ 0,  1,  2],
 [ 3,  4,  5]],

[[ 6,  7,  8],
[ 9, 10, 11]],

[[12, 13, 14],
[15, 16, 17]]])

如果我想将数字 12 分割为 17,我会使用:

arr[2, 0:2, 0:3]

但是我如何将数组切片以获得 12 到 16?

您需要先 "flatten" 最后两个维度。只有这样你才能提取你想要的元素:

xf = x.view(x.size(0), -1)  # flatten the last dimensions
xf[2, 0:5]
Out[87]: tensor([12, 13, 14, 15, 16])

另一种方法是简单地索引张量并切片所需的内容,如:

# input tensor 
t = tensor([[[ 0,  1,  2],
             [ 3,  4,  5]],

           [[ 6,  7,  8],
            [ 9, 10, 11]],

           [[12, 13, 14],
            [15, 16, 17]]])

# slice the last `block`, then flatten it and 
# finally slice all elements but the last one
In [10]: t[-1].view(-1)[:-1]   
Out[10]: tensor([12, 13, 14, 15, 16])

请注意,由于这是一个基本切片,因此它 returns 一个 view。因此,对切片部分进行任何更改也会影响原始张量。例如:

# assign it to some variable name
In [11]: sliced = t[-1].view(-1)[:-1] 
In [12]: sliced      
Out[12]: tensor([12, 13, 14, 15, 16])

# modify one element
In [13]: sliced[-1] = 23   

In [14]: sliced  
Out[14]: tensor([12, 13, 14, 15, 23])

# now, the original tensor is also updated
In [15]: t  
Out[15]: 
tensor([[[ 0,  1,  2],
         [ 3,  4,  5]],

        [[ 6,  7,  8],
         [ 9, 10, 11]],

        [[12, 13, 14],
         [15, 23, 17]]])