27個Jupyter Notebook使用技巧及快捷鍵(翻譯版)


Jupyter Notebook

  Jupyter Notebook 以前被稱為IPython notebook。Jupyter Notebook是一款能集各種分析包括代碼、圖片、注釋、公式及自己畫的圖一體的靈活工具。

  Jupyter 具有可擴展性。它支持多種語言,能容易的部署到自己的計算機或遠程服務器上。用戶只要通過ssh或http就能訪問遠程的Jupyter。更贊的是Jupyter完全免費。

Jupyter接口

1 快捷鍵

  正如大神所知,使用快捷鍵能省很多時間。在菜單Help→Keyboard Shortcuts中向用戶展示很多快捷鍵。每次升級Jupyter時都需要看下該菜單,因為升級的同時會增加很多快捷鍵。

     訪問並快速學習快捷鍵的另一種方式是使用命令面板:Cmd+Shift+P或Ctrl+Shift+P,后者在Linux和Windows系統都適用。在不知道某個動作的快捷鍵或該動作沒有快捷鍵時,你可以使用這個對話框通過名稱來運行任何命令。

     該功能類似在Mac上的Spotlight搜索。一旦開始使用就會停不下來。

命令面板

  作者喜歡的快捷鍵:

  •  Esc+F:查找並替換代碼但不包括輸出內容。
  • Esc+0:切換輸出單元。
  • 選擇多個單元:
    •      Shift+J 或Shift+Down:向下選擇單元格。
    • Shift+K或Shift+Up:向上選擇單元格
  • 選定單元格之后,可以同時刪除、復制、剪切、粘貼及運行這些單元格。在需要移動notebook中部分內容時,該功能很有用。
    • Shit+M:合並多個單元格。

 

 

    2 優雅的展示變量信息

  第一部分內容很多人都知道。當一個Jupyter以一個變量的名字結束或未分配輸出語句時,Jupyter會自動展示變量的內容而無需使用print 語句。當使用Pandas的DataFrames時,該功能很有用。因為Jupyter會把結果以表格形式輸出。

         知道的人不是很多的是可以通過修改kernel選項ast_note_interactivity的值使Jupyter自動展示變量及語句的輸出。這樣你就可以很方便的查看多條語句的輸出內容。

In [1]:

from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all" 

In [2]:

from pydataset import data

quakes = data('quakes')

quakes.head()

quakes.tail()

Out[2]:

 

lat

long

depth

mag

stations

1

-20.42

181.62

562

4.8

41

2

-20.62

181.03

650

4.2

15

3

-26.00

184.10

42

5.4

43

4

-17.97

181.66

626

4.1

19

5

-20.42

181.96

649

4.0

11

Out[2]:

 

lat

long

depth

mag

stations

996

-25.93

179.54

470

4.4

22

997

-12.28

167.06

248

4.7

35

998

-20.13

184.20

244

4.5

34

999

-17.40

187.80

40

4.5

14

1000

-21.59

170.56

165

6.0

119

 

 

  如果你想讓所有Jupyter的工具(Notebook 和Console)都有該功能,可以創建一個文件:~/.ipython/profile_default/ipython_config.py,文件的內容如下:

c = get_config()

#Run all nodes interactively

c.InteractiveShell.ast_node_interactivity = "all"

  

3 輕松連接到幫助文檔

  點擊help菜單,你會輕松地找到NumPython,Pandas,Scipy和Matplotlib的oneline document鏈接。

  不要忘記庫、方法和變量是以’?’什么開頭的。你可以通過Docstring來快速訪問相關語法.

In [3]:
?str.replace()
 
Docstring:
S.replace(old, new[, count]) -> str

Return a copy of S with all occurrences of substring
old replaced by new.  If the optional argument count is
given, only the first count occurrences are replaced.
Type:      method_descriptor

4 在notebooks中畫圖

有很多包都可以在notebook中畫圖。

  • matplotlib:(標准庫),使用%matplotlib inline激活.
  • -%matplotlib notebook:該命令也能提供交互但由於在服務器端做渲染所以比較慢。
  • -mpld3:使用d3給matplotlib代碼做渲染。雖然不完整,但很漂亮。
  • -bokeh:做交互圖像的很好選擇。
  • -plot.ly:能產生很漂亮的圖形但是收費。

 

 

5 Jupyter的魔法命令

  上面提到的%matplotlib inline只是Jupyter魔法命令的一個例子。

In [53]:

# This will list all magic commands

%lsmagic

  

Out[53]:

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

作者推薦查看文檔the documentation for all Jupyter magic commands ,在該文檔中總能找到你想查的。作者比較喜歡的語法糖如下所示:

6 Jupyter語法糖: -%env:設置環境變量

  可以在不啟動Jupyter server進程的情況下管理notebook的環境變量。一些包如theano用環境變量來控制行為。此時,%env就很方便。

In [55]:

# Running %env without any arguments

# lists all environment variables

# The line below sets the environment

# variable OMP_NUM_THREADS

%env OMP_NUM_THREADS=4

env: OMP_NUM_THREADS=4

7 Jupyter語法糖:-%run:執行Python代碼

  %run可以運行.py文件。鮮為人知的是,該語法糖也可以執行其他的Jupyter notebooks。這非常有用。

  注意:用%run和import 一個包不是一回事。

In [56]:

# this will execute and show the output from

# all code cells of the specified notebook

%run ./two-histograms.ipynb

  

8 Jupyter語法糖:-%:load:從外部腳本插入代碼

In [ ]:

# Before Running

%load ./hello_world.py

In [61]:

# After Running

# %load ./hello_world.py

if __name__ == "__main__":

        print("Hello World!")

Hello World!

  

9 Jupyter語法糖: -%store:在不同的notebooks之間傳遞變量

  %store命令可以在兩個不同的notebooks之間傳遞變量。

In [62]:

data = 'this is the string I want to pass to different notebook'

%store data

del data # This has deleted the variable 

Stored 'data' (str)

Now, in a new notebook…

In [1]:

%store -r data

print(data)

this is the string I want to pass to different notebook

  

10 Jupyter語法糖  -%who:列出所有的全局變量

%who命令在沒有參數的情況下能列出目前存在的所有全局變量。如果使用一個參數例如str,則只會列出對應類型的變量。

 

In [1]:

one = "for the money"

two = "for the show"

three = "to get ready now go cat go"

%who str

 

one three two   

  

11 Jupyter語法糖——Timing

  對timing很有用的有兩個語法糖:%%time和%timeit。當一些代碼很慢且有想知道哪些地方慢時這兩個語法糖很有用。

  %%time展示單元格中代碼單次運行信息。

In [4]:

%%time

import time

for _ in range(1000):

    time.sleep(0.01)# sleep for 0.01 seconds

 

CPU times: user 21.5 ms, sys: 14.8 ms, total: 36.3 ms

Wall time: 11.6 s

  

  %%timeit使用Python的timeit包。該命令默認運行代碼100,000次,求最快三次的均值。

In [3]:

import numpy

%timeit numpy.random.normal(size=100)

 

The slowest run took 7.29 times longer than the fastest. This could mean that an intermediate result is being cached.

100000 loops, best of 3: 5.5 µs per loop

  

12 Jupyter語法糖—%%writefile和%pycat:導出單元格內容/展示外部腳本內容

  使用語法糖%%writefile保存單元格內容到外部文件。%pycat正好相反,該命令高亮展示外部文件內容。

%%writefile pythoncode.py

 

import numpy

def append_if_not_exists(arr, x):

    if x not in arr:

        arr.append(x)

       

def some_useless_slow_function():

    arr = list()

    for i in range(10000):

        x = numpy.random.randint(0, 10000)

        append_if_not_exists(arr, x)

 

Writing pythoncode.py

In [8]:

%pycat pythoncode.py

 

import numpy

def append_if_not_exists(arr, x):

    if x not in arr:

        arr.append(x)

       

def some_useless_slow_function():

    arr = list()

    for i in range(10000):

        x = numpy.random.randint(0, 10000)

        append_if_not_exists(arr, x)

  

13 語法糖—%prun:展示程序中每個函數耗費的時間

  使用%run statement_name將以有序表展示代碼中每個內部函數被調用次數,每次調用花費的時間及運行耗費的總時間。

 

 1 %prun some_useless_slow_function()
 2 
 3  
 4 
 5          26324 function calls in 0.556 seconds
 6 
 7  
 8 
 9    Ordered by: internal time
