27 個Jupyter Notebook的小提示與技巧


Jupyter notebook, 前身是 IPython notebook, 它是一個非常靈活的工具,有助於幫助你構建很多可讀的分析,你可以在里面同時保留代碼,圖片,評論,公式和繪制的圖像。

screenshot

Jupyter具有非常強的可擴展性,支持很多編程語言,並且易於部署到你的個人電腦和幾乎所有的服務器上 -- 你只需要使用ssh或http接入即可。最重要的是,它完全免費。

Jupyter默認設置使用 Python kernel,正因此以前叫做 IPython notebook. Jupyter notebook 源自於 Jupyter 項目, Jupyter這個名字是它被設計所支持三個核心編程語言的縮寫詞:JUlia,PYThon, 和 R, 啟發自木星這個詞:Jupiter.

接下來的內容將向你展示27個讓 Jupyter 用的更加舒心的建議與技巧。

1. Keyboard Shortcuts

每一個進階用戶都知道,鍵盤快捷鍵將會為我們節省許多時間。Jupyter在頂部的菜單里保留了許多快捷鍵:Help > keyboard Shortcuts. 每次更新Jupyter時,都值得再次進行查看,因為新的快捷鍵總是不斷被添加進來。

另一個查看快捷鍵的方式是使用命令面板:Cmd + Shift + P(或者Linux和Windows上 Ctrl + Shift + P)。這個對話框將會幫助你通過名稱運行任何命令 -- 這非常有用,尤其當你不知道一個命令的快捷鍵或者你想要執行的命令沒有快捷鍵時。這個功能非常類似與Mac上的Spotlight搜索,一旦你開始使用這個功能,你就會發現沒有它的日子該怎么辦!

command_pannel

這里是一些我喜歡的快捷鍵:

  • Esc + F 查找和替換你的代碼,但不包括代碼的輸出內容。

  • Esc + o 打開代碼塊輸出。

  • 選擇多個 cell。 Shift + JShift + Down 向下選中下一個cell. 你可以通過 Shift + KShift + Up 向上選中 cell。(譯者:jk,與vim的移動方式一致)

    • 一旦 cell 被選中,接着你可以進行批量刪除/復制/剪切/粘貼.當你需要移動一部分notebook時,這非常有用。

    • 你也可以執行 Shift + M (譯者:m記為merge)對多個cell進行合並。

      merge

2. Pretty Display of Varibles

這部分內容可能很多人都知道。如果對帶有一個變量或是未賦值語句的cell執行操作,Jupyter 將會自動打印該變量而無需一個輸出語句。這非常有用,尤其是使用 Pandas DataFrames 進行處理時,因為輸出將會被整齊地格式化為一個表格。

接下來的內容可能沒那么人知道:你可以選擇修改 ast_note_iteractively kernal 選項來使得 Jupyter 為每一行的變量或語句執行這個操作,以便你可以立即看到多條語句一起輸出。

 
line1 = "this is from line 1" line2 = "this is from line 2" line1 line2 
 
'this is from line 2'
 
from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = "all" 
 
line1
line2 
 
'this is from line 1'
'this is from line 2'

如果你想要所有的Jupyter實例(Notebook和Console)都設置該選項,只需創建 ~/.ipython/profile_default/ipython_config.py 文件並寫入一下內容:

c = get_config() # Run all nodes interactively c.InteractiveShell.ast_node_interactivity = "all" 

Help 菜單你可以找到一些常用庫文檔的連接,包括 NumPy, Pandas, SciPy 和 Matplotlib.

同時別忘了在一個庫,方法或變量前加上 ?,你可以獲得它的一個快速語法說明。

 
?sum() 

4. Plotting in notebooks

在 notebook 中生成繪圖有許多選項:

  • matplotlib, 使用%matplotlib inline進行激活。

  • %matplotlib notebook提供了一些交互性,不過可能會有點慢,因為渲染由服務器端完成。

  • mpld3為matplotlib代碼提供了另一個渲染器(使用d3)。非常漂亮,不過尚不完備還有待發展。

  • bokeh是構建交互性繪圖的一個更好的選擇。

  • plot.ly也可以生成漂亮的繪圖,不過是付費服務。

5. Jupyter Magic Commands

上面的 %matplotlib inline 就是一個所謂的 Jupyter Magic (Jupyter魔法)命令。

 
%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.

推薦閱讀the documentation for all Jupyter magic commands,你會發現這非常有用。下面是一些我所喜愛的魔法命令:

6. Jupyter Magic - %env:Set Environment Variables

你可以管理notebook的環境變量而無需重啟jupyter server. 一些庫(比如theano)使用環境變量來控制行為,%env是最方便的一個途徑。

 
# 單獨運行 %env 會列出所有環境變量

