为什么 env 在 Azure ML 笔记本和 Azure ML 终端中不同?

Why is env different in an Azure ML notbook and an Azure ML terminal?

我正在使用 MS Azure ML 并发现当我启动笔记本时(从 Azure ML Studio)它在不同的环境中执行,而不是我创建 Python 脚本和 运行 它来自工作室。我希望能够创建一个特定的环境并让笔记本使用它。 Notebook似乎运行的环境没有包含我需要的包,我想保留不同的环境。

首先打开一个终端,使用您之后要在笔记本上使用的相同计算目标,并使用和现有环境,您可以这样做:

conda activate existing_env
conda install ipykernel
python -m ipykernel install --user --name existing_env --display-name "Python 3.8 - Existing Environment"   

但是,要创建新环境并在您的 AzureML Notebook 中使用它,您必须执行以下命令:

conda create --name new_env python=3.8
conda activate new_env
conda install pip
conda install ipykernel
python -m ipykernel install --user --name new_env --display-name "Python 3.8 - New Environment"

最后但同样重要的是,您必须编辑 Jupyter 内核显示名称:

重要请确保您感到舒适运行所有这些步骤:

jupyter kernelspec list
cd <folder-that-matches-the-kernel-of-your-environment>
sudo nano kernel.json

然后编辑名称以匹配您想要的名称并保存文件。

使用 Pip、Conda、Docker image & Dockerfile 我们可以为您自己的脚本创建 ML 环境。

I want to be able to create a specific environment

要手动创建环境,

from azureml.core.environment import Environment
Environment(name="myenv")

使用 Conda 依赖项或 pip 要求文件使用以下代码创建环境:

#### From a Conda specification file
myenv = Environment.from_conda_specification(name = "myenv",
                                             file_path = "path-to-conda-specification-file")

#### From a pip requirements file
myenv = Environment.from_pip_requirements(name = "myenv",
                                          file_path = "path-to-pip-requirements-file")

The environment that the Notebook seems to run does not contain the packages I need and I want to preserve different environments.

要将包添加到您的环境中,可以使用 Conda、pip 或私有 wheel 文件,但建议使用 CondaDependency class.

from azureml.core.environment import Environment
from azureml.core.conda_dependencies import CondaDependencies

myenv = Environment(name="myenv")
conda_dep = CondaDependencies()

#### Installs numpy version 1.17.0 conda package
conda_dep.add_conda_package("numpy==1.17.0")

#### Installs pillow package
conda_dep.add_pip_package("pillow")

#### Adds dependencies to PythonSection of myenv
myenv.python.conda_dependencies=conda_dep

使用命令 myenv.register(workspace=ws)

在工作区中注册您的环境

list(workspace) 列出 workspace

中的环境

到运行你的具体环境:

from azureml.core import Run
Run.get_environment()

要在笔记本中安装 Conda 环境作为内核,请参阅 add a new Jupyter kernel 代码应遵循相同的顺序:

conda create --name newenv
conda activate newenv
conda install pip
conda install ipykernel
python -m ipykernel install --user --name newenv --display-name "Python (newenv)"

要添加、更改或删除 Jupyter 内核,请参考此 article

请参阅此 Document 了解更多详情