文章目录
0. 前言
- 安装:
pip install jupyter
1. 远程访问
1.1. 方法一
- 第一步:生成配置文件
jupyter notebook --generate-config
- 第二步:进入python命令行,生成密码。
>>> from notebook.auth import passwd
>>> passwd()
Enter password:
Verify password:
'sha1:xxxxxxxxxx'
- 第三步:修改默认配置文件
vim ~/.jupyter/jupyter_notebook_config.py
。
c.NotebookApp.ip='*' # 就是设置所有ip皆可访问
c.NotebookApp.password = u'sha:xxxx...' # 即上一部生成的值
c.NotebookApp.open_browser = False # 禁止自动打开浏览器
c.NotebookApp.port = 8888 #随便指定一个端口
- 第四步:启动jupyter
jupyter notebook
1.2. 方法二
- 第一步:新建配置文件
config.json
{
"NotebookApp": {
"ip": "0.0.0.0",
"port": 8888,
"open_browser": false,
"token": ""
}
}
- 第二步:运行命令
jupyter notebook --config /path/to/config.json >> /dev/null &
2. 小技巧
2.1. 重载模块
import imp
imp.reload(module_name)
2.2. 执行命令行命令
- 在语句最开始添加一个感叹号,如
!ls
2.3. 设置主题
- Github
- 安装:
pip install jupyterthemes
- 基本使用:
jt -l # 查看可用主题列表
jt -r # 选择默认主题
jt -t themename # 选择主题
2.4. 添加ikernel
- 安装 ipykernel 或 jupyter,即
pip install ipykernel
或pip install jupyter
。 - 添加 kernel 命令:
python -m ipykernel install --name mykernel_name
。 - 注意:有可能会因为权限不足安装失败,这时需要执行
sudo /path/to/my/python -m ipykernel install --name mykernel_name
2.5. 计时
- 在一个cell最开始添加
%%time
,会计算当前cell的运行时间。 - 对某一行添加
%time
,则会计算当前行的运行时间。 - 对某一行添加
%timeit
,则会多次运行本行(说是默认跑100000次,但我是的时候跑了1loop,7runs),计算平均时间与方差。
3. 碰到的问题
3.1. 创建文件时 Permission Denied
- 问题描述:
nohup jupyter notebook
是不能正常运行的。 - 解决:将需要常见文件的文件夹配置权限,即
chmod 777 /path/to/target/dir
。
3.2. Win10中偶尔出现的Matplotlib问题
- 问题描述:
- 当使用
plt.imshow(img)
等展示图片时不会显示图片。 - 报错:
UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.
- 当使用
- 解决:在import完之后添加
%matplotlib notebook
3.3. 在 jupyter 中展示视频
- 问题描述:
- Jupyter 中展示图片一般使用 matplotlib 的
plt.imshow
即可。 - 但如何在jupyter中展示视频(连续展示多张图片)?
- Jupyter 中展示图片一般使用 matplotlib 的
- 解决:使用 IPython 解决
- PS: 如果视频是由多张图片组成,可以直接通过
display(Image(data=img_path))
来实现。
- PS: 如果视频是由多张图片组成,可以直接通过
from IPython.display import clear_output, display, Image
import cv2
import time
cap = cv2.VideoCapture("/path/to/xx.mp4")
while True:
ret, frame = cap.read()
if not ret:
break
clear_output()
_, img = cv2.imencode('.png', frame)
display(Image(data=img))
time.sleep(0.1)
4. 进阶扩展包
- 安装:
pip install jupyter_contrib_nbextensions
jupyter contrib nbextension install—user
pip install jupyter_nbextensions_configurator
-
资料:
- 数据科学家效率提升必备技巧之Jupyter Notebook篇:介绍了Autopep8, Collapsible Headings, Gist-it
- 99 ways to extend the Jupyter ecosystem