美文网首页
TensorFlow学习中遇到的坑(二)

TensorFlow学习中遇到的坑(二)

作者: 圣_狒司机 | 来源:发表于2018-07-30 09:52 被阅读463次

    np.float32 和 tf.float32有什么区别

    因为熟悉了numpy,所以在tensorflow中张量初始化更喜欢用numpy来做,可是你这么写:

    a = tf.Variable(np.random.random([2,3]),np.float32)
    x = tf.placeholder(tf.float32,[None,3])
    y = tf.placeholder(tf.float32,[None,3])
    y = x*a
    

    就会始终报错!显示数据类型错误,可是你已经注明了float32了,还能有什么类型错误呢?
    print一下a和x:

    print(a,'\n',x)
    

    显示:

    <tf.Variable 'Variable_171:0' shape=(2, 3) dtype=float64_ref> 
     Tensor("Placeholder_146:0", shape=(?, 3), dtype=float32)
    

    发现a 是float64,明明注明了是32位的,这可能是TensorFlow 的一个bug?

    解决办法:

    需要强制转换:

    a = tf.cast(a,tf.float32)
    

    其实转换为 tf.cast(a,np.float32)也是可以的,也就是说np.float32 和 tf.float32没有区别!
    这样就通过了:

    a = tf.Variable(np.random.random([2,3]))
    a = tf.cast(a,tf.float32)
    x = tf.placeholder(tf.float32,[None,3])
    y = tf.placeholder(tf.float32,[None,3])
    y = x*a
    

    无报错!

    相关文章

      网友评论

          本文标题:TensorFlow学习中遇到的坑(二)

          本文链接:https://www.haomeiwen.com/subject/gguxvftx.html