【问题标题】:Tensorflow wrong result in calculation (small digits incorrect) [duplicate]Tensorflow错误导致计算(小数字不正确)[重复]
【发布时间】:2021-07-14 11:48:16
【问题描述】:

我在 TensorFlow 中做了以下简单的计算,惊讶地发现结果与我预期的不一样。 我的代码:

a = tf.constant([[0.2,1],[0.3,0.75]])
b = tf.constant([[0.2,0.1],[0.8,0.2]])
print(tf.square(a)+tf.square(b))

它提供结果:

tf.Tensor(
[[0.08000001 1.01      ]
 [0.73       0.6025    ]], shape=(2, 2), dtype=float32)

但是,我本来期望:

tf.Tensor(
[[0.08       1.0     ]
 [0.73       0.6025    ]], shape=(2, 2), dtype=float32)

因为这将是我计算的数学正确结果。出了什么问题?

【问题讨论】:

    标签: python tensorflow tensor


    【解决方案1】:

    使用float32准确率时,结果

    >>> tf.square(0.2).numpy()
    0.040000003
    

    意思是

    >>> (tf.square(a)+tf.square(b))[0][0].numpy()
    0.080000006
    

    当整个结果数组被打印出来时,元素被四舍五入为0.08000001

    还有,

    >>> (tf.square(1.0)+tf.square(0.1)).numpy()
    1.01
    

    应该是这样,这意味着 TensorFlow 正在正确地进行计算。

    【讨论】:

    • 嗯,(0.2)^2 = 0.04 所以 TensorFlow 给出了错误的结果,即 0.040000003。所以这并不能真正回答我的问题。您的意思是由于float32的位长不足导致TensorFlow中的错误结果吗?避免此问题的常见做法是什么?
    • 似乎使用 tf.float16 数据类型会产生正确的结果:>>> tf.cast(tf.square(0.2), tf.float16).numpy() 0.04
    • 您能解释一下基本概念吗?我需要这个适用于每个例子,而不仅仅是这个。对我来说,较小的浮点位长度会产生更好的结果是没有意义的——我认为这只对这个特定的例子更有效。
    猜你喜欢
    • 2018-05-23
    • 1970-01-01
    • 1970-01-01
    • 2021-10-05
    • 2021-04-23
    • 1970-01-01
    • 2019-07-31
    • 1970-01-01
    • 2018-04-20
    相关资源
    最近更新 更多