2

Is there any way, in Pytorch, to convert a 1d tensor([[1., 2., 3., 4.]]) into

tensor([[1., 2., 3., 4.], 
        [2., 1., 2., 3.], 
        [3., 2., 1., 2.], 
        [4., 3., 2., 1.]]) 
iacob
  • 20,084
  • 6
  • 92
  • 119
elroy so
  • 21
  • 1
  • it looks like you are looking to compute the distance from the diagonal, rather than expanding. What exactly are you after? – Shai Jun 10 '21 at 06:22

1 Answers1

0

torch.roll unfortunately only applies dimension-wise, so you will have to expand and use something like torch.gather, along with a set of index shifts:

t = tensor([[1., 2., 3., 4.]])

idx = torch.arange(4)
idx = torch.stack([torch.roll(idx, shift) for shift in range(0,-4,-1)])

torch.gather(t.expand(4,-1), 1, idx)
iacob
  • 20,084
  • 6
  • 92
  • 119