2016-07-23 140 views
18

的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,但是自述文件中的這條語句表明存在更直接的方式。在那兒?如果是這樣,是否有任何進一步的文件和/或如何有效地做到這一點的例子?

回答

27

如果將圖像存儲在內存緩衝區中,這很容易做到。下面,我給出一個例子,其中一個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)。 –

3

接着腳本不使用中間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) 
0

這是爲了完成安傑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) 

這可能是短到足以對他的回答評論,但是這些容易被人忽視(我也可能做其他的事情),所以在這裏,希望它有幫助!

乾杯,
安德烈斯

相關問題