Marzi Heidari
Marzi Heidari

Reputation: 2730

in-place shuffle torch.Tensor in the order of a numpy.ndarray

I want to change the order of elements of a torch.Tensor from default to a numpy.ndarray. In other words, I want to shuffle it so that the order of its elements be specified with a numpy array; the important thing about this problem is that I don't want any third object to be created (because of memory limits) Is there something like below code in python 2.7?

torch_tensor.shuffle(order)

Upvotes: 2

Views: 3012

Answers (1)

MBT
MBT

Reputation: 24169

Edit: This should be an in-place version:

import torch
import numpy as np

t = torch.rand(10)
print('Original Tensor:', t)

order = np.array(range(10))
np.random.shuffle(order)
print('Order:', order)

# in-place changing of values
t[np.array(range(10))] = t[order]
print('New Tensor:', t)

Output:

Original Tensor: tensor([ 0.3380,  0.3450,  0.2253,  0.0279,  0.3945,  0.6055,  0.1489,
         0.7676,  0.4213,  0.2683])
Order: [7 1 3 6 2 9 0 5 4 8]
New Tensor: tensor([ 0.7676,  0.3450,  0.0279,  0.1489,  0.2253,  0.2683,  0.3380,
         0.6055,  0.3945,  0.4213])

I hope this is roughly what you were looking for!

Upvotes: 3

Related Questions