如何在 TensorFlow 中累积应用函数列表

How to apply list of functions cumulatively in TensorFlow

假设我有输入 x 和函数列表 [f, g, h, j] 是否有 TensorFlow 函数来获取这些的组合?即 [f(x), g(f(x)), h(g(f(x))), j(h(g(f(x))))].

Python 可以将可调用项(即函数)分配给变量。如果您使用此功能,您可以轻松地遍历可调用列表以获取组合:

def compose(x):
    # For more clarity, let's actually assign callables to variables
    f = tf.nn.leaky_relu
    g = lambda x: -x
    h = tf.nn.sigmoid
    j = tf.reduce_mean

    callables = [f, g, h, j]
    results = []
    for func in callables:
        x = func(x)
        results.append(x)
    return results

这种情况的并行形式,如 tf.map_fn,在这种情况下是不可能的,因为一个元素依赖于先前的元素;流程本质上是顺序的。