python Tensorflow L2在轴上的损失 [英] python tensorflow l2 loss over axis
问题描述
我正在使用带有tensorflow的python 3 我有一个矩阵,每一行都是一个向量,我想得到一个距离矩阵-这是使用 l2范数丢失,矩阵中的每个值都是两个向量之间的距离
I am using python 3 with tensorflow I have a matrix, each row is a vector, I want to get a distance matrix - that is computer using the l2 norm loss, each value in the matrix will be a distance between two vectors
例如
Dij = l2_distance(M(i,:), Mj(j,:))
谢谢
这不是 的重复,另一个问题是关于计算矩阵的每一行,我需要每一行与其他每一行之间的成对范数距离.
edit: this is not a duplicate of that other question is about computing the norm for the each row of a matrix, I need the pairwise norm distance between each row to every other row.
推荐答案
此答案显示了如何计算该对-向量集合之间平方差的明智和.通过简单地用平方根进行后组合,就可以达到所需的成对距离:
This answer shows how to compute the pair-wise sum of squared differences between a collection of vectors. By simply post-composing with the square root, you arrive at your desired pair-wise distances:
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. ]]
这篇关于python Tensorflow L2在轴上的损失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!