Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert a list of tensors in a list of floats?

I got a list of tensors like the following one:

[tensor(0.9757), tensor(0.9987), tensor(0.9990), tensor(0.9994), tensor(0.9994)]

How can I change the type of the entire list and obtain something like:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[0.9757, 0.9987, 0.9990, 0.9994, 0.9994]

Thanks for the help!

>Solution :

You can use .item() and a list comprehension, assuming that every element is a one-element tensor:

result = [tensor.item() for tensor in data]
print(type(result[0]))
print(result)

This prints the desired result, albeit with some unavoidable precision error:

<class 'float'>
[0.9757000207901001, 0.9987000226974487, 0.9990000128746033, 0.9994000196456909, 0.9994000196456909]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading