Transform Indices on Indexes

Let

x = tensor([[[[0, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]]]])

if we do x.nonzero() we get

x.nonzero() = tensor([[
[0, 0, 0, 1],
[0, 0, 0, 2],
[0, 0, 0, 3],
[0, 0, 1, 0],
[0, 0, 1, 1],
[0, 0, 1, 2],
[0, 0, 1, 3],
[0, 0, 2, 0],
[0, 0, 2, 1],
[0, 0, 2, 2],
[0, 0, 2, 3],
[0, 0, 3, 0],
[0, 0, 3, 1],
[0, 0, 3, 2],
[0, 0, 3, 3]])

It is possible to have a 1-D Array where we return the number of the index of x :

tensor([[[[ 1,2,3],[4,5,6,7],
[ 8,9,10,11],[12,13,14,15]]])

Your desired output format won’t work as it’s a nested tensor. However, you could flatten x to get at least the desired output values in a flattened shape:

x.view(-1).nonzero()
# tensor([[ 1],
#         [ 2],
#         [ 3],
#         [ 4],
#         [ 5],
#         [ 6],
#         [ 7],
#         [ 8],
#         [ 9],
#         [10],
#         [11],
#         [12],
#         [13],
#         [14],
#         [15]])