【问题标题】:Keras is installed in Anaconda virtual environment but can't be importedAnaconda虚拟环境安装Keras但无法导入
【发布时间】:2019-12-23 18:13:44
【问题描述】:

我已将 keras 安装到我的 Anaconda 虚拟环境中,但我无法导入模块:

$ conda list | grep keras
keras                     2.2.4                    py37_1    conda-forge
keras-applications        1.0.8                      py_0  
keras-preprocessing       1.1.0                      py_1  
keras-retinanet           0.5.0                    pypi_0    pypi

$ python
Python 3.7.3 | packaged by conda-forge | (default, Mar 27 2019, 23:01:00) 
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import keras
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'keras'

可能有什么问题?

【问题讨论】:

  • *.com/questions/39930952/… 是否安装了tensorflow?存在依赖问题。
  • 是的,tensorflow 1.14 版也已安装。
  • 您的“conda list”命令是否有可能发出一些警告或其他诊断信息,而您没有看到因为“|grep keras”?你可以“导入张量流”吗? (我知道这两个问题都是长镜头,但不知何故,这种奇怪的行为会有一个合乎逻辑的答案!)
  • 我最近遇到了这个问题,在我重新启动 anaconda 时已解决。你试过吗?

标签: python keras


【解决方案1】:

最好的选择是为您的虚拟环境使用 venv。如需说明:

Mac OS 和 Linux:如何设置虚拟环境

1) 克隆 repo 后,cd 进入 repo 并运行命令:python3 -m venv venv

    This will create the virtual environment. Make sure to name it venv because the .gitignore file
    has been initialized to ignore it by default. 

2) 运行以下命令激活虚拟环境:source venv/bin/activate

3) 要下载所需的软件包,只需运行:pip install -r requirements.txt

    This will go to the requirements file that is already generated in the repo and download any dependecies.

4) 添加任何包后,请确保通过运行以下命令更新 requirements.txt 文件:pip freeze &gt; requirements.txt

5) 随时可以运行deactivate 离开虚拟环境。

Windows:如何设置虚拟环境

1) 克隆 repo 后,cd 进入 repo 并运行命令:python -m venv venv

    This will create the virtual environment. Make sure to name it venv because the .gitignore file
    has been initialized to ignore it by default. 

2) 运行以下命令激活虚拟环境:venv\Scripts\activate.bat

    To activate the virtual environment inside of a code editor's bash, run: venv\Scripts\activate.ps1

3) 要下载所需的软件包,只需运行:pip install -r requirements.txt

4) 添加任何包后,请确保通过运行以下命令更新 requirements.txt 文件:pip freeze 然后将它们粘贴到requirements.txt 文件中。

5) 您可以随时运行deactivate 离开虚拟环境。

最后,只需输入pip install keras

【讨论】: