【问题标题】:How to prevent matplotlib from to showing a figure even with plt.close() in jupyter notebook即使在 jupyter notebook 中使用 plt.close(),如何防止 matplotlib 显示图形
【发布时间】:2021-04-20 16:22:00
【问题描述】:

我在我的神经网络训练循环中创建了一个 matplotlib 图,用于创建 Tensorboard 图像。因此,我使用plot_to_image() 将图形转换为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..')
    # ...

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

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

【问题讨论】:

标签: python tensorflow matplotlib jupyter-notebook tensorboard


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-12
    • 2013-09-14
    • 1970-01-01
    • 2021-05-24
    • 1970-01-01
    • 2019-04-26
    • 2017-05-11
    相关资源
    最近更新 更多