PyTorch torch.unique Function


Pytorch torch 参考手册Pytorch torch Reference Manual

torch.uniqueIt is a function in PyTorch used to get unique values. It returns the unique values in the 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

Examples

import torch

# Create a tensor
x = torch.tensor([1, 2, 2, 3, 1, 4, 3])

# Get unique values
unique_vals = torch.unique(x)
print(f"Unique values: {unique_vals}")

# Also return indices
unique_vals, inverse_idx = torch.unique(x, return_inverse=True)
print(f"Inverse indices: {inverse_idx}")

# Also return counts
unique_vals, counts = torch.unique(x, return_counts=True)
print(f"Counts: {counts}")

Pytorch torch 参考手册Pytorch torch Reference Manual

Other Extensions