假设有两个三维向量集,用矩阵表示:
要求A,B两个集合中的元素两两间欧氏距离。
先求出ABT:
然后对A和BT分别求其中每个向量的模平方,并扩展为2*3矩阵:
![](https://i-blog.csdnimg.cn/blog_migrate/97c2b1825c6be92a2c847ef960128175.png)
![](https://i-blog.csdnimg.cn/blog_migrate/6f6728b8cd3dfb9b39259302507a5637.png)
将上面这个矩阵一开平方,就得到了A,B向量集两两间的欧式距离了。
算法:
def EuclideanDistances(A, B):
BT = B.transpose()
# vecProd = A * BT
vecProd = np.dot(A,BT)
# print(vecProd)
SqA = A**2
# print(SqA)
sumSqA = np.matrix(np.sum(SqA, axis=1))
sumSqAEx = np.tile(sumSqA.transpose(), (1, vecProd.shape[1]))
# print(sumSqAEx)
SqB = B**2
sumSqB = np.sum(SqB, axis=1)
sumSqBEx = np.tile(sumSqB, (vecProd.shape[0], 1))
SqED = sumSqBEx + sumSqAEx - 2*vecProd
SqED[SqED<0]=0.0
ED = np.sqrt(SqED)
return ED
scipy调用:
distance.cdist([[1,2,3],[4,5,6]],[[2,3,4],[5,6,7],[8,9,10]])