【发布时间】: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