繁体   English   中英

“未找到导入 tensorflow 模块”仅在 jupyter 笔记本上,但不在 jupyter 实验室或终端上

[英]"Importing tensorflow module not found" Only on jupyter notebook but not jupyter lab or terminal

我启动 powershell anaconda 提示并激活新项目的环境。 然后我使用 tensorflow 网站pip install tensorflow

为了验证安装是否成功,我从终端中打开 python 并导入 tensorflow :

> python
Python 3.7.10 (default, Feb 26 2021, 13:06:18) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import tensorflow as tf
>>> tf
<module 'tensorflow' from 'C:\\Users\\myname\\Anaconda3\\envs\\test_env\\lib\\site-packages\\tensorflow\\__init__.py'>

一切似乎都在工作,我继续启动一个 jupyter notebook 并在一个新的单元格中执行导入。 但是,当我运行 cell import tensorflow时,我收到以下错误:

---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-3-d6579f534729> in <module>
----> 1 import tensorflow

ModuleNotFoundError: No module named 'tensorflow'

To double check, I close the jupyter notebook session, and launch a jupyter lab session instead - all from the same Anaconda powershell terminal with the correct environment activated. 当我在 jupyterlab 下运行 import 语句时,一切正常。

到底是怎么回事?

  1. 为什么import语句在终端和jupyter实验室下有效
  2. 为什么它在 jupyter notebook 中不起作用?
  3. 我如何解决它?

[编辑:]

在 jupyter 实验室和笔记本电脑上,我运行了命令!conda info并且可以确认安装 tensorflow 的环境确实处于活动状态。

按照以下步骤使用 PIP 在虚拟环境中安装 Tenosrflow

#Install virtualenv
sudo pip3 install virtualenv
#Create virtual environment name: venv
virtualenv venv
#Activate venv
source venv/bin/activate
#Install tensorflow
venv$ pip3 install tensorflow
#Install Jupyter notebook
venv$ pip3 install notebook
# Launch jupyter notebook
venv$ jupyter notebook

以下是我在机器上解决问题的根本原因和步骤(macOS Monterey 12.5.1)

我案件的根本原因

Python 3.8.x 作为命令行开发工具的一部分安装在我的机器上。 这是因为当我尝试通过运行命令code-select --install安装 xcode-select 时安装了 Python 。 这意味着 Python 的主要安装位于/Library/Developer/CommandLineTools/Frameworks/Python.framework/Versions (请参阅文档)。 因此,在创建虚拟环境时,将从上述位置加载 Python 路径。 同时,我通过 brew package manager 安装了 Jupyter notebook。 因此,它们(Python 和 Jupyter)无法相互通信。

如何解决问题

删除了已通过 brew 安装的 Jupyter notebook 的安装。 然后将其安装在我的项目所在的特定虚拟环境中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM