【发布时间】:2018-01-15 05:22:57
【问题描述】:
我想计算一组 Tensor 之间的成对距离(例如 4 张量)。每个矩阵都是 2D 张量。我不知道如何以矢量化格式执行此操作。我写了以下 sudo-code 来确定我需要什么:
E.shape => [4,30,30]
sum = 0
for i in range(4):
for j in range(4):
res = calculate_distance(E[i],E[j]) # E[i] is one the 30*30 Tensor
sum = sum + reduce_sum(res)
这是我最后一次尝试:
x_ = tf.expand_dims(E, 0)
y_ = tf.expand_dims(E, 1)
s = x_ - y_
P = tf.reduce_sum(tf.norm(s, axis=[-2, -1]))
此代码有效但我不知道如何批量执行此操作。例如,当E.shape 是[BATCH_SIZE * 4 * 30 * 30] 时,我的代码不起作用并且会发生内存不足。我怎样才能有效地做到这一点?
编辑:一天后,我找到了解决方案。它并不完美但有效:
res = tf.map_fn(lambda x: tf.map_fn(lambda y: tf.map_fn(lambda z: tf.norm(z - x), x), x), E)
res = tf.reduce_mean(tf.square(res))
【问题讨论】:
-
定义您要计算的确切公式以及矩阵形状。是这个 - math.stackexchange.com/q/507742/238620 吗?
-
@Maxim 是的。我想计算一组矩阵之间的成对距离,但我不知道该怎么做。
-
据我所知,它是在 2D 矩阵之间定义的,而不是 3D。
-
@Maxim 感谢您的回复,编辑我的问题 :)
标签: tensorflow machine-learning keras matrix-multiplication