在 Tensorflow 中计算张量的线性组合

Compute a linear combination of tensors in Tensorflow

我正在尝试计算 Tensorflow 中相同维度的 n 张量的线性组合。标量系数是 Tensorflow Variables.

由于 tf.scalar_mul 没有概括为张量向量乘以标量向量,到目前为止我使用 tf.gather 并在 python for 循环中单独执行每个乘法,然后将结果列表转换为张量并在第零轴上对它们求和。像这样:

coefficients = tf.Variable(tf.constant(initial_value, shape=[n]))
components = []
for i in range(n):
    components.append(tf.scalar_mul(tf.gather(coefficients, i), tensors[i]))
combination = tf.reduce_sum(tf.convert_to_tensor(components), axis=0)

这工作正常,但根本不能很好地扩展。我的应用程序需要计算 n 线性组合,这意味着我有 n^2 收集和乘法运算。 n 的值越大,计算时间越短,程序的内存使用量大得不合理。

在 Tensorflow 中是否有一种更自然的方法来计算像这样的线性组合,它会更快、资源占用更少?

使用广播。假设 coefficients 有形状 (n,)tensors 形状 (n,...) 你可以简单地使用

coefficients[:, tf.newaxis, ...] * tensors

在这里,您需要重复 tf.newaxis 次,因为 tensors 除了大小 n 之外还有其他维度。所以例如如果 tensors 的形状为 (n, a, b) 你会使用 coefficients[:, tf.newaxis, tf.newaxis]

这会将系数变成与 tensors 维数相同的张量,但除第一个维外的所有维的大小都是 1,因此它们可以广播到形状tensors.

一些备选方案:

  • 首先将 coefficients 定义为具有正确维数的变量(在我看来有点难看)。
  • 如果您不喜欢索引语法,请使用 tf.reshapecoefficients 重塑为 (n, 1, ...)
  • 使用tf.transpose将尺寸n的尺寸移动到tensors。然后维度对齐广播而不需要添加维度 coefficients.

另请参阅 the numpy docs on broadcasting——它在 Tensorflow 中的工作方式基本相同。

有一个名为 TWIT 的新 PyPI 模块,张量加权插值传输,可以快速执行此操作。它是用 C 编写的核心操作。