简体   繁体   中英

Simple Torch7 equivalent to numpy.roll

Is there any simple way of rolling a tensor in torch7 like numpy.roll and numpy.rollaxis in python?

Thanks!

You can achieve the effects of numpy's rollaxis with torch's permute . While rollaxis requires the start and end position of the one axis to move, permute requires the new positions of all axis. Eg for a 3-dimensional tensor np.rollaxis(x, 0, 3) (move the 1st axis to the end) would be equivalent to x:permute(2, 3, 1) .

I'm not aware of an easy replacement for numpy's roll , but scatter seems like a decent candidate. Call it with the required dimension and the new order of elements after the shift. (Requires one new order of elements for each single row.) The following example shifts each row of x (containing 2 rows and 4 columns with random values) 2 to the right along the last axis:

th> x = torch.zeros(2, 4):uniform(0, 10)
th> y = torch.zeros(2, 4):scatter(2, torch.LongTensor{{3, 4, 1, 2}, {3, 4, 1, 2}}, x)
th> x
 0.7295  3.2218  7.3979  5.5500
 8.4354  3.6722  5.5463  3.4323
[torch.DoubleTensor of size 2x4]
th> y
 7.3979  5.5500  0.7295  3.2218
 5.5463  3.4323  8.4354  3.6722
[torch.DoubleTensor of size 2x4]

也许您可以尝试lutorpy,以便可以在python中使用numpy数组,然后将其传递到Torch模块并转换回去。

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