酸洗scipy interp1d样条

时间:2015-10-01 09:02:28

标签: python scipy

我想知道是否有一种简单的方法可以在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) 个对象。天真的方法似乎不起作用。

---------------------------------------------------------------------------
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

这引发了以下PicklingError:

{{1}}

2 个答案:

答案 0 :(得分:3)

可能会使用__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])

答案 1 :(得分:0)

嗨,如果您愿意使用其他包装,则可以使用dill而不是泡菜:

import dill as pickle
import scipy.interpolate as interpolate
import numpy as np 

interpolation = interpolate.interp1d(np.arange(0,10), np.arange(0,10))
with open("test_interp", "wb") as dill_file:
     pickle.dump(inv_cdf, dill_file)
with open("test_interp", "rb") as dill_file:
     interpolation = pickle.load(dill_file)

在我的Python 3.6上工作