无法腌制scipy.spatial.KDTree对象

时间:2016-06-09 10:10:45

标签: python scipy pickle

我有一个代码,我建立了一个巨大的树,我需要保存它以供以后使用。 不幸的是,我似乎无法挑选scipy.spatial.KDTree个对象。

事实上,当我运行时:

import pickle
import scipy.spatial
tree=scipy.spatial.KDTree([[1,2,3]])
pickle.dump(tree,open('tree.p','wb'))

我收到错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python2.7/pickle.py", line 1370, in dump
    Pickler(file, protocol).dump(obj)
  File "/usr/lib64/python2.7/pickle.py", line 224, in dump
    self.save(obj)
  File "/usr/lib64/python2.7/pickle.py", line 331, in save
    self.save_reduce(obj=obj, *rv)
  File "/usr/lib64/python2.7/pickle.py", line 419, in save_reduce
    save(state)
  File "/usr/lib64/python2.7/pickle.py", line 286, in save
    f(self, obj) # Call unbound method with explicit self
  File "/usr/lib64/python2.7/pickle.py", line 649, in save_dict
    self._batch_setitems(obj.iteritems())
  File "/usr/lib64/python2.7/pickle.py", line 663, in _batch_setitems
    save(v)
  File "/usr/lib64/python2.7/pickle.py", line 331, in save
    self.save_reduce(obj=obj, *rv)
  File "/usr/lib64/python2.7/pickle.py", line 401, in save_reduce
    save(args)
  File "/usr/lib64/python2.7/pickle.py", line 286, in save
    f(self, obj) # Call unbound method with explicit self
  File "/usr/lib64/python2.7/pickle.py", line 562, in save_tuple
    save(element)
  File "/usr/lib64/python2.7/pickle.py", line 286, in save
    f(self, obj) # Call unbound method with explicit self
  File "/usr/lib64/python2.7/pickle.py", line 748, in save_global
    (obj, module, name))     pickle.PicklingError: Can't pickle <class 'scipy.spatial.kdtree.leafnode'>: it's not found as scipy.spatial.kdtree.leafnode

鉴于此,有没有办法腌制它?或至少保存可用于快速重建树的对象的一部分?否则除了scipy.spatial.KDTree还有其他快速选项吗?

1 个答案:

答案 0 :(得分:6)

使用cKDTree代替KDTree,如下所示:

import pickle
import scipy.spatial
tree=scipy.spatial.cKDTree([[1,2,3]])
pickle.dump(tree,open('tree.p','wb'))