评估TensorFlow中多维输入之间的成对欧氏距离

问题描述 投票:1回答:1

我有两个形状的二维张量,比如m X d和n X d。什么是优化的(即没有for循环)或评估这两个张量之间的成对欧氏距离的张量流方式,以便得到形状m X n的输出张量。我需要它来创建高斯核的平方项,最终得到一个大小为m x n的协方差矩阵.enter image description here

等效的未经优化的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))
tensorflow kernel covariance gaussian tensor
1个回答
1
投票

我在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))
© www.soinside.com 2019 - 2024. All rights reserved.