PyTorch torch.unique function
PyTorch torch reference manual
torch.unique is a function in PyTorch used to get the unique values. It returns the unique values in a tensor and can optionally return the corresponding indices.
Function definition
torch.unique(input, sorted=True, return_inverse=False, return_counts=False, dim=None)
Usage examples
Example
import
torch
Creating tensors
x
=
torch.
tensor
(
[
1
,
2
,
2
,
3
,
1
,
4
,
3
]
)
Get unique values
unique_vals
=
torch.
unique
(
x
)
(
f
"Unique values: {unique_vals}"
)
Also return the indices
unique_vals
,
inverse_idx
=
torch.
unique
(
x
,
return_inverse
=
True
)
(
f
"Inverse indices: {inverse_idx}"
)
Also return the counts
unique_vals
,
counts
=
torch.
unique
(
x
,
return_counts
=
True
)
(
f
"Counts: {counts}"
)