Tensorflow添加浮点数可提供其他数字

时间:2018-09-17 13:42:17

标签: python tensorflow precision

所以我想知道为什么在添加它们时却没有得到下面两个浮点数的总和。根据浮点数的长度以及该点之前是否有非零数字,结果将添加一个附加数字或减去一个附加数字,或者只是不将它们相加。下面的代码例如:

import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt

with tf.Graph().as_default():
    a = tf.Variable(1, name="Var_a")
    dx = tf.Variable(1.33333, name='dx')
    dt = tf.Variable(5e-10, name='dt')
    dz = tf.Variable(1.0, name='dz')


    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        a = dt+dx
        a = a-dz
        print dx.eval()
        print dt.eval()
        print (dt+dx).eval()
        print (dx+dt).eval()
        print a.eval()
        writer = tf.summary.FileWriter("/tmp/tensorlog")
        writer.add_graph(sess.graph)

给出以下结果:

>>>1.33333
>>>5e-10
>>>1.33333
>>>1.33333
>>>0.33333004

因此加法没有发生,减法也没有给出正确的结果。在此先感谢您的任何想法。

1 个答案:

答案 0 :(得分:2)

TensorFlow变量默认为32位浮点数,它们没有足够的精度来跟踪差异dt,该差异相对于其余值而言太小。使用dtype=tf.float64提高精度,您将看到正确的结果:

import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt

with tf.Graph().as_default():
    a = tf.Variable(1, name="Var_a", dtype=tf.float64)
    dx = tf.Variable(1.33333, name='dx', dtype=tf.float64)
    dt = tf.Variable(5e-10, name='dt', dtype=tf.float64)
    dz = tf.Variable(1.0, name='dz', dtype=tf.float64)


    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        a = dt+dx
        a = a-dz
        print dx.eval()
        print dt.eval()
        print (dt+dx).eval()
        print (dx+dt).eval()
        print a.eval()
        writer = tf.summary.FileWriter("/tmp/tensorlog")
        writer.add_graph(sess.graph)

输出:

1.33333
5e-10
1.3333300005
1.3333300005
0.33333000049999995

但是请注意,使用tf.float64而不是tf.float32会浪费内存和时间,因此仅在确实需要高精度时才使用tf.float64。通常,32位浮点值精确到小数点后7位,而64位浮点值精确到小数点后15位。

相关问题