Jupyter自定義設置詳解


今天專門花時間總結梳理一下jupyter的一些高級設置,jupyter我已經介紹過一次基本內容了,Setup and Linux | James Chen’s Blogs,尤其是如何在服務器運行jupyter並且在本地瀏覽器顯示,簡直是使用python進行機器學習、深度學習、大數據的工作者的巨大福音。作為一個重度python&jupyter使用者,我已經習慣於在jupyter上進行大量的實驗以及一次性的小工作、作業,需要跑很久的代碼才會在運行通過后用VSCode編輯一下提交上去跑。用jupyter寫了很多腳本,尤其適合可視化、展示和教學。可以在我的GitHub找到很多用jupyter寫的代碼,事實上很多教程和實驗大家也都習慣於jupyter做了,比如我在這篇Deep Learning Practice介紹的資源中就有大量用jupyter寫的。

下面就講一下jupyter的一些高級玩法。

自定義主題

https://github.com/dunovank/jupyter-themes
Markdown

jupyter extension

相見恨晚,用着非常非常爽,強烈推薦
https://github.com/ipython-contrib/jupyter_contrib_nbextensions

1
2
3
4
pip install jupyter_contrib_nbextensions
jupyter contrib nbextension install --user
pip3 install jupyter_contrib_nbextensions
jupyter contrib nbextension install --user

推薦使用的插件

table of contents

設置着很簡單,找到后打個對勾就行了,效果很棒
Markdown

jupyter支持markdown,只需要將某個代碼框選為markdown格式,使用table of contents插件,就會自動在左邊欄生成目錄。對於寫的很長的代碼,可以幫助整理思路,快速定位代碼。大家用jupyter一般是做前期的各種各樣的實驗,思路可能比較發散,所以用table of contents可以幫忙梳理思路,也方便以后再尋找、理解代碼

freeze

可以“冰凍”某個代碼塊,有個代碼塊兒暫時不再使用,就可以暫時冰凍,這樣就無法運行,也不會被誤刪除。是個很有用的功能。
Markdown

highlighter

可以高亮注釋
Markdown

Gist-it

Adds a button to publish the current notebook as a gist

Snippets menu

幫助懶人插入一些經典庫的經典方法的代碼塊,感覺很不錯哦,比去Stack Overflow搜要快一些~不過支持的還是比較少的。
Markdown

Snippet:

強烈強烈推薦!感覺有望幫助節約不少寫代碼的時間

Markdown

This extension adds a drop-down menu to the IPython toolbar that allows easy insertion of code snippet cells into the current notebook. The code snippets are defined in a JSON file in nbextensions/snippets/snippets.json and an example snippet is included with this extension

Snippets are specified by adding a new JSON block to the list of existing snippets in $(jupyter —data-dir)/nbextensions/snippets/snippets.json. (I put my customized json file in jupyter-notebooks directory in /Users/james/) For example, to add a new snippet that imports numpy, matplotlib, and a print statement, the JSON file should be modified。

先分別列一下各種情景下需要導入哪些庫:

Basic science
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import argparse, sys, os, errno
%pylab inline
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('ggplot')
import seaborn as sns
import h5py
import os
from tqdm import tqdm
import scipy
import sklearn
from scipy.stats import pearsonr
import warnings
warnings.filterwarnings('ignore')
Highlevel plot
1
2
3
4
5
6
7
8
import matplotlib.animation as animation
from matplotlib import rc
from IPython.display import HTML, Image
rc('animation', html='html5')
import plotly
import plotly.offline as off
import plotly.plotly as py
import plotly.graph_objs as go
Deeplearning keras
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import keras
from keras import backend as K
from keras.callbacks import TensorBoard
from keras.callbacks import EarlyStopping
from keras.optimizers import Adam
from keras.callbacks import ModelCheckpoint
import tensorflow as tf
from keras.models import Model
from keras.layers import Input, Conv2D, MaxPooling2D, UpSampling2D,Lambda, Dot,average,add, concatenate
from keras.layers.normalization import BatchNormalization
from keras.layers.core import Dropout, Activation,Reshape
from keras.layers.merge import concatenate
from keras.callbacks import TensorBoard, EarlyStopping, ModelCheckpoint
from keras.initializers import RandomNormal
import os
os.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID'
os.environ['CUDA_VISIBLE_DEVICES'] = '4'
from keras.backend.tensorflow_backend import set_session
config = tf.ConfigProto()
config.gpu_options.per_process_gpu_memory_fraction = 0.99
(tf.Session(config=config))
Pytorch
1
2
3
4
import torch
import math
import torch.nn as nn
import torch.nn.functional as F

