属性错误:'Tensor'对象没有'numpy'属性。

101
我该如何解决这个问题?我从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)]]
9个回答

101
我怀疑你从复制代码的地方启用了动态执行,即在程序开始时调用tf.enable_eager_execution()
你可以做同样的事情。
更新:请注意,TensorFlow 2.0默认启用了动态执行。因此上面的答案仅适用于TensorFlow 1.x。

6
它改变了TensirFlie APIs,使得它们立即在张量上执行操作(而不是将操作添加到图表中)。有关详细信息,请参见上面答案中的链接。 - ash

99

既然被接受的答案对我没有解决问题,那么我想这可能对一些遇到问题且已经有tensorflow版本>= 2.2.0和启用急切执行的人有所帮助。

问题似乎是,在某些函数在拟合时model.fit()期间,@tf.function装饰器为了性能原因禁止执行类似tensor.numpy()的函数。

对我而言,解决方案是像这样将标志传递给model.compile()run_eagerly=True

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

32

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

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

tf.config.run_functions_eagerly(True)

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

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


就记录而言,这个答案是唯一一个让我改变错误输出的东西。我遇到了这个错误,但是我使用的是TF 2.0,而不是1.x,所以我认为这就是为什么大多数其他答案对我没有帮助的原因。 - Charlie

23

如果你的代码被包装在@tf.function或Keras层内部,那么在TF2.0中也可能会出现这种情况。这两者都在图模式下运行。由于急切和图形模式之间的行为差异以及人们没有意识到它们正在切换上下文,因此有很多秘密破损的代码存在,所以要小心!


@Stark 请查看Alexander的回答:https://dev59.com/Iuk5XIcBkEYKwwoY7OHv#63596006 或者 https://stackoverflow.com/a/68057458/9095840 - markemus

10

这在旧版本的TF中发生。因此,请尝试pip install tensorflow --upgrade进行升级。

否则运行

import tensorflow as tf
tf.enable_eager_execution()

如果你正在使用Jupyter笔记本,请重启内核。


2

你也可以使用tf.get_static_value()来获取张量的值。这样做的好处是不需要急切模式。参见文档此处


这并没有回答问题。一旦您拥有足够的声望,您将能够评论任何帖子;相反,提供不需要询问者澄清的答案。- 来自审核 - SandPiper

1

tf.multinomial 返回一个 Tensor 对象,其中包含形状为 [batch_size, num_samples] 的抽样的 2D 列表。对该张量对象调用 .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()

1

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


0

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

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

我使用带有tensorflow 1.14.0的anaconda 3。我使用以下命令升级了tensorflow

conda update tensorflow

现在TensorFlow已经更新到2.0.0版本,问题已经修复。尝试使用此方法查看是否解决了您的问题。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接