[英]python tensorflow l2 loss over axis
此答案顯示了如何計算向量集合之間的平方差的成對和。 通過簡單地用平方根進行后組合,您可以得出所需的成對距離:
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. ]]
您可以基於歐幾里得距離(L2損失)的公式編寫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)))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.