作者:alian | 来源:互联网 | 2023-01-30 10:26
我想在PyTorch张量中找到不同的值.
是否有一些有效的方法来复制Tensorflow的独特操作?
1> Alex Glinsk..:
在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())
2> entrophy..:
执行此操作的最佳方法(最简单的方法)是转换为numpy并使用numpy的内置unique
函数.像这样.
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]