评估 TensorFlow 中多维输入之间的成对欧氏距离
Evaluating the pairwise euclidean distance between multi-dimensional inputs in TensorFlow
我有两个形状为 m X d 和 n X d 的二维张量。什么是优化的(即没有 for 循环)或张量流评估这两个张量之间的成对欧氏距离的方法,以便我得到形状为 m X n 的输出张量。我需要它来创建高斯核的平方项,最终得到大小为 m x n 的协方差矩阵。
等效的未优化 numpy 代码如下所示
difference_squared = np.zeros((x.shape[0], x_.shape[0]))
for row_iterator in range(difference_squared.shape[0]):
for column_iterator in range(difference_squared.shape[1]):
difference_squared[row_iterator, column_iterator] = np.sum(np.power(x[row_iterator]-x_[column_iterator], 2))
我在 here 的帮助下找到了答案。假设这两个张量是 x1 和 x2,它们的维度是 m X d 和 n X d,它们的成对欧几里德距离由
给出
tile_1 = tf.tile(tf.expand_dims(x1, 0), [n, 1, 1])
tile_2 = tf.tile(tf.expand_dims(x2, 1), [1, m, 1])
pairwise_euclidean_distance = tf.reduce_sum(tf.square(tf.subtract(tile_1, tile_2)), 2))
我有两个形状为 m X d 和 n X d 的二维张量。什么是优化的(即没有 for 循环)或张量流评估这两个张量之间的成对欧氏距离的方法,以便我得到形状为 m X n 的输出张量。我需要它来创建高斯核的平方项,最终得到大小为 m x n 的协方差矩阵。
等效的未优化 numpy 代码如下所示
difference_squared = np.zeros((x.shape[0], x_.shape[0]))
for row_iterator in range(difference_squared.shape[0]):
for column_iterator in range(difference_squared.shape[1]):
difference_squared[row_iterator, column_iterator] = np.sum(np.power(x[row_iterator]-x_[column_iterator], 2))
我在 here 的帮助下找到了答案。假设这两个张量是 x1 和 x2,它们的维度是 m X d 和 n X d,它们的成对欧几里德距离由
给出tile_1 = tf.tile(tf.expand_dims(x1, 0), [n, 1, 1])
tile_2 = tf.tile(tf.expand_dims(x2, 1), [1, m, 1])
pairwise_euclidean_distance = tf.reduce_sum(tf.square(tf.subtract(tile_1, tile_2)), 2))