Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if NaN in Tensorflow

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
like image 749
Masood Delfarah Avatar asked Aug 25 '17 02:08

Masood Delfarah


2 Answers

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
like image 121
Psidom Avatar answered Oct 30 '22 14:10

Psidom


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")
like image 23
ChaosPredictor Avatar answered Oct 30 '22 15:10

ChaosPredictor