How to use tf.while_loop() in tensorflow

前端 未结 1 369
猫巷女王i
猫巷女王i 2021-01-30 05:35

This is a generic question. I found that in the tensorflow, after we build the graph, fetch data into the graph, the output from graph is a tensor. but in many cases, we need to

1条回答
  •  攒了一身酷
    2021-01-30 06:08

    What is stopping you from adding more functionality to the body? You can build whatever complex computational graph you like in the body and take whatever inputs you like from the enclosing graph. Also, outside of the loop, you can then do whatever you want with whatever outputs you return. As you can see from the amount of 'whatevers', TensorFlow's control flow primitives were built with much generality in mind. Below is another 'simple' example, in case it helps.

    import tensorflow as tf
    import numpy as np
    
    def body(x):
        a = tf.random_uniform(shape=[2, 2], dtype=tf.int32, maxval=100)
        b = tf.constant(np.array([[1, 2], [3, 4]]), dtype=tf.int32)
        c = a + b
        return tf.nn.relu(x + c)
    
    def condition(x):
        return tf.reduce_sum(x) < 100
    
    x = tf.Variable(tf.constant(0, shape=[2, 2]))
    
    with tf.Session():
        tf.global_variables_initializer().run()
        result = tf.while_loop(condition, body, [x])
        print(result.eval())
    

    0 讨论(0)
提交回复
热议问题