Tesorflow中計算Pairwise的Euclidean Distance

問題場景

已知兩組向量為:
\begin{array}{l}{X=\left\{\mathbf{x}_{1}, \mathbf{x}_{2}, \cdots, \mathbf{x}_{n}\right\}} \\ {Y=\left\{\mathbf{y}_{1}, \mathbf{y}_{2}, \cdots, \mathbf{y}_{m}\right\}}\end{array}
現(xiàn)在要計算X中每一個向量和Y中每一個向量的歐式距離。

解決思路一

X中向量使用tf.tile復制m次,把Y中向量復制n次。
\left[\begin{array}{cccc}{\mathbf{x}_{1}} & {\mathbf{x}_{1}} & {\cdots} & {\mathbf{x}_{1}} \\ {\mathbf{x}_{2}} & {\mathbf{x}_{2}} & {\cdots} & {\mathbf{x}_{2}} \\ {\vdots} & {\vdots} & {\vdots} & {\vdots} \\ {\mathbf{x}_{n}} & {\mathbf{x}_{n}} & {\cdots} & {\mathbf{x}_{n}}\end{array}\right] - \left[\begin{array}{cccc}{\mathbf{y}_{1}} & {\mathbf{y}_{2}} & {\cdots} & {\mathbf{y}_{m}} \\ {\mathbf{y}_{1}} & {\mathbf{y}_{2}} & {\cdots} & {\mathbf{y}_{m}} \\ {\vdots} & {\vdots} & {\vdots} & {\vdots} \\ {\mathbf{y}_{1}} & {\mathbf{y}_{2}} & {\cdots} & {\mathbf{y}_{m}}\end{array}\right]
然后按照向量距離公式\|\mathbf{x}-\mathbf{y}\|就可以得到n\times m的距離矩陣了。
缺點:

  1. 計算量大,復雜度大概是n\times m \times k,k為向量維度。
  2. tf.tile后要保存兩個很大的矩陣,占資源

解決思路二

利用完全平方公式,對于距離矩陣D中的D_{ij}元素(表示X中第i個向量和Y中的第j個向量之間的歐式距離):
\begin{aligned} D_{i j} &=\left(\mathbf{x}_{i}-\mathbf{y}_{j}\right)^{2} \\ &=\mathbf{x}_{i}^{2}-2 \mathbf{x}_{i} \mathbf{y}_{j}+\mathbf{y}_{j}^{2} \end{aligned}
其中的\mathbf{x}_{i} \mathbf{y}_{j}矩陣可以由兩個向量相乘快速計算。

import tensorflow as tf


def euclidean_dist(x, y):
    square_x = tf.reduce_sum(tf.square(x), axis=-1)
    square_y = tf.reduce_sum(tf.square(y), axis=-1)
    # expand dims for broadcasting
    ex = tf.expand_dims(square_x, axis=-1)
    ey = tf.expand_dims(square_y, axis=-2)
    # XY matrix
    xy = tf.einsum('bij,bkj->bik', x, y)
    # 如果沒有batch_size這個維度,可以寫成:
    # xy = tf.einsum('ij,kj->ik', x, y)
    # compute distance,浮點防溢出
    dist = tf.sqrt(ex - 2 * xy + ey + 1e-10)
    return dist

計算dist的時候加上了1e-10,因為\sqrt{x}x=0處導數(shù)不存在,需要做平滑。

優(yōu)點:

  1. XY中向量的平方不用重復計算,加速運算。
  2. xy矩陣是標量矩陣,節(jié)約顯存資源,這個有時很重要!
最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容