【问题标题】:2D Histogram with weights on TensorflowTensorflow 上带有权重的 2D 直方图
【发布时间】:2022-01-06 18:34:52
【问题描述】:

我需要在 Tensorflow 上使用带有权重的 2D 直方图。但是,我在here 中找到的唯一解决方案没有实现诸如numpy implementation 中的权重参数。查看source code of numpy implementation,我能够对找到的 tensorflow 实现执行以下操作,但它仍然无法按预期工作:

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!

我承认我不确切知道在 numpy 版本中权重是如何实现的,但这是我迄今为止最好的猜测。有人可以帮帮我吗?

【问题讨论】:

    标签: python numpy tensorflow histogram histogram2d


    【解决方案1】:

    我设法使用tensorflow-probability 包实现直方图使其工作。决赛如下:

    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)
    

    【讨论】:

      猜你喜欢
      • 2019-03-30
      • 2019-11-20
      • 2015-10-12
      • 1970-01-01
      • 2016-11-08
      • 2021-07-19
      • 1970-01-01
      • 1970-01-01
      • 2013-02-24
      相关资源
      最近更新 更多