ModuleNotFoundError:没有名为“tensorflow.contrib”的模块; “tensorflow”不是一个包

2024-03-31

我正在尝试开始使用 Tensorflow,但遇到错误。 我在谷歌和这个网站上搜索,但没有找到答案。

让我解释一下。我目前在我的计算机上使用 anaconda3。我使用“Anaconda Prompt”来安装tensorflowpip install -q --upgrade tensorflow。 它有效,但是当我运行这段代码时(来自here https://www.tensorflow.org/get_started/eager):

from __future__ import absolute_import, division, print_function

import os
import matplotlib.pyplot as plt

import tensorflow as tf
import tensorflow.contrib.eager as tfe

tf.enable_eager_execution()

print("TensorFlow version: {}".format(tf.VERSION))
print("Eager execution : {}".format(tf.executing_eagerly()))

我收到以下错误:

Traceback (most recent call last):
File "<ipython-input-11-9a561e7b074b>", line 1, in <module>
runfile('C:/Users/emile/Desktop/tensorflow.py', wdir='C:/Users/emile/Desktop')

File "C:\Users\emile\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile
execfile(filename, namespace)

File "C:\Users\emile\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)

File "C:/Users/emile/Desktop/tensorflow.py", line 6, in <module>
import tensorflow as tf

File "C:\Users\emile\Desktop\tensorflow.py", line 7, in <module>
import tensorflow.contrib.eager as tfe

ModuleNotFoundError: No module named 'tensorflow.contrib'; 'tensorflow' is not a package

也许问题是由 Anaconda 引起的?

非常感谢。


这是一个有趣的发现,我希望这可以帮助在 Anaconda 或类似集成环境下开发的其他人,在这些环境中,您的程序不是直接从命令行运行的,例如就像“python myprogram.py”。

该问题可能是由程序本身名为tensorflow.py 引起的。它运行在一个环境中,它不是作为“主”模块启动的,而是由另一个 Python 程序(在本例中为 anaconda)加载的。

当以这种方式加载 python 程序时,解释器将其作为模块读取,并将其放入模块列表中(与文件同名),因此现在 sys.modules["tensorflow"] 指向加载的用户程序(而不是安装的张量流模块)。当遇到“import tensorflow as tf”行时,Python 会看到“tensorflow”已经导入,并且简单地执行tf=sys.modules["tensorflow"],这是对你自己的参考tensorflow.py(已经是一个问题,但你不必tf.enable_eager_execution()然而 - 如果你这样做就会失败,因为yourtensorflow.py没有这样的功能)。

现在,有趣的部分:

import tensorflow.contrib.eager as tfe

Python 已经导入了“tensorflow”(您的模块!),因此它希望在与加载的 tensorflow.py 相同的目录中找到任何子模块。特别是,它期望该目录是一个 Python 包(有__init__.py在其中),但显然不是,因此出现“...不是包”错误消息。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

ModuleNotFoundError:没有名为“tensorflow.contrib”的模块; “tensorflow”不是一个包 的相关文章

随机推荐