恢复内存 scipy 插值

2 投票
1 回答
712 浏览
提问于 2025-04-17 22:53

我在使用scipy的LinearNDInterpolator这个模块时,发现内存好像有点问题,感觉在某个地方丢失了内存。如果有人能告诉我怎么恢复内存就太好了。我做的事情大概是这样的(我在旁边监控内存使用情况):

import numpy as np
from scipy import interpolate as irp # mem: 14.7 MB

X = np.random.random_sample( (2**18,2) ) # mem: 18.7 MB
Y = np.random.random_sample( (2**18,1) ) # mem: 20.7 MB
f = irp.LinearNDInterpolator( X, Y ) # mem: 85.9 MB
del f # mem: 57.9 MB

我进行的插值计算其实要小很多,但很多时候会导致崩溃。有没有人能告诉我,这些额外的内存是在哪里消耗的,以及我该怎么恢复它呢?

编辑 1:

这是我用memory_profiler得到的输出:

Line #    Mem usage    Increment   Line Contents
================================================
4   15.684 MiB    0.000 MiB   @profile
5                             def wrapper():
6   19.684 MiB    4.000 MiB     X = np.random.random_sample( (2**18,2) )
7   21.684 MiB    2.000 MiB     Y = np.random.random_sample( (2**18,1) )
8   86.699 MiB   65.016 MiB     f = irp.LinearNDInterpolator( X, Y )
9   58.703 MiB  -27.996 MiB     del f

编辑 2:

我实际运行的代码如下。每个xtr是(2*w^2,w^2)的uint8格式。这个代码在w=61之前都能正常工作,但前提是我得分别运行每个w(比如r_[21]到r_[51],一个一个来)。奇怪的是,61以下的每个值都占用很多内存,但直到61的时候才会出现内存不足的情况。

from numpy import *
from scipy import interpolate as irp

for w in r_[ 21:72:10 ]:
    print w
    t = linspace(-1,1,w)
    xx,yy = meshgrid(t,t)
    xx,yy = xx.flatten(), yy.flatten()
    P = c_[sign(xx)*abs(xx)**0.65, sign(yy)*abs(yy)**0.65]
    del t

    x = load('../../windows/%d/raw/xtr.npy'%w)
    xo = zeros(x.shape,dtype=uint8)
    for i in range(x.shape[0]):
        f = irp.LinearNDInterpolator( P, x[i,:] )
        out = f( xx, yy )
        xo[i,:] = out
        del f, out

    save('../../windows/%d/lens/xtr.npy'%w,xo)
    del x, xo

在w=61时,它报了这个错:

Python(10783) malloc: *** mmap(size=16777216) failed (error code=12)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug
Traceback (most recent call last):
File "make_lens.py", line 16, in <module>
f = irp.LinearNDInterpolator( P, x[i,:] )
File "interpnd.pyx", line 204, in scipy.interpolate.interpnd.LinearNDInterpolator.__init__ (scipy/interpolate/interpnd.c:3794)
File "qhull.pyx", line 1703, in scipy.spatial.qhull.Delaunay.__init__ (scipy/spatial/qhull.c:13267)
File "qhull.pyx", line 1432, in scipy.spatial.qhull._QhullUser.__init__ (scipy/spatial/qhull.c:11989)
File "qhull.pyx", line 1712, in scipy.spatial.qhull.Delaunay._update (scipy/spatial/qhull.c:13470)
File "qhull.pyx", line 526, in scipy.spatial.qhull._Qhull.get_simplex_facet_array (scipy/spatial/qhull.c:5453)
File "qhull.pyx", line 594, in scipy.spatial.qhull._Qhull._get_simplex_facet_array (scipy/spatial/qhull.c:6010)
MemoryError

编辑 3:

这是一个与上面代码类似的链接,但和我的数据无关:

http://pastebin.com/BKYzVVTS

我遇到的错误和上面的一样。我用的是一台配有2GB内存的intel core 2 duo的macbook。读取的x和写入的xo加起来大约只有53MB,但随着循环的进行,内存使用量却远远超过了实际需要的量。

1 个回答

0

这个问题在我使用的SciPy版本之后的更新中被修复了:

https://github.com/scipy/scipy/issues/3471

撰写回答