Average value of flux tensor

How do I calculate the median value of a list in tensorflow? how

node = tf.median(X)

      

X is a placeholder
In numpy, I can directly use np.median to get the median value. How can I use numpy operation on tensorflow?

+6


source to share


4 answers


edit: This answer is outdated, use Lucas Venezian Povoa's solution instead. It's easier and faster.

You can calculate the median in tensorflow using:

def get_median(v):
    v = tf.reshape(v, [-1])
    mid = v.get_shape()[0]//2 + 1
    return tf.nn.top_k(v, mid).values[-1]

      



If X is already a vector, you can skip reshaping.

If you are worried that the median is the average of the two middle elements for vectors of even size, you should use this instead:

def get_real_median(v):
    v = tf.reshape(v, [-1])
    l = v.get_shape()[0]
    mid = l//2 + 1
    val = tf.nn.top_k(v, mid).values
    if l % 2 == 1:
        return val[-1]
    else:
        return 0.5 * (val[-1] + val[-2])

      

+3


source


To calculate the median of an array using, tensorflow

you can use a function quantile

, since 50% quantile is median

.

import tensorflow as tf
import numpy as np 

np.random.seed(0)   
x = np.random.normal(3.0, .1, 100)

median = tf.contrib.distributions.percentile(x, 50.0)

tf.Session().run(median)

      

This code does not have the same behavior np.median

, because the parameter interpolation

approximates the result with a value lower

, higher

or nearest

.



If you want to use the same behavior, you can use:

median = tf.contrib.distributions.percentile(x, 50.0, interpolation='lower')
median += tf.contrib.distributions.percentile(x, 50.0, interpolation='higher')
median /= 2.
tf.Session().run(median)

      

Also, the code above is equivalent np.percentile(x, 50, interpolation='midpoint')

.

+7


source


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)

      

It is as fast as (in my experience) using tf.contrib.distributions.percentile(v, 50.0)

, and returns one of the real items.

+2


source


There is currently no median function in TF. The only way to use the numpy operation in TF is after the graph has started:

import tensorflow as tf
import numpy as np

a = tf.random_uniform(shape=(5, 5))

with tf.Session() as sess:
    np_matrix = sess.run(a)
    print np.median(np_matrix)

      

+1


source







All Articles