简体   繁体   English

Tensorflow - 矩阵中点的欧几里德距离

[英]Tensorflow - Euclidean Distance of Points in Matrix

I have an*m tensor that basically represents m points in n dimensional euclidean space.我有一个*m 张量,它基本上表示 n 维欧几里得空间中的 m 个点。 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.也就是说,如果我的列向量是点 a、b、c 等,我想计算 euc(a, b)、euc(b, c) 等。

The result would be an m-1 length 1D-tensor with each pairwise euclidean distance.结果将是具有每个成对欧几里得距离的 m-1 长度的一维张量。

Anyone know who this can be performed in TensorFlow?有谁知道这可以在 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. 因为两点之间矢量的L2范数是两者之间的距离。

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:将您的 n*m 向量传递给函数,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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