AttributeError:“张量”对象没有属性“numpy”

Posted

技术标签:

【中文标题】AttributeError:“张量”对象没有属性“numpy”【英文标题】:AttributeError: 'Tensor' object has no attribute 'numpy' 【发布时间】:2019-02-20 18:37:52 【问题描述】:

如何解决这个错误我从 GitHub 下载了这段代码。

predicted_id = tf.multinomial(tf.exp(predictions), num_samples=1)[0][0].numpy()

抛出错误

AttributeError: 'Tensor' object has no attribute 'numpy'

请帮我解决这个问题!

我用过:

sess = tf.Session()
    with sess.as_default():
       predicted_id = tf.multinomial(tf.exp(predictions), num_samples=1)[0][0].eval()

我得到了这个错误。谁能帮帮我,我只是想让它工作,为什么这么难?

D:\Python>python TextGenOut.py
  File "TextGenOut.py", line 72
    predicted_id = tf.multinomial(tf.exp(predictions), num_samples=1)[0][0].eval()
    ^
IndentationError: unexpected indent

D:\Python>python TextGenOut.py
2018-09-16 21:50:57.008663: I T:\src\github\tensorflow\tensorflow\core\platform\cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2
2018-09-16 21:50:57.272973: W T:\src\github\tensorflow\tensorflow\core\framework\op_kernel.cc:1275] OP_REQUIRES failed at resource_variable_ops.cc:480 : Not found: Container localhost does not exist. (Could not find resource: localhost/model/embedding/embeddings)
Traceback (most recent call last):
  File "C:\Users\fried\AppData\Roaming\Python\Python36\site-packages\tensorflow\python\client\session.py", line 1278, in _do_call
    return fn(*args)
  File "C:\Users\fried\AppData\Roaming\Python\Python36\site-packages\tensorflow\python\client\session.py", line 1263, in _run_fn
    options, feed_dict, fetch_list, target_list, run_metadata)
  File "C:\Users\fried\AppData\Roaming\Python\Python36\site-packages\tensorflow\python\client\session.py", line 1350, in _call_tf_sessionrun
    run_metadata)