# 帶參數的話則會設置該變量 比如 OMP_NUM_THREADS=4 %env OMP_NUM_THREADS=4 
 
env: OMP_NUM_THREADS=4

7. Jupyter Magic - %run:Excute python code

%run可以從.py文件執行Python代碼. 更少的人知道的是它也可以執行其他的Jupyter notebook,這也非常有用。

注意使用%run並不等同於導入一個Python模塊.

 
# this will execute and show the output from
# all code cells of the specified notebook %run ./LinearRegression.ipynb 
 
Coefficients: 
 [ 938.23786125]
Residual sum of squares: 2548.07
Variance score: 0.47

8. Jupyter Magic - %load:Insert the code from an external script

這將會使用外部腳本來代替cell的內容。你可以使用本地機器上的文件也可以使用一個URL.

9. Jupyter Magic - %store:Pass variables between notebooks

%store命令可以讓你在兩個不同的notebook間傳遞變量。

10. Jupyter Magic - %who:List all variables of global scope.

不帶參數的%who命令將會列出全局范圍內存在的所有變量。如果傳入參數,比如str,將會列出指定類型的所有變量。

 
%who 
 
FormatCode	 Image	 InteractiveShell	 datasets	 diabetes	 diabetes_X	 diabetes_X_test	 diabetes_X_train	 diabetes_y_test	 
diabetes_y_train	 display	 line1	 line2	 linear_model	 name	 names	 np	 numpy	 
os	 plt	 regr	 time	 x	 

11. Jupyter Magic - Timing

對於計時有兩個十分有用的魔法命令:%%time%timeit. 如果你有些代碼運行地十分緩慢,而你想確定是否問題出在這里,這兩個命令將會非常方便。

  • %%time 將會給出cell的代碼運行一次所花費的時間。
 
%%time import time for _ in range(1000): time.sleep(0.01)# sleep for 0.01 seconds 
 
CPU times: user 196 ms, sys: 21.4 ms, total: 217 ms
Wall time: 11.6 s
  • %timeit 使用Python的timeit模塊,它將會執行一個語句100,000次(默認情況下),然后給出運行最快3次的平均值。
 
import numpy %timeit numpy.random.normal(size=100) 
 
The slowest run took 46.45 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 6.26 µs per loop

12. Jupyter Magic - %%writefile and %pycat:Export the contents of a cell/Show the contents of an external script

使用%%writefile魔法保存cell的內容到一個外部文件。%pycat則剛好相反,並且會向你展示高亮后的外部文件。

13. Jupyter Magic - %prun:Show how much time your program spent in each function

使用%prun statement_name將會產生一個有序表格來展示在該語句中所調用的每個內部函數調用的次數,每次調用的時間與該函數累計運行的時間。

 
%prun print('hello') 
 
hello
 

14. Jupyter Magic - Debugging with %pdb

Jupyter有一個自己的python調試器接口(pdb),這使得我們能夠進入函數內部看看到底發生了什么。

你可以在這里查看pdb的命令列表

15. Suppress the output of a final function

有時候你可能會想要抑制最后一行函數的輸出,比如當我們繪制圖像的時候。為此,你只需加上一個分號即可。

 
%matplotlib inline from matplotlib import pyplot as plt import numpy x = numpy.linspace(0, 1, 1000)**1.5 
 
# Here you get the output of the function
plt.hist(x) 
 
(array([ 216.,  126.,  106.,   95.,   87.,   81.,   77.,   73.,   71.,   68.]),
 array([ 0. ,  0.1,  0.2,  0.3,  0.4,  0.5,  0.6,  0.7,  0.8,  0.9,  1. ]),
 )
 
# By adding a semicolon at the end, the output is suppressed.
plt.hist(x); 
 

16. Executing Shell Commands

在 notebook 中執行 shell 命令非常容易,你可以像下面這樣列出當前目錄下的文件:

!ls
 
!ls
 
JupyterNotebookTips.ipynb      LinearRegression.ipynb
JupyterNotebookTips.ipynb-meta LinearRegression.ipynb-meta

或是檢查或管理包.

 
!pip list | grep pandas 
 
pandas (0.18.1)

17. Using LaTeX for formulas

當你在 markdown cell 中書寫LaTeX時,它會被 MathJax 渲染成一個公式。(譯者:下文中介紹的Jupyter插件中有個插件關於LaTeX,提供了更多LaTeX功能)

$$ P(A \mid B) = \frac{P(B \mid A) \, P(A)}{P(B)} $$

會被渲染成為:

markdown 是 notebook 中十分重要的一部分,別忘了使用它來傳達你的想法!

18. Run code from a different kernel in a notebooks

