3
votes

I have this code:

import torch

list_of_tensors = [ torch.randn(3), torch.randn(3), torch.randn(3)]
tensor_of_tensors = torch.tensor(list_of_tensors)

I am getting the error:

ValueError: only one element tensors can be converted to Python scalars

How can I convert the list of tensors to a tensor of tensors in pytorch?

1
Does this answer your question? converting list of tensors to tensors pytorch - dennlinger
Thanks for the comment, I saw this post, but it does not answer my question I don't want 1 big tensor, I want a tensor of tensors. - Kenny Smith
What is the difference in your opinion between a "tensor of tensors", and an additional dimension in your tensor? - dennlinger
Using tensor.cat, I will get a tensor of size 9. I would like to get a tensor of size (3,3) - Kenny Smith
Sorry, I sloppily linked to the wrong answer, I apologize. The function you are looking for is torch.stack(), and this has also been answered on Stackoverflow before, although I can't change my duplication vote. See for example here. If you need more detail, feel free to respond. - dennlinger

1 Answers

4
votes

Here is a solution:

tensor_of_tensors = torch.stack((list_of_tensors))
print(tensor_of_tensors) #shape (3,3)