我正在为一个相当大的数据集创建一个径向基函数插值模型.主要调用`scipy.interpolate.Rbf(,)需要大约一分钟和14 GB的RAM.
因为并非每台应该运行的机器都能够执行此操作,并且由于程序将经常在同一数据集上运行,所以我想将结果挑选到文件中.这是一个简化的例子:
import scipy.interpolate as inter
import numpy as np
import cPickle
x = np.array([[1,2,3],[3,4,5],[7,8,9],[1,5,9]])
y = np.array([1,2,3,4])
rbfi = inter.Rbf(x[:,0], x[:,1], x[:,2], y)
RBFfile = open('picklefile','wb')
RBFpickler = cPickle.Pickler(RBFfile,protocol=2)
RBFpickler.dump(rbfi)
RBFfile.close()
RBFpickler.dump()调用导致无法pickle< type’instancemethod’>错误.
据我所知,这意味着那里有一个方法(好吧,rbfi()是可调用的),并且由于某些原因我不太明白它不能被腌制.
有没有人知道以某种方式腌制这种方式或以其他方式保存inter.Rbf()调用的结果?
那里有一些形状(nd,n)和(n,n)的数组(rbfi.A,rbfi.xi,rbfi.di …),我假设存储了所有有趣的信息.我想我可以腌制那些阵列,但后来我不知道怎样才能再将物体放在一起……
编辑:
附加约束:我不允许在系统上安装其他库.我可以包含它们的唯一方法是它们是纯Python,我只需将它们包含在脚本中而无需编译任何东西.
最佳答案 我使用dill来序列化结果……或者如果你想要一个缓存函数,你可以使用klepto来缓存函数调用,这样你就可以最小化函数的重新评估.
Python 2.7.6 (default, Nov 12 2013, 13:26:39)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import scipy.interpolate as inter
>>> import numpy as np
>>> import dill
>>> import klepto
>>>
>>> x = np.array([[1,2,3],[3,4,5],[7,8,9],[1,5,9]])
>>> y = np.array([1,2,3,4])
>>>
>>> # build an on-disk archive for numpy arrays,
>>> # with a dictionary-style interface
>>> p = klepto.archives.dir_archive(serialized=True, fast=True)
>>> # add a caching algorithm, so when threshold is hit,
>>> # memory is dumped to disk
>>> c = klepto.safe.lru_cache(cache=p)
>>> # decorate the target function with the cache
>>> c(inter.Rbf)
<function Rbf at 0x104248668>
>>> rbf = _
>>>
>>> # 'rbf' is now cached, so all repeat calls are looked up
>>> # from disk or memory
>>> d = rbf(x[:,0], x[:,1], x[:,2], y)
>>> d
<scipy.interpolate.rbf.Rbf object at 0x1042454d0>
>>> d.A
array([[ 1. , 1.22905719, 2.36542472, 1.70724365],
[ 1.22905719, 1. , 1.74422655, 1.37605151],
[ 2.36542472, 1.74422655, 1. , 1.70724365],
[ 1.70724365, 1.37605151, 1.70724365, 1. ]])
>>>
继续…
>>> # the cache is serializing the result object behind the scenes
>>> # it also works if we directly pickle and unpickle it
>>> _d = dill.loads(dill.dumps(d))
>>> _d
<scipy.interpolate.rbf.Rbf object at 0x104245510>
>>> _d.A
array([[ 1. , 1.22905719, 2.36542472, 1.70724365],
[ 1.22905719, 1. , 1.74422655, 1.37605151],
[ 2.36542472, 1.74422655, 1. , 1.70724365],
[ 1.70724365, 1.37605151, 1.70724365, 1. ]])
>>>
获取klepto和莳萝:https://github.com/uqfoundation