我有两个1DTensor:
A = torch.tensor([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
B = torch.tensor([2, 5, 6, 8, 12, 15, 16])
Tensor非常巨大,长度不同,值的顺序更快,也没有排序。
我想得到B中(i)存在于A中(ii)不存在于A中的元素的个数。因此,输出将是:
Exists: 4
Do not exist: 3
我试过:
exists = torch.eq(A,B).sum().item()
not_exist = torch.numel(B) - exists
但这给出了错误:
RuntimeError: The size of tensor a (10) must match the size of tensor b (7) at non-singleton dimension 0
下面的方法是可行的,但它首先需要创建一个boolean
Tensor,然后对true
元素求和。它对非常大的Tensor有效吗?
exists = np.isin(A,B).sum()
not_exist = torch.numel(B) - exists
有没有更好或更有效的方法?
1条答案
按热度按时间rsl1atfo1#
请尝试以下操作:进口 Torch
更新:
你可以坚持使用原生的PyTorch方法,比如广播。这种方法可能会占用更多内存,但对于大型Tensor更有效,特别是在使用GPU加速时。