在TensorFlow中计算两个二进制张量间的成对欧氏距离
计算TensorFlow中二进制区域点的成对欧氏距离
嘿,看起来你已经搞定了最关键的一步——把二进制张量转换成坐标点了!接下来计算成对欧氏距离其实很简单,TensorFlow的广播机制就能帮你轻松实现,下面给你两种实用的方法:
方法一:手动计算(直观易懂)
我们可以利用TensorFlow的广播特性,把两个坐标数组扩展维度后做元素级运算,最后求和开根号得到欧氏距离:
import tensorflow as tf import numpy as np # 你的输入张量 input1 = tf.constant(np.array([[1,0,0], [0,1,0], [0,0,1]])) input2 = tf.constant(np.array([[0,1,0], [0,0,1], [0,1,0]])) # 转换为坐标点(你已经实现的部分) coord1 = tf.where(tf.cast(input1, tf.bool)) coord2 = tf.where(tf.cast(input2, tf.bool)) # 扩展维度:把coord1变成(N, 1, D),coord2变成(1, M, D),D是维度数(这里是2) coord1_expanded = tf.expand_dims(coord1, axis=1) coord2_expanded = tf.expand_dims(coord2, axis=0) # 计算每个点对的差值平方 squared_diff = tf.square(coord1_expanded - coord2_expanded) # 对坐标维度求和,再开根号得到欧氏距离 pairwise_distances = tf.sqrt(tf.reduce_sum(squared_diff, axis=-1)) # 查看结果 print(pairwise_distances.numpy())
运行这段代码后,你会得到一个(3, 3)的矩阵(你的input2实际包含3个点哦~),每个元素对应coord1中第i个点和coord2中第j个点的欧氏距离。
方法二:用tf.norm简化代码
如果你觉得手动写平方求和开根号太繁琐,可以直接用tf.norm函数,它默认计算L2范数(也就是欧氏距离),代码更紧凑:
# 沿用上面的coord1和coord2 coord1_expanded = tf.expand_dims(coord1, axis=1) coord2_expanded = tf.expand_dims(coord2, axis=0) # 计算差值后直接求L2范数 pairwise_distances = tf.norm(coord1_expanded - coord2_expanded, axis=-1)
这个结果和方法一完全一致,只是代码更简洁。
额外提示
- 高维场景适配:不管是2D区域、3D体还是更高维的超体,这个方法都通用——
tf.where会自动返回对应维度的坐标,reduce_sum或tf.norm都会沿着坐标维度(最后一维)计算,无需修改代码。 - 数值稳定性:如果担心开根号带来的数值问题,或者只需要平方距离(很多机器学习任务中够用),可以去掉
tf.sqrt,直接使用tf.reduce_sum(squared_diff, axis=-1),这样计算更快更稳定。
内容的提问来源于stack exchange,提问作者Miguel Monteiro
相关产品推荐
相关产品推荐

