如何在二维张量中获取相同值的张量的索引?

How to get indices of tensors of same value in a 2-d tensor?

如标题所述,给定一个二维张量,假设:

tensor([
    [0, 1, 0, 1], # A
    [1, 1, 0, 1], # B
    [1, 0, 0, 1], # C
    [0, 1, 0, 1], # D
    [1, 1, 0, 1], # E
    [1, 1, 0, 1]  # F
])

很容易看出“A和D”、“B、E和F”是两组张量,

具有相同的值(即 A == D 和 B == E == F)。

所以我的问题是:

How to get indices of those groups?

详情:

Input: tensor above

Output: (0, 3), (1, 4, 5)

使用 PyTorch 函数的解决方案:

import torch

x = torch.tensor([
    [0, 1, 0, 1], # A
    [1, 1, 0, 1], # B
    [1, 0, 0, 1], # C
    [0, 1, 0, 1], # D
    [1, 1, 0, 1], # E
    [1, 1, 0, 1]  # F
])

_, inv, counts = torch.unique(x, dim=0, return_inverse=True, return_counts=True)
print([tuple(torch.where(inv == i)[0].tolist()) for i, c, in enumerate(counts) if counts[i] > 1])
# > [(0, 3), (1, 4, 5)]