10

I am trying to run a loop based on the size of the array. how to do that in tensorflow ? For example

# input pipeline with all files available in the folder
a = tf.Variable([1,2,3,4,5],dtype = tf.int32)
loop = tf.size(a)
....
for i in range(loop):
    print(sess.run(a))

I wanted to print the array a for 5 times. but it says loop is a tensor object and cannot taken as integer. I have tried taking the loop variable as

loop = tf.cast(tf.size(a),tf.int32),
loop = tf.shape_n(a),
loop = tf.shape(a)[0]

it has the same error.

2 Answers 2

3

Not really sure what you want to achieve here. loop is a tf.Tensor and range expects an integer as argument, hence the error. If you just want to print a 5 times, why don't you just set loop to the numerical value of 5?

Otherwise, the following code should work, as loop.eval() returns the value of loop which is 5:

a = tf.Variable([1,2,3,4,5],dtype = tf.int32)
loop = tf.size(a)
....
for i in range(loop.eval()):
    print(sess.run(a))

If you don't want to execute the TF graph multiple times, take a look at tf.while_loop.

Sign up to request clarification or add additional context in comments.

Comments

2

tf.size() does not give you a value or list.

a = tf.Variable([1,2,3,4,5],dtype = tf.int32)

v = a.get_shape()
loop = v.num_elements()

...

Perhaps, try this.

1 Comment

I have used tf.shape in place of tf.size in the above answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.