Jupyter Notebook


1.1 执行shell命令

直接在命令之前放一个“!”,就能执行shell命令。甚至可以将值传递给shell,像下面这样:

!pwd
!echo "Hello World"
directory = !pwd
print(directory)

1.2 更换主题

  1. 安装
pip install jupyterthemes
  1. 加载可用主题列表:
jt -l
  1. 选择你想要的主题:
# selecting a particular theme
jt -t <name of the theme>
# reverting to original Theme
jt -r

1.3 笔记本扩展

笔记本扩展(nbextensions)是一种JavaScript模块,可以加载到笔记本前端页面上,可以大大提升用户体验。

1.3.1 Hinterland

Hinterland功能可以让你每敲完一个键,就出现下拉菜单,可以直接选中你需要的词汇。

1.3.2 Snippets

Snippets在工具栏里加了一个下拉菜单,可以非常方便的直接插入代码段,完全不用手动敲。

1.3.3 目录

这个功能可以自动找到所有的标题,生成目录。

并且这个目录还是移动的呦,你可以放在侧边栏,也可以拖动到任何你喜欢的地方悬浮起来。

1.3.4 折叠一个标题下的全部内容

如果你的代码太长,觉得滚动过去太麻烦,可以直接折叠掉。

1.3.5 Autopep8

一键美化代码,强迫症的福音。

1.3.6 安装方法

pip install jupyter_contrib_nbextensions && jupyter contrib nbextension install
#incase you get permission errors on MacOS,
pip install jupyter_contrib_nbextensions && jupyter contrib nbextension install --user

然后把Jupyter打开,你就可以看到NBextensions这个选项卡了。

widgets.DatePicker( description=’Pick a Date’, disabled=False )

1.4 Jupyter小工具

还有一些Jupyter小工具,比如滑块、文本框之类的部分,可以做一些方便的交互。

1.4.1 滑块

def f(x):
 return x
# Generate a slider 
interact(f, x=10,);

1.4.2 布尔值生成复选框

# Booleans generate check-boxes
interact(f, x=True);

1.4.3 字符串生成文本区域

# Strings generate text areas
interact(f, x='Hi there!');

1.4.4 播放器

play = widgets.Play(
  # interval=10,
  value=50,
 min=0,
 max=100,
 step=1,
 description="Press play",
 disabled=False
)
slider = widgets.IntSlider()
widgets.jslink((play, 'value'), (slider, 'value'))
widgets.HBox([play, slider])

1.4.5 日历

widgets.DatePicker(
 description='Pick a Date',
 disabled=False
)

1.4.6 调色盘

widgets.ColorPicker(
 concise=False,
 description='Pick a color',
 value='blue',
 disabled=False
)

1.4.7 标签

tab_contents = ['P0', 'P1', 'P2', 'P3', 'P4']
children = [widgets.Text(description=name) for name in tab_contents]
tab = widgets.Tab()
tab.children = children
for i in range(len(children)):
 tab.set_title(i, str(i))
tab

安装方法

# pip
pip install ipywidgets
jupyter nbextension enable --py widgetsnbextension
# Conda
conda install -c conda-forge ipywidgets
#Installing ipywidgets with conda automatically enables the extension

使用“interact”功能自动创建UI控件,这是使用IPython最方便的方法。

# Start with some imports!
from ipywidgets import interact
import ipywidgets as widgets

1.5 放PPT

人在江湖飘,难免遇到要做PPT的时候。

但是,如果你的内容都已经放在Jupyter里了,再重新导入PPT,太麻烦了,我们自动转换吧。

一种方法是用Jupyter内置的PPT选项,依次点击菜单栏里的View → Cell Toolbar → Slideshow,之后每个单元格上面都会有一个灰色的横条,选Sub-Slide。 然后输入以下代码:

jupyter nbconvert *.ipynb --to slides --post serve
# insert your notebook name instead of *.ipynb

你也可以提前换好主题,比如onedork主题,然后再转换成PPT的的时候就是同一个主题风格的PPT了。

不过,用PyTorch默认方法生成的PPT代码不能编辑,这个时候就要用到RISE插件了。

RISE用到reveal.js来运行PPT,可以不退出PPT,直接运行代码。

先来安装RISE,

pip install RISE

然后调用JS和CSS:

jupyter-nbextension install rise --py --sys-prefix
#enable the nbextension:
jupyter-nbextension enable rise --py --sys-prefix

安装好啦,现在重新打开你的Jupyter Notebook,发现一个新的扩展,名叫“Enter/Exit RISE Slideshow”。戳一下,一个可以边演示边改的PPT就好了。

1.6 嵌入链接和pdf

扔链接再跳转实在是太麻烦了,不如直接把素材放进Jupyter里面。

