3

I create a matplotlib figure within my neural network training loop for creating a Tensorboard image. Therefore, I use plot_to_image() to convert the figure to an image as mentioned in the official Tensorboard guide.

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=3)
    # Add the batch dimension
    image = tf.expand_dims(image, 0)
    return image


for epoch in range(n_epochs):
    # ...
    # error_fig = >some fancy plt.fig for visualizing stuff in Tensorboard<
    tf.summary.image(name='train_error_img', data=plot_to_image(error_fig), step=epoch)
    print('Some metrics for this particular epoch..')
    # ...

The plt.close(figure) should prevent the figure to be shown. However, in my jupyter notebook, I get an empty space in my output between the print statements. If I highlight the output, I can even see the three images I create for each epoch as a blank space (Yes, I call the function three different times for one epoch for different figures).

enter image description here

My question now is:
How can I change this behaviour but still get my print statement shown?
Thanks in advance

Crysers
  • 455
  • 2
  • 13
  • You might try plt.figure(figsize=(0,0)) before closing the fig. Hacky but simple. – stever Jan 15 '21 at 17:51
  • Similar issue https://stackoverflow.com/questions/18717877/prevent-plot-from-showing-in-jupyter-notebook –  Jan 18 '21 at 11:32

1 Answers1

0

Managed to solve my problem by using plt.ioff() at the start of my training routine and plt.ion() at the end. The answer was given in a comment of the question linked by @TFer. Thanks!

Crysers
  • 455
  • 2
  • 13