Tensorflow while loop: working with lists

import tensorflow as tf

array = tf.Variable(tf.random_normal([10]))
i = tf.constant(0)
l = []

def cond(i,l):
   return i < 10

def body(i,l):
   temp = tf.gather(array,i)
   l.append(temp)
   return i+1,l

index,list_vals = tf.while_loop(cond, body, [i,l])

I want to handle the tensor array in the same way as described in the code above. In the body of the while loop, I want to process the array element by element in order to apply some function. For demonstration, I gave a small piece of code. However, it produces an error message as follows.

ValueError: Number of inputs and outputs of body must match loop_vars: 1, 2

Any help in resolving this is appreciated.

thank

+6
source share
2 answers

Referring to the documentation:

loop_vars is a (possibly nested) tuple, namedtuple or list of tensors Which are transmitted as cond, and sobody

You cannot pass a regular python array as a tensor. What you can do is:

i = tf.constant(0)
l = tf.Variable([])

def body(i, l):                                               
    temp = tf.gather(array,i)
    l = tf.concat([l, [temp]], 0)
    return i+1, l

index, list_vals = tf.while_loop(cond, body, [i, l],
                                 shape_invariants=[i.get_shape(),
                                                   tf.TensorShape([None])])

, tf.while_loop , .

sess = tf.Session()
sess.run(tf.global_variables_initializer())
sess.run(list_vals)
Out: array([-0.38367489, -1.76104736,  0.26266089, -2.74720812,  1.48196387,
            -0.23357525, -1.07429159, -1.79547787, -0.74316853,  0.15982138], 
           dtype=float32)
+9

TF TensorArray . ,

, , Tensor .

, while_loop map_fn. "" .

,

import tensorflow as tf

array = tf.Variable(tf.random_normal([10]))
step = tf.constant(0)
output = tf.TensorArray(dtype=tf.float32, size=0, dynamic_size=True)

def cond(step, output):
    return step < 10

def body(step, output):
    output = output.write(step, tf.gather(array, step))
    return step + 1, output

_, final_output = tf.while_loop(cond, body, loop_vars=[step, output])

final_output = final_output.stack()

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(sess.run(final_output))
0

Source: https://habr.com/ru/post/1664232/


All Articles