Create a single tensor from list of tensors

Hi,
I’m trying to create tensor from a variable data, which is a list. According to the documentation , I should be able to that using torch.Tensor() method. I have ensured that the list doesn’t contain any strings.
The list looks like this:
[tensor([[ 4.6291e-03, -1.3071e-05, -1.0033e-03, …, 3.7078e-02,
7.7851e-03, 3.4532e-02],
[ 7.5976e-03, -1.4478e-05, 6.4205e-03, …, 2.3013e-02,
9.6373e-03, 3.6175e-02],
[ 1.0242e-02, -2.6630e-05, 1.5521e-03, …, 3.2181e-02,
1.6385e-02, 8.6033e-03],
…,
[ 6.9822e-03, -4.2445e-05, 5.6378e-03, …, 1.9608e-02,
8.2644e-03, 1.8788e-02],
[ 6.9822e-03, -4.2445e-05, 5.6378e-03, …, 1.9608e-02,
8.2644e-03, 1.8788e-02],
[ 7.3356e-03, -2.1180e-05, 4.7856e-03, …, 1.7249e-02,
6.8688e-03, 4.0911e-02]])]

However, I am getting ValueError: only one element tensors can be converted to Python scalars. I’m unable to figure out what exactly is the error trying to say.
Please see below the code snippet.


I think I might have missed something very trivial, but I’ve been stuck here for quite some time. Any direction as to why this error occurs would be greatly appreciated.
Thanks in advance :slight_smile:

If I understood your question correctly, you have a python list and want to convert to a pytorch tensor.

python_list = [[1,2,3], [4, 5, 6]]

torch_list = torch.tensor(python_list)

Can you point out where you are getting the error in the code?

Yes, that’s right.
In #3,
X = torch.FloatTensor(data)
This is where I’m getting the error. I have also tried X = torch.Tensor(data) , but ended up with the same error.

Hi!
I have mistaken list of tensor as a simple python list. (So I have also changed the title of question.)
The variable ‘data’ was actually a list of tensors with only one item. And I can’t create a tensor from a list of tensors using torch.Tensor() method. Hence the error.
I used the below method to turn the list of tensor into a single tensor :
X = torch.stack(data)
And it works now. Thanks! :slight_smile:

3 Likes