了解肌腱流中的while循环。

[英]Understanding the while loop in Tensorflow


I am using the Python API for Tensorflow. I am trying to implement the Rosenbrock function given below without the use of a Python loop:

我正在使用Python API进行Tensorflow。我正在尝试在不使用Python循环的情况下实现Rosenbrock函数:

Rosenbrock function

My current implementation is as follows:

我目前的执行情况如下:

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

I have tried implementing the summation in a tf.while_loop(); however, I found the API somewhat unintuitive when it comes to using an index integer that is meant to remain separate from the data. The example given in the documentation uses the data as the index (or vice-versa):

我已经尝试在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])

1 个解决方案

#1


10  

This can be achieved using the tf.while_loop() and standard tuples as per the second example in the documentation.

这可以通过使用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]

It is important to note that the index increment should occur in the body of the loop similar to a standard while loop. In the solution given, it is the first item in the tuple returned by the body() function.

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

Additionally, the loop condition function must allot a parameter for the summation although it is not used in this particular example.

此外,循环条件函数还必须为求和提供一个参数,尽管在这个特殊的例子中没有使用它。

智能推荐

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2017/05/04/7deed5cfbbb4d0f7906dc48b888f0d60.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告