python求向量集合中兩兩向量對應的歐式距離


python求向量集合中兩兩向量對應的歐式距離

為了使用矩陣加速運算,因此向量集合轉換成矩陣的形式,如n×m的矩陣,n為向量的個數,m為向量的維度。

方法1

def f(mat):
    """

    :param mat: 矩陣n*m
    :return: n個向量間兩兩之間對應的長度,共n*(n-1)/2個
    """
    result = np.array([])
    for i in range(mat.shape[0]-1):
        result = np.concatenate((result,np.sqrt(np.sum((mat[i]-mat[i+1:])**2,axis=1))))
    return result

依次取集合中的每個向量,計算與其他向量組成的矩陣的距離

np.sqrt(np.sum((mat[i]-mat[i+1:])**2,axis=1))

測試用例

mat = np.array([[1,2,3],[2,3,4],[0,4,2],[5,3,2]])

輸出結果

不過仍存在for循環,所以還得進一步優化

方法2

def f(mat):
    """
    計算矩陣每個向量與其他向量的歐式距離
    :param mat: n*m的矩陣,表示n個m維向量
    :return: n*n的返回結果,對應位置值為第i與第j個向量的歐式距離(去除重復應返回n*(n-1)/2個結果)
    """
    mat1 = np.expand_dims(mat, 1)
    mat2 = np.expand_dims(mat, 0)
    return np.sqrt(np.sum((mat1 - mat2) ** 2, axis=-1))

完全通過矩陣運算,速度會更快.

原理通過矩陣運算自動復制維度元素,當然也可以通過如下手動指定復制元素,結果相同。

可以推導下,就是在計算向量間對應元素相減的平方和,在開根號

mat1 = np.expand_dims(mat, 1).repeat(mat.shape[0],1)
mat2 = np.expand_dims(mat, 0).repeat(mat.shape[0],0)

測試用例

 mat = np.array([[1,2,3],[2,3,4],[0,4,2],[5,3,2]])

輸出結果


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM