python tensorflow l2 轴损失

python tensorflow l2 loss over axis

我正在使用 python 3 和 tensorflow 我有一个矩阵,每一行都是一个向量,我想得到一个距离矩阵 - 即计算机使用 l2 norm loss,矩阵中的每个值都是两个向量之间的距离

例如

Dij = l2_distance(M(i,:), Mj(j,:)) 

谢谢

编辑: 这不是重复 另一个问题是关于计算矩阵每一行的范数,我需要每一行与其他每一行之间的成对范数距离。

可以根据欧氏距离(L2 loss)的公式写一个TensorFlow运算

distance = tf.sqrt(tf.reduce_sum(tf.square(tf.subtract(x1, x2))))

样本为

import tensorflow as tf

x1 = tf.constant([1, 2, 3], dtype=tf.float32)
x2 = tf.constant([4, 5, 6], dtype=tf.float32)

distance = tf.sqrt(tf.reduce_sum(tf.square(tf.subtract(x1, x2))))

with tf.Session() as sess:
  print(sess.run(distance))

正如@fuglede 所指出的,如果你想输出成对的距离,那么我们可以使用

tf.sqrt(tf.square(tf.subtract(x1, x2)))

展示了如何计算向量集合之间的成对差平方和。通过简单地 post - 与平方根组合,您可以得到所需的成对距离:

M = tf.constant([[0, 0], [2, 2], [5, 5]], dtype=tf.float64)
r = tf.reduce_sum(M*M, 1)
r = tf.reshape(r, [-1, 1])
D2 = r - 2*tf.matmul(M, tf.transpose(M)) + tf.transpose(r)
D = tf.sqrt(D2)

with tf.Session() as sess:
    print(sess.run(D))

# [[0.         2.82842712 7.07106781]
#  [2.82842712 0.         4.24264069]
#  [7.07106781 4.24264069 0.        ]]