在Python中保存KDTree对象?

在Python中保存KDTree对象?,第1张

在Python中保存KDTree对象?

KDtree使用嵌套定义其节点类型(innernode,leafnode)。Pickle仅适用于模块级别的类定义,因此嵌套类会使其崩溃:

import cPickleclass Foo(object):    class Bar(object):        passobj = Foo.Bar()print obj.__class__cPickle.dumps(obj)<class '__main__.Bar'>cPickle.PicklingError: Can't pickle <class '__main__.Bar'>: attribute lookup __main__.Bar failed

但是,有一个(棘手的)解决方法,可以将类定义猴子修补

scipy.spatial.kdtree
at模块范围中,以便选择器可以找到它们。如果您所有读取和写入腌制KDtree对象的代码都安装了这些修补程序,则此hack应该可以正常工作:

import cPickleimport numpyfrom scipy.spatial import kdtree# patch module-level attribute to enable pickle to workkdtree.node = kdtree.KDTree.nodekdtree.leafnode = kdtree.KDTree.leafnodekdtree.innernode = kdtree.KDTree.innernodex, y = numpy.mgrid[0:5, 2:8]t1 = kdtree.KDTree(zip(x.ravel(), y.ravel()))r1 = t1.query([3.4, 4.1])raw = cPickle.dumps(t1)# read in the pickled treet2 = cPickle.loads(raw)r2 = t2.query([3.4, 4.1])print t1.tree.__class__print repr(raw)[:70]print t1.data[r1[1]], t2.data[r2[1]]

输出:

<class 'scipy.spatial.kdtree.innernode'>"ccopy_regn_reconstructornp1n(cscipy.spatial.kdtreenKDTreenp2nc_[3 4] [3 4]


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5674898.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存