我們繼續接著上篇文章進行,分享後面的 14 條實用小技巧。
15. IPython Magic - 高解析度的圖形輸出IPython 的魔術命令只需要一行代碼,就可以讓你的圖形輸出在 Retina 屏幕(例如新款的 MacBook)上獲得雙倍的精度。「注意:下面這個例子在非 Retina 的屏幕上不會生效」
x = range(1000)
y = [i ** 2 for i in x]
plt.plot(x,y)
plt.show();%config InlineBackend.figure_format ='retina'
plt.plot(x,y)
plt.show();
16. 抑制函數的輸出內容有時候在最後一行抑制函數的輸出是很方便的,例如在繪圖時。要實現整個目標,你只需要在最後添加一個分號就可以。
%matplotlib inline
from matplotlib import pyplot as plt
import numpy
x = numpy.linspace(0, 1, 1000)**1.5# 這樣執行會得到下面的輸出和圖形。
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. ]),
<a list of 10 Patch objects>)# 通過添加一個分號在後面,就可以抑制這段輸出。
plt.hist(x);
17. 執行 shell 命令從你的 notebook 中執行 shell 命令是很簡單的。你可以直接使用下面的命令去檢查當前文件夾中可用的數據集:
!ls *.csvnba_2016.csv titanic.csv pixar_movies.csv whitehouse_employees.csv或者去檢查和管理包。
!pip install numpy !pip list | grep pandasRequirement already satisfied (use --upgrade to upgrade): numpy in /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages pandas (0.18.1)
18. 使用 LaTeX 編輯公式當你在一個 Markdown 的塊中寫 LaTeX 代碼時,它可以使用 MathJax 渲染成目標公式。
這個:
$P(A \mid B) = \frac{P(B \mid A)P(A)}{P(B)}$將會變成這個:
jupyter-notebook-latexMarkdown 在 notebook 中是很重要的一部分內容,所以不要忘記去使用它豐富的表現能力。
19. 在 notebook 中使用不同的內核運行代碼只要你想,你就可以將不同內核上的代碼結合到一個 notebook 中來。
你只需要在每個代碼的開始處使用 IPython 的魔術命令,命令內容為你想要使用的內核的名稱。
%%bash
for i in {1..5}
do echo "i is $i"
donei is 1
i is 2
i is 3
i is 4
i is 5
20. 為 Jupyter 安裝其它內核Jupyter 有一個非常好的特性就是可以為不同語言運行內核。舉個慄子,下面就是如何去安裝和運行 R 內核。
簡單選項:使用 Anaconda 安裝 R如果你是使用 Anaconda 來管理你的環境,那麼安裝 R 就是很簡單的事情。只需要運行下面的代碼就可以:
conda install -c r r-essentials
複雜選項:手動安裝 R 內核如果你沒有使用 Anaconda,這個過程會略微複雜一點。首先,如果你沒有安裝 R 的話先從 CRAN 中安裝 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
21. 在同一個 notebook 中同時運行 R 和 Python最好的解決方案就是安裝 rpy2(還需要一個 R 的工作版本),具體實現可以用 pip 很輕鬆的完成:
pip install rpy2你可以同時使用兩種語言,甚至在內部傳遞變量:
%load_ext rpy2.ipython%R require(ggplot2)array([1], dtype=int32)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]
})%%R -i df ggplot(data = df) + geom_point(aes(x = X, y= Y, color = Letter, size = Z))實例出處 「Revolutions Blog[1]」
22. 用另外一種語言寫函數有時候 numpy 的速度還是不太夠,我需要去寫一些更快的代碼。
原則上,你可以在動態庫中編譯函數並編寫 python 裝飾器...
但是當這個無聊的部分已經為你完成時,是不是會感覺非常棒?
你可以在 cython 或者 fortran 中寫你的函數,然後直接在 python 代碼中使用它們。
首先,你需要安裝:
!pip install cython fortran-magic%load_ext Cython%%cython
def myltiply_by_2(float x):
return 2.0 * xmyltiply_by_2(23.)我個人比較喜歡使用 fortran,因為當寫一些數字運算的函數時非常方便。更多的fortran使用細節[2]你可以在這裡查閱。
%load_ext fortranmagic%%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_fortrancompute_fortran([1, 2, 3], [4, 5, 6])同樣還有一些其它系統方法可以加速你的 python 代碼。更多的例子點擊這裡查看:加速python細節[3]。
23. 多行光標操作Jupyter 支持多光標操作,類似於 Sublime Text。按下 Alt 鍵的同時,直接點擊並拖動滑鼠選取。
多行光標操作24. Jupyter-contrib extensionsJupyter-contrib extensions[4] 是一個擴展包集合,給 Jupyter 提供了更多的功能,例如包括拼寫檢查和代碼格式。
下面的命令將會安裝擴展包,和一個基於菜單的配置程序,幫助你在 Jupyter 的主屏幕瀏覽和啟動擴展包。
!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
nbextensions 配置程序25. 從 Jupyter notebook 創建一個展示結果Damian Avila 的作品 RISE[5] 可以讓你從已有的 notebook 中創建一個 PPT 風格的展示結果。
你可以使用 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
26. Jupyter 的輸出系統notebook 顯示為 HTML,並且代碼塊的輸出也可以是 HTML,因此你可以在輸出時返回任何結果:視頻/音頻/圖片。
在這個例子中,我掃描了倉庫中包含圖片的一個文件夾,並且展示了前五幅縮略圖:
import os
from IPython.display import display, Image
names = [f for f in os.listdir('../images/ml_demonstrations/') if f.endswith('.png')]
for name in names[:5]:
display(Image('../images/ml_demonstrations/' + name, width=100))我們可以用 bash 命令創建一個同樣的 list,因為魔術命令和 bash 調用返回 python 變量:
names = !ls ../images/ml_demonstrations/*.png names[:5]['../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']
27. 大數據分析有許多方法在查詢/處理大數據時是可用的:
ipyparallel (以前的 ipython 集群)[6] 在處理 python 中的 map-reduce 操作時,是一個很好的選擇。我們在 rep[7] 中使用它並行訓練機器學習模型。28. 分享 notebook分享你的 notebook 最簡單的方法就是使用 notebook 文件(.ipynb),但是對那些不使用 Jupyter 的人來說,你仍然有一些其它選擇:
使用 File > Download as > HTML 菜單選項來將你的 notebook 轉化為 HTML 文件。上傳你的 .ipynb 文件到 Google Colab[10]。以 gists 的形式分享你的 notebook 文件或者上傳到 GitHub,無論哪種方式都可以渲染你的 notebook。看這個 git 分享的例子[11]。如果你選擇將 notebook 上傳到 GitHub 上,你可以使用 mybinder[12] 服務來允許某人有權限訪問你的倉庫。利用 jupyterhub[13] 來設置你自己的系統,當你有一個微課或者講座,但是沒有時間去關注學生的機器狀況時,這是一個很方便的方法。把你的 notebook 保存起來(例如 dropbox),然後把連結放到 nbviewer[14]。無論你保存的主機是什麼,nbviewer 都會渲染你的 notebook。使用 File > Download as > PDF 菜單選項來將你的 notebook 保存為一個 PDF。如果你選擇這種路線,那我強烈建議你閱讀一下這篇 Julius Schulz 的優秀文章:Making publication ready Python notebooks[15]。Reference[1]Revolutions Blog: http://blog.revolutionanalytics.com/2016/01/pipelining-r-python.html
[2]fortran使用細節: http://arogozhnikov.github.io/2015/11/29/using-fortran-from-python.html
[3]加速python細節: http://arogozhnikov.github.io/2015/09/08/SpeedBenchmarks.html
[4]Jupyter-contrib extensions: https://github.com/ipython-contrib/jupyter_contrib_nbextensions
[5]RISE: https://github.com/damianavila/RISE
[6]ipyparallel (以前的 ipython 集群): https://github.com/ipython/ipyparallel
[7]rep: https://github.com/yandex/rep
[8]pyspark: http://www.cloudera.com/documentation/enterprise/5-5-x/topics/spark_ipython.html
[9]%%sql: https://github.com/jupyter-incubator/sparkmagic
[10]Google Colab: https://colab.research.google.com/notebooks/intro.ipynb
[11]git 分享的例子: https://github.com/dataquestio/solutions/blob/master/Mission202Solution.ipynb
[12]mybinder: http://mybinder.org/
[13]jupyterhub: https://github.com/jupyterhub/jupyterhub
[14]nbviewer: http://nbviewer.jupyter.org/
[15]Making publication ready Python notebooks: http://blog.juliusschulz.de/blog/ultimate-ipython-notebook