tensorflow divide with 0/0=:0

Viewed 4652

I'd like division to return 0. for 0./0. instead of NaN or an error in a tensorflow application.

I know how I can do this in numpy [1], [2], but I'm new to tensorflow.

How can this be achieved?

1 Answers

This question is asked 2 years ago, not sure whether this API is supported at that time, but Tensorflow 2.X really support it now:

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

Args:

x: A Tensor. Must be one of the following types: float32, float64.

y: A Tensor whose dtype is compatible with x.

name: A name for the operation (optional).

Returns:

The element-wise value of the x divided by y.

You need pay attention to the argument type, they should be only tf.float32 or tf.float64, if tf.int*, tf2.x will report error. The following is my testing codes runned correctly in 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)
Related