将 tf.float32 转换为常规 python 浮点数

Convert a tf.float32 to a regular python float

这是我的代码:

import tensorflow as tf

loss = tf.keras.losses.MeanSquaredError()

a = loss(y_true=tf.constant([1.0, 2.0, 3.0]), y_pred=tf.constant([2.0, 2.0, 4.0]))
print(a)

b = tf.constant([2.0, 2.0, 4.0])[0]
a = loss(y_true=tf.constant([1.0], dtype=tf.float32), y_pred=tf.constant([b], dtype=tf.float32)) #error occurs here
print(a)

这是错误:

Traceback (most recent call last): File "test.py", line 9, in a = loss(y_true=tf.constant([1.0], dtype=tf.float32), y_pred=tf.constant([b], dtype=tf.float32)) File "D:\documenten\programs\Python.6.2\lib\site-packages\tensorflow_core\python\framework\constant_op.py", line 227, in constant allow_broadcast=True) File "D:\documenten\programs\Python.6.2\lib\site-packages\tensorflow_core\python\framework\constant_op.py", line 235, in _constant_impl t = convert_to_eager_tensor(value, ctx, dtype) File "D:\documenten\programs\Python.6.2\lib\site-packages\tensorflow_core\python\framework\constant_op.py", line 96, in convert_to_eager_tensor return ops.EagerTensor(value, ctx.device_name, dtype) ValueError: TypeError: Scalar tensor has no len()

在这个例子中,我不能使用 'b' 来放入另一个张量,但是常规的 float 工作得很好。 有没有一种方法可以将 tf.float32 更改为常规 python 浮点数?

要获得一个简单的 python 浮点数:float(b)

尽管如此,我认为您的错误发生主要是因为您试图将 b 变成 tf.constant,而它已经是 tf.constant

要转换张量的数据类型,您可以使用 tf.cast

所以你上面的代码也适用于这种情况:

loss = tf.keras.losses.MeanSquaredError()

a = loss(y_true=tf.constant([1.0, 2.0, 3.0]), y_pred=tf.constant([2.0, 2.0, 4.0]))
print(a)

b = tf.constant([2.0, 2.0, 4.0])[0]
b = tf.cast(b, dtype=tf.float32)

a = loss(y_true=tf.constant([1.0], dtype=tf.float32), y_pred=[b]) 
print(a)