0%

Jupyter Notebook搭配Conda Environment食用

Install miniconda

与Anaconda相比,Miniconda要轻量化得多。Miniconda仅包含conda,Python以及少量的依赖包。miniconda的安装方法见官网说明文档。只需要下载对应操作系统的installer,然后按提示一步步进行即可。

Install jupyter notebook

1
pip install notebook

Create conda environment

1
conda create -n dl_env

Add conda environment to jupyter notebook

添加前

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# list现有的kernel
(base) root@kaka:~/tmp/envs# jupyter kernelspec list
Available kernels:
python3 /root/miniconda3/share/jupyter/kernels/python3

# 查看具体的kernel信息
(base) root@kaka:~/tmp/envs# cat /root/miniconda3/share/jupyter/kernels/python3/kernel.json
{
"argv": [
"python",
"-m",
"ipykernel_launcher",
"-f",
"{connection_file}"
],
"display_name": "base_py3",
"language": "python"
}

添加方法

1
2
3
4
5
6
7
8
# 先激活要添加的虚拟环境
conda activate dl_env
# 安装ipykernel
pip install --user ipykernel
# 把虚拟环境添加到jupyter, --name就是jupyter notebook展示的名称,可以自定义,为了方便管理一般选择和虚拟环境一样的名称
python -m ipykernel install --user --name=dl_env
# 退出虚拟环境
conda deactivate

添加后:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
(base) root@kaka:~/tmp/envs# jupyter kernelspec list
Available kernels:
dl_env /root/.local/share/jupyter/kernels/dl_env
python3 /root/miniconda3/share/jupyter/kernels/python3

# 新添加的kernel,可以看到使用的是虚拟环境dl_env里的python
(base) root@kaka:~/tmp/envs# cat /root/.local/share/jupyter/kernels/dl_env/kernel.json
{
"argv": [
"/root/miniconda3/envs/dl_env/bin/python",
"-m",
"ipykernel_launcher",
"-f",
"{connection_file}"
],
"display_name": "dl_env",
"language": "python"
}

删除conda虚拟环境

1
conda remove --name dl_env --all

从jupyter从移除kernel

1
jupyter kernelspec uninstall dl_env

其他

国内用户可以切换一下源,加快访问速度

Reference