How two rows can be swapped in a torch tensor?

Viewed 7757
var = [[0, 1, -4, 8],
       [2, -3, 2, 1],
       [5, -8, 7, 1]]

var = torch.Tensor(var)

Here, var is a 3 x 4 (2d) tensor. How the first and second row can be swapped to get the following 2d tensor?

2, -3, 2, 1 
0, 1, -4, 8
5, -8, 7, 1
4 Answers

The other answer does not work, as some dimensions get overwritten before they are copied:

>>> var = [[0, 1, -4, 8],
       [2, -3, 2, 1],
       [5, -8, 7, 1]]
>>> x = torch.tensor(var)
>>> index = torch.LongTensor([1, 0, 2])
>>> x[index] = x
>>> x
tensor([[ 0,  1, -4,  8],
        [ 0,  1, -4,  8],
        [ 5, -8,  7,  1]])

For me, it suffices to create a new tensor (with separate underlying storage) to hold the result:

>>> x = torch.tensor(var)
>>> index = torch.LongTensor([1, 0, 2])
>>> y = torch.zeros_like(x)
>>> y[index] = x

Alternatively, you can use index_copy_ (following this explanation in discuss.pytorch.org), although I don't see an advantage for either way at the moment.

You can use index_select for this:

>>> idx = torch.LongTensor([1,0,2])
>>> var.index_select(0, idx)

tensor([[ 2, -3,  2,  1],
        [ 0,  1, -4,  8],
        [ 5, -8,  7,  1]])

As other answers suggested that your permutation index should be a tensor itself, but it is not necessary. You can swap 1st and 2nd row like this:

>>> var
tensor([[ 0,  1, -4,  8],
        [ 2, -3,  2,  1],
        [ 5, -8,  7,  1]])

>>> var[[0, 1]] = var[[1, 0]]

>>> var
tensor([[ 2, -3,  2,  1],
        [ 0,  1, -4,  8],
        [ 5, -8,  7,  1]])

var can be a NumPy array or PyTorch tensor.

Related