Change the shape of tensor

Hi,

I want to change the tensor shape from:

[[[[ 1.,  2.,  3.,  4.],
   [ 5., 6., 7.,  8.]],

  [[ 9.,  10.,  11.,  12.],
   [ 13.,  14.,  15.,  16.]]]]

to

[[[[ 1, 2, 3, 4, 9, 10, 11, 12],
   [ 5, 6, 7, 8, 13, 14, 15, 16]]]]

Thanks

I found this solution:

temp1 = test[0,0]
for i in range(1, test.shape[1]):
    temp1 = torch.cat([temp1, test[0, i]], dim=1)

Is there any faster solution than that?

Hi,
you can try to use torch.reshape:

x = torch.tensor([[[[ 1.,  2.,  3.,  4.],
   [ 5., 6., 7.,  8.]],
  [[ 9.,  10.,  11.,  12.],
   [ 13.,  14.,  15.,  16.]]]])
x = x.reshape(1,1,2,8)

Thanks for your reply.
Your code generates following tensor that is not what I want:

tensor([[[[ 1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.],
          [ 9., 10., 11., 12., 13., 14., 15., 16.]]]])

Sorry,
I had read output too fast, try this:

x.reshape(4,4).index_select(0,torch.tensor([0,2,1,3])).reshape(1,1,2,8)
1 Like

Thanks for your reply.
The shape of x is different. I think I can not determine the numbers of elements manually because it changes every time.
Is there any solution?

will this work

a, b = y.split(split_size=1, dim=-3)
torch.cat((a, b), dim=-1)

or

torch.cat(y.split(split_size=1, dim=-3), dim=-1)