我正在尝试在PyTorch张量中查找不同的值。 是否有Tensorflow的unique op的高效类比?
0.4.0版本中有一个torch.unique()方法。
在torch <= 0.3.1
版本中,你可以尝试:
import torch
import numpy as np
x = torch.rand((3,3)) * 10
np.unique(x.round().numpy())
def unique(tensor1d):
t, idx = np.unique(tensor1d.numpy(), return_inverse=True)
return torch.from_numpy(t), torch.from_numpy(idx)
例子:
t, idx = unique(torch.LongTensor([1, 1, 2, 4, 4, 4, 7, 8, 8]))
# t --> [1, 2, 4, 7, 8]
# idx --> [0, 0, 1, 2, 2, 2, 3, 4, 4]
torch.eq()
获取两个张量之间的公共项torch.unique
获得公共项:import torch as pt
a = pt.tensor([1,2,3,2,3,4,3,4,5,6])
b = pt.tensor([7,2,3,2,7,4,9,4,9,8])
equal_data = pt.eq(a, b)
pt.unique(pt.cat([a[equal_data],b[equal_data]]))