Tensorflow中值 [英] Tensorflow median value

查看:90
本文介绍了Tensorflow中值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何计算张量流中列表的中位数? 像

How can I calculate the median value of a list in tensorflow? Like

node = tf.median(X)

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

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?

推荐答案

此答案已过时,请改用Lucas Venezian Povoa的解决方案.它更简单,更快.

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

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

You can calculate the median inside 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]

如果X已经是矢量,则可以跳过重塑.

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

如果您关心中间值是偶数向量的两个中间元素的平均值,则应该改用以下值:

If you care about the median value being the mean 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])

这篇关于Tensorflow中值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