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?
0 Divided by a Number 0a=0 Dividing 0 by any number gives us a zero. Zero will never change when multiplying or dividing any number by it.
To perform element-wise division on two tensors in PyTorch, we can use the torch. div() method. It divides each element of the first input tensor by the corresponding element of the second tensor.
Behavior on division by zero can be changed using seterr. When both x1 and x2 are of an integer type, divide will return integers and throw away the fractional part. Moreover, division by zero always yields zero in integer arithmetic. >>> np.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With