Hi,
If we have a linear tensor of 24 elements from 0 to 23.
X = [0 1 2 3 …23]
How can we reshape it to something like that
Y = [[0,1 2 3 12 13 14 15],
[4 5 6 7 16 17 18 19],
[8 9 10 11 20 21 22 23]]
Thanks
Hi,
If we have a linear tensor of 24 elements from 0 to 23.
X = [0 1 2 3 …23]
How can we reshape it to something like that
Y = [[0,1 2 3 12 13 14 15],
[4 5 6 7 16 17 18 19],
[8 9 10 11 20 21 22 23]]
Thanks
x = torch.range(1,24)
print (x)
x = x.view(3,-1)
print (x)
Output:
tensor([[ 1., 2., 3., 4., 5., 6., 7., 8.],
[ 9., 10., 11., 12., 13., 14., 15., 16.],
[17., 18., 19., 20., 21., 22., 23., 24.]])
Well The issue is we don’t want it [1 2 3 4 5 6 7 8]
we want it to be [0 1 2 3 12 13 14 15]
and so on… there is gap. See expected output given in the question
Well you can first split your original tensor in half, reshape both halves and concatenate them again:
# initilizing list
X = list(range(0, 24))
# converting list to array
X = np.array(X)
# converting array to tensor
X = torch.from_numpy(X)
# split tensor in half
X_split = torch.split(X, int(X.shape[0]/2), dim=0)
# reshape the two tensors
X_left = X_split[0].view(3,-1)
X_right = X_split[1].view(3,-1)
# concatenate the reshaped tensors again
X = torch.cat((X_left, X_right), dim=1)
That wil give you:
tensor([[ 0, 1, 2, 3, 12, 13, 14, 15],
[ 4, 5, 6, 7, 16, 17, 18, 19],
[ 8, 9, 10, 11, 20, 21, 22, 23]])
Ohh I didn’t notice. Sorry about that. Chris (@vdw) has just posted a solution. I was about to write the same. See if that works for you.