Pytorch tensor 如何找到特定值的索引 (index)

使用 torch.nonzero(),返回非零值的索引 (index)
其中 True 算作非零数,False 算作零,所以可以巧用判别式来找到 Tensor 特定值的索引,如我们要找 tensor a 里面 10 这个数字的 index,可以这样做

import torch

a = torch.arange(3*5).reshape(3,5).view(-1)

b = torch.nonzero(a==10).squeeze()

print(b) # tensor(10)

你可能感兴趣的:(Python,pytorch,python)