'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?
Solution 1:[1]
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].
Solution 2:[2]
TF supports strided slicing. That'll be the most native way to do what you need.
>>> a = np.asarray([[1,2,3], [4,5,6]])
>>> a
array([[1, 2, 3],
[4, 5, 6]])
>>> a[::-1, :]
array([[4, 5, 6],
[1, 2, 3]])
>>> a[::, ::-1]
array([[3, 2, 1],
[6, 5, 4]])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | draw |
| Solution 2 | Yaoshiang |
