【问题标题】:Is there an easy way to compute Euclidean distance matrix in TensorFlow?有没有一种简单的方法可以在 TensorFlow 中计算欧几里得距离矩阵?
【发布时间】:2020-12-16 14:38:34
【问题描述】:

在给定 Gram 矩阵或坐标的情况下,是否有一种有效的方法可以在 TensorFlow 中计算欧几里得距离矩阵?

欧几里得距离矩阵是一个 n×n 矩阵,其元素由每对点 (x,y,z) 之间的平方距离给出。 Gram矩阵就是内积矩阵。因此,如果 X 是一个 3×n 矩阵,其列是点,则 Gram 矩阵由 X^T@X 给出。有一个简单的公式可以将 Gram 矩阵转换为距离平方矩阵。

换句话说,有没有一种简单的方法可以在 TensorFlow(特别是 v1)中编写以下 numpy/scipy 函数?如果是这样,哪个效率更高?

# Compute Euclidean distance matrix from Gram matrix
def euclidean_dist_from_gram(gram):
    temp = np.tile(np.diag(gram), (nodes,1))
    return temp + temp.T - 2*gram
# Compute Euclidean distance matrix from coordinates
def euclidean_dist_from_pts(xyz):
    return spt.distance.squareform(spt.distance.pdist(xyz.T, 'sqeuclidean'))

编辑:通过首先导入以下依赖项并生成随机数据,可以在 numpy 和 scipy 中运行上述两个函数:

import scipy.spatial as spt
xyz = np.random.uniform(-20, 20, (3,500))
gram = xyz.T@xyz

【问题讨论】:

  • 您能否使用生成的数据为这两种情况添加示例?
  • 添加了我认为你想要的!

标签: python numpy tensorflow scipy


【解决方案1】:

想通了,所以我想我会发布我自己问题的答案。从 Gram 矩阵计算欧几里得距离矩阵是最简单的,所以这里是 TensorFlow 实现(假设 3 x n 坐标矩阵 xyz)。我没有意识到的是我必须使用 tf.expand_dims 才能使用 tf.tile,然后它匹配 numpy 实现。

gram = tf.linalg.matmul(tf.transpose(xyz), xyz)
g = tf.tile(tf.expand_dims(tf.linalg.diag_part(gram), 0), tf.constant([n,1]))
euclidean_dist = g + tf.transpose(g) - 2*gram

【讨论】:

    猜你喜欢
    • 2020-06-16
    • 1970-01-01
    • 2014-05-08
    • 2012-06-27
    • 2016-08-02
    • 2017-03-21
    • 2014-11-18
    • 2015-01-13
    相关资源
    最近更新 更多