使用 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)
本文介绍了如何利用PyTorch的torch.nonzero()函数找到Tensor中非零值的索引,特别是在寻找特定数值如10的索引时。通过将条件判断与该函数结合,可以轻松获取目标值的索引位置。例如,对于一个reshape后的3x5 Tensor,可以将其view为一维并使用torch.nonzero(a==10).squeeze()来获取10的索引。
使用 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)
5026