属性错误:模块“tensorflow”没有“python”属性。

20
>import tensorflow

>import tensorflow.contrib

>tensorflow.contrib

module 'tensorflow.contrib' from 'D:\\ProgramData\\Anaconda3\\lib\\site-packages\\tensorflow\\contrib\\__init__.py'

>import tensorflow.python

>tensorflow.python

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'tensorflow' has no attribute 'python'

正如您所看到的,我在cmd(win 10)中运行这段代码。 "import tensorflow.contrib" 和 "import tensorflow.python" 都可以,但是命令 "tensorflow.contrib" 和 "tensorflow.python" 是不同的。一个返回目录,另一个返回AttributeError错误。

有人知道为什么吗?


我认为 pip install -U keras 应该可以解决。 - Mahesh Karia
其实我已经有最新的Keras模块了,不过还是谢谢。 - cmjdxy
3个回答

16

tensorflow.__init__()明确地在从tensorflow.python模块中导入所有内容后删除对其的引用。

这样做的原因是为了在顶层tensorflow命名空间中提供对python包中包含的子模块的访问权限。还有一些来自tensorflow.core包的东西也被导入并在tensorflow命名空间中提供。

我认为这个想法不是直接导入tensorflow.python。那些旨在被应用程序使用的python类、对象和子模块通过简单的import tensorflow即可使用。


谢谢您的回复,我认为这听起来很合理。 - cmjdxy
@mhawke,让我困扰的是语句import tensorflow.python并没有导致AttributeError错误。有没有可能你能给出解释呢? - Mr Tsjolder
1
@MrTsjolder:导入成功是因为包存在,所以不会出现“AttributeError”。为什么会失败呢?问题在于执行import tensorflow.python时,首先导入的是tensorflow,而不是tensorflow.pythontensorflow.__init__.py明确地从tensorflow.python中导入所需内容,然后删除对python的引用,因此它不在导入代码的命名空间中。由于已经导入了tensorflow.python,所以不会再次导入,因此删除的引用仍然被删除。 - mhawke
那么这句话的意思是TensorFlow的python.keras模块的导入将会引向哪里呢? - ben26941

2
您可以通过以下方式导入tensorflow.python
from tensorflow import python as tf_python

-4

对我来说,使用以下导入行起作用:

from tensorflow.python import keras

干杯!


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