Tensorflow中值

时间:2017-05-06 19:39:52

标签: python numpy tensorflow median

如何计算tensorflow中列表的中值? 喜欢

{{1}}

X是占位符
在numpy中,我可以直接使用np.median来获得中值。如何在tensorflow中使用numpy操作?

4 个答案:

答案 0 :(得分:7)

要计算tensorflow数组的中位数,您可以使用quantile函数,因为50%的分位数是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)

此代码与np.median的行为不同,因为interpolation参数会将结果近似为lowerhighernearest样本值。

如果您想要相同的行为,可以使用:

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)

除此之外,上面的代码相当于np.percentile(x, 50, interpolation='midpoint')

答案 1 :(得分:4)

编辑:这个答案已经过时,请使用Lucas Venezian Povoa的解决方案。它更简单,更快捷。

您可以使用以下方法计算张量流量的中位数:

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]

如果X已经是矢量,则可以跳过重新整形。

如果你关心中值是偶数大小的矢量的两个中间元素的平均值,你应该使用它:

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

答案 2 :(得分:3)

我们可以将BlueSun的解决方案修改为在GPU上更快:

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)

这与使用tf.contrib.distributions.percentile(v, 50.0)的速度(以我的经验)一样快,并且返回实际元素之一。

答案 3 :(得分:0)

目前TF中有no median function。在TF中使用numpy操作的唯一方法是运行图表后:

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)