PyTorch 获取二维张量中的值索引 [英] PyTorch get indices of value in two-dimensional tensor

查看:57
本文介绍了PyTorch 获取二维张量中的值索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下张量(或任何具有二维的随机张量),我想获得101"的索引:

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:

推荐答案

(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])

这篇关于PyTorch 获取二维张量中的值索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