PyTorch中的唯一张量值

aro*_*osa 10 pytorch

我想在PyTorch张量中找到不同的值.
是否有一些有效的方法来复制Tensorflow的独特操作?

Ale*_*sky 11

在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())
Run Code Online (Sandbox Code Playgroud)


ent*_*phy 5

执行此操作的最佳方法(最简单的方法)是转换为numpy并使用numpy的内置unique函数.像这样.

def unique(tensor1d):
    t, idx = np.unique(tensor1d.numpy(), return_inverse=True)
    return torch.from_numpy(t), torch.from_numpy(idx)  
Run Code Online (Sandbox Code Playgroud)

所以,当你尝试它:

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]
Run Code Online (Sandbox Code Playgroud)