【问题标题】:Matplotlib doesn't release memory after savefig and close()在 savefig 和 close() 之后 Matplotlib 不释放内存
【发布时间】:2015-09-18 07:55:56
【问题描述】:

我有一段代码可以正常循环一次或两次,但最终会增加内存。我尝试使用memory_profiler 定位内存泄漏,结果如下:

row_nr    Memory_usage    Memory_diff    row_text
 470     52.699 MiB     0.000 MiB      ax.axis('off')
 471     167.504 MiB    114.805 MiB    fig.savefig('figname.png', dpi=600)
 472     167.504 MiB    0.000 MiB      fig.clf()
 473     109.711 MiB    -57.793 MiB    plt.close()
 474     109.711 MiB    0.000 MiB      gc.collect()`

我创建了这样的图形: fig, ax = plt.subplots()

有什么建议 109 - 52 = 57 MiB 去哪儿了?

我正在使用 python 3.3。

【问题讨论】:

  • stackoverflow.com/questions/7125710/… 的可能重复尽管这是一种解决方法,但不是解决此问题的明确方法。
  • 这个问题更笼统,可能是其中一种场景涵盖了您的情况。如果没有,请告诉我们有关用例的更多详细信息stackoverflow.com/questions/7101404/…。
  • 感谢您的尝试,不幸的是它有效,我没有在 django 中运行任何东西,所以没有帮助。我可以尝试多处理,但如上所述,只是避免问题而不解决问题。我正在使用子图(“fig, ax= plt.subplots()”)所以我不能从 fig = plt.figure() 更改为 fig = figure.Figure(),或者?还有其他建议吗?
  • 在每个循环结束时尝试plt.close('all')。使用 agg 后端为我工作。

标签: python matplotlib memory-leaks


【解决方案1】:
# Clear the current axes.
plt.cla() 
# Clear the current figure.
plt.clf() 
# Closes all the figure windows.
plt.close('all')

希望对你有帮助

【讨论】:

  • 还要加上import gc; gc.collect(),确保你清除内存!
【解决方案2】:

plt.ioff() 在笔记本上为我工作, plt.close(fig) 否则。

【讨论】:

    【解决方案3】:

    这里发布的任何内容都没有为我工作。就我而言,它与通过 SSH 解释器在服务器上运行有关。显然这将使用非交互模式,并开始正常清除所有内存:

    import matplotlib
    matplotlib.use('Agg')
    

    来源:https://matplotlib.org/stable/faq/howto_faq.html#work-with-threads

    【讨论】:

    • 这个答案应该被接受。这是 matplotlib github.com/matplotlib/matplotlib/issues/20300 中的一个已知错误
    • 这将内存使用量从 GB 减少到 MB。谢谢!正如你所说,其他帖子都不适合我。
    • 就我而言,它与 SSH 无关,我在本地运行 Python 脚本(保存数字)。
    • 也从 Eclipse 的 Python 运行,从运行结束时的 30GB 到一致的 100MB。尝试了其他一切都无济于事。
    【解决方案4】:

    取自这里:Matplotlib errors result in a memory leak. How can I free up that memory?

    哪个有原始参考:https://www.mail-archive.com/matplotlib-users@lists.sourceforge.net/msg11809.html

    要得到斧头和图:

    代替:

    import matplotlib.pyplot as plt
    fig,ax = plt.subplots(1)
    

    使用:

    from matplotlib import figure
    fig = figure.Figure()
    ax = fig.subplots(1)
    

    也不需要做plt.close() 或任何事情。它对我有用。

    【讨论】:

      【解决方案5】:
      # Clear the current axes.
      plt.cla() 
      # Clear the current figure.
      plt.clf() 
      # Closes all the figure windows.
      plt.close('all')   
      plt.close(fig)
      gc.collect()
      

      这对我有用。只需将这些行放在循环的末尾!

      【讨论】:

        猜你喜欢
        • 2018-04-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-24
        • 2014-02-19
        • 1970-01-01
        • 2011-10-29
        相关资源
        最近更新 更多