如何在 Tensorboard 中显示自定义图像(例如 Matplotlib Plots)?

新手上路,请多包涵

Tensorboard 自述文件的 图像仪表板 部分说:

由于图像仪表板支持任意 png,您可以使用它将自定义可视化(例如 matplotlib 散点图)嵌入到 TensorBoard 中。

我看到了如何将 pyplot 图像写入文件,作为张量读回,然后与 tf.image_summary() 一起使用以将其写入 TensorBoard,但自述文件中的这一声明表明有更直接的方法。有没有?如果是这样,是否有任何进一步的文档和/或示例来说明如何有效地执行此操作?

原文由 RobR 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 725
2 个回答

如果您在内存缓冲区中有图像,这很容易做到。下面,我展示了一个示例,其中将 pyplot 保存到缓冲区,然后将其转换为 TF 图像表示,然后将其发送到图像摘要。

 import io
import matplotlib.pyplot as plt
import tensorflow as tf

def gen_plot():
    """Create a pyplot plot and save to buffer."""
    plt.figure()
    plt.plot([1, 2])
    plt.title("test")
    buf = io.BytesIO()
    plt.savefig(buf, format='png')
    buf.seek(0)
    return buf

# Prepare the plot
plot_buf = gen_plot()

# Convert PNG buffer to TF image
image = tf.image.decode_png(plot_buf.getvalue(), channels=4)

# Add the batch dimension
image = tf.expand_dims(image, 0)

# Add image summary
summary_op = tf.summary.image("plot", image)

# Session
with tf.Session() as sess:
    # Run
    summary = sess.run(summary_op)
    # Write summary
    writer = tf.train.SummaryWriter('./logs')
    writer.add_summary(summary)
    writer.close()

这给出了以下 TensorBoard 可视化:

在此处输入图像描述

原文由 Andrzej Pronobis 发布,翻译遵循 CC BY-SA 3.0 许可协议

我的回答有点晚了。使用 tf-matplotlib ,一个简单的散点图可以归结为:

 import tensorflow as tf
import numpy as np

import tfmpl

@tfmpl.figure_tensor
def draw_scatter(scaled, colors):
    '''Draw scatter plots. One for each color.'''
    figs = tfmpl.create_figures(len(colors), figsize=(4,4))
    for idx, f in enumerate(figs):
        ax = f.add_subplot(111)
        ax.axis('off')
        ax.scatter(scaled[:, 0], scaled[:, 1], c=colors[idx])
        f.tight_layout()

    return figs

with tf.Session(graph=tf.Graph()) as sess:

    # A point cloud that can be scaled by the user
    points = tf.constant(
        np.random.normal(loc=0.0, scale=1.0, size=(100, 2)).astype(np.float32)
    )
    scale = tf.placeholder(tf.float32)
    scaled = points*scale

    # Note, `scaled` above is a tensor. Its being passed `draw_scatter` below.
    # However, when `draw_scatter` is invoked, the tensor will be evaluated and a
    # numpy array representing its content is provided.
    image_tensor = draw_scatter(scaled, ['r', 'g'])
    image_summary = tf.summary.image('scatter', image_tensor)
    all_summaries = tf.summary.merge_all()

    writer = tf.summary.FileWriter('log', sess.graph)
    summary = sess.run(all_summaries, feed_dict={scale: 2.})
    writer.add_summary(summary, global_step=0)

执行时,这会在 Tensorboard 中产生以下图

请注意, tf-matplotlib 负责评估任何张量输入,避免 pyplot 线程问题,并支持运行时关键绘图的 blitting。

原文由 chrish. 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题