在具有4GB内存的计算机上,这种简单的插值会导致内存错误:
(基于:http://docs.scipy.org/doc/scipy/reference/tutorial/interpolate.html)
import numpy as np
from scipy.interpolate import interp1d
x = np.linspace(0, 10, 80000)
y = np.cos(-x**2/8.0)
f2 = interp1d(x, y, kind='cubic')
我考虑过将数据切割成块,但有没有办法可以在不需要太多内存的情况下执行这种三次样条插值? 为什么它甚至遇到麻烦?
答案 0 :(得分:12)
如果您在发生错误时查看回溯,您会看到如下内容:
---------------------------------------------------------------------------
MemoryError Traceback (most recent call last)
<ipython-input-4-1e538e8d766e> in <module>()
----> 1 f2 = interp1d(x, y, kind='cubic')
/home/warren/local_scipy/lib/python2.7/site-packages/scipy/interpolate/interpolate.py in __init__(self, x, y, kind, axis, copy, bounds_error, fill_value)
390 else:
391 minval = order + 1
--> 392 self._spline = splmake(x, y, order=order)
393 self._call = self.__class__._call_spline
394
/home/warren/local_scipy/lib/python2.7/site-packages/scipy/interpolate/interpolate.py in splmake(xk, yk, order, kind, conds)
1754
1755 # the constraint matrix
-> 1756 B = _fitpack._bsplmat(order, xk)
1757 coefs = func(xk, yk, order, conds, B)
1758 return xk, coefs, order
MemoryError:
失败的功能是scipy.interpolate._fitpack._bsplmat(order, xk)
。此函数创建一个具有形状(len(xk), len(xk) + order - 1)
的二维64位浮点数组。在你的情况下,这超过51GB。
而不是interp1d
,看看InterpolatedUnivariateSpline
是否适合您。例如,
import numpy as np
from scipy.interpolate import InterpolatedUnivariateSpline
x = np.linspace(0, 10, 80000)
y = np.cos(-x**2/8.0)
f2 = InterpolatedUnivariateSpline(x, y, k=3)
我没有收到内存错误。