Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tensorflow median value

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?

like image 438
Yingchao Xiong Avatar asked May 06 '17 19:05

Yingchao Xiong


2 Answers

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.

like image 97
noname Avatar answered Sep 23 '22 13:09

noname


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

like image 20
Lucas Venezian Povoa Avatar answered Sep 26 '22 13:09

Lucas Venezian Povoa