【问题标题】:Convert a tf.float32 to a regular python float将 tf.float32 转换为常规 python 浮点数
【发布时间】:2020-04-21 09:12:16
【问题描述】:

这是我的代码:

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(最近一次调用最后一次): 文件“test.py”,第 9 行,在 a = 损失(y_true=tf.constant([1.0], dtype=tf.float32), y_pred=tf.constant([b], dtype=tf.float32)) 文件“D:\documenten\programs\Python\3.6.2\lib\site-packages\tensorflow_core\python\framework\constant_op.py”,第 227 行,常量 允许广播=真) _constant_impl 中的文件“D:\documenten\programs\Python\3.6.2\lib\site-packages\tensorflow_core\python\framework\constant_op.py”,第 235 行 t = convert_to_eager_tensor(值,ctx,dtype) 文件“D:\documenten\programs\Python\3.6.2\lib\site-packages\tensorflow_core\python\framework\constant_op.py”,第 96 行,在 convert_to_eager_tensor 返回 ops.EagerTensor(值,ctx.device_name,dtype) ValueError: TypeError: Scalar tensor has no len()

在这个例子中,我不能使用 'b' 来输入另一个张量,但是常规的浮点数可以正常工作。 有没有办法把 tf.float32 改成普通的 python 浮点数?

【问题讨论】:

    标签: python tensorflow tensor


    【解决方案1】:

    获取一个简单的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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-12
      • 2010-09-10
      • 1970-01-01
      • 2020-03-21
      • 1970-01-01
      • 2013-08-19
      相关资源
      最近更新 更多