Wasi Ahmad
Wasi Ahmad

Reputation: 37761

How two rows can be swapped in a torch tensor?

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

Upvotes: 5

Views: 12140

Answers (4)

shaneb
shaneb

Reputation: 1494

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.

Upvotes: 3

iacob
iacob

Reputation: 24351

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]])

Upvotes: 2

warriorUSP
warriorUSP

Reputation: 373

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.

Upvotes: 3

mbpaulus
mbpaulus

Reputation: 7711

Generate the permutation index you desire:

index = torch.LongTensor([1,0,2])

Apply the permutation:

var[index] = var

Upvotes: 0

Related Questions