python - 如何计算一个矩阵中向量之间的欧式距离?
问题描述
我想计算特征中向量的欧几里得距离,这是从网络得到的一个 tf.Tensor。
我尝试了以下方式,但失败并出现错误:
'Tensor' object is not iterable
所以我想通过矩阵来计算一个矩阵中的行之间的距离,而不需要对每一行进行迭代。
features, _ = mnist_net(images)
feature_matrix = np.zeros(shape=(FLAGS.batch_size,FLAGS.batch_size))
for i in range (FLAGS.batch_size):
for j in range (FLAGS.batch_size):
aa = tf.slice(features,[i,0],[1,50])
bb = tf.slice(features,[j,0],[1,50])
feature_matrix[i,j] = tf.sqrt(sum((aa-bb)**2))
解决方案
tf.norm
您可以使用/简单地实现这一点tf.linalg.norm
:
feature_matrix = tf.linalg.norm(features[:, tf.newaxis] - features, axis=-1)
例如:
import tensorflow as tf
with tf.Session() as sess:
features = tf.placeholder(tf.float32, [None, None])
feature_matrix = tf.linalg.norm(features[:, tf.newaxis] - features, axis=-1)
print(sess.run(feature_matrix, feed_dict={features: [[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9],
[10, 11, 12]]}))
输出:
[[ 0. 5.196152 10.392304 15.588457]
[ 5.196152 0. 5.196152 10.392304]
[10.392304 5.196152 0. 5.196152]
[15.588457 10.392304 5.196152 0. ]]
编辑:
如果不能使用tf.norm
,下面是等效的实现:
sqdiff = tf.squared_difference(features[:, tf.newaxis], features)
feature_matrix = tf.sqrt(tf.reduce_sum(sqdiff, axis=-1))
推荐阅读
- python - 不熟悉的 Python 语法(例如 obj1 =
( )(obj2)) - c# - 将 func 参数类型转换为对象类型
- powershell - 如何构建一个可以定期从 Internet 获取内容并使用 PowerShell 将其保存到每个新的 csv 文件的脚本?
- flutter - 为什么 Flutter App 在 Chrome 中打开而不是在模拟器上打开?
- python - 在 Python 中导入程序时,如何使某些变量无法访问?
- javascript - 如何在使用 iframe 创建的所见即所得编辑器中禁用内联 css 输入?
- php - 如何根据 url 隐藏 Wordpress 中的部分(页眉和页脚)?
- vue.js - VueJS - 如何在传递值其他选项值时显示输入文本以及选择的选项
- php - 为什么在调试过程中mysqli->$errno 被设置为0?
- flutter - Flutter 像whatsapp call 一样长时间显示通知