簡體   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