Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: 'Tensor' object cannot be interpreted as an integer

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.

like image 282
Raady Avatar asked Jan 22 '17 07:01

Raady


2 Answers

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.

like image 177
guinny Avatar answered Oct 07 '22 14:10

guinny


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.

like image 2
Shobeir Avatar answered Oct 07 '22 15:10

Shobeir