我想知道是否有一种简单的方法来腌制 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)
也许用__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)