#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:一个张量,其数据类型与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)
tf.where(tf.less(s, 1e-7), s, 1./s)
- Yaroslav Bulatovtf.realdiv(a, b)
的函数,而不仅仅是简单的倒数。使用div0 = lambda s: tf.where(tf.less(s, 1e-7), s, 1./s)
,我可以使用a * div0(b)
,但这既不易读,也不够健壮 / 最优性能。 - A Sz