Shortcuts

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
  • 输入 (张量) – 输入张量

  • sorted (bool) – 是否在返回输出之前按升序对唯一元素进行排序。

  • return_inverse (bool) – 是否也返回原始输入中元素在返回的唯一列表中的索引。

  • return_counts (布尔值) – 是否也返回每个唯一元素的计数。

  • dim (int, 可选) – 要操作的维度。如果 None,则返回展平输入的唯一值。否则,由给定维度索引的每个张量被视为要应用唯一操作的元素之一。有关更多详细信息,请参见示例。默认值:None

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
优云智算