我想在torch.sort对排序张量进行操作和其他一些修改后取回原始张量顺序,以便不再对张量进行排序。最好用一个例子来解释这一点:
x = torch.tensor([30., 40., 20.])
ordered, indices = torch.sort(x)
# ordered is [20., 30., 40.]
# indices is [2, 0, 1]
ordered = torch.tanh(ordered) # it doesn't matter what operation is
final = original_order(ordered, indices)
# final must be equal to torch.tanh(x)
Run Code Online (Sandbox Code Playgroud)
我以这种方式实现了该功能:
def original_order(ordered, indices):
z = torch.empty_like(ordered)
for i in range(ordered.size(0)):
z[indices[i]] = ordered[i]
return z
Run Code Online (Sandbox Code Playgroud)
Is there a better way to do this? In particular, it is possible to avoid the loop and compute …