如果想要的話,你可以將多個 kernel 的代碼組合到一個 notebook 中。

在每個cell的開頭使用相關的魔法命令來聲明你想使用的 kernel:

  • %%bash

  • %%HTML

  • %%python2

  • %%python3

  • %%ruby

  • %%perl

 
%%bash
for i in {1..5} do echo "$i" done 
 
1
2
3
4
5

19. Install other kernels for Jupyter

Jupyter 其中的一個重要特色就是能夠運行不同語言,你只需安裝相關的 kernel 即可。比如,下面的例子是如何安裝 R kernel.

  • 快捷選擇:使用anaconda安裝 R kernel

如果你使用 anaconda 安裝你的環境,這會相當簡單。你只需要在 terminal 中運行下面的命令:

conda install -c r r-essentials
  • 不那么快捷的方式:手動安裝 R kernel

如果你不是使用 anaconda, 這個過程可能稍顯復雜。如果你還沒有安裝的話, 你需要從 CRAN安裝。(譯者: 也可使用 brew cask install r-gui)

安裝 R 完畢后,打開 R console 並運行如下命令:

  1. install.packages(c( 'repr', 'IRdisplay', 'crayon', 'pbdZMQ', 'devtools'))
  2. devtools::install_github( 'IRkernel/IRkernel')
  3. IRkernel::installspec() # to register the kernel in the current R installation

20. Running R and Python in the same notebook

對於此最好的解決方案是安裝 rpy2(需要安裝一個可以工作的 R ), 通過 pip 可以很容易安裝:

pip install rpy2

你可以同時使用這兩種語言,甚至在它們之間傳遞變量:

一個很好的示例 Revolutions Blog

21. Writing functions in other languages

有時候 numpy 的速度仍舊不夠快,我們需要自己寫一些更快的代碼。

原則上,你可以以動態鏈接庫的方式編譯函數,然后用 python 進行包裝。

不過如果有人能夠幫你完成這部分煩人的工作是不是非常棒呢?

你可以用 cython 或 fortran 寫函數並直接從 Python 代碼進行調用。

首先你需要安裝:

pip install cython fortran-magic

個人來說我更喜歡使用 fortran, 我發現它對數值統計函數十分方便。更多用法上的細節可以在這里找到.

也有一些其他方式可以加速你的Python代碼。更多示例可以在這里找到/

22. Multicursor support

Jupyter 支持多光標操作,與 Sublime Text 類似。按住 Alt 進行點擊和拖拽鼠標即可。

multiline

23. Jupyter-contrib extensions

Jupyter-contrib extensions 是一系列能夠給 Jupyter 帶來許多功能的擴展,比如 jupyter spell-checkercode-formatter.

譯者:使用conda安裝是最方便的,更多安裝與使用信息可以看Jupyter-contrib extensions. 啟用插件可以使用jupyter_nbextensions_configurator , 通過打開 http://localhost:8888/nbextensions/ 進行設置,里面有很多實用的插件,具體自行發現。

conda install -c conda-forge jupyter_contrib_nbextensions

nbextensions

24. Create a presentation from a Jupyter notebook

Damian Avila的 RISE 允許你從已有的一個 notebook 創建一個 powerpoint 風格的報告。

你可以通過 conda 安裝 RISE:

conda install -c damianavila82 rise

或通過 pip:

pip install RISE

然后執行下面的代碼安裝並啟用擴展:

jupyter-nbextension install rise --py --sys-prefix
jupyter-nbextension enable rise --py --sys-prefix

25. The Jupyter output system

notebook 以 HTML 的方式進行展示,cell 的輸出也可以是 HTML,所以事實上你可以返回任何東西:視頻/音頻/圖像。

下面的例子我掃描了 images 目錄下的 png 文件,並輸出它們的縮略圖.(譯者:因為當前該目錄下只有兩個 png 文件,所以僅輸出兩個)

 
import os from IPython.display import display, Image names = [f for f in os.listdir('../images/') if f.endswith('.png')] for name in names[:5]: display(Image('../images/' + name, width=100)) 
 

26. 'Big data' analysis

對於大規模數據樣本的查詢/處理也有一些解決方案:

27. Sharing notebooks

分享 notebook 最簡單的方式是直接使用 notebook 文件(.ipynb).不過對於那些不使用 Jupyter 的人來說,你也可以這么做:

  • 使用菜單項 File > Download as > HTML 將 notebook 轉換成 HTML。

  • 使用 gist 或 github 分享 notebook,它們都會對 notebook 進行渲染展示。

    • 如果你上傳 notebook 到一個 github 倉庫,你可以使用十分便利的mybinder服務來允許第三者半小時時間以交互性身份訪問你的倉庫。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM