How to swap lines from a 2D tensor?

Given the following 2D tensor whit shape [N,E]:

#N=3, E=3
r1 = torch.tensor([
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
])

how to swap the r1 “rows” to get results like the one shown below:

r1 = torch.tensor([
    [1, 2, 3],
    [7, 8, 9],
    [4, 5, 6]
    
])

Note: any permutation between the “rows” would be valid.

Hi!

>>> r1[[0,2,1]]
tensor([[1, 2, 3],
        [7, 8, 9],
        [4, 5, 6]])

Is this what you want?

Hello @Ruslan_Baynazarov,

It’s good answer, thank you! The following is a code snippet showing the complete example:

batch_size = 3
embedding_size = 4
sample = torch.rand(batch_size, embedding_size)
# tensor([[0.8855, 0.1571, 0.2649, 0.6999],
#         [0.0864, 0.3912, 0.1669, 0.6979],
#         [0.3881, 0.5181, 0.4245, 0.3675]])

shuffle_index = torch.randperm(batch_size)
# tensor([2, 0, 1])

shuffled_sample = sample[[shuffle_index]]
# tensor([[0.3881, 0.5181, 0.4245, 0.3675],
#         [0.8855, 0.1571, 0.2649, 0.6999],
#         [0.0864, 0.3912, 0.1669, 0.6979]])