Python Pytorch张量-如何通过特定张量获取索引
我有张量Python Pytorch张量-如何通过特定张量获取索引,python,pytorch,Python,Pytorch,我有张量 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]) 有没有办法获得qlike的索引 indexes = t.index(q) # get back [0, 3] 在Pytork中?请尝试此操作,我没有在这台电脑上安装torch import torch t = torch.tensor([[1, 0, 0
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])
有没有办法获得q
like的索引
indexes = t.index(q) # get back [0, 3]
在Pytork中?请尝试此操作,我没有在这台电脑上安装torch
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])
编辑说明:针对Shai提出的问题进行编辑 怎么样
In [1]: torch.nonzero((t == q).sum(dim=1) == t.size(1))
Out[1]:
tensor([[ 0],
[ 3]])
比较t==q
在t
和q
之间执行元素级比较,因为您要查找整行匹配,所以需要沿行.sum(dim=1)
并查看哪一行是完美匹配的==t.size(1)
从v0.4.1开始,支持
dim
参数:
torch.all(t==q, dim=1)
一种更为pytorch原生的方法是:
torch.all(q.repeat((t.shape[1],1))==t, dim=1)
您的代码执行元素级比较,结果是
[[0,0]、[0,1]、[0,2]、[0,3]、[1,1]、[1,1]、[1,3]、[2,2]、[2,3]、[3,0]、[3,1]、[3,2]、[3,3]
。您需要比较行。@Shai Ic,这很容易修复