【问题标题】:tensorflow tutorial code fails with AttributeError: 'Tensor' object has no attribute 'numpy'tensorflow 教程代码因 AttributeError 失败:“Tensor”对象没有属性“numpy”
【发布时间】:2019-01-24 19:29:06
【问题描述】:

刚刚使用 Python 3.6.6 和 CUDA 9.0 在 Win10 上安装了 tensorflow-gpu 1.10 在https://colab.research.google.com/github/tensorflow/tensorflow/blob/master/tensorflow/contrib/eager/python/examples/notebooks/custom_training.ipynb#scrollTo=_WRu7Pze7wk8尝试示例代码

问题就在顶部:

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

在 Google Notebook 上运行时会失败并显示

RuntimeError: 启用急切执行时不支持 tf.Variable。请改用 tf.contrib.eager.Variable

你应该解决这个问题。修复后,代码在 Notebook 上运行不会出错。

但是,当我将它复制到本地 .py 文件并运行它时,我得到了这个非常意外的错误:

Traceback(最近一次调用最后一次): 文件“linear.py”,第 15 行,在 断言模型(3.0).numpy()== 15.0 AttributeError:“张量”对象没有属性“numpy”

但是在 Python 的交互模式下...

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

什么给了? (请记住,我是一个完全的 Python 和 tensorflow 菜鸟)

【问题讨论】:

    标签: python tensorflow


    【解决方案1】:
    1. 关于谷歌笔记本中的RuntimeError。您正在 GitHub 的 master 分支中查看笔记本的版本。该版本的笔记本旨在与代码库的master 分支同步,其中tf.Variable 工作得很好。如果您正在寻找与 TensorFlow 的特定发布版本相对应的笔记本,您应该查看相应发布分支中的版本。例如,https://colab.research.google.com/github/tensorflow/tensorflow/blob/r1.10/tensorflow/contrib/eager/python/examples/notebooks/eager_basics.ipynb 似乎 www.tensorflow.org/tutorials 错误地链接到 master 分支版本,所以这肯定是网站上的一个错误。

    更新:网站已修复,链接应指向相应的发布分支。

    1. 第二个错误表明缺少对tf.enable_eager_execution() 的调用,或者代码正在with tf.Graph().as_default() 块内运行。可能会发生这种情况吗?

    希望对您有所帮助。

    【讨论】:

    • 我收到与 OP 相同的错误。刚刚检查了我的 colab 笔记本和官方 colab 笔记本上的 TF 版本 - 它们是相同的。这真是令人费解。
    猜你喜欢
    • 2022-10-24
    • 2020-07-18
    • 2023-02-02
    • 2021-08-29
    • 1970-01-01
    • 2015-05-16
    • 2020-06-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多