gpt4 book ai didi

python-3.x - Tensorflow中的欧氏距离,转换矩阵

转载 作者:行者123 更新时间:2023-12-02 03:01:41 24 4
gpt4 key购买 nike

我有一个knn分类项目,需要用tensorflow计算欧几里得距离,以便比较。

没有tensorflow的原代码是这样的:

def euclidean_distance(self,x1, x2):
distance = 0.0
for i in range(len(x1)):
distance += pow( x1[i] - x2[i], 2)
print(distance)
return math.sqrt(distance)

在 tensorflow 中是这样的:

distance = 0.0
for i in range(len(x1)):
distance = tf.negative(tf.sqrt(tf.reduce_sum(tf.square(tf.subtract(x1, x2)))))
return distance

这样对吗?由于该代码距离变成了张量,我需要一种将该张量转换为普通矩阵的方法。

感谢任何帮助,谢谢!

最佳答案

为了得到 nd array(matrix) 你需要像 blow 一样运行图形

session=tf.Session()
nd_distance=session.run(distance)

您必须将代码更改为

......
......
distance = tf.sqrt(tf.reduce_sum(tf.square(tf.subtract(x1, x2))))
nd_distance=session.run(distance)
print (nd_distance)
return nd_distance

我不认为需要 tf.negative 函数和 for loop

关于python-3.x - Tensorflow中的欧氏距离,转换矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45454354/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com