了解Tensorflow中的while循环

Joh*_* P. 9 python optimization while-loop tensorflow

我正在使用TensorflowPython API.我试图在不使用Python循环的情况下实现下面给出的Rosenbrock函数:

Rosenbrock功能

我目前的实施如下:

def rosenbrock(data_tensor):
    columns = tf.unstack(data_tensor)

    summation = 0
    for i in range(1, len(columns) - 1):
        first_term = tf.square(tf.subtract(columns[i + 1], tf.square(columns[i])))
        second_term = tf.square(tf.subtract(columns[i], 1.0))
        summation += tf.add(tf.multiply(100.0, first_term), second_term)

    return summation
Run Code Online (Sandbox Code Playgroud)

我试过在一个实现总结tf.while_loop(); 但是,我发现在使用一个与数据保持独立的索引整数时,API有点不直观.文档中给出的示例使用数据作为索引(反之亦然):

i = tf.constant(0)
c = lambda i: tf.less(i, 10)
b = lambda i: tf.add(i, 1)
r = tf.while_loop(c, b, [i])
Run Code Online (Sandbox Code Playgroud)

Joh*_* P. 13

这可以使用文档中的第二个示例使用tf.while_loop()标准元组来实现.

def rosenbrock(data_tensor):
    columns = tf.unstack(data_tensor)

    # Track both the loop index and summation in a tuple in the form (index, summation)
    index_summation = (tf.constant(1), tf.constant(0.0))

    # The loop condition, note the loop condition is 'i < n-1'
    def condition(index, summation):
        return tf.less(index, tf.subtract(tf.shape(columns)[0], 1))

    # The loop body, this will return a result tuple in the same form (index, summation)
    def body(index, summation):
        x_i = tf.gather(columns, index)
        x_ip1 = tf.gather(columns, tf.add(index, 1))

        first_term = tf.square(tf.subtract(x_ip1, tf.square(x_i)))
        second_term = tf.square(tf.subtract(x_i, 1.0))
        summand = tf.add(tf.multiply(100.0, first_term), second_term)

        return tf.add(index, 1), tf.add(summation, summand)

    # We do not care about the index value here, return only the summation
    return tf.while_loop(condition, body, index_summation)[1]
Run Code Online (Sandbox Code Playgroud)

值得注意的是,索引增量应该出现在循环体中,类似于标准的while循环.在给出的解决方案中,它是body()函数返回的元组中的第一个项.

此外,循环条件函数必须为求和分配参数,尽管在此特定示例中未使用该参数.