如何根据相同大小的索引张量对张量进行重新排序

乘风 pytorch 545

原文标题How to reorder tensor based on indexes tensor from the same size

说我有tensorA和索引TensorA = [1, 2, 3, 4]indexes = [1, 0, 3, 2]

我想从这两个中创建一个新的Tensor,结果如下:[2, 1, 4, 3]结果的每个元素都是来自A的元素,并且顺序由索引定义Tensor。有没有办法用 PyTorchtensorops 没有循环?

我的目标是为 2D 做它Tensor,但我不认为没有循环可以做到这一点,所以我想将它投影到 1D,完成工作并将其投影回 2D。

原文链接:https://stackoverflow.com//questions/71575211/how-to-reorder-tensor-based-on-indexes-tensor-from-the-same-size

回复

我来回复
  • teplandr的头像
    teplandr 评论

    您可以使用分散:

    A = torch.tensor([1, 2, 3, 4])
    indices = torch.tensor([1, 0, 3, 2])
    result = torch.tensor([0, 0, 0, 0])
    print(result.scatter_(0, indices, A))
    
    2年前 0条评论
  • aretor的头像
    aretor 评论

    在 1D 中,您可以简单地执行A[indexes]

    在 2D 中,它仍然可以通过这种方式实现:

    A = torch.arange(5, 10).repeat(3, 1)  # shape: (3, 5)
    indexes = torch.stack([torch.randperm(5) for _ in range(3)])  # shape (3, 5)
    
    A_sort = A[torch.arange(3).unsqueeze(1), indexes]
    print(A_sort)
    
    2年前 0条评论