给出以下张量(或任何二维的随机张量),我想得到'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]])
从相关答案中,我知道我可以做这样的事情:
idxs = torch.tensor([(i == 101).nonzero() for i in tens])
但是,这似乎很混乱,并且可能非常缓慢。有没有更好的方法来做到这一点,而且又更快呢?
仅讨论一维张量的相关问题:
答案 0 :(得分:2)
(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])