tensorflow.python.framework.errors_impl.FailedPreconditionError: Error while reading resource variable model/dense/kernel from Container: localhost. This could mean that the variable was uninitialized. Not found: Container localhost does not exist. (Could not find resource: localhost/model/dense/kernel)
         [[Node: model/dense/MatMul/ReadVariableOp = ReadVariableOp[dtype=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"](model/dense/kernel)]]

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "TextGenOut.py", line 72, in <module>
    predicted_id = tf.multinomial(tf.exp(predictions), num_samples=1)[0][0].eval()
  File "C:\Users\fried\AppData\Roaming\Python\Python36\site-packages\tensorflow\python\framework\ops.py", line 680, in eval
    return _eval_using_default_session(self, feed_dict, self.graph, session)
  File "C:\Users\fried\AppData\Roaming\Python\Python36\site-packages\tensorflow\python\framework\ops.py", line 4951, in _eval_using_default_session
    return session.run(tensors, feed_dict)
  File "C:\Users\fried\AppData\Roaming\Python\Python36\site-packages\tensorflow\python\client\session.py", line 877, in run
    run_metadata_ptr)
  File "C:\Users\fried\AppData\Roaming\Python\Python36\site-packages\tensorflow\python\client\session.py", line 1100, in _run
    feed_dict_tensor, options, run_metadata)
  File "C:\Users\fried\AppData\Roaming\Python\Python36\site-packages\tensorflow\python\client\session.py", line 1272, in _do_run
    run_metadata)
  File "C:\Users\fried\AppData\Roaming\Python\Python36\site-packages\tensorflow\python\client\session.py", line 1291, in _do_call
    raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.FailedPreconditionError: Error while reading resource variable model/dense/kernel from Container: localhost. This could mean that the variable was uninitialized. Not found: Container localhost does not exist. (Could not find resource: localhost/model/dense/kernel)
         [[Node: model/dense/MatMul/ReadVariableOp = ReadVariableOp[dtype=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"](model/dense/kernel)]]

Caused by op 'model/dense/MatMul/ReadVariableOp', defined at:
  File "TextGenOut.py", line 66, in <module>
    predictions, hidden = model(input_eval, hidden)
  File "C:\Users\fried\AppData\Roaming\Python\Python36\site-packages\tensorflow\python\keras\engine\base_layer.py", line 736, in __call__
    outputs = self.call(inputs, *args, **kwargs)
  File "TextGenOut.py", line 39, in call
    x = self.fc(output)
  File "C:\Users\fried\AppData\Roaming\Python\Python36\site-packages\tensorflow\python\keras\engine\base_layer.py", line 736, in __call__
    outputs = self.call(inputs, *args, **kwargs)
  File "C:\Users\fried\AppData\Roaming\Python\Python36\site-packages\tensorflow\python\keras\layers\core.py", line 943, in call
    outputs = gen_math_ops.mat_mul(inputs, self.kernel)
  File "C:\Users\fried\AppData\Roaming\Python\Python36\site-packages\tensorflow\python\ops\gen_math_ops.py", line 4750, in mat_mul
    name=name)
  File "C:\Users\fried\AppData\Roaming\Python\Python36\site-packages\tensorflow\python\framework\op_def_library.py", line 510, in _apply_op_helper
    preferred_dtype=default_dtype)
  File "C:\Users\fried\AppData\Roaming\Python\Python36\site-packages\tensorflow\python\framework\ops.py", line 1094, in internal_convert_to_tensor
    ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)
  File "C:\Users\fried\AppData\Roaming\Python\Python36\site-packages\tensorflow\python\ops\resource_variable_ops.py", line 1045, in _dense_var_to_tensor
    return var._dense_var_to_tensor(dtype=dtype, name=name, as_ref=as_ref)  # pylint: disable=protected-access
  File "C:\Users\fried\AppData\Roaming\Python\Python36\site-packages\tensorflow\python\ops\resource_variable_ops.py", line 1000, in _dense_var_to_tensor
    return self.value()
  File "C:\Users\fried\AppData\Roaming\Python\Python36\site-packages\tensorflow\python\ops\resource_variable_ops.py", line 662, in value
    return self._read_variable_op()
  File "C:\Users\fried\AppData\Roaming\Python\Python36\site-packages\tensorflow\python\ops\resource_variable_ops.py", line 745, in _read_variable_op
    self._dtype)
  File "C:\Users\fried\AppData\Roaming\Python\Python36\site-packages\tensorflow\python\ops\gen_resource_variable_ops.py", line 562, in read_variable_op
    "ReadVariableOp", resource=resource, dtype=dtype, name=name)
  File "C:\Users\fried\AppData\Roaming\Python\Python36\site-packages\tensorflow\python\framework\op_def_library.py", line 787, in _apply_op_helper
    op_def=op_def)
  File "C:\Users\fried\AppData\Roaming\Python\Python36\site-packages\tensorflow\python\util\deprecation.py", line 454, in new_func
    return func(*args, **kwargs)
  File "C:\Users\fried\AppData\Roaming\Python\Python36\site-packages\tensorflow\python\framework\ops.py", line 3155, in create_op
    op_def=op_def)
  File "C:\Users\fried\AppData\Roaming\Python\Python36\site-packages\tensorflow\python\framework\ops.py", line 1717, in __init__
    self._traceback = tf_stack.extract_stack()