總結起來就是下面這樣,注意語法別錯,東西一多看着還是很頭疼的,配置好就可以用了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
大專欄  Jupyter自定義設置詳解e">40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
{
"snippets" : [
{
"name" : "science basic",
"code" : [
"import argparse, sys, os, errno",
"%pylab inline",
"import numpy as np",
"import pandas as pd",
"import matplotlib.pyplot as plt",
"plt.style.use('ggplot')",
"import seaborn as sns",
"import h5py",
"import os",
"from tqdm import tqdm",
"import scipy",
"import sklearn",
"from scipy.stats import pearsonr",
"import warnings",
"warnings.filterwarnings('ignore')"
]
},
{
"name" : "high level plot",
"code" : [
"import matplotlib.animation as animation",
"from matplotlib import rc",
"from IPython.display import HTML, Image",
"rc('animation', html='html5')",
"import plotly",
"import plotly.offline as off",
"import plotly.plotly as py",
"import plotly.graph_objs as go"
]
},
{
"name" : "deep learning",
"code" : [
"import keras",
"from keras import backend as K",
"from keras.callbacks import TensorBoard",
"from keras.callbacks import EarlyStopping",
"from keras.optimizers import Adam",
"from keras.callbacks import ModelCheckpoint",
"import tensorflow as tf",
"from keras.models import Model",
"from keras.layers import Input, Conv2D, MaxPooling2D, UpSampling2D,Lambda, Dot,average,add, concatenate",
"from keras.layers.normalization import BatchNormalization",
"from keras.layers.core import Dropout, Activation,Reshape",
"from keras.layers.merge import concatenate",
"from keras.callbacks import TensorBoard, EarlyStopping, ModelCheckpoint",
"from keras.initializers import RandomNormal",
"import os",
"os.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID'",
"os.environ['CUDA_VISIBLE_DEVICES'] = '4'",
"from keras.backend.tensorflow_backend import set_session",
"config = tf.ConfigProto()",
"config.gpu_options.per_process_gpu_memory_fraction = 0.99",
"set_session(tf.Session(config=config))"
]
},
{
"name" : "pytorch",
"code" : [
"import torch",
"import math",
"import torch.nn as nn",
"import torch.nn.functional as F"
]
}
]
}

這個配置這里坑了我很久,主要是snippets不會顯示錯誤信息,debug得很仔細一個一個找,因此花了很久發現是keras部分的幾個破雙引號沖突了,還有一個注釋竟然也忘刪了,折騰了很久才配置好。用sublime text是可以很容易發現語法錯誤的,可惜最開始沒在意

本地的snippets.json在:

1
/Users/james/Library/Jupyter/nbextensions/snippets/snippets.json

我在james目錄下也放了一份,因為最近估計需要不斷更新完善,所以就放一份在:

1
/Users/james/snippets.json

每次修改后,需要同步到本地以及ibme、cnode、hpc1幾個機器上面,這樣不用我幾個地方都各自改一遍,費事。

首先找到各個機器上的json文件在哪兒

1
$(jupyter --data-dir)/nbextensions/snippets/snippets.json

然后寫個同步的腳本syncsnip.sh

1
2
3
4
cp /Users/james/snippets.json /Users/james/Library/Jupyter/nbextensions/snippets/snippets.json
rsync -avzh /Users/james/snippets.json ibme:/Share/home/chenxupeng/.local/share/jupyter/nbextensions/snippets/
rsync -avzh /Users/james/snippets.json cnode:/home/chenxupeng/.local/share/jupyter/nbextensions/snippets/snippets.json
rsync -avzh /Users/james/snippets.json hpc1:/home/chenxupeng/.local/share/jupyter/nbextensions/snippets/

然后做個同步快捷方式:

1
alias snip='bash syncsnip.sh'

測試幾個機器的配置均通過

配置好了還是很美的:

Markdown

jupyter dashboard
看起來是可以進一步幫助展示的利器

1
2
3
4
pip install jupyter_dashboards
jupyter dashboards quick-setup --sys-prefix
jupyter nbextension install --py jupyter_dashboards --sys-prefix
jupyter nbextension enable --py jupyter_dashboards --sys-prefix

不過用了一下,過分自動化的布局反而限制的比較死,,不太好看

hide input

不顯示code,只顯示output,適合展示時用。

ipywidgets interactive coding

使用專為jupyter設計的ipywidgets,可以更好地展示、調整代碼,尤其適合運行較快、有較多參數需要探索、選取的場合,比如繪圖

以使用python的seaborn繪制boxplot為例,我們有多個參數待選,比如:

  • context & style 可以設置不同的背景和字體風格
  • width & height 設置圖片的寬和高
  • boxplot/violinplot 使用傳統的box表示還是用可以同時表示點的分布密度的violinplot表示
  • showdot & showbox 可以選擇是否顯示點,以及是否顯示box,或者同時都顯示、都不顯示
  • fondsize & dotsize,分別調整文字大小和點的大小
  • boxwidth 調整box和violin的寬度
  • ylim 調整縱坐標的最大與最小值
  • compareheight* 調整幾個注釋文字距離box頂點的高度
  • palettesind 選擇第幾套配色方案
  • saturation 調整色彩飽和度

可以看到python的繪圖函數一般都留有很大的調整空間,可選參數較多,可以組合出很多效果,但是也給調整帶來了很多麻煩。如果把這些參數都傳入繪圖函數中,每次調整其中的一個或幾個,依照經驗來調整,效率就比較低。這個時候就可以考慮使用ipywidgets方便地調整這些參數。通過ipywidgets,可以把這些控制浮點型、整型或字符串控制參數用Float、Int slider、Dropdown,RadioButtion等控制,不需要每次更改參數再運行代碼框,可以快速地調整出自己想要的圖像。

效果如下:

Markdown

一份示例代碼plots_roc.ipynb放在了something more


免責聲明!

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



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