如何使用scipy.sparse.csr_matrix.min忽略隐式零?

2024-10-09 20:25:58 发布

您现在位置:Python中文网/ 问答频道 /正文

目标

我有一个三维空间中大约500K点的列表。我想找到第一个最近邻距离最大的两个坐标

接近

我正在使用scipy计算稀疏距离矩阵:

from scipy.spatial import cKDTree

tree = cKDTree(points, 40)
spd = tree.sparse_distance_matrix(tree, 0.01)
spo = spd.tocsr()
spo.eliminate_zeros()

我消除了显式的零来解释对角线元素,其中每个点和它本身之间的距离是计算出来的

我现在想找到每行/每列中最小距离的坐标,它应该对应于每个点的第一个最近邻,如下所示:

spo.argmin(axis=0)

通过找到这个数组中元素的最大距离,我应该能够找到第一个最近邻距离最大的两个元素

问题

问题是scipy.sparse.csr_matrixminargmin函数也考虑了隐式零,对于这个应用程序,我不希望这样。我如何解决这个问题?有了这个庞大的矩阵,性能和内存都是问题。或者对于我想做的事情有完全不同的方法吗


Tags: fromtree元素距离目标列表矩阵scipy
1条回答
网友
1楼 · 发布于 2024-10-09 20:25:58

我没有找到距离矩阵的解决方案,但我似乎忽略了使用树的query方法的最明显的解决方案

所以为了找到第一个最近邻居之间的最大距离,我做了(用一个形状为(N,3)的numpy数组的向量):

tree = cKDTree(vectors, leaf_size)
# get the indexes of the first nearest neighbor of each vertex
# we use k=2 because k=1 are the points themselves with distance 0
nn1 = tree.query(vectors, k=2)[1][:,1]
# get the vectors corresponding to those indexes. Basically this is "vectors" sorted by
# first nearest neighbor of each point in "vectors".
nn1_vec = vectors[nn1]
# the distance between each point and its first nearest neighbor
nn_dist = np.sqrt(np.sum((vectors - nn1_vec)**2, axis=1))
# maximum distance
return np.max(nn_dist)

相关问题 更多 >

    热门问题