FailedPreconditionError (see above for traceback): Error while reading resource variable model/dense/kernel from Container: localhost. This could mean that the variable was uninitialized. Not found: Container localhost does not exist. (Could not find resource: localhost/model/dense/kernel)
         [[Node: model/dense/MatMul/ReadVariableOp = ReadVariableOp[dtype=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"](model/dense/kernel)]]

【问题讨论】:

【参考方案1】:

对于在 TF 2.0.0 中仍然存在此问题的人,请运行: tf.config.run_functions_eagerly(True) top of ur program 它可以完美运行!

【讨论】:

请说明您在什么情况下收到此错误。【参考方案2】:

由于接受的答案并没有为我解决问题,所以我认为它可能对一些面临问题并且已经拥有 tensorflow 版本 >= 2.2.0 并启用了急切执行的人有所帮助。

问题似乎是在拟合期间的某些功能model.fit() 出于性能原因,@tf.function 装饰器禁止执行像 tensor.numpy() 这样的函数。

我的解决方案是将标志 run_eagerly=True 传递给 model.compile(),如下所示:

model.compile(..., run_eagerly=True)

【讨论】:

这解决了最新版tensorflow的问题。 +1【参考方案3】:

我在 tf.function() 中遇到了同样的问题:但对我有用的是通过 tf.convert_to_tensor Doku 将 numpy 数组转换为张量流张量,然后继续使用张量流。也许这个技巧对任何人都有用......

【讨论】:

【参考方案4】:

Tensorflow 2 有一个配置选项可以“急切地”运行函数,这将允许通过.numpy() 方法获取张量值。要启用急切执行,请使用以下命令:

tf.config.run_functions_eagerly(True)

请注意,这主要用于调试。

另请参阅:https://www.tensorflow.org/api_docs/python/tf/config/run_functions_eagerly

【讨论】:

这个解决方案对我有用,非常完美!【参考方案5】:

如果您的代码包装在 @tf.function 或 Keras 层中,这也可能发生在 TF2.0 中。两者都以图形模式运行。那里有很多秘密破坏的代码,因为急切模式和图形模式之间的行为不同,而且人们不知道他们正在切换上下文,所以要小心!

【讨论】:

【参考方案6】:

我怀疑你复制代码的地方有eager execution enabled,即在程序开始时调用了tf.enable_eager_execution()

你也可以这样做。 希望有帮助。

更新:请注意,TensorFlow 2.0 中默认启用了急切执行。所以上面的答案只适用于 TensorFlow 1.x

【讨论】:

就是这样,谢谢。顺便说一句,急切执行有什么作用? 它更改了 TensirFlie API,以便它们立即对张量执行操作(而不是将操作添加到图形中)。有关详细信息,请参阅上面答案中的链接 能否请您添加一个不同的参考,以便知道如何在不急于执行的情况下做到这一点? 难以置信...谢谢!我在使用官方 TF 教程时遇到了同样的问题:\ 链接现在断开了,它说 404 page not found :(【参考方案7】:

它发生在旧版本的 TF 中。所以试试pip install tensorflow --upgrade

否则运行

import tensorflow as tf
tf.enable_eager_execution()

如果您使用的是 Jupyter 笔记本,请重新启动内核。

【讨论】:

【参考方案8】:

当我运行类似以下的代码时,我看到了类似的错误,

tensor = tf.multiply(ndarray, 42)
tensor.numpy()  # throw AttributeError: 'Tensor' object has no attribute 'numpy'

我使用 anaconda 3 和 tensorflow 1.14.0。我用下面的命令升级了 tensorflow

conda update tensorflow

现在 tensorflow 是 2.0.0,问题已修复。试试这个,看看它是否能解决您的问题。

【讨论】:

在 TF 2.0.0 中这仍然是一个问题 好吧,如果你看到响应,问题是它应该是急切的执行。这就是 TF 2 中“固定”的原因,因为它默认具有急切执行。但是问题总是一样的,你不能在 NOT Eager Execution 中使用.numpy() 方法。【参考方案9】:

tf.multinomial 返回一个张量对象,该对象包含一个二维列表,其中包含形状为[batch_size, num_samples] 的绘制样本。在该张量对象上调用 .eval() 预计会返回一个 numpy ndarray。

类似这样的:

predicted_id = tf.multinomial(tf.exp(predictions), num_samples=1)[0][0].eval()

您还需要确保会话处于活动状态(否则没有多大意义):

sess = tf.Session()
with sess.as_default():
    predicted_id = tf.multinomial(tf.exp(predictions), num_samples=1)[0][0].eval()

【讨论】:

现在我得到这个错误:raise ValueError("Cannot evaluate tensor using eval(): No default" ValueError: Cannot evaluate tensor using eval(): no default session is registered. Use with sess.as_default() or将显式会话传递给eval(session=sess) 对不起,如果这很愚蠢,但我对 python 很陌生。 啊 - 这是因为您没有建立会话。更新上面的帖子。 @FriederMüller 你也应该使用 this post 作为参考

以上是关于AttributeError:“张量”对象没有属性“numpy”的主要内容,如果未能解决你的问题,请参考以下文章

AttributeError:“张量”对象在注意力模型中没有“分配”属性

AttributeError:“张量”对象没有属性“to_sparse”

AttributeError:“张量”没有属性:“向后”

AttributeError:模块“张量流”没有属性“会话”

pytorch,AttributeError:模块“火炬”没有属性“张量”

AttributeError:“元组”对象没有属性“大小”