开发者社区> 问答> 正文

将tf.float32转换为常规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)

这是错误:

追溯(最近一次通话最近):文件“ test.py”,第9行,位于=丢失(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行,以常量allow_broadcast = True)文件“ D:\ documenten \ programs \ Python \ 3.6.2 \ lib \ site-packages \ tensorflow_core \ python \ framework \ constant_op.py“,第235行,在_constant_impl中t = convert_to_eager_tensor(value,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(value,ctx.device_name,dtype)ValueError:TypeError:Scalar张量没有len()

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

展开
收起
祖安文状元 2020-02-22 16:05:09 2615 0
2 条回答
写回答
取消 提交回答
  • 强转: float(xx)

    2020-03-14 14:30:01
    赞同 展开评论 打赏
  • 要获得一个简单的python float: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)
    
    2020-02-22 16:05:17
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
From Python Scikit-Learn to Sc 立即下载
Data Pre-Processing in Python: 立即下载
双剑合璧-Python和大数据计算平台的结合 立即下载