torch.unique¶
- torch.unique(input, sorted=True, return_inverse=False, return_counts=False, dim=None) Tuple[张量, 张量, 张量]¶
返回输入张量的唯一元素。
注意
此函数与
torch.unique_consecutive()不同之处在于,此函数还会消除非连续的重复值。注意
目前在CUDA实现和CPU实现中, torch.unique 总是会在开始时对张量进行排序,无论 sort 参数如何。 排序可能会很慢,因此如果输入张量已经排序,建议使用
torch.unique_consecutive(),这样可以避免排序。- Parameters
- Returns
包含的张量或张量元组
output (Tensor): 唯一标量元素的输出列表。
inverse_indices (Tensor): (可选) 如果
return_inverse为 True,将会有一个额外的返回张量(与输入形状相同)表示原始输入中元素在输出中的索引位置;否则,此函数将只返回一个张量。counts (Tensor): (可选) 如果
return_counts为 True,将会有一个额外的返回张量(与输出形状相同或输出.size(dim),如果指定了 dim)表示每个唯一值或张量的出现次数。
- Return type
示例:
```html>>> 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], ... ], ... ]) >>> # 如果我们调用 `torch.unique(a, dim=0)`,每个张量 `a[idx, :, :]` >>> # 将会被比较。我们可以看到 `a[0, :, :]` 和 `a[2, :, :]` 匹配 >>> # 彼此,所以其中一个将被移除。 >>> (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]]]) >>> # 注意 `a` 中的哪些子张量与 `a_unique_dim0` 中的子张量匹配: >>> (a_unique_dim0[0, :, :] == a[1, :, :]).all() tensor(True) >>> (a_unique_dim0[1, :, :] == a[0, :, :]).all() tensor(True) >>> # 对于 `torch.unique(a, dim=1)`,每个张量 `a[:, idx, :]` 被 >>> # 比较。`a[:, 0, :]` 和 `a[:, 1, :]` 匹配彼此,所以其中一个 >>> # 将被移除。 >>> (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]]]) >>> # 对于 `torch.unique(a, dim=2)`,张量 `a[:, :, idx]` 被比较。 >>> # `a[:, :, 0]` 和 `a[:, :, 1]` 匹配彼此。同时,`a[:, :, 2]` 和 >>> # `a[:, :, 3]` 也匹配彼此。所以在这种情况下,两个子张量将被移除。 >>> (a[:, :, 0] == a[:, :, 1]).all() tensor(True) >>> (a[:, :,</span