Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert PyTorch tensor to python list

Tags:

python

pytorch

How do I convert a PyTorch Tensor into a python list?

My current use case is to convert a tensor of size [1, 2048, 1, 1] into a list of 2048 elements.

My tensor has floating point values. Is there a solution which also accounts for int and possibly other data types?

like image 934
Tom Hale Avatar asked Dec 23 '18 11:12

Tom Hale


People also ask

How do I convert a list to a PyTorch tensor in Python?

To convert a Python list to a tensor, we are going to use the tf. convert_to_tensor() function and this function will help the user to convert the given object into a tensor. In this example, the object can be a Python list and by using the function will return a tensor.

How do I flatten in PyTorch?

flatten. Flattens input by reshaping it into a one-dimensional tensor. If start_dim or end_dim are passed, only dimensions starting with start_dim and ending with end_dim are flattened.


Video Answer


2 Answers

Use Tensor.tolist() e.g:

>>> import torch >>> a = torch.randn(2, 2) >>> a.tolist() [[0.012766935862600803, 0.5415473580360413],  [-0.08909505605697632, 0.7729271650314331]] >>> a[0,0].tolist() 0.012766935862600803 

To remove all dimensions of size 1, use a.squeeze().tolist().

Alternatively, if all but one dimension are of size 1 (or you wish to get a list of every element of the tensor) you may use a.flatten().tolist().

like image 185
Tom Hale Avatar answered Sep 23 '22 19:09

Tom Hale


Tensor to list:

a_list  = embeddings.tolist() 

list to Tensor:

a_tensor = torch.Tensor(a_list).cuda() 
like image 33
Wesam Na Avatar answered Sep 21 '22 19:09

Wesam Na