如何计算向量和三维张量之间的欧氏距离?

2024-04-26 06:22:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个张量a,大小为(1,L),和一个三维张量B,大小为(NKL)。显然,在B中存在大小为(KL)的N阵列,这里称之为C。你知道吗

现在,我如何计算AC之间的平均欧氏距离(平均AC的每一行的距离),而不迭代C中的每一行,最后返回一个大小为(1,N)的向量?你知道吗


Tags: 距离向量
1条回答
网友
1楼 · 发布于 2024-04-26 06:22:45

您可以使用^{}^{}来实现这一点:

import tensorflow as tf

with tf.Graph().as_default(), tf.Session() as sess:
    a = tf.placeholder(tf.float32, [1, None])
    b = tf.placeholder(tf.float32, [None, None, None])
    dist = tf.reduce_mean(tf.norm(b - a, axis=2), axis=1)
    print(sess.run(dist, feed_dict={a: [[1, 2, 3]],
                                    b: [[[ 4,  5,  6], [ 7,  8,  9]],
                                        [[10, 11, 12], [13, 14, 15]]]}))
    # [ 7.7942286 18.186533 ]

编辑:在a中有几个向量的情况下的变体:

import tensorflow as tf

with tf.Graph().as_default(), tf.Session() as sess:
    a = tf.placeholder(tf.float32, [None, None])
    b = tf.placeholder(tf.float32, [None, None, None])
    a_exp = tf.expand_dims(tf.expand_dims(a, 1), 1)
    dist = tf.reduce_mean(tf.norm(b - a_exp, axis=3), axis=2)
    print(sess.run(dist, feed_dict={a: [[1, 2, 3], [4, 5, 6]],
                                    b: [[[ 4,  5,  6], [ 7,  8,  9]],
                                        [[10, 11, 12], [13, 14, 15]]]}))
    # [[ 7.7942286 18.186533 ]
    #  [ 2.598076  12.990381 ]]

相关问题 更多 >