복붙노트

[PYTHON] Tensorflow : Tensorboard에서 사용자 정의 이미지를 표시하는 방법 (예 : Matplotlib Plots)

PYTHON

Tensorflow : Tensorboard에서 사용자 정의 이미지를 표시하는 방법 (예 : Matplotlib Plots)

Tensorboard ReadMe의 이미지 대시 보드 섹션은 다음과 같이 말합니다 :

pyplot 이미지를 파일로 쓰고 텐서로 다시 읽은 다음 tf.image_summary ()를 사용하여 TensorBoard에 쓰는 방법을 봅니다. 그러나 readme의이 문장은 더 직접적인 방법이 있음을 시사합니다. 거기 있니? 그렇다면 추가 문서 및 / 또는이를 효율적으로 수행하는 방법에 대한 예가 있습니까?

해결법

  1. ==============================

    1.메모리 버퍼에 이미지가 있으면 작업하기가 쉽습니다. 아래에서, 나는 pyplot을 버퍼에 저장 한 다음 TF 이미지 표현으로 변환 한 후 이미지 요약으로 보내는 예제를 보여줍니다.

    메모리 버퍼에 이미지가 있으면 작업하기가 쉽습니다. 아래에서, 나는 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 시각화가 제공됩니다.

  2. ==============================

    2.다음 스크립트는 중간 RGB / PNG 인코딩을 사용하지 않습니다. 또한 실행 중 추가 작업 구성으로 문제가 해결되고 단일 요약이 다시 사용됩니다.

    다음 스크립트는 중간 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)
    
  3. ==============================

    3.내 대답이 조금 늦었 어. tf-matplotlib를 사용하면 간단한 산점도가 다음과 같이 나타납니다.

    내 대답이 조금 늦었 어. 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을 지원합니다.

  4. ==============================

    4.이것은 Andrzej Pronobis의 답을 완성하고자합니다. 밀접하게 그의 좋은 게시물을 따라, 나는이 최소한의 작업 예제를 설정 :

    이것은 Andrzej 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)
    

    writer는 tf.summary.FileWriter의 인스턴스입니다. 이로 인해 다음과 같은 오류가 발생했습니다. AttributeError : 'Tensor'객체에 'value'속성이 없습니다. 이 github 게시물에 대한 해결책이 있습니다. 요약을 작성자에게 추가하기 전에 평가 (문자열로 변환)해야합니다. 그래서 나를위한 작업 코드는 다음과 같이 남았습니다 (마지막 줄에 .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)
    

    이것은 그의 대답에 대한 논평이 될만큼 충분히 짧을 수 있지만, 쉽게 간과 될 수 있습니다. (그래서 나는 다른 다른 것을 할 수도 있습니다.) 그래서 여기에 도움이되기를 바랍니다!

    건배, 안드레

  5. from https://stackoverflow.com/questions/38543850/tensorflow-how-to-display-custom-images-in-tensorboard-e-g-matplotlib-plots by cc-by-sa and MIT license