10 
11  
12 
13    ncalls  tottime  percall  cumtime  percall filename:lineno(function)
14 
15     10000    0.527    0.000    0.528    0.000 <ipython-input-46-b52343f1a2d5>:2(append_if_not_exists)
16 
17     10000    0.022    0.000    0.022    0.000 {method 'randint' of 'mtrand.RandomState' objects}
18 
19         1    0.006    0.006    0.556    0.556 <ipython-input-46-b52343f1a2d5>:6(some_useless_slow_function)
20 
21      6320    0.001    0.000    0.001    0.000 {method 'append' of 'list' objects}
22 
23         1    0.000    0.000    0.556    0.556 <string>:1(<module>)
24 
25         1    0.000    0.000    0.556    0.556 {built-in method exec}
26 
27         1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
28 
29  

14 Jupyter語法糖—%pdb

  Jupyter有自己的調試接口The Python Debugger (pdb). 。調試能進入函數內部並判斷函數內部發生事項。

  在這里看pdb可使用的命令列表:pdb 

In [ ]:
%pdb

def pick_and_take():
    picked = numpy.random.randint(0, 1000)
    raise NotImplementedError()
    
pick_and_take()
 
Automatic pdb calling has been turned ON
 
---------------------------------------------------------------------------
NotImplementedError                       Traceback (most recent call last)
<ipython-input-24-0f6b26649b2e> in <module>()
      5     raise NotImplementedError()
      6 
----> 7 pick_and_take()

<ipython-input-24-0f6b26649b2e> in pick_and_take()
      3 def pick_and_take():
      4     picked = numpy.random.randint(0, 1000)
----> 5     raise NotImplementedError()
      6 
      7 pick_and_take()

NotImplementedError: 
 
> <ipython-input-24-0f6b26649b2e>(5)pick_and_take()
      3 def pick_and_take():
      4     picked = numpy.random.randint(0, 1000)
----> 5     raise NotImplementedError()
      6 
      7 pick_and_take()

15 壓縮最后一行函數的輸出

  有時抑制最后一行代碼的函數輸出很有必要且方便:只需要在代碼末尾價格分號。例如畫圖。

In [4]:

%matplotlib inline

from matplotlib import pyplot as plt

import numpy

x = numpy.linspace(0, 1, 1000)**1.5

In [5]:

# Here you get the output of the function

plt.hist(x)

Out[5]:

(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. ]),

 <a list of 10 Patch objects>)

 

In [6]:

# By adding a semicolon at the end, the output is suppressed.

plt.hist(x);

 

16 執行shell命令

  在notebook中執行shell命令很簡單。可通過在notebook中執行shell命令檢查當前文件夾中包含哪些數據集。

In [7]:

!ls *.csv

nba_2016.csv             titanic.csv

pixar_movies.csv         whitehouse_employees.csv

Or to check and manage packages.

In [8]:

!pip install numpy

!pip list | grep pandas

 
Requirement already satisfied (use --upgrade to upgrade): numpy in /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages

pandas (0.18.1)

17 使用LaTeX寫公式

  當在Markdown單元格中寫LaTeX時,會使用MathJax展示成公式。

This:

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

顯示形式如下:

P(A∣B)=P(B∣A)P(A)P(B)P(A∣B)=P(B∣A)P(A)P(B)

Markdown是notebooks重要的一部分,記得要用它。

18 在notebook中運行使用不同kernel的代碼

  如果願意,可以把使用不同kernels的代碼放在一個notebook中。

  只需要在每個單元格的開頭使用Jupyter語法糖加上相應kernel的名稱。

  • %%bash
  • %%HTML
  • %%python2
  • %%python3
  • %%ruby
  • %%perl
In [6]:
%%bash
for i in {1..5}
do
   echo "i is $i"
done
 
i is 1
i is 2
i is 3
i is 4
i is 5

19 為Jupyter安裝其他的kernels

  能運行不同的語言是Jupyter很好的一個特性。下面為如何運行R kernel的例子。

  •  簡安裝:使用Anaconda安裝R kernel

        如果用Anaconda啟動環境,運行R很簡單。只需要在終端運行下面的代碼:

conda install –c  r r-essentials
  • 非簡安裝:手動安裝R kernel

  如果你不用Anaconda,安裝過程稍微復雜。你如果沒安裝R,首先需要安裝R。

  安裝后,啟動R界面並運行下面的代碼:

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

20 在同一個notebook中運行R和Python

  最好的解決方案是安裝rpy2:可以通過pip install rpy2安裝。

  安裝后就可以同時使用兩種語言,並可以在兩種語言之間傳遞變量。

