【问题标题】:Understanding the while loop in Tensorflow理解 Tensorflow 中的 while 循环
【发布时间】:2017-10-03 05:28:29
【问题描述】:

我正在使用Python API for Tensorflow。我正在尝试在不使用 Python 循环的情况下实现下面给出的Rosenbrock function

我目前的实现如下:

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

我尝试在tf.while_loop() 中实现求和;但是,当涉及到使用旨在与数据保持分离的索引整数时,我发现 API 有点不直观。 documentation 中给出的示例使用数据作为索引(反之亦然):

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])

【问题讨论】:

  • 只使用for循环合适吗?使用 while_loop 有什么好处?还是有必要?
  • 在他上面的代码中,for循环会执行python代码。如果我们将他的 for 循环的主体称为“f”,那么您可以将 python 代码视为执行 f,f,f,f,f,... f。所以它会调用那个“body”函数 N 次,函数的图形将因此具有该函数 N 次。如果您使用 tf.while_loop,那么您只会在图中看到该函数一次。
  • tf.while_loop 的优点是:1) 您可以并行运行迭代;2) 您可以在条件语句中使用运行时常量。例如,如果您想运行优化器直到满足某个容差,那么您必须使用 tf.while_loop 变体,因为 python 最初无法评估条件
  • @bremen_matt,如果迭代具有顺序依赖关系,那么并行计算如何工作?
  • 看看这个。我发现它很有帮助github.com/tensorflow/tensorflow/issues/1984

标签: python optimization while-loop tensorflow


【解决方案1】:

这可以按照documentation 中的第二个示例使用tf.while_loop() 和标准tuples 来实现。

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]

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

此外,循环条件函数必须为求和分配一个参数,尽管在此特定示例中没有使用它。

【讨论】:

    猜你喜欢
    • 2017-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-18
    • 1970-01-01
    • 2019-04-28
    • 2017-09-27
    相关资源
    最近更新 更多