简体   繁体   中英

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)

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM