How to stack over for loop?

I have a loop, and I am getting a 10x10 tensor for each iteration of that loop. Lets assume that I am running that loop five times, and the output after the loop completes should be the concatenation of these tensors, i.e., a size of 10x10x5. How to concatenate this?

outx = []
for i in range(5):
    tmp = net(x) # this will return a 10x10 tensor
    outx = # need to cat tmp with outx in dim=2

outx - should have a dimension of 10x10x5
3 Likes

Building the list and then using stack at the end is reasonable:

outx = []
for i in range(5):
    tmp = net(x) # this will return a 10x10 tensor
    outx.append(tmp)

outx = torch.stack(outx, 2)

Best regards

Thomas

5 Likes

Hi @tom ,
I had a question, if the outputs that I want to append to a list are my model outputs, Will appending them to a list and then applying torch.stack break the computation graph?
Thank you.

No. If any of the inputs in the list (which torch.stack will iterate over) requires gradient, so does the output and the graph is connected accordingly.

Best regards

Thomas

1 Like