gpt4 book ai didi

python - PyTorch 获取二维张量中的值索引

转载 作者:行者123 更新时间:2023-12-04 10:41:25 25 4
gpt4 key购买 nike

给定以下张量(或任何具有二维的随机张量),我想获得“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])

但这看起来很困惑,而且可能很慢。有没有更好的方法来做到这一点,它既快速又更具火炬感?

仅讨论一维张量的相关问题:
  • How Pytorch Tensor get the index of specific value
  • How Pytorch Tensor get the index of elements?
  • 最佳答案

    怎么样(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])

    关于python - PyTorch 获取二维张量中的值索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59908433/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com