栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Saving KDTree object in Python?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Saving KDTree object in Python?

KDtree uses nested classes to define its node types (innernode, leafnode).
Pickle only works on module-level class definitions, so a nested class trips
it up:

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

However, there is a (hacky) workaround by monkey-patching the class
definitions into the

scipy.spatial.kdtree
at module scope so the pickler can
find them. If all of your pre which reads and writes pickled KDtree objects
installs these patches, this hack should work fine:

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

Output:

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/662549.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号