Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tensorflow divide with 0/0=:0

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?

like image 509
A Sz Avatar asked Aug 02 '17 16:08

A Sz


People also ask

How do you get a zero in division?

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.

How do you divide a tensor?

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.

How do I avoid division by zero in Numpy?

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.


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)
like image 126
Clock ZHONG Avatar answered Oct 02 '22 07:10

Clock ZHONG