>>> output = torch.unique(torch.tensor([1, 3, 2, 3], dtype=torch.long))
>>> output
tensor([1, 2, 3])
>>> output, inverse_indices = torch.unique(
... torch.tensor([1, 3, 2, 3], dtype=torch.long), sorted=True, return_inverse=True)
>>> output
tensor([1, 2, 3])
>>> inverse_indices
tensor([0, 2, 1, 2])
>>> output, inverse_indices = torch.unique(
... torch.tensor([[1, 3], [2, 3]], dtype=torch.long), sorted=True, return_inverse=True)
>>> output
tensor([1, 2, 3])
>>> inverse_indices
tensor([[0, 2],
[1, 2]])
>>> a = torch.tensor([
... [
... [1, 1, 0, 0],
... [1, 1, 0, 0],
... [0, 0, 1, 1],
... ],
... [
... [0, 0, 1, 1],
... [0, 0, 1, 1],
... [1, 1, 1, 1],
... ],
... [
... [1, 1, 0, 0],
... [1, 1, 0, 0],
... [0, 0, 1, 1],
... ],
... ])
>>> # If we call `torch.unique(a, dim=0)`, each of the tensors `a[idx, :, :]`
>>> # will be compared. We can see that `a[0, :, :]` and `a[2, :, :]` match
>>> # each other, so one of them will be removed.
>>> (a[0, :, :] == a[2, :, :]).all()
tensor(True)
>>> a_unique_dim0 = torch.unique(a, dim=0)
>>> a_unique_dim0
tensor([[[0, 0, 1, 1],
[0, 0, 1, 1],
[1, 1, 1, 1]],
[[1, 1, 0, 0],
[1, 1, 0, 0],
[0, 0, 1, 1]]])
>>> # Notice which sub-tensors from `a` match with the sub-tensors from
>>> # `a_unique_dim0`:
>>> (a_unique_dim0[0, :, :] == a[1, :, :]).all()
tensor(True)
>>> (a_unique_dim0[1, :, :] == a[0, :, :]).all()
tensor(True)
>>> # For `torch.unique(a, dim=1)`, each of the tensors `a[:, idx, :]` are
>>> # compared. `a[:, 0, :]` and `a[:, 1, :]` match each other, so one of
>>> # them will be removed.
>>> (a[:, 0, :] == a[:, 1, :]).all()
tensor(True)
>>> torch.unique(a, dim=1)
tensor([[[0, 0, 1, 1],
[1, 1, 0, 0]],
[[1, 1, 1, 1],
[0, 0, 1, 1]],
[[0, 0, 1, 1],
[1, 1, 0, 0]]])
>>> # For `torch.unique(a, dim=2)`, the tensors `a[:, :, idx]` are compared.
>>> # `a[:, :, 0]` and `a[:, :, 1]` match each other. Also, `a[:, :, 2]` and
>>> # `a[:, :, 3]` match each other as well. So in this case, two of the
>>> # sub-tensors will be removed.
>>> (a[:, :, 0] == a[:, :, 1]).all()
tensor(True)
>>> (a[:, :, 2] == a[:, :, 3]).all()
tensor(True)
>>> torch.unique(a, dim=2)
tensor([[[0, 1],
[0, 1],
[1, 0]],
[[1, 0],
[1, 0],
[1, 1]],
[[0, 1],
[0, 1],
[1, 0]]])
For web site terms of use, trademark policy and other policies applicable to The PyTorch Foundation please see
www.linuxfoundation.org/policies/. The PyTorch Foundation supports the PyTorch open source
project, which has been established as PyTorch Project a Series of LF Projects, LLC. For policies applicable to the PyTorch Project a Series of LF Projects, LLC,
please see www.lfprojects.org/policies/.