假设有两个三维向量集,用矩阵表示:
要求A,B两个集合中的元素两两间欧氏距离。
先求出ABT:
然后对A和BT分别求其中每个向量的模平方,并扩展为2*3矩阵:
然后:
将上面这个矩阵一开平方,就得到了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