2

Given the following tensor (or any random tensor with two dimension), I want to get the index of '101':

tens = tensor([[  101,   146,  1176, 21806,  1116,  1105, 18621,   119,   102,     0,
             0,     0,     0],
        [  101,  1192,  1132,  1136,  1184,   146,  1354,  1128,  1127,   117,
          1463,   119,   102],
        [  101,  6816,  1905,  1132, 14918,   119,   102,     0,     0,     0,
             0,     0,     0]])

From the related answers I know that I can do something like this:

idxs = torch.tensor([(i == 101).nonzero() for i in tens])

But this seems messy and potentially quite slow. Is there a better way to do this that is fast and more torch-y?

Related questions discussing only one-dimensional tensor:

1 Answer 1

2

How about (tens == 101).nonzero()[:, 1]

In [20]: from torch import tensor                                                                       

In [21]: tens = torch.tensor([[  101,   146,  1176, 21806,  1116,  1105, 18621,   119,   102,     0, 
    ...:              0,     0,     0], 
    ...:         [  101,  1192,  1132,  1136,  1184,   146,  1354,  1128,  1127,   117, 
    ...:           1463,   119,   102], 
    ...:         [  101,  6816,  1905,  1132, 14918,   119,   102,     0,     0,     0, 
    ...:              0,     0,     0]])                                                                

In [22]: (tens == 101).nonzero()[:, 1]                                                                  
Out[22]: tensor([0, 0, 0])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.