代码之家  ›  专栏  ›  技术社区  ›  thebeancounter

python tensorflow l2轴上损失

  •  0
  • thebeancounter  · 技术社区  · 7 年前

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

    例如

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

    谢谢

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

    2 回复  |  直到 7 年前
        1
  •  1
  •   fuglede    7 年前

    This answer 演示如何计算向量集合之间的平方差的对和。通过简单地用平方根进行后置合成,您就可以得到所需的成对距离:

    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.        ]]
    
        2
  •  0
  •   afagarap jezrael    7 年前

    可以根据欧几里得距离(l2损失)公式编写张量流运算。

    enter image description here

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