Search code examples
pythonnumpyluatorch

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!


Solution

  • 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. E.g. 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]