无法在Jupyter Notebook中导入tensorflow

3 投票
2 回答
11074 浏览
提问于 2025-05-18 21:19

我正在使用Jupyter Notebook,想要导入tensorflow。结果出现了这个错误:

---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-15-64156d691fe5> in <module>()
----> 1 import tensorflow as tf

ModuleNotFoundError: No module named 'tensorflow'

我是在我的虚拟环境中输入 jupyter notebook 来启动这个笔记本的:

(labs) Sahands-MBP:part1 sahandzarrinkoub$ jupyter notebook

tensorflow肯定是在这个虚拟环境中安装好的:

(labs) Sahands-MBP:part1 sahandzarrinkoub$ python
Python 3.6.4 |Anaconda, Inc.| (default, Jan 16 2018, 12:04:33) 
[GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import tensorflow
>>> 

那么为什么找不到呢?Jupyter是在哪里查找这些包的呢?我甚至在我的虚拟环境外面也安装了tensorflow。

相关问题:

  • 暂无相关问题
暂无标签

2 个回答

3

可能是你的Jupyter笔记本在查找一个和你安装tensorflow的路径不一样的地方。你需要确保Jupyter通过正确的内核打开正确的Python。
解决这个问题的一种方法是通过在终端输入以下命令来安装nb_conda:

conda install -c anaconda-nb-extensions nb_conda

然后你可以运行Jupyter,当你从“新建”下拉菜单中选择一个笔记本时,确保选择的是连接到你想要的内核的Python(这个内核里有你需要的所有库和依赖,比如tensorflow)。

3

看起来你正在尝试使用来自你基础Python的Jupyter安装,也就是在你的labs虚拟环境之外。

解决这个问题一个简单的方法就是在你的虚拟环境里再安装一次Jupyter,也就是在labs里面进行安装。

pip install jupyter

还有一个更通用的方法,可以避免在每个虚拟环境中都安装多个Jupyter,那就是使用Jupyter内核;你可以参考我在这里的详细回答,这个回答是关于PySpark的,实际上很容易调整到你的情况。

撰写回答