具有自定义垃圾箱的Tensorflow直方图

时间:2018-09-24 14:56:33

标签: python-3.x tensorflow

我有两个张量-一个具有bin规范,另一个具有观测值。我想计算每个bin中有多少个值。 我知道如何在NumPy或裸Python中执行此操作,但是我需要在纯TensorFlow 中执行此操作。 tf.histogram_fixed_width是否有更复杂的版本,带有用于bin规范的参数?

示例:

# Input - 3 bins and 2 observed values
bin_spec = [0, 0.5, 1, 2]
values = [0.1, 1.1]
# Histogram
[1, 0, 1]

1 个答案:

答案 0 :(得分:1)

这似乎可行,尽管我认为这是相当消耗内存和时间的。

import tensorflow as tf

bins = [-1000, 1, 3, 10000]
vals = [-3, 0, 2, 4, 5, 10, 12]

vals = tf.constant(vals, dtype=tf.float64, name="values")
bins = tf.constant(bins, dtype=tf.float64, name="bins")

resh_bins = tf.reshape(bins, shape=(-1, 1), name="bins-reshaped")
resh_vals = tf.reshape(vals, shape=(1, -1), name="values-reshaped")

left_bin = tf.less_equal(resh_bins, resh_vals, name="left-edge")
right_bin = tf.greater(resh_bins, resh_vals, name="right-edge")

resu = tf.logical_and(left_bin[:-1, :], right_bin[1:, :], name="bool-bins")
counts = tf.reduce_sum(tf.to_float(resu), axis=1, name="count-in-bins")

with tf.Session() as sess:
    print(sess.run(counts))