In [1]:

%load_ext rpy2.ipython

In [2]:

%R require(ggplot2)

Out[2]:

array([1], dtype=int32)

In [3]:

import pandas as pd

df = pd.DataFrame({

        'Letter': ['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c'],

        'X': [4, 3, 5, 2, 1, 7, 7, 5, 9],

        'Y': [0, 4, 3, 6, 7, 10, 11, 9, 13],

        'Z': [1, 2, 3, 1, 2, 3, 1, 2, 3]

    })

In [4]:

%%R -i df

ggplot(data = df) + geom_point(aes(x = X, y= Y, color = Letter, size = Z))

21 使用其他語言寫函數

  有時候numpy的速度比較慢,需要寫效率更高的代碼。原則上,可以在動態包中編譯代碼和寫Python wrappers.

  如果這些枯燥的部門有人幫你做是不是很好?

  可以在cpython中寫fortran代碼並直接在Python代碼中使用。

  首先需要安裝:

!pip install cython fortran-magic

In [ ]:

%load_ext Cython

In [ ]:

%%cython

def myltiply_by_2(float x):

    return 2.0 * x

In [ ]:

myltiply_by_2(23.)

Personally I prefer to use fortran, which I found very convenient for writing number-crunching functions. More details of usage can be found here.

In [ ]:

%load_ext fortranmagic

In [ ]:

%%fortran

subroutine compute_fortran(x, y, z)

    real, intent(in) :: x(:), y(:)

    real, intent(out) :: z(size(x, 1))

    z = sin(x + y)

end subroutine compute_fortran

In [ ]:

compute_fortran([1, 2, 3], [4, 5, 6])

22. Multicursor support

Jupyter支持多種cursors,類似Sublime text.按下Alt鍵拖動鼠標。

23 Jupyter-contrib extensions

Jupyter-contrib extensions是一個家族,該家族使Jupyter功能更強大,例如jupyter shell-checker 和code-formatter。

下面的命令會安裝extensions,

The following commands will install the extensions, as well as a menu based configurator that will help you browse and enable the extensions from the main Jupyter notebook screen.

!pip install https://github.com/ipython-contrib/jupyter_contrib_nbextensions/tarball/master

!pip install jupyter_nbextensions_configurator

!jupyter contrib nbextension install --user

!jupyter nbextensions_configurator enable --user

24 根據Jupyter notebook創建演示用文檔

  使用Damian Avila的RISE能根據現存的notebook創建PowerPoint形式的演示文檔。

  可以使用conda安裝RISE:

conda install -c damianavila82 rise

或者使用pip:

pip install RISE

通過下面的代碼安裝entension並使其生效:

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

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

25 Jupyter輸出系統

  notebook以HTML的形式展示,單元格中的內容也可以輸出成HTML。因此幾乎可以輸出任何內容:video/audio/images

  下面的例子瀏覽文件夾中的所有圖像,並展示前5個的粗略圖。

 

通過bash命令也可以創建同樣的List,因為語法糖和bash命令偶讀返回Python變量。

In [10]:
names = !ls ../images/ml_demonstrations/*.png
names[:5]
Out[10]:
['../images/ml_demonstrations/colah_embeddings.png',
 '../images/ml_demonstrations/convnetjs.png',
 '../images/ml_demonstrations/decision_tree.png',
 '../images/ml_demonstrations/decision_tree_in_course.png',
 '../images/ml_demonstrations/dream_mnist.png']

26 大數據分析

  查詢和處理大數據有很多解決方案:

27 共享notebooks

  共享notebook最簡單的方法是使用notebook文件(.ipynb)。對於不使用Jupyter的人,有下面一些可行辦法:

  •  使用File>Download as >HTML菜單選項把notebook轉換成HTML文件。
  • 通過gists或github分享notebook File。例子。
    • 如果把notebook上傳到notebook,你可以使用mybinder服務允許別人在半個小時內通過Jupyter訪問你的內容。
  • 使用jupyterhub啟動你的系統。在准備課程且沒時間考慮學生的機器性能時使用該功能很方便。
  • 將notebook保存到比如dropbox中,然后將連接放到nbviewer. nbviewer將會渲染你存儲在任何地方的notebook.

 

原文地址:27 Jupyter Notebook tips, tricks and shortcuts

 

 

 

 


免責聲明!

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



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