Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pytorch tensor - How to get the indexes by a specific tensor

Tags:

python

pytorch

I have a tensor

t = torch.tensor([[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [1, 0, 0, 0]])

and a query tensor

q = torch.tensor([1, 0, 0, 0])

Is there a way to get the indexes of q like

indexes = t.index(q) # get back [0, 3]

in pytorch?

like image 374
do. Avatar asked Jan 27 '23 15:01

do.


2 Answers

How about

In [1]: torch.nonzero((t == q).sum(dim=1) == t.size(1))
Out[1]: 
tensor([[ 0],
        [ 3]])

Comparing t == q performs element-wise comparison between t and q, since you are looking for entire row match, you need to .sum(dim=1) along the rows and see what row is a perfect match == t.size(1).


As of v0.4.1, torch.all() supports dim argument:

torch.all(t==q, dim=1)
like image 143
Shai Avatar answered Jan 30 '23 05:01

Shai


Please try this, I do not have torch installed on this PC.

import torch

t = torch.tensor([[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [1, 0, 0, 0]])
q = torch.tensor([1, 0, 0, 0])

index = torch.nonzero(torch.sum((t == q), dim=1) == t.shape[1])

Edit note: edited for the issue raised by Shai.

like image 35
hyloop Avatar answered Jan 30 '23 05:01

hyloop