I have two tensors of sequences of size [batch_size, seq_length, 2]. I want to compute mean Euclidean distance between tensors. What is the elegant way to do this?
In Mathematics, the Euclidean distance is defined as the distance between two points. In other words, the Euclidean distance between two points in the Euclidean space is defined as the length of the line segment between two points.
How to Calculate Euclidean Distance in Python? The formula to calculate the distance between two points (x1 1 , y1 1 ) and (x2 2 , y2 2 ) is d = √[(x2 – x1)2 + (y2 – y1)2].
The L2 norm calculates the distance of the vector coordinate from the origin of the vector space. As such, it is also known as the Euclidean norm as it is calculated as the Euclidean distance from the origin. The result is a positive distance value.
Euclidean distance is calculated as the square root of the sum of the squared differences between the two vectors. If the distance calculation is to be performed thousands or millions of times, it is common to remove the square root operation in an effort to speed up the calculation.
Given the two tensors A
& B
each with shape [batch_size, seq_length, 2]
, you can compute the Euclidean distance (L2 norm) using tf.norm
:
l2_norm = tf.norm(A-B, ord='euclidean')
You can also use tf.math.reduce_euclidean_norm:
tf.math.reduce_euclidean_norm(
input_tensor, axis=None, keepdims=False, name=None
)
see the documentation here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With