【问题标题】:tensorflow divide with 0/0=:0张量流除以 0/0=:0
【发布时间】:2018-01-09 23:48:52
【问题描述】:

我希望除法返回 0.0./0. 而不是 NaN 或 tensorflow 应用程序中的错误。

我知道如何在 numpy [1][2] 中做到这一点,但我是 tensorflow 的新手。

如何做到这一点?

【问题讨论】:

  • tf.where(tf.less(s, 1e-7), s, 1./s)
  • 是的,稳健性,您通常不应该对浮点数进行精确相等测试,这些测试在现代硬件上可能会不确定地失败 (blog.nag.com/2011/02/wandering-precision.html)
  • @YaroslavBulatov 我想要tf.realdiv(a, b) 的等价物,而不仅仅是倒置。使用div0 = lambda s: tf.where(tf.less(s, 1e-7), s, 1./s),我可以使用a * div0(b),但这既不可读,也不认为这是健壮/最佳性能明智的。
  • 对于遇到这种情况的人 - Yaroslav Bulatov 的建议可能会导致 NaN,不管事实上 NaN 位于 tf.where 调用的未采用分支上.在github上看到这个问题:github.com/tensorflow/tensorflow/issues/20091
  • 即使这个问题很老了,tf.math.divide_no_nan (tensorflow.org/api_docs/python/tf/math/divide_no_nan) 应该做你想做的事

标签: python tensorflow division


【解决方案1】:

这个问题是2年前问的,不确定当时是否支持这个API,但是Tensorflow 2.X现在真的支持了:

#Computes a safe divide which returns 0 if the y is zero.
tf.math.divide_no_nan(
    x, y, name=None
)

参数:

x:张量。必须是以下类型之一:float32、float64。

y:dtype 与 x 兼容的张量。

name:操作的名称(可选)。

返回:

x 除以 y 的元素值。

需要注意参数类型,只能是tf.float32或者tf.float64,如果是tf.int*,tf2.x会报错。以下是我在colab中正确运行的测试代码:

import tensorflow as tf
myShape=(30,30)
a = tf.constant(2, shape=myShape, dtype=tf.float32)
z = tf.constant(0, shape=myShape, dtype=tf.float32 )
cz2 = tf.math.divide_no_nan(a, z)
print(cz2)

【讨论】:

  • 一开始我的测试代码出错了,因为我没有将dtype赋值为tf.float*,它的默认是整数类型,这会导致错误,不知道为什么tensorflow团队能忍受这个限制。
  • 似乎该方法仅在 2.0 中引入,然后向后移植到 1.15 版本(2019 年 10 月 16 日发布),因为 1.14 API 中不存在该方法。因此,在最初提出问题时,它肯定不在 API 中。
  • @ASz ,是的,Tensorflow 仍处于积极开发状态,这些 API 不断变化,在最近的版本中有时仍会添加新的 API 和修改。相比tensorflows的索引机制,我更喜欢使用numpy的API,numpy的API比目前的tensorflow的API更灵活稳定但限制更少。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-12
  • 1970-01-01
  • 2020-06-01
  • 1970-01-01
  • 2020-12-17
  • 2013-05-09
相关资源
最近更新 更多