Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TensorFlow - Ignore infinite values when calculating the mean of a tensor

This is probably a basic question, but I can't find a solution:

I need to calculate the mean of a tensor ignoring any non-finite values.

For example mean([2.0, 3.0, inf, 5.0]) should return 3.333 and not inf nor 2.5.

I have tried sess.run(tf.reduce_mean([2.0, 3.0, inf, 5.0])) but it returns inf.

like image 603
ESala Avatar asked Apr 21 '17 14:04

ESala


2 Answers

The given answer is almost correct. The question asked about ignoring non-finite values, the answer only ignores infinite values. They are not the same thing, specifically about nan.

To actually ignore any non-finite values (including nan), use this slightly simpler line instead:

mymean = tf.reduce_mean(tf.boolean_mask(x, tf.is_finite(x))
like image 20
LucasB Avatar answered Oct 21 '22 04:10

LucasB


You could use a combination of is_finite and boolean_mask.

import tensorflow as tf

x = tf.constant([2, 3, float('Inf'), 5])
mymean = tf.reduce_mean(tf.boolean_mask(x, tf.is_finite(x)))

sess = tf.Session()
sess.run(mymean)

Note that is_finite will get rid of NaN values as well.

like image 68
P-Gn Avatar answered Oct 21 '22 04:10

P-Gn