【问题标题】:How to calculate the euclidean distance between a 2-D tensor and a 3-D tensor?如何计算 2-D 张量和 3-D 张量之间的欧几里得距离?
【发布时间】:2019-03-19 10:52:39
【问题描述】:

我有一个形状为 (?, L) 的二维张量 A,它指的是通过神经网络获得的特征(其中 '?' 是批量大小)和一个形状为 (N, K, L 的 3-D 张量 B )。显然,B中有N个形状为(K,L)的数组,称为C 在这里。

现在,我如何计算 mean euclidean distance(平均一行 A 和每一行 C 的距离) A和每个C的每一行没有AC中每一行的迭代,最后返回一个向量形状为 (?, N) ?

例如,当A的形状为(1,L)时,可以得到如下结果:

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 = ([[1, 2, 3], [4, 5, 6]]) 时(这只是 A 的一个例子,形状为 ( 2, 3)),我怎样才能得到上面问题的结果,形状为 [2, 2] ?

【问题讨论】:

  • 我们需要一些数据和代码来重现您的问题。此外,您实现目标的尝试也丢失了。
  • 我已经把问题说清楚了,举个例子,你能帮我解决一下吗?

标签: python tensorflow


【解决方案1】:
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])
    newA = tf.expand_dims(A, 0)
    dist = tf.reduce_mean(tf.norm(B - newA, 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]]]}))

【讨论】:

  • 我试过了,但效果不好。假设当batch_size = 2时a = ([1, 2, 3], [4, 5, 6])的形状为(2, 3),而b保持上述值。假设我应该得到形状为 (2, 2) 的结果,其中第一行等于 [7.7942286 18.186533 ] 是 [1, 2, 3] 与表示为 a 的 3-D 张量之间的距离,并且第二行等于[2.598076 12.990381]是[4,5,6]和a之间的距离。但是上面的代码返回的结果是[5.196152 15.588457],形状为(1, 2),显然是不正确的。
【解决方案2】:

问题已解决如下:

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 ]]

【讨论】:

    猜你喜欢
    • 2019-06-06
    • 2021-09-14
    • 2020-09-10
    • 2018-10-04
    • 1970-01-01
    • 1970-01-01
    • 2020-06-18
    • 1970-01-01
    • 2017-03-12
    相关资源
    最近更新 更多