0

I need to use a 2D Histogram with weights on Tensorflow. However, the only solution I found in here does not implements the weights argument such as in numpy implementation. Looking at the source code of numpy implementation, I was able to do the following to the found tensorflow implementation, but it still does not work as expected:

def get2dHistogram(x, y, weights,
               value_range,
               nbins=100,
               dtype=tf.dtypes.int32):

x_range = value_range[0]
y_range = value_range[1]

x = tf.histogram_fixed_width_bins(x, y_range, nbins=tf.size(x), dtype=dtype)
x = tf.math.bincount(x, weights=weights, minlength=tf.size(y))
y = tf.histogram_fixed_width_bins(y, y_range, nbins=tf.size(y), dtype=dtype)
y = tf.math.bincount(y, weights=weights, minlength=tf.size(y))

histy_bins = tf.histogram_fixed_width_bins(y, y_range, nbins=nbins, dtype=dtype)

H = tf.map_fn(lambda i: tf.histogram_fixed_width(x[histy_bins == i], x_range, nbins=nbins), tf.range(nbins))
return H # Matrix!

I confess I do not know exactly how the weights are implemented in the numpy version, but that was my best guess so far. Can anybody help me?

1 Answers1

0

I managed to make it work using the tensorflow-probability package for the histogram implementation. The final is below:

def get2dHistogram(x, y, weights,
               value_range,
               nbins=100,
               dtype=tf.dtypes.int32):

x_range = tf.linspace(value_range[0][0], value_range[0][1], num=nbins+1)
x = tf.clip_by_value(x, value_range[0][0], value_range[0][1])

histy_bins = tf.histogram_fixed_width_bins(y, value_range[1], nbins=nbins, dtype=dtype)

hists = []
for i in range(nbins):
    _x = x[histy_bins == i]
    _w = weights[histy_bins == i]
    
    hist = tfp.stats.histogram(_x, edges=x_range, weights=_w)
    
    hists.append(hist)

return tf.stack(hists, axis=0)