python矩阵的平方_NumPy之计算两个矩阵的成对平方欧氏距离
問題描述
設
(; 表示縱向連接) 和
, 計算矩陣
中每一個行向量和矩陣
中每一個行向量的平方歐氏距離 (pairwise squared Euclidean distance), 即計算:
(這是一個
矩陣).
這個計算在度量學習, 圖像檢索, 行人重識別等算法的性能評估中有著廣泛的應用.
公式轉化
在 NumPy 中直接利用上述原式來計算兩個矩陣的成對平方歐氏距離, 要顯式地使用二重循環, 而在 Python 中循環的效率是相當低下的. 如果想提高計算效率, 最好是利用 NumPy 的特性將原式轉化為數組/矩陣運算. 下面就嘗試進行這種轉化.
先將原式展開為:
下面逐項地化簡或轉化為數組/矩陣運算的形式:
式中,
表示按元素積 (element-wise product), 又稱為 Hadamard 積;
表示維的全1向量 (all-ones vector), 余者類推. 上式中
的作用是計算
每行元素的和, 返回一個列向量;
的作用類似于 NumPy 中的廣播機制, 在這里是將一個列向量擴展為一個矩陣, 矩陣的每一列都是相同的.
所以:
上述轉化式中出現了
(矩陣乘) , 矩陣乘在 NumPy 等很多庫中都有高效的實現, 對代碼的優化是有好處的.
特別地, 當
時, 原式等于
, 注意到第一項和第二項互為轉置. 當
且
(即
和
的每一個行向量的范數均為1時), 原式等于
,
是
全1矩陣.
代碼實現
sklearn 中已經包含了用 NumPy 實現的計算 "兩個矩陣的成對平方歐氏距離" 的函數 (sklearn.metrics.euclidean_distances
import numpy as np
def euclidean_distances(x, y, squared=True):
"""Compute pairwise (squared) Euclidean distances."""
assert isinstance(x, np.ndarray) and x.ndim == 2
assert isinstance(y, np.ndarray) and y.ndim == 2
assert x.shape[1] == y.shape[1]
x_square = np.sum(x*x, axis=1, keepdims=True)
if x is y:
y_square = x_square.T
else:
y_square = np.sum(y*y, axis=1, keepdims=True).T
distances = np.dot(x, y.T)
# use inplace operation to accelerate
distances *= -2
distances += x_square
distances += y_square
# result maybe less than 0 due to floating point rounding errors.
np.maximum(distances, 0, distances)
if x is y:
# Ensure that distances between vectors and themselves are set to 0.0.
# This may not be the case due to floating point rounding errors.
distances.flat[::distances.shape[0] + 1] = 0.0
if not squared:
np.sqrt(distances, distances)
return distances
如果想進一步加速, 可以將
x_square = np.sum(x*x, axis=1, keepdims=True)
替換為
x_square = np.expand_dims(np.einsum('ij,ij->i', x, x), axis=1)
以及將
y_square = np.sum(y*y, axis=1, keepdims=True).T
替換為
y_square = np.expand_dims(np.einsum('ij,ij->i', y, y), axis=0)
使用 np.einsum 的好處是不會產生一個和 x 或 y 同樣形狀的臨時數組 (x*x 或 y*y 會產生一個和 x 或 y 同樣形狀的臨時數組).
PyTorch 中也包含了計算 "兩個矩陣的成對平方歐氏距離" 的函數
另外上述的轉化公式也可以用在其他 Python 框架 (如 TensorFlow) 或其他語言中, 這里就不展開敘述了.
版權聲明
版權聲明:自由分享,保持署名-非商業用途-非衍生,知識共享3.0協議。
如果你對本文有疑問或建議,歡迎留言!轉載請保留版權聲明!
參考
總結
以上是生活随笔為你收集整理的python矩阵的平方_NumPy之计算两个矩阵的成对平方欧氏距离的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python权限不够无法写入_解决pyt
- 下一篇: python就是玩具_极客老爹的玩具DI