Convert PyTorch tensor to python list

Question:

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

I want 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 works with other data types such as int?

Asked By: Tom Hale

||

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().

Answered By: Tom Hale

Tensor to list:

a_list  = embeddings.tolist()

list to Tensor:

a_tensor = torch.Tensor(a_list).cuda()
Answered By: Wesam Na

#@pyorch tensor to list or strings

in[]
#bbox predictions
boxes = predictions[:, :4]
print(boxes)

out[]

tensor(54.97658) tensor(393.99637) tensor(225.55316) tensor(879.53503)
tensor(670.91669) tensor(400.35202) tensor(810.) tensor(878.34045)
tensor(219.87546) tensor(408.02075) tensor(346.14133) tensor(860.66687)
tensor(13.24882) tensor(217.30855) tensor(800.23413) tensor(737.75751)
tensor(0.12453) tensor(552.29401) tensor(76.41209) tensor(885.35455)
tensor(656.11823) tensor(625.61261) tensor(689.63586) tensor(713.37250)

after

in[]

boxes = boxes.tolist()
print(boxes)
    
out []
    
54.97657775878906 393.9963684082031 225.55316162109375 879.5350341796875
670.9166870117188 400.3520202636719 810.0 878.3404541015625
219.87545776367188 408.020751953125 346.1413269042969 860.6668701171875
13.24881649017334 217.3085479736328 800.234130859375 737.7575073242188
0.12453281879425049 552.2940063476562 76.4120864868164 885.3545532226562
656.1182250976562 625.6126098632812 689.6358642578125 713.3724975585938
Answered By: Bharath Kumar
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.