python - Tensorflow:有没有办法在没有 tf.bincount 的情况下构建加权直方图?

标签 python gpu tensorflow

在我看来,numpy 函数 bincount 非常有用且易于使用,所以我很自然地使用 TensorFlow 中的模拟函数。最近我了解到,不幸的是 tf.bincount 没有 GPU 支持(您可以阅读 here )。是否有其他方法可以在 TensorFlow 中使用 GPU 高效地绘制加权直方图(如下面的示例所示)?

sess = tf.Session()

values = tf.random_uniform((1,50),10,20,dtype = tf.int32)
weights = tf.random_uniform((1,50),0,1,dtype = tf.float32)

counts = tf.bincount(values, weights = weights)

histogram = sess.run(counts)
print(histogram)

最佳答案

根据ekelsen on GitHub的建议,tf.bincount 的一个高效且支持 GPU 的替代方案是 tf.unsorted_segment_sum。 正如您可以在 documentation 中读到的那样,您可以使用权重为 data、值为 segments_ids 的函数。第三个参数 num_segments 应该 ≥ bincount 返回的直方图的大小(如果 > 在上一个直方图的最后一个之后只有零个元素)。在我上面的示例中,它将是:

sess = tf.Session()

values = tf.random_uniform((1,50),10,20,dtype = tf.int32)
weights = tf.random_uniform((1,50),0,1,dtype = tf.float32)
bins = 50
counts = tf.unsorted_segment_sum(weights, values, bins)

histogram = sess.run(counts)
print(histogram)

和输出:

[ 0.          0.          0.          0.          0.          
  0.          0.          0.          0.          0.          
  2.92621088  1.12118244  2.79792929  0.96016133  2.75781202  
  2.55233836  2.71923089  0.75750649  2.84039998  3.41356659  
  0.          0.          0.          0.          0.          
  0.          0.          0.          0.          0.        ]

关于python - Tensorflow:有没有办法在没有 tf.bincount 的情况下构建加权直方图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45147868/

相关文章:

python - 在 GPU 上结合使用 Flair 和 TensorFlow 会产生错误

tensorflow - 如何在 Tensorflow 中创建动态数量的层?

python - 澄清 word2vec `generate_batch()` 是如何工作的?

python - 为什么 Python 不索引我的列表并用新的索引版本覆盖它?仍在打印原件

video - 压缩 MP4 文件时 FFMPEG 命令行不使用 GPU

python - 是什么导致 Python 的 float_repr_style 使用 legacy?

GPU 的 Python 编码

python - 如何使用 sparse_softmax_cross_entropy_with_logits 在 tensorflow 中实现加权交叉熵损失

python - 如何使用pathlib获取Python中两个绝对路径之间的相对路径?

python - 在 Django 的 subview 中获取 url 父参数