如何将 PyTorch 张量列表转换为浮点数列表?

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

我有一张张量列表,如下所示:

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

如何更改整个列表的类型并获得如下内容:

[0.9757, 0.9987, 0.9990, 0.9994, 0.9994]

感谢您的帮助!

您可以使用 .item() 和列表理解,假设每个元素都是 one-element 张量:

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

这会打印出所需的结果,尽管存在一些不可避免的精度错误:

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