Tensorflow median value

Yingchao Xiong picture Yingchao Xiong · May 6, 2017 · Viewed 7.8k times · Source

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?

Answer

Lucas Venezian Povoa picture Lucas Venezian Povoa · Dec 5, 2017

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