简体   繁体   中英

Tensorflow - Euclidean Distance of Points in Matrix

I have an*m tensor that basically represents m points in n dimensional euclidean space. I wanted calculate the pairwise euclidean distance between each consecutive point.

That is, if my column vectors are the points a, b, c, etc., I want to calculate euc(a, b), euc(b, c), etc.

The result would be an m-1 length 1D-tensor with each pairwise euclidean distance.

Anyone know who this can be performed in TensorFlow?

Okay, I figured out something that works. Let me know if anyone has a better solution, though.

def pairwise_euclidean_distance (input_layer):
    original_size = input_layer.get_shape().as_list()

    subtrahend = tf.pad(input_layer, [[0, 0], [1, 0], [0, 0], [0, 0]])
    subtrahend = tf.slice(subtrahend, [0, 0, 0, 0], original_size)

    distance = tf.sqrt(tf.reduce_sum(tf.square(tf.subtract(input_layer, subtrahend)), axis=[2,3]))

    return distance

You can simplify the distance calculation like below. Because L2 norm of the vector between two points is the distance between the two.

def distance(point1, point2):
    l2_norm = tf.norm(point1-point2, ord='euclidean')
    return l2_norm

Define a function to calculate distances

calc_distance = lambda f, g: tf.norm(fg, axis=1, ord='euclidean')

Pass your n*m vector to the function, example:

P = tf.constant([[1, 2], [3, 4], [2, 1], [0, 2], [2, 3]], dtype=tf.float32)

distances = calc_distance(P[:-1:], P[1::])

print(distances)

<tf.Tensor: shape=(4,), dtype=float32, numpy=array([2.8284273, 3.1622777, 2.2360682, 2.2360682], dtype=float32)>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM