如何使用Jupyter笔记本中的实时绘图(matplotlib)避免内存泄漏?

2024-06-17 15:32:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用Jupyter笔记本训练一个大的DQN。我很难找到一种方法来实时更新这个绘图,而不会导致内存泄漏。我目前有一个肮脏的实现,每集使用约1GB的RAM(14000个步骤)。当我看完下面的截图这样的7集时,我的系统内存已经用完了一半

从我在其他帖子中读到的内容来看,无论是gc.collect()还是del figfig.clear()等等,尝试在同一线程中绘图都会导致内存泄漏。如何在循环中更新此绘图而不导致内存泄漏

I found a similar question here,但我不太明白如何将其应用到我的案例中,使用动态更新的多个图形和数据

clear_output(wait=True)
plt.close()
plt.ion()
fig, axs = plt.subplots(2, figsize=(10,7))
fig.tight_layout()
color = [int((item + 1) * 255 / 2) for item in p_reward_history]
axs[0].scatter(tindex, p_reward_history[-plot_len:], c=color[-plot_len:], cmap='RdYlGn', linewidth=3)
axs[0].set_title('P&L Individual Transactions')
axs[0].plot(zero_line, color="black", linewidth=3)
axs[0].set_facecolor('#2c303c')
axs[1].set_title('P&L Running Total')
axs[1].set_facecolor('#2c303c')
axs[1].plot(running_rewards_history, color="#94c273", linewidth=3)

动态变量是running_reward_historyp_reward_history。这两个列表都将新值附加到每个循环中

当前的实现如下所示: enter image description here

我更喜欢在Jupyter笔记本中工作,但如果我需要在常规shell中进行训练以便异步更新,这对我来说没问题


Tags: 内存绘图plotfig动态笔记本jupyterplt