Kenny Smith
Kenny Smith

Reputation: 889

Convert a list of tensors to tensors of tensors pytorch

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?

Upvotes: 9

Views: 10725

Answers (2)

Aarish Alam
Aarish Alam

Reputation: 11

You can also typecast the torch tensors to NumPy array and then convert them to tensors

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

Upvotes: 0

Prajot Kuvalekar
Prajot Kuvalekar

Reputation: 6618

Here is a solution:

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

Upvotes: 12

Related Questions