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