简体   繁体   中英

tensorflow tutorial code fails with AttributeError: 'Tensor' object has no attribute 'numpy'

Just installed tensorflow-gpu 1.10 on Win10 using Python 3.6.6 and CUDA 9.0 Trying the sample code at https://colab.research.google.com/github/tensorflow/tensorflow/blob/master/tensorflow/contrib/eager/python/examples/notebooks/custom_training.ipynb#scrollTo=_WRu7Pze7wk8

Problems right at the top:

class Model(object):   def __init__(self):
    # Initialize variable to (5.0, 0.0)
    # In practice, these should be initialized to random values.
    self.W = tf.Variable(5.0)
    self.b = tf.Variable(0.0)
       def __call__(self, x):
    return self.W * x + self.b    model = Model()

assert model(3.0).numpy() == 15.0

When run on Google Notebook it fails with

RuntimeError: tf.Variable not supported when eager execution is enabled. Please use tf.contrib.eager.Variable instead

You should fix that. With it fixed, the code runs without error on Notebook.

However when I copy it to a local .py file and run that, I get this really unexpected error:

Traceback (most recent call last): File "linear.py", line 15, in assert model(3.0).numpy() == 15.0 AttributeError: 'Tensor' object has no attribute 'numpy'

However in Python's interactive mode...

>>> import tensorflow as tf
>>> tf.enable_eager_execution()
>>> v = tf.contrib.eager.Variable(4.7)
>>> print( v.numpy() )
4.7
>>>

What gives?? (please bear in mind that I am a total Python and tensorflow noob)

  1. Regarding the RuntimeError in the Google Notebook. You're looking at the version of the notebook in the master branch in GitHub. That version of the notebook is meant to be in sync with the master branch of the codebase, where tf.Variable works just fine. If you're looking for the notebook corresponding to a particular release version of TensorFlow, you should look at the version in the corresponding release branch. For example, https://colab.research.google.com/github/tensorflow/tensorflow/blob/r1.10/tensorflow/contrib/eager/python/examples/notebooks/eager_basics.ipynb It seems www.tensorflow.org/tutorials is incorrectly linking to the master branch version, so that is certainly a bug on the website.

Update : The website has been fixed, links should point to the appropriate release branch.

  1. The second error suggests that there is either a missing call to tf.enable_eager_execution() or the code is being run inside a with tf.Graph().as_default() block. Is that what might be happening?

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM