本文介绍了Matplotlib错误会导致内存泄漏.如何释放内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行django应用程序,其中包括matplotlib,并允许用户指定图形的轴.这可能会导致溢出错误:超出Agg复杂度"

I am running a django app that includes matplotlib and allows the user to specify the axes of the graph. This can result in 'Overflow Error: Agg complexity exceeded'

当发生这种情况时,最多会占用100MB的RAM.通常,我使用fig.gcf()plot.close()gc.collect()释放该内存,但是与错误关联的内存似乎与绘图对象无关.

When that happens up to 100MB of RAM get tied up. Normally I free that memory up using fig.gcf(), plot.close(), and gc.collect(), but the memory associated with the error does not seem to be associated with the plot object.

有人知道我该如何释放那段记忆吗?

Does anyone know how I can release that memory?

谢谢.

这是一些给我Agg复杂度错误的代码.

Here is some code that gives me the Agg Complexity Error.

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import gc

a = np.arange(1000000)
b = np.random.randn(1000000)

fig = plt.figure(num=1, dpi=100, facecolor='w', edgecolor='w')
fig.set_size_inches(10,7)
ax = fig.add_subplot(111)
ax.plot(a, b)

fig.savefig('yourdesktop/random.png')   # code gives me an error here

fig.clf()    # normally I use these lines to release the memory
plt.close()
del a, b
gc.collect()

推荐答案

我假设您可以至少运行一次您发布的代码.该问题仅在运行多次发布的代码后才会显现出来.正确吗?

I assume you can run the code you posted at least once. The problem only manifests itself after running the posted code many times. Correct?

如果是这样,以下内容可以在没有真正确定问题根源的情况下避免该问题.也许这是一件坏事,但这在紧要关头起作用:只需使用multiprocessing在单独的进程中运行内存密集型代码.您不必担心fig.clf()plt.close()del a,bgc.collect().进程结束后,所有内存将被释放.

If so, the following avoids the problem without really identifying the source of the problem.Maybe that is a bad thing, but this works in a pinch: Simply use multiprocessing to run the memory-intensive code in a separate process. You don't have to worry about fig.clf() or plt.close() or del a,b or gc.collect(). All memory is freed when the process ends.

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np

import multiprocessing as mp

def worker():
    N=1000000
    a = np.arange(N)
    b = np.random.randn(N)

    fig = plt.figure(num=1, dpi=100, facecolor='w', edgecolor='w')
    fig.set_size_inches(10,7)
    ax = fig.add_subplot(111)
    ax.plot(a, b)

    fig.savefig('/tmp/random.png')   # code gives me an error here

if __name__=='__main__':
    proc=mp.Process(target=worker)
    proc.daemon=True
    proc.start()
    proc.join()

您也不必proc.join(). join将阻塞主进程,直到worker完成.如果省略join,则主要过程将继续,而worker过程在后台运行.

You don't have to proc.join() either. The join will block the main process until the worker completes. If you omit the join, then the main process simply continues with the worker process working in the background.

这篇关于Matplotlib错误会导致内存泄漏.如何释放内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 17:29