【问题标题】:Create a custom Tensorflow histogram summary创建自定义 TensorFlow 直方图摘要
【发布时间】:2017-06-20 03:43:48
【问题描述】:

关于在 TF 中创建自定义标量摘要有几个 SO 答案(herehere),但我找不到有关创建自定义直方图摘要的任何内容。文档似乎非常缺乏自定义摘要。我有一个 numpy 数组,我想总结一下 - 关于如何做的任何想法?

(tf.Summary.Value 有一个我尝试使用的 histo 字段,但它需要一个 tensorflow::HistogramProto;也没有关于该类的文档,所以我不知道如何制作它。我已尝试在下面创建一个最小的失败示例)。

import tensorflow as tf
import numpy as np
sess = tf.Session()
means_placeholder = tf.placeholder(tf.float32)
tf.summary.histogram('means', means_placeholder)
summaries = tf.summary.merge_all()
writer = tf.summary.FileWriter('./summaries')
means = np.random.random(10)    
writer.add_summary(tf.Summary(value=[tf.Summary.Value(tag='means', histo=means)]))

【问题讨论】:

标签: python tensorflow


【解决方案1】:

这段代码有效:

import tensorflow as tf

import numpy as np

def log_histogram(writer, tag, values, step, bins=1000):
    # Convert to a numpy array
    values = np.array(values)

    # Create histogram using numpy
    counts, bin_edges = np.histogram(values, bins=bins)

    # Fill fields of histogram proto
    hist = tf.HistogramProto()
    hist.min = float(np.min(values))
    hist.max = float(np.max(values))
    hist.num = int(np.prod(values.shape))
    hist.sum = float(np.sum(values))
    hist.sum_squares = float(np.sum(values**2))

    # Requires equal number as bins, where the first goes from -DBL_MAX to bin_edges[1]
    # See https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/framework/summary.proto#L30
    # Thus, we drop the start of the first bin
    bin_edges = bin_edges[1:]

    # Add bin edges and counts
    for edge in bin_edges:
        hist.bucket_limit.append(edge)
    for c in counts:
        hist.bucket.append(c)

    # Create and write Summary
    summary = tf.Summary(value=[tf.Summary.Value(tag=tag, histo=hist)])
    writer.add_summary(summary, step)
    writer.flush()

sess = tf.Session()
placeholder = tf.placeholder(tf.float32)

tf.summary.histogram('N(0,1)', placeholder)
summaries = tf.summary.merge_all()
writer = tf.summary.FileWriter('./summaries')

mu, sigma = 0, 0.1 # mean and standard deviation
s = np.random.normal(mu, 1, 10000)
log_histogram(writer, 'N(0,1)', s, 1, bins=100)

source

【讨论】:

    猜你喜欢
    • 2017-10-03
    • 2012-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多