首页 文章

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

提问于
浏览
1

我有两个形状的二维张量,比如m X d和n X d . 什么是优化的(即没有for循环)或评估这两个张量之间的成对欧氏距离的张量流方式,以便得到形状m X n的输出张量 . 我需要它来创建高斯核的平方项,以最终具有大小为m×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))

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))
    

相关问题