繁体   English   中英

如何防止 matplotlib 在 jupyter notebook 中使用 plt.close() 显示图形

[英]How to prevent matplotlib from to showing a figure even with plt.close() in jupyter notebook

我在我的神经网络训练循环中创建了一个 matplotlib 图形,用于创建 Tensorboard 图像。 因此,我使用plot_to_image()将图形转换为官方 Tensorboard 指南中提到的图像。

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..')
    # ...

plt.close(figure)应该防止显示图形。 但是,在我的 jupyter 笔记本中,我在打印语句之间的 output 中有一个空白区域。 如果我突出显示 output,我什至可以将我为每个时期创建的三个图像视为一个空白区域(是的,我将 function 称为一个时期的三个不同时间,用于不同的数字)。

在此处输入图像描述

我现在的问题是:
如何更改此行为但仍显示我的打印语句?
提前致谢

通过在我的训练程序开始时使用plt.ioff()plt.ion()使用 plt.ion() 设法解决了我的问题。 答案在@TFer 链接的问题的评论中给出。 谢谢!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM