How to Display Custom Images in Tensorboard (e.g. Matplotlib Plots)?

前端 未结 5 2064
遇见更好的自我
遇见更好的自我 2020-12-04 22:01

The Image Dashboard section of the Tensorboard ReadMe says:

Since the image dashboard supports arbitrary pngs, you can use this to embed custom visual

5条回答
  •  借酒劲吻你
    2020-12-04 22:25

    Finally there is some official documentation about "Logging arbitrary image data" with an example of matplotlib created images.
    They write:

    In the code below, you'll log the first 25 images as a nice grid using matplotlib's subplot() function. You'll then view the grid in TensorBoard:

    # Clear out prior logging data.
    !rm -rf logs/plots
    
    logdir = "logs/plots/" + datetime.now().strftime("%Y%m%d-%H%M%S")
    file_writer = tf.summary.create_file_writer(logdir)
    
    def plot_to_image(figure):
      """Converts the matplotlib plot specified by 'figure' to a PNG image and
      returns it. The supplied figure is closed and inaccessible after this call."""
      # Save the plot to a PNG in memory.
      buf = io.BytesIO()
      plt.savefig(buf, format='png')
      # Closing the figure prevents it from being displayed directly inside
      # the notebook.
      plt.close(figure)
      buf.seek(0)
      # Convert PNG buffer to TF image
      image = tf.image.decode_png(buf.getvalue(), channels=4)
      # Add the batch dimension
      image = tf.expand_dims(image, 0)
      return image
    
    def image_grid():
      """Return a 5x5 grid of the MNIST images as a matplotlib figure."""
      # Create a figure to contain the plot.
      figure = plt.figure(figsize=(10,10))
      for i in range(25):
        # Start next subplot.
        plt.subplot(5, 5, i + 1, title=class_names[train_labels[i]])
        plt.xticks([])
        plt.yticks([])
        plt.grid(False)
        plt.imshow(train_images[i], cmap=plt.cm.binary)
      
      return figure
    
    # Prepare the plot
    figure = image_grid()
    # Convert to image and log
    with file_writer.as_default():
      tf.summary.image("Training data", plot_to_image(figure), step=0)
    
    %tensorboard --logdir logs/plots
    

提交回复
热议问题