How can I calculate the median value of a list in tensorflow? Like
node = tf.median(X)
X is the placeholder
In numpy, I can directly use np.median to get the median value. How can I use the numpy operation in tensorflow?
We can modify BlueSun's solution to be much faster on GPUs:
def get_median(v):
v = tf.reshape(v, [-1])
m = v.get_shape()[0]//2
return tf.reduce_min(tf.nn.top_k(v, m, sorted=False).values)
This is as fast as (in my experience) using tf.contrib.distributions.percentile(v, 50.0)
, and returns one of the actual elements.
For calculating median of an array with tensorflow
you can use the percentile
function, since the 50th percentile is the median.
import tensorflow as tf
import tensorflow_probability as tfp
import numpy as np
np.random.seed(0)
x = np.random.normal(3.0, .1, 100)
median = tfp.stats.percentile(x, 50.0, interpolation='midpoint')
tf.Session().run(median)
The code above is equivalent to np.percentile
(x, 50, interpolation='midpoint')
.
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