我有一个knn分类项目,该项目需要使用张量流来计算欧式距离以进行比较。
没有张量流的原始代码是这样的:
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),您需要像打击一样运行图
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/