张量流中两个同阶张量之间的广播

Broadcasting between two same-rank tensors in tensorflow

我有两个张量 xs,形状为:

> x.shape
TensorShape([Dimension(None), Dimension(3), Dimension(5), Dimension(5)])
> s.shape
TensorShape([Dimension(None), Dimension(12), Dimension(5), Dimension(5)])

我想通过维度1广播xs之间的点积如下:

> x_s.shape
TensorShape([Dimension(None), Dimension(4), Dimension(5), Dimension(5)])

哪里

x_s[i, 0, k, l] = sum([x[i, j, k, l] * s[i, j, k, l] for j in range (3)])
x_s[i, 1, k, l] = sum([x[i, j-3, k, l] * s[i, j, k, l] for j in range (3, 6)])
x_s[i, 2, k, l] = sum([x[i, j-6, k, l] * s[i, j, k, l] for j in range (6, 9)])
x_s[i, 3, k, l] = sum([x[i, j-9, k, l] * s[i, j, k, l] for j in range (9, 12)])

我有这个实现:

s_t = tf.transpose(s, [0, 2, 3, 1]) # [None, 5, 5, 12]
x_t = tf.transpose(x, [0, 2, 3, 1]) # [None, 5, 5, 3]
x_t = tf.tile(x_t, [1, 1, 1, 4]) # [None, 5, 5, 12]

x_s = x_t * s_t # [None, 5, 5, 12]
x_s = tf.reshape(x_s, [tf.shape(x_s)[0], 5, 5, 4, 3]) # [None, 5, 5, 4, 3]
x_s = tf.reduce_sum(x_s, axis=-1) # [None, 5, 5, 4]
x_s = tf.transpose(x_s, [0, 3, 1, 2]) # [None, 4, 5, 5]

我知道由于 tile 这在内存中效率不高。此外,reshapetransposeelement-wisereduce_sum 操作可能会损害较大张量的性能。有没有其他方法可以使它更清洁?

只是一些建议,可能不会比你的快。先把stf.split分成四个张量,然后用tf.tensordot得到最后的结果,像这样

splits = tf.split(s, [3] * 4, axis=1)
splits = map(lambda split: tf.tensordot(split, x, axes=[[1], [1]]), splits)
x_s = tf.stack(splits, axis=1)

你有什么证据表明 reshape 很贵吗?以下使用重塑和维度广播:

x_s = tf.reduce_sum(tf.reshape(s, (-1, 4, 3, 5, 5)) *
                    tf.expand_dims(x, axis=1), axis=2)