Convert PyTorch tensor to python list

PythonPytorch

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

Tensor to list:

a_list  = embeddings.tolist()

list to Tensor:

a_tensor = torch.Tensor(a_list).cuda()

Solution 3 - Python

#@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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTom HaleView Question on Stackoverflow
Solution 1 - PythonTom HaleView Answer on Stackoverflow
Solution 2 - PythonWesam NaView Answer on Stackoverflow
Solution 3 - PythonBharath KumarView Answer on Stackoverflow