Masood Delfarah
Masood Delfarah

Reputation: 697

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

Upvotes: 10

Views: 20086

Answers (6)

John Targaryen
John Targaryen

Reputation: 1194

To make everything a tf operation, I used this to convert a single value to 0 if it's NaN:

value_not_nan = tf.dtypes.cast(tf.math.logical_not(tf.math.is_nan(value)), dtype=tf.float32)
tf.math.multiply_no_nan(value, value_not_nan)

Upvotes: 0

ChaosPredictor
ChaosPredictor

Reputation: 4051

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")

Upvotes: 3

akuiper
akuiper

Reputation: 214957

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

Upvotes: 8

hugoxia
hugoxia

Reputation: 508

I hope this can help you. math.is_nan

import math
if math.isnan(float(v)):
    v = 0.0

Upvotes: -4

ospahiu
ospahiu

Reputation: 3525

Libraries like numpy (in this case, tensorflow) often have their own boolean implementations, comparing the memory addresses of a custom boolean type, and CPython's built in using is is going to result in erratic behaviour.

Either just check implicit boolean-ness -> if tf.is_nan(v) or do a equality comparison if tf.is_nan(v) == True.

Upvotes: 0

Daniyal Ahmed
Daniyal Ahmed

Reputation: 755

You could use tf.is_nan in combination with tf.cond to change values if the tensorflow value is NAN.

Upvotes: 0

Related Questions