酸洗scipy interp1d样条

cel*_*cel 8 python scipy

我想知道是否有一种简单的方法来腌制 interp1d在scipy中挑选物体.天真的方法似乎不起作用.

import pickle
import numpy as np

from scipy.interpolate import interp1d

x = np.linspace(0,1,10)
y = np.random.rand(10)

sp = interp1d(x, y)

with open("test.pickle", "wb") as handle:
    pickle.dump(sp, handle)
Run Code Online (Sandbox Code Playgroud)

这引发了以下PicklingError:

---------------------------------------------------------------------------
PicklingError                             Traceback (most recent call last)
<ipython-input-1-af4e3326e7d1> in <module>()
     10 
     11 with open("test.pickle", "wb") as handle:
---> 12     pickle.dump(sp, handle)

PicklingError: Can't pickle <function interp1d._call_linear at 0x1058abf28>: attribute lookup _call_linear on scipy.interpolate.interpolate failed
Run Code Online (Sandbox Code Playgroud)

Vah*_*hid 4

也许用__getstate____setstate__方法将其包装在另一个类中:

from scipy.interpolate import interp1d


class interp1d_picklable:
    """ class wrapper for piecewise linear function
    """
    def __init__(self, xi, yi, **kwargs):
        self.xi = xi
        self.yi = yi
        self.args = kwargs
        self.f = interp1d(xi, yi, **kwargs)

    def __call__(self, xnew):
        return self.f(xnew)

    def __getstate__(self):
        return self.xi, self.yi, self.args

    def __setstate__(self, state):
        self.f = interp1d(state[0], state[1], **state[2])
Run Code Online (Sandbox Code Playgroud)

  • 这基本上会腌制“xi”和“yi”数组以及 keyargs(如果有)。当 unpickle 时,你会再次调用 `interp1d`...如果你的目标是节省 CPU 功率,那么这不是一个解决方案。 (3认同)