我想在Tensorflow中计算一批特征的成对平方距离。我有一个简单的实现,通过平铺原始张量来使用+和*操作:
def pairwise_l2_norm2(x, y, scope=None):
with tf.op_scope([x, y], scope, 'pairwise_l2_norm2'):
size_x = tf.shape(x)[0]
size_y = tf.shape(y)[0]
xx = tf.expand_dims(x, -1)
xx = tf.tile(xx, tf.pack([1, 1, size_y]))
yy = tf.expand_dims(y, -1)
yy = tf.tile(yy, tf.pack([1, 1, size_x]))
yy = tf.transpose(yy, perm=[2, 1, 0])
diff = tf.sub(xx, yy)
square_diff = tf.square(diff)
square_dist = tf.reduce_sum(square_diff, 1)
return square_dist
此函数将大小为(m,d)和(n,d)的两个矩阵作为输入,并计算每个行向量之间的平方距离。输出是大小为(m,n)的矩阵,元素为'd_ij = dist(x_i,y_j)'。
问题是我有很多批处理,并且高暗度特征'm,n,d'复制张量会占用大量内存。我正在寻找另一种方法来实现此目的,而不会增加内存使用量,仅存储最终的距离张量。有点像是双循环原始张量。
您可以使用一些线性代数将其转换为矩阵运算。请注意,你所需要的矩阵D
,其中a[i]
是i
你原来的矩阵的行和第
D[i,j] = (a[i]-a[j])(a[i]-a[j])'
您可以将其重写为
D[i,j] = r[i] - 2 a[i]a[j]' + r[j]
哪里r[i]
是i
原始矩阵的第th行的平方范数。
在支持标准广播规则的系统中,您可以将其r
视为列向量,并写D
为
D = r - 2 A A' + r'
在TensorFlow中,您可以将其写为
A = tf.constant([[1, 1], [2, 2], [3, 3]])
r = tf.reduce_sum(A*A, 1)
# turn r into column vector
r = tf.reshape(r, [-1, 1])
D = r - 2*tf.matmul(A, tf.transpose(A)) + tf.transpose(r)
sess = tf.Session()
sess.run(D)
结果
array([[0, 2, 8],
[2, 0, 2],
[8, 2, 0]], dtype=int32)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句