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?
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.
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.
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()
.
Tensor to list:
a_list = embeddings.tolist()
list to Tensor:
a_tensor = torch.Tensor(a_list).cuda()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With