How to Reverse Order of Rows in a Tensor

I'm trying to reverse the order of the rows in a tensor that I create. I have tried with tensorflow and pytorch. Only thing I have found is the torch.flip() method. This does not work as it reverses not only the order of the rows, but also all of the elements in each row. I want the elements to remain the same. Is there an array operation of this to index the integers? For instance:

 tensor_a = [1, 2, 3] [4, 5, 6] [7, 8, 9] I want it to be returned as: [7, 8, 9] [4, 5, 6] [1, 2, 3] however, torch.flip(tensor_a) = [9, 8, 7] [6, 5, 4] [3, 2, 1] 

Anyone have any suggestions?

2 Answers

According to documentation torch.flip has argument dims, which control what axis to be flipped. In this case torch.flip(tensor_a, dims=(0,)) will return expected result. Also torch.flip(tensor_a) will reverse all tensor, and torch.flip(tensor_a, dims=(1,)) will reverse every row, like [1, 2, 3] --> [3, 2, 1].

1

I am not sure about the performance of the solution I have, but you can do something as follow:

import torch y = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # Uncomment the next two lines so u can see it works on GPU as well # device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") # y.to(device) y = y[[2, 1, 0], :] # y = y[::-1, :] # this works in numpy but not in pytorch :( print(y) 

You can check numpy documentation on Slicing and Advanced Indexing for similar examples. Hope this helps.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like