即使在 jupyter 笔记本中使用 plt.close(),如何防止 matplotlib 显示图形
How to prevent matplotlib from to showing a figure even with plt.close() in jupyter notebook
我在我的神经网络训练循环中创建了一个 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 notebook 中,我在 print 语句之间的输出中得到一个空 space 。如果我突出显示输出,我什至可以看到我为每个时期创建的三张图像为空白 space(是的,我为不同的数字在一个时期调用了三次不同的函数)。
我现在的问题是:
我怎样才能改变这种行为,但仍然显示我的打印语句?
提前致谢
通过在我的训练程序开始时使用 plt.ioff()
并在训练结束时使用 plt.ion()
设法解决了我的问题。答案在@TFer 链接的问题的评论中给出。谢谢!
我在我的神经网络训练循环中创建了一个 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 notebook 中,我在 print 语句之间的输出中得到一个空 space 。如果我突出显示输出,我什至可以看到我为每个时期创建的三张图像为空白 space(是的,我为不同的数字在一个时期调用了三次不同的函数)。
我现在的问题是:
我怎样才能改变这种行为,但仍然显示我的打印语句?
提前致谢
通过在我的训练程序开始时使用 plt.ioff()
并在训练结束时使用 plt.ion()
设法解决了我的问题。答案在@TFer 链接的问题的评论中给出。谢谢!