Getting largest values in a tensor

Say I have a tensor a = [[2,9,0],[4,1,3],[7,6,8]] and I want the largest 4 values and their indices, so [(9, [0, 1]), (8, [2, 2]), (7, [2, 0]), (6, [2, 1])], would it be more efficient to do torch.topk(a.view([1, 9]), 4) and then search through the original tensor for those values to get the positions of each value or would it be more efficient to convert the tensor to a list of lists?

I’d probably go for your topk call on a flattened tensor and unreaveling the indices as described here:

Best regards

Thomas

2 Likes