Pytorch how to stack a torch tensor

I use resnet to predict EEG response to image data. And the input data is a matrix x_i with size of 1 * 3 * 500 * 500. Then the output is a vector y_i with size of 1 * 1 * 17 * 100. Let’s call the output EEG response. there is a loop like the following:
for i in range(number of input data):
y_i = model(x_i)

if max_i=200, I would to stack all the y_i to create a matrix with size of 200 * 1 * 17 * 100. How to realize that?

See torch.stack().

Hi Nikiguo (and gphilip)!

For the specific use case you detail, you will prefer torch.cat().
(torch.stack() will create a new dimension along which to stack.)

>>> import torch
>>> torch.__version__
'1.9.0'
>>> y_0 = torch.arange (5).unsqueeze (0)
>>> y_1 = torch.arange (5).unsqueeze (0) + 10
>>> y_2 = torch.arange (5).unsqueeze (0) + 20
>>> y_0.shape
torch.Size([1, 5])
>>> y_list = [y_0, y_1, y_2]
>>> torch.cat (y_list).shape
torch.Size([3, 5])
>>> torch.cat (y_list)
tensor([[ 0,  1,  2,  3,  4],
        [10, 11, 12, 13, 14],
        [20, 21, 22, 23, 24]])
>>> torch.stack (y_list).shape
torch.Size([3, 1, 5])
>>> torch.stack (y_list)
tensor([[[ 0,  1,  2,  3,  4]],

        [[10, 11, 12, 13, 14]],

        [[20, 21, 22, 23, 24]]])

(In your case, you could use stack() followed by squeeze() to
eliminate one of the singleton dimensions.)

Best.

K. Frank

1 Like

Hi thank you for your help, gphilip. It can work but would increase the dimension of the data. But this can be solved by using squeeze().

1 Like

aha thanks a lot Frank. That is helpful and it works well for me.