张量流除以0/0 =:0

A S*_* Sz 5 python division tensorflow

我想分工返回0.0./0.,而不是NaN在一个tensorflow应用程序或错误.

我知道如何在numpy [1],[2]中做到这一点,但我是张力流的新手.

怎么能实现这一目标?

Clo*_*ONG 6

这个问题是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
)
Run Code Online (Sandbox Code Playgroud)

参数:

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)
Run Code Online (Sandbox Code Playgroud)