1.6.1 嵌入链接

#Note that http urls will not be displayed. Only https are allowed inside the Iframe
from IPython.display import IFrame
IFrame('https://en.wikipedia.org/wiki/HTTPS', width=800, height=450)

操作方式如下,当然你需要把链接换成你要放的链接:

from IPython.display import IFrame
IFrame('https://www.astrondog.com', width=800, heigh=450)

1.6.2 嵌入pdf

from IPython.display import IFrame
IFrame('https://arxiv.org/pdf/1406.2661.pdf', width=800, height=450)

1.7 图片

1.7.1 输出矢量图

import matplotlib
import matplotlib.pyplot as plt
%matplotlib inline
%config InlineBackend.figure_format = 'svg'

1.7.2 指定文件名后缀pdf或eps保存

plt.savefig('tmp.pdf', bbox_inches='tight')
plt.show()

1.7.3 图片插入

方法1:(MarkDown模式下)(不能改变大小)(只能居中)

title

方法2:(MarkDown模式下)(不能改变大小)(可居中)(推荐)

img

方法3:(Code模式下)(不能改变大小)(不可居中)

from IPython.display import Image
Image(filename = 'https://github.com/AstronDog/blog-pic/raw/master/logo.png', width=100, height=60)

方法4:(Code模式下)(不能改变大小)(不可居中)

%%html
<img src='./logo.png', width=100, height=60>

img

1.8 魔法命令 Magic Command

magic函数主要包含两大类,一类是行魔法(Line magic)前缀为%,一类是单元魔法(Cell magic)前缀为%%; 行魔法只对命令所在的行有效,而单元魔法则必须出现在单元的第一行,对整个单元的代码进行处理。

%lsmagic #打印当前可以用的魔法命令,当我们想使用一个魔法命令,而不知怎么拼写函数名时,可以使用%lsmagic来查询;

1.8.1 使用%lsmagic查看所有的魔法命令

%lsmagic
Available line magics:
%alias  %alias_magic  %autocall  %automagic  %autosave  %bookmark  %cat  %cd  %clear  %colors  %config  %connect_info  %cp  %debug  %dhist  %dirs  %doctest_mode  %ed  %edit  %env  %gui  %hist  %history  %killbgscripts  %ldir  %less  %lf  %lk  %ll  %load  %load_ext  %loadpy  %logoff  %logon  %logstart  %logstate  %logstop  %ls  %lsmagic  %lx  %macro  %magic  %man  %matplotlib  %mkdir  %more  %mv  %notebook  %page  %pastebin  %pdb  %pdef  %pdoc  %pfile  %pinfo  %pinfo2  %popd  %pprint  %precision  %profile  %prun  %psearch  %psource  %pushd  %pwd  %pycat  %pylab  %qtconsole  %quickref  %recall  %rehashx  %reload_ext  %rep  %rerun  %reset  %reset_selective  %rm  %rmdir  %run  %save  %sc  %set_env  %store  %sx  %system  %tb  %time  %timeit  %unalias  %unload_ext  %who  %who_ls  %whos  %xdel  %xmode

Available cell magics:
%%!  %%HTML  %%SVG  %%bash  %%capture  %%debug  %%file  %%html  %%javascript  %%js  %%latex  %%perl  %%prun  %%pypy  %%python  %%python2  %%python3  %%ruby  %%script  %%sh  %%svg  %%sx  %%system  %%time  %%timeit  %%writefile

Automagic is ON, % prefix IS NOT needed for line magics.

1.8.2 使用%magic查看各个命令的说明

%magic

1.8.3 查看具体命令的说明,可以通过在命令后添加?, 如:

%alias?

1.8.4 常用的命令总结

1.8.4.1 %matplotlib inline :将matplotlib画出的图直接显示在Notebook之中,不以单独窗口显示

%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
plt.plot(np.arange(10))

1.8.4.2 %timeit %%timeit #为代码执行计时

import numpy as np
%timeit np.sin(24)
The slowest run took 31.04 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 737 ns per loop
%%timeit
x=np.sin(20)
np.cos(-x)
The slowest run took 42.58 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 1.65 µs per loop

1.8.4.3 %%writefile #后面紧接着一个file_name.py,表示在jupyter notebook里面创建一个py文件,后面cell里面的内容为py文件内容

%%writefile test_peace.py
import numpy as np
print(np.random.randint(1,5))
Writing test_peace.py

在当前路径下会生成一个test_peace.py的文件,内容就是cell里面的内容

1.8.4.4 %run #后面紧接着一个相对地址的file_name.py,表示运行一个py文件

%run test_peace.py

Author: Jun Wang
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source Jun Wang !