最近要用到sklearn.neighbor.KDTree
,它有一个attribute是data
是指构造KDTree数据的memoryview。简单使用后发现memoryview有点像C里的指针
import numpy as np
from sklearn.neighbors import KDTree
from time import time
if __name__ == '__main__':
pts = np.random.randn(10, 3)
print("pts:", pts)
# t1 = time()
tree = KDTree(pts)
# print("kdtree build time:", time() - t1)
pts_rebuild_copy = np.array(tree.data)
pts_rebuild_nocopy = np.array(tree.data, copy=False)
pts_rebuild_copy[0] = [1, 1, 1]
print("pts_1:", pts)
pts_rebuild_nocopy[1] = [1, 1, 1]
print("pts_2:", pts)
输出结果为
pts: [[ 0.06880616 0.96098154 1.17762945]
[-1.17038063 -0.26971611 -1.63170026]
[ 0.2531622 1.01200955 0.47513764]
[ 1.14337371 -1.22593015 -1.64465175]
[ 1.16018094 -1.24631525 -1.42440624]
[-0.20000339 -1.83829021 1.12720473]
[-1.47188812 0.57656556 -0.53477847]
[-1.50508239 -1.02217681 -0.92497212]
[ 0.14878263 -1.48558938 0.0131429 ]
[-0.84247113 -0.64958466 1.60158359]]
pts_1: [[ 0.06880616 0.96098154 1.17762945]
[-1.17038063 -0.26971611 -1.63170026]
[ 0.2531622 1.01200955 0.47513764]
[ 1.14337371 -1.22593015 -1.64465175]
[ 1.16018094 -1.24631525 -1.42440624]
[-0.20000339 -1.83829021 1.12720473]
[-1.47188812 0.57656556 -0.53477847]
[-1.50508239 -1.02217681 -0.92497212]
[ 0.14878263 -1.48558938 0.0131429 ]
[-0.84247113 -0.64958466 1.60158359]]
pts_2: [[ 0.06880616 0.96098154 1.17762945]
[ 1. 1. 1. ]
[ 0.2531622 1.01200955 0.47513764]
[ 1.14337371 -1.22593015 -1.64465175]
[ 1.16018094 -1.24631525 -1.42440624]
[-0.20000339 -1.83829021 1.12720473]
[-1.47188812 0.57656556 -0.53477847]
[-1.50508239 -1.02217681 -0.92497212]
[ 0.14878263 -1.48558938 0.0131429 ]
[-0.84247113 -0.64958466 1.60158359]]
也就是说,tree.data就是指向内存中存放pts的地址,np.array(tree.data, copy=True)是对pts的deepcopy而np.array(tree.data, copy=False)是对pts的浅拷贝