Home > Software engineering >  How to convert a list of PyTorch tensors to a list of floats?
How to convert a list of PyTorch tensors to a list of floats?

Time:03-04

I have 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:

[0.9757, 0.9987, 0.9990, 0.9994, 0.9994]

Thanks for the help!

CodePudding user response:

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]
  • Related