一、计算原理
假设有两个维向量和,其中,。那么根据欧氏距离计算公式,它们之间的欧氏距离为
二、利用Python3直接计算
import math
# calculating euclidean distance by formulation
# vector1 and vector2 are both 1d tensor (1d tensor = vector)
def euclidean_distance(vector1, vector2, dim):
s = 0
for i in range(dim):
s = s + (vector1[i] - vector2[i]) ** 2
return math.sqrt(s)
三、调用TensorFlow2.x函数计算
import tensorflow as tf
# calculating euclidean distance by tensorflow2.x
# vector1 and vector2 are both 1d tensor (1d tensor = vector)
def euclidean_distance_by_tf(vector1, vector2):
return tf.sqrt(tf.reduce_sum(tf.square(vector1 - vector2)))
代码解释(个人的理解):第一步:vector1 - vector2,得到一个新的临时向量temp_vector1;第二步:对temp_vector1的每个元素求平方,得到一个新的临时向量temp_vector2;第三步:对temp_vector2的每个元素求和,得到一个标量s;第四步:对s开方。最终求得两个向量之间的欧氏距离。所以,上述代码与下面的代码等价:
import tensorflow as tf
# calculating euclidean distance by tensorflow2.x
# vector1 and vector2 are both 1d tensor (1d tensor = vector)
def euclidean_distance_by_tf(vector1, vector2):
temp_vector1 = vector1 - vector2
temp_vector2 = tf.square(temp_vector1)
s = tf.reduce_sum(temp_vector2)
return tf.sqrt(s)
在你搜索到的有关博客中,有可能是带tf.Session()的,但tf.Session()实际上是TensorFlow1.x的内容,那么在TensorFlow2.x版本中是已经被完全抛弃。所以在使用TensorFlow2.x时,如果你是一位TensorFlow初学者,那么强烈建议不要使用像下面一样的代码:
with tf.Session() as sess:
#TODO
四、参考
五、附录
完整代码
import math
import tensorflow as tf
# test case for calculating euclidean distance of two vectors by tensorflow
def tc():
# create vectors
zero = tf.constant([0, 0, 0], tf.float32)
v1 = tf.constant([1, 0, 2], tf.float32)
v2 = tf.constant([99, 1000, -200], tf.float32)
print(zero)
print(v1)
print(v2)
# calculating euclidean distance by tensorflow
print(euclidean_distance_by_tf(v1, zero))
print(euclidean_distance_by_tf(v2, zero))
print(euclidean_distance_by_tf(v1, v2))
print(euclidean_distance_by_tf(v2, v1))
# calculating euclidean distance by formulation
print(euclidean_distance(v1, zero, 3))
print(euclidean_distance(v2, zero, 3))
print(euclidean_distance(v1, v2, 3))
print(euclidean_distance(v2, v1, 3))
# calculating euclidean distance by tensorflow
def euclidean_distance_by_tf(vector1, vector2):
return tf.sqrt(tf.reduce_sum(tf.square(vector1 - vector2)))
# calculating euclidean distance by tensorflow
def euclidean_distance_by_tf1(vector1, vector2):
temp_vector1 = vector1 - vector2
temp_vector2 = tf.square(temp_vector1)
s = tf.reduce_sum(temp_vector2)
return tf.sqrt(s)
# calculating euclidean distance by formulation
def euclidean_distance(vector1, vector2, dim):
s = 0
for i in range(dim):
s = s + (vector1[i] - vector2[i]) ** 2
return math.sqrt(s)
# enter of program
if __name__ == '__main__':
tc()
输出
tf.Tensor([0. 0. 0.], shape=(3,), dtype=float32)
tf.Tensor([1. 0. 2.], shape=(3,), dtype=float32)
tf.Tensor([ 99. 1000. -200.], shape=(3,), dtype=float32)
tf.Tensor(2.236068, shape=(), dtype=float32)
tf.Tensor(1024.598, shape=(), dtype=float32)
tf.Tensor(1024.8942, shape=(), dtype=float32)
tf.Tensor(1024.8942, shape=(), dtype=float32)
2.23606797749979
1024.598030937011
1024.8941408750466
1024.8941408750466