I would like to check a tensorflow variable and set it to zero if it is NaN.
How can I do this? The following trick seems not to work:
if tf.is_nan(v) is True:
v = 0.0
If v
is a 0d tensor, you might use tf.where
to test and update the value:
import numpy as np
v = tf.constant(np.nan) # initialize a variable as nan
v = tf.where(tf.is_nan(v), 0., v)
with tf.Session() as sess:
print(sess.run(v))
# 0.0
For Tensorflow 2.0
you can you:
import tensorflow as tf
if tf.math.is_nan(v):
print("v is NaN")
or with numpy
import numpy as np
if np.is_nan(v):
print("v is NaN")
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