Skip to content Skip to sidebar Skip to footer

Tensorflow Value Error : Cannot Evaluate Tensor Using Eval

I am new to tensorflow and getting Tensorflow value error with following script : W = tf.Variable(10) print(W.eval()) Also I tried thisway : with Session() as sess: pr

Solution 1:

From the documentation:

When you launch the graph, variables have to be explicitly initialized before you can run Ops that use their value. You can initialize a variable by running its initializer op, restoring the variable from a save file, or simply running an assign Op that assigns a value to the variable. In fact, the variable initializer op is just an assign Op that assigns the variable's initial value to the variable itself.

# Launch the graph in a session.   with tf.Session() as sess:
    # Run the variable initializer.
    sess.run(w.initializer)
    # ...you now can run ops that use the value of 'w'...

The most common initialization pattern is to use the convenience function global_variables_initializer() to add an Op to the graph that initializes all the variables. You then run that Op after launching the graph.

# Add an Op to initialize global variables.
  init_op = tf.global_variables_initializer()   
  # Launch the graph in a session.with tf.Session() as sess:
      # Run the Op that initializes global variables.
      sess.run(init_op)
      # ...you can now run any Op that uses variable values...

as a result you need to use something like:

import tensorflow as tf  
W = tf.Variable(10)
print('W: {0}'.format(W))
sess = tf.Session()
with sess.as_default():
    sess.run(W.initializer)
    print(W.eval())

FYI In TensorFlow, what is the difference between Session.run() and Tensor.eval()?

Solution 2:

You need to explicitly run an initializer operation

sess.run(tf.variables_initializer(W))

before evaluating any nodes which are dependent on W.

Solution 3:

Another example,

import tensorflow as tf  
    W = tf.Variable(tf.truncated_normal([700,10]))
   sess = tf.Session()
   with sess.as_default():
        sess.run(W.initializer)
        print(W.eval())

result:

[[-0.3294761   0.6800459   1.33331    ...  1.42762    -1.3164878
   1.4831722 ]
 [-1.0402402   0.52254885 -1.344712   ... -0.30849338  0.15020785
   1.6682776 ]
 [-1.1791034   1.4859517  -1.7137778  ...  0.844212    1.5928217
  -0.21043983]
 ...
 [ 0.01982834 -1.1290654   0.33557415 ...  0.0510614  -0.6524679
   0.16643837]
 [-0.09969945 -0.10285325 -1.1134144  ...  1.2253191   0.13343143
  -1.7491579 ]
 [-1.9345136   0.63447094  1.1200713  ...  0.5357313   1.8579113
   0.8549472 ]]

Post a Comment for "Tensorflow Value Error : Cannot Evaluate Tensor Using Eval"