2016-07-23 5 views
18

TensorboardのReadMeの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イメージは以下のように戻って、ファイルを読むために書くことができます方法を見てTensorBoardに書き込むためにtf.image_summary()とともに使用しますが、readmeのこのステートメントはより直接的な方法があることを示しています。ある?もしそうなら、それをどのように効率的に行うかについてのさらなる文書や例がありますか?

答えて

27

メモリバッファにイメージがある場合は、非常に簡単です。以下では、パイロットをバッファに保存して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

はあなたに感謝します。あなたの例は確かに働きます。何らかの理由で、私の実際のスクリプト(他の要約などがあります)に同じメソッドを統合しても、その解決策は安定していないようです。 1つまたは2つのイメージを要約ファイルに書き込んだり、次のエラーメッセージで失敗します。 'tensorflow.python.framework.errors.NotFoundError:FetchOutputs node ImageSummary_2:0:見つかりません'。たぶん何らかのタイミング問題かもしれません。何か案は? – RobR

+0

なぜそれが起こるのか分かりません。コードを見ずに言うのは難しい。 –

+1

'tf.image_summary'は廃止予定です。 APIが変更されました。代わりに 'tf.summary.image'を使用してください(cf [user guide](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'答えを完了する予定:図の

サイズは、実行時に動作します

ソリューション同じままと予想されます。

作家が tf.summary.FileWriterのインスタンスである
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) 

:密接に彼の素敵なポストに続いて、私はこの最小限の作業例を設定します。ライターに追加される前に概要が評価されるようにしている(文字列に変換): は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) 

これは彼の答えにコメントするのに十分に短いかもしれないが、これらは簡単に見落とさすることができます(と私は別の何か別のことをやっているかもしれない)、だからここには、それが助けて欲しいです!

乾杯、
アンドレス

関連する問題