腌制scipy interp1d样条函数

8

我想知道是否有一种简单的方法来在scipy中pickle一个interp1d对象。天真的方法似乎不起作用。

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错误:
---------------------------------------------------------------------------
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
2个回答

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

1
是的,这会起作用。事实上,我就是这样实现的。 - cel
3
这基本上是将xiyi数组以及关键字参数进行腌制。当反腌化时,您需要再次调用interp1d... 如果您的目标是节省CPU功耗,则这不是一个解决方案。 - fheshwfq

1

嗨,如果您愿意使用不同的软件包,您可以使用dill代替pickle:

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上运行正常


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接