[英]How to find the closest corresponding vectors between two coordinate matrices?
I have the following problem in Python I need to solve: 我在Python中需要解决以下问题:
Given two coordinate matrices (NumPy ndarrays) A
and B
, find for all coordinate vectors a
in A
the corresponding coordinate vectors b
in B
, such that the Euclidean distance ||ab||
给定两个坐标的矩阵(NumPy的ndarrays)
A
和B
,找到所有坐标向量a
在A
对应的坐标向量b
在B
,使得欧几里德距离||ab||
is minimized. 最小化。 The coordinate matrices
A
and B
can have different number of coordinate vectors (that is, different number of rows). 坐标矩阵
A
和B
可以具有不同数量的坐标向量(即,不同的行数)。
This method should return a matrix of coordinate vectors C
where the ith vector c
in C
is the vector from B
that minimizes the Euclidean distance with the ith coordinate vector a
in A
. 此方法应返回坐标向量的矩阵
C
其中第i个矢量c
在C
是从向量B
最小化的坐标向量与第i的欧几里德距离a
在A
。
For example, lets say 例如,让我们说
A = np.array([[1,1], [3,4]])
and B = np.array([[1,2], [3,6], [8,1]])
A = np.array([[1,1], [3,4]])
和B = np.array([[1,2], [3,6], [8,1]])
The Euclidean distances between the vector [1,1]
in A
and the vectors in B
are: A
的向量[1,1]
与B
中的向量之间的欧几里德距离为:
1, 5.385165, 7
So the first vector in C
would be [1,2]
所以
C
的第一个向量是[1,2]
Similarly the distances for the vector [3,4]
in A
and the vectors in B
are: 类似地,
A
的矢量[3,4]
和B
中的矢量的距离是:
2.828427, 2, 5.830952
So the second and last vector in C
would be [3,6]
因此,
C
的第二个和最后一个向量将是[3,6]
So C = [[1,2], [3,6]]
所以
C = [[1,2], [3,6]]
How to code this efficiently in Python? 如何在Python中有效地编码?
You could use cdist
from scipy.spatial.distance
to efficiently get the euclidean distances and then use np.argmin
to get the indices corresponding to minimum values and use those to index into B
for the final output. 您可以使用
cdist
的scipy.spatial.distance
来有效地获取欧氏距离,然后使用np.argmin
来获取与最小值对应的索引,并使用这些索引将B
索引为最终输出。 Here's the implementation - 这是实施 -
import numpy as np
from scipy.spatial.distance import cdist
C = B[np.argmin(cdist(A,B),1)]
Sample run - 样品运行 -
In [99]: A
Out[99]:
array([[1, 1],
[3, 4]])
In [100]: B
Out[100]:
array([[1, 2],
[3, 6],
[8, 1]])
In [101]: B[np.argmin(cdist(A,B),1)]
Out[101]:
array([[1, 2],
[3, 6]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.