Tensorflow:如何显示在Tensorboard自定义图像(如Matplotlib图)

问题描述:

的Tensorboard自述的Image Dashboard节说:Tensorflow:如何显示在Tensorboard自定义图像(如Matplotlib图)

Since the image dashboard supports arbitrary pngs, you can use this to embed custom visualizations (e.g. matplotlib scatterplots) into TensorBoard.

我看到pyplot图像是如何被写入文件,读回的张量,然后与tf.image_summary()一起使用,将其写入TensorBoard,但是自述文件中的这条语句表明存在更直接的方式。在那儿?如果是这样,是否有任何进一步的文件和/或如何有效地做到这一点的例子?

如果将图像存储在内存缓冲区中,这很容易做到。下面,我给出一个例子,其中一个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可视化:

enter image description here

+0

谢谢。你的例子确实有效。由于某些原因,虽然当我在我的实际脚本(其他摘要等)中集成相同的方法时,解决方案似乎并不稳定。是将数据写入一个或两个图像的摘要文件,然后因以下错误消息:“tensorflow.python.framework.errors.NotFoundError:FetchOutputs节点ImageSummary_2:0:未发现”。也许是某种时机问题。有任何想法吗? – RobR

+0

我不知道为什么会发生。很难说没有看到代码。 –

+1

'tf.image_summary'现在已被弃用。 API已经改变。使用'tf.summary.image'代替(参见[用户指南](https://www.tensorflow.org/api_docs/python/tf/contrib/deprecated/image_summary)。 –

接着脚本不使用中间RGB/PNG编码。它还解决了执行期间额外操作构造的问题,单个摘要被重用。

图的规模预计在执行过程中保持不变

解决方案,工程:

import matplotlib.pyplot as plt 
import tensorflow as tf 
import numpy as np 

def get_figure(): 
    fig = plt.figure(num=0, figsize=(6, 4), dpi=300) 
    fig.clf() 
    return fig 


def fig2rgb_array(fig, expand=True): 
    fig.canvas.draw() 
    buf = fig.canvas.tostring_rgb() 
    ncols, nrows = fig.canvas.get_width_height() 
    shape = (nrows, ncols, 3) if not expand else (1, nrows, ncols, 3) 
    return np.fromstring(buf, dtype=np.uint8).reshape(shape) 


def figure_to_summary(fig): 
    image = fig2rgb_array(fig) 
    summary_writer.add_summary(
    vis_summary.eval(feed_dict={vis_placeholder: image})) 


if __name__ == '__main__': 
     # construct graph 
     x = tf.Variable(initial_value=tf.random_uniform((2, 10))) 
     inc = x.assign(x + 1) 

     # construct summary 
     fig = get_figure() 
     vis_placeholder = tf.placeholder(tf.uint8, fig2rgb_array(fig).shape) 
     vis_summary = tf.summary.image('custom', vis_placeholder) 

     with tf.Session() as sess: 
     tf.global_variables_initializer().run() 
     summary_writer = tf.summary.FileWriter('./tmp', sess.graph) 

     for i in range(100): 
      # execute step 
      _, values = sess.run([inc, x]) 
      # draw on the plot 
      fig = get_figure() 
      plt.subplot('111').scatter(values[0], values[1]) 
      # save the summary 
      figure_to_summary(fig) 

这是为了完成安杰Pronobis的回答。密切关注他的好贴,我成立了这个最小工作例如

plt.figure() 
    plt.plot([1, 2]) 
    plt.title("test") 
    buf = io.BytesIO() 
    plt.savefig(buf, format='png') 
    buf.seek(0) 
    image = tf.image.decode_png(buf.getvalue(), channels=4) 
    image = tf.expand_dims(image, 0) 
    summary = tf.summary.image("test", image, max_outputs=1) 
    writer.add_summary(summary, step) 

如果作家是tf.summary.FileWriter一个实例。 这给了我以下错误: AttributeError的:“张量”对象没有属性“值” 对于其中this github post有溶液:摘要已经被评估(转换成字符串)被添加到写入器之前。所以对我来说,工作代码保持如下(只需添加.eval()调用中的最后一行):

plt.figure() 
    plt.plot([1, 2]) 
    plt.title("test") 
    buf = io.BytesIO() 
    plt.savefig(buf, format='png') 
    buf.seek(0) 
    image = tf.image.decode_png(buf.getvalue(), channels=4) 
    image = tf.expand_dims(image, 0) 
    summary = tf.summary.image("test", image, max_outputs=1) 
    writer.add_summary(summary.eval(), step) 

这可能是短到足以对他的回答评论,但是这些容易被人忽视(我也可能做其他的事情),所以在这里,希望它有帮助!

干杯,
安德烈斯