Converting all nan values to zero in tensforflow

Issue

I am trying to convert all nan values to zero in my final results. I am not able to execute it properly!

The following is the code: also availvable on colab : link

import tensorflow as tf
import numpy as np

ts = tf.constant([[0,0]]) 
tx = tf.constant([[0,1]]) 

out = ts / (ts + fx)

out.numpy() # array([nan,  0.])

tf.math.is_nan(out).numpy() # array([ True, False]

out.numpy()[(tf.math.is_nan(out).numpy())] = 0
out.numpy() #array([nan,  0.])

out.numpy() should give array([0., 0.])

Solution

Change:

out.numpy()[(tf.math.is_nan(out).numpy())] = 0

To:

out = tf.where(tf.math.is_nan(out), 0., out)

Answered By – Djinn

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published