Iggy Green
Iggy Green

Reputation: 5

Tensorflow how to get tensor value

In python I can use

a = np.array([[3], [6], [9]])

Obviously,

a[0][0] = 3
a[1][0] = 6
a[2][0] = 9

But I tried to do the same thing with tensorflow

import tensorflow as tf
a = tf.Variable(np.array([[3], [6], [9]]))
init = tf.initialize_all_variables()

with tf.Session() as ss:
   ss.run(init)
   for i in range(3):
       print sess.run(a[i][0])

If I print it(use for loop), I got TypeError: 'Variable' object is not callable

How can I resolve this error? Thanks very much for any help!

Upvotes: 0

Views: 9821

Answers (2)

sygi
sygi

Reputation: 4647

You can define another op, that is dependent on the original variable, that contains the slice of your tensor:

import tensorflow as tf
a = tf.Variable(np.array([[3], [6], [9]]))
part = []
for i in range(3):
    part.append(a[i][0])
init = tf.initialize_all_variables()

with tf.Session() as ss:
   ss.run(init)
   for op in part:
       print ss.run(op)

Upvotes: 1

Dmytro Danevskyi
Dmytro Danevskyi

Reputation: 3159

Despite tensorflow and numpy are quite similar at the first glance, tensorflow workflow substantially differs from numpy's. When using tensorflow, you should first define the computational graph -- the rules defining the connections between tensors.

In your case, the graph consists of only one variable a. Once the graph was defined, you would be able to compute the values of different nodes in a graph by running a tensorflow session. In your case, to print a value of a, use the following code:

sess = tf.Session()
init = tf.initialize_all_variables()
sess.run(init)
print(sess.run(a))

Upvotes: 0

Related Questions