在 Python 中找到 3D 中给定点最近点的最快方法
假设我在 A 中有 10,000 个点,在 B 中有 10,000 个点,并且想要找出 A 中与每个 B 点最接近的点。
目前,我只是循环遍历 B 和 A 中的每个点来找到距离最近的点。 IE。
B = [(.5, 1, 1), (1, .1, 1), (1, 1, .2)]
A = [(1, 1, .3), (1, 0, 1), (.4, 1, 1)]
C = {}
for bp in B:
closestDist = -1
for ap in A:
dist = sum(((bp[0]-ap[0])**2, (bp[1]-ap[1])**2, (bp[2]-ap[2])**2))
if(closestDist > dist or closestDist == -1):
C[bp] = ap
closestDist = dist
print C
但是,我确信有一种更快的方法可以做到这一点......有什么想法吗?
So lets say I have 10,000 points in A and 10,000 points in B and want to find out the closest point in A for every B point.
Currently, I simply loop through every point in B and A to find which one is closest in distance. ie.
B = [(.5, 1, 1), (1, .1, 1), (1, 1, .2)]
A = [(1, 1, .3), (1, 0, 1), (.4, 1, 1)]
C = {}
for bp in B:
closestDist = -1
for ap in A:
dist = sum(((bp[0]-ap[0])**2, (bp[1]-ap[1])**2, (bp[2]-ap[2])**2))
if(closestDist > dist or closestDist == -1):
C[bp] = ap
closestDist = dist
print C
However, I am sure there is a faster way to do this... any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在这种情况下,我通常使用 kd-tree 。
有一个用 SWIG 包装的 C++ 实现与 BioPython 捆绑在一起,易于使用。
I typically use a kd-tree in such situations.
There is a C++ implementation wrapped with SWIG and bundled with BioPython that's easy to use.
您可以使用一些空间查找结构。一个简单的选项是 八叉树;更高级的包括 BSP 树。
You could use some spatial lookup structure. A simple option is an octree; fancier ones include the BSP tree.
您可以使用 numpy 广播。例如,
将打印 2,1,0,它们分别是 a 中最接近 B 的 1,2,3 行的行。
否则,您可以使用广播:
我希望有所帮助。
You could use numpy broadcasting. For example,
will print 2,1,0 which are the rows in a that are closest to the 1,2,3 rows of B, respectively.
Otherwise, you can use broadcasting:
I hope that helps.