【问题标题】:pickling scipy interp1d spline酸洗 scipy interp1d 样条
【发布时间】:2019-04-03 22:45:32
【问题描述】:

我想知道是否有一种简单的方法可以在 scipy 中腌制 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

【问题讨论】:

    标签: python scipy


    【解决方案1】:

    也许用__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])
    

    【讨论】:

    • 是的,这会起作用。事实上我是这样实现的。
    • 这基本上会腌制xiyi 数组和keyargs(如果有的话)。解压时,您会再次调用interp1d...如果您的目标是节省 CPU 功率,那么这不是解决方案。
    【解决方案2】:

    您好,如果您愿意使用其他软件包,您可以使用 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-15
      • 2016-01-05
      • 2016-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-29
      相关资源
      最近更新 更多