1
votes

I tried to use while loop in Tensorflow.

The code is::

import tensorflow as tf

sess=tf.Session()


rois_boxes = tf.concat([tf.ones([12,5]),tf.zeros([12,5]) ], axis=0)

img_ids = tf.unique(rois_boxes[:,0])
img_ids = tf.cast(img_ids[0], tf.int32)



regions_features=tf.constant(55, dtype=tf.int32)

def body(regions_features, img_ids):
        regions_features = img_ids[0]
        img_ids = img_ids[1:]
        return regions_features


def condition(regions_features, img_ids):
        return tf.not_equal(tf.size(img_ids), 0)


x = tf.Variable(tf.constant(0, shape=[2, 2]))

regions_features = tf.while_loop(condition, body, [regions_features, img_ids])

This code return this error::

Traceback (most recent call last): File "", line 1, in File "/home/ashwaq/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/ops/control_flow_ops.py", line 2775, in while_loop result = context.BuildLoop(cond, body, loop_vars, shape_invariants) File "/home/ashwaq/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/ops/control_flow_ops.py", line 2604, in BuildLoop pred, body, original_loop_vars, loop_vars, shape_invariants) File "/home/ashwaq/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/ops/control_flow_ops.py", line 2561, in _BuildLoop nest.assert_same_structure(list(packed_vars_for_body), list(body_result)) File "/home/ashwaq/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/util/nest.py", line 199, in assert_same_structure % (len_nest1, nest1, len_nest2, nest2)) ValueError: The two structures don't have the same number of elements.

First structure (2 elements): [<tf.Tensor 'while/Identity:0' shape=() dtype=int32>, <tf.Tensor 'while/Identity_1:0' shape=(?,) dtype=int32>]

Second structure (1 elements): [<tf.Tensor 'while/strided_slice_1:0' shape=() dtype=int32>]

why this problem happend? and how can I pass different variables into body and condition of while loop without any problems??

1
body must return the next value of both region_features and img_ids. And tf.while_loop will return the last value of both of them.jdehesa
As I said, the body function also needs to return both variable values (i.e. return regions_features, img_ids).jdehesa

1 Answers

0
votes

This works for me, it finds 2^5.

i = tf.get_variable('i', initializer=tf.constant(1))
pow_2 = tf.get_variable('X', initializer=tf.constant(2))
def cond(tensor):
    return tensor[0] < 5
def body(tensor):
    return tf.stack([tensor[0] + 1, tensor[1] * 2])

T = tf.while_loop(cond, body, loop_vars=[tf.stack([i, pow_2])])