跟我一起學(xué)scikit-learn03:IPython簡介

IPython是公認(rèn)的現(xiàn)代科學(xué)計算中最重要的python工具之一,它是一個加強(qiáng)版的Python交互式命令行工具,與系統(tǒng)自帶的Python交互環(huán)境相比,IPython具有以下幾個明顯特征:

  • 可以在IPython環(huán)境下直接執(zhí)行Shell命令;
  • 自帶jupyter notebook可視化Web UI,在機(jī)器學(xué)習(xí)、探索數(shù)據(jù)、可視化數(shù)據(jù)、繪制圖形等場景特別有用;
  • 擁有內(nèi)省、Tab補(bǔ)全、魔術(shù)命令等更強(qiáng)大的交互功能。

由于IPython是在Python基礎(chǔ)上的加強(qiáng)和改進(jìn),因此Python支持的操作IPython都能支持,這里只介紹IPython獨有的特性。

(1)IPython輸出排版更簡潔、優(yōu)美

# ipython
Python 3.7.1 (default, Dec 14 2018, 19:28:38)Type 'copyright', 'credits' or 'license' for more informationIPython 7.2.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: import numpy as np
In [2]: data = {i:np.random.randn() for i in range(8)}
In [3]: data
Out[3]:
{0: -0.5766847959613532,
1: 0.07627853416398143,
2: -0.4324362233814661,
3: 0.32576247075662484,
4: -1.743157746859355,
5: -0.19424417929423804,
6: 0.5078689531612759,
7: 0.6473981700412317}

下面是直接使用python輸出的結(jié)果:

# python
>>> import numpy as np
>>> data = {i:np.random.randn() for i in range(8)}
>>> data
{0: -0.9975960400502005, 1: 0.5798703673494191, 2: 1.0895077046329829, 3: -0.6487195966701562, 4: 0.25476223198417464, 5: 0.33126542254804864, 6: 0.731273711422529, 7: -0.2774254426274084}

(2)IPython支持Tab補(bǔ)全

例如,我們想知道np.random下面有哪些以rand開頭的方法,就可以輸入np.random.rand后按Tab鍵,如果只匹配到一個,則直接補(bǔ)全;如果匹配到多個,則列出所有。


image

(3)IPython支持Shell快捷鍵

IPython支持常用的Shell快捷鍵:

  • Ctrl+A:移動光標(biāo)到本行的開頭;
  • Ctrl+E:移動光標(biāo)到本行的結(jié)尾;
  • Ctrl+U:刪除光標(biāo)前面的所有字符;
  • Ctrl+K:刪除光標(biāo)后面的所有字符,包括光標(biāo)位置的字符;
  • Ctrl+L:清屏;
  • Ctrl+P:以當(dāng)前輸入的字符作為起始字符,在命令歷史中向后搜索匹配的命令;
  • Ctrl+N:以當(dāng)前輸入的字符作為起始字符,在命令歷史中向前搜索匹配的命令;
  • Ctrl+C:中斷執(zhí)行;

(4)IPython支持更強(qiáng)大的內(nèi)?。◣椭┕δ?/h3>

Python只能使用help()函數(shù)來查閱幫助文檔,IPython除了可以使用help()函數(shù)之外,還可以直接在一個對象后面加一個問號"?"來查閱幫助文檔:

In [19]: np.random.randn?
Docstring:
randn(d0, d1, ..., dn)
Return a sample (or samples) from the "standard normal" distribution.
……

使用兩個問號"??"可以查看源代碼:

In [20]: np.random??
……
from __future__ import division, absolute_import, print_function
import warnings
# To get sub-modules
from .info import __doc__, __all__
……

使用星號問號"*?"可以匹配所有的函數(shù)和對象:

In [21]: np.random.rand*?
np.random.rand
np.random.randint
np.random.randn
np.random.random
np.random.random_integers
np.random.random_sample

(5)IPython支持強(qiáng)大的魔術(shù)命令

魔術(shù)命令以百分號%開頭,常用的魔術(shù)命令有:

  • %run:直接運(yùn)行一個python腳本,將其中的變量和函數(shù)引入到當(dāng)前會話中
# cat hello.py
msg = 'hello ipython'
print(msg)

In [1]: %run hello.py
hello ipython
In [2]: msg
Out[2]: 'hello ipython'  
  • %timeit:用來快速評估代碼的執(zhí)行效率
In [3]: import numpy as np
In [4]: a = np.random.randn(100,100)
In [5]: %timeit np.dot(a,a)
22.8 μs ± 55.7 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  • %who和%whos:查看當(dāng)前會話的變量列表
In [7]: %who
a        msg    np
In [8]: %whos
Variable  Type      Data/Info
-------------------------------
a          ndarray    100x100: 10000 elems, type `float64`, 80000 bytes
msg        str        hello ipython
np        module    <module 'numpy' from '/ro<...>kages/numpy/__init__.py'>
  • %quickref:顯示IPython的快速參考文檔
  • %magic:顯示所有的魔術(shù)命令及其詳細(xì)文檔
  • %reset:刪除當(dāng)前會話的所有變量和導(dǎo)入的模塊
  • %logstart:開始記錄IPython輸入的所有命令,默認(rèn)保存到當(dāng)前工作目錄下的ipython_log.py文件中
  • %logstop:停止記錄,關(guān)閉log文件

同樣,在魔術(shù)命令后面也可以加問號"?"查看幫助文檔

In [9]: %reset?
Docstring:
Resets the namespace by removing all names defined by the user, if
called without arguments, or by removing some types of objects, such
as everything currently in IPython's In[] and Out[] containers (see
the parameters for details).
……

(6)IPython可以直接執(zhí)行Shell命令

在IPython環(huán)境中可以直接執(zhí)行Shell命令,只需要造該Shell命令前加嘆號"!"即可

In [11]: !ifconfig | grep "inet "
        inet 192.168.126.111  netmask 255.255.255.0  broadcast 192.168.126.255
        inet 127.0.0.1  netmask 255.0.0.0
        inet 192.168.122.1  netmask 255.255.255.0  broadcast 192.168.122.255

(7)自動開啟魔術(shù)命令

當(dāng)使用%automagic on啟動自動魔術(shù)命令后,輸入魔術(shù)命令時可以省略百分號“%”

In [12]: %automagic on
Automagic is ON, % prefix IS NOT needed for line magics.
In [13]: pwd
Out[13]: '/root/ipython'
In [14]: ls
chapter10.ipynb  hello.py
In [15]: cd ..
/root
In [16]: pwd
Out[16]: '/root'

(8)重新加載函數(shù)reload

使用reload()函數(shù)可以使得模塊的修改立即生效:
假設(shè)現(xiàn)在有一個模塊hello.py,里面有一個say_hello函數(shù)

# cat hello.py
def say_hello():
    print('hello ipython')

In [1]: import hello
In [2]: hello.say_hello()
hello ipython

現(xiàn)在修改hello.py內(nèi)容如下:

# cat hello.py
def say_hello():
    print('ipython is a great tool')

如果直接調(diào)用say_hello()函數(shù),得到的依然是舊的結(jié)果,只有調(diào)用reload()函數(shù)重新載入該模塊,才能得到最新的輸出

In [7]: import importlib
In [8]: importlib.reload(hello)
Out[8]: <module 'hello' from '/root/ipython/hello.py'>
In [9]: hello.say_hello()
ipython is a great tool

(9)IPython支持圖形界面jupyter

除了控制臺環(huán)境外,ipython另外一個強(qiáng)大的功能是圖形環(huán)境。與控制臺環(huán)境相比,它有兩個顯著的特點:方便編寫多行代碼;可以直接把數(shù)據(jù)可視化,顯示在當(dāng)前頁面下。安裝外jupyter后,直接在命令行輸入ipython notebook,啟動網(wǎng)頁版的圖形編程環(huán)境,它會在命令行啟動一個輕量級的Web服務(wù)器,同時用默認(rèn)瀏覽器打開當(dāng)前目錄所在的頁面,在這個頁面下可以直接打開某個notebook或者創(chuàng)建一個新的notebook。一個notebook是以.ipynb作為后綴的、基于json格式的文本文件。

# ipython notebook
[I 21:56:32.378 NotebookApp] JupyterLab extension loaded from C:\ProgramData\Anaconda3\lib\site-packages\jupyterlab 
[I 21:56:32.378 NotebookApp] JupyterLab application directory is C:\ProgramData\Anaconda3\share\jupyter\lab 
[I 21:56:32.397 NotebookApp] Serving notebooks from local directory: C:\Users\Mloong 
[I 21:56:32.397 NotebookApp] The Jupyter Notebook is running at: 
[I 21:56:32.398 NotebookApp] http://localhost:8888/?token=5fd5db92f5cfe7f6a7c520ac3ec58fc7042cea5429750682 
[I 21:56:32.398 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation). 
[C 21:56:32.621 NotebookApp] Copy/paste this URL into your browser when you connect for the first time, to login with a token: http://localhost:8888/?token=5fd5db92f5cfe7f6a7c520ac3ec58fc7042cea5429750682 
[I 21:56:33.943 NotebookApp] Accepting one-time-token-authenticated connection from ::1
……
image

我們新建一個notebook,并畫一個正弦曲線:

# 設(shè)置inline方式,直接把圖片畫在網(wǎng)頁上
% matplotlib inline
# 導(dǎo)入必要的庫
import numpy as np
import matplotlib.pyplot as plt
# 在[0,2*PI]直接取100個點
x = np.linspace(0,2*np.pi,num=100)
# 計算這100個點的正弦值,并保存到變量y中
y = np.sin(x)
# 畫出x,y,即正弦曲線
plt.plot(x,y)
image

幾乎所有的IPython控制臺的技巧都可以在IPython notebook里使用。一個比較大的區(qū)別是,IPython notebook使用cell作為一個代碼單元。在控制臺里,寫完代碼直接按Enter鍵即可運(yùn)行,而在IPython notebook里需要單擊“運(yùn)行”按鈕或者使用快捷鍵Ctrl+Enter才能運(yùn)行當(dāng)前cell的代碼。另外一個區(qū)別是IPython notebook有兩個模式,一個是編輯模式,可以直接在這個cell上編寫代碼。另一個是命令模式,即輸入的按鍵作為命令,而不是作為文本處理。使用Ctrl+M快捷鍵可以在編輯模式和命令模式之間切換。

命令模式下常用的快捷鍵有:

  • J:移到上一個cell
  • K:移到下一個cell
  • A:在前面插入一個cell
  • B:在后面插入一個cell
  • DD:刪除當(dāng)前cell
  • Ctrl+Enter:執(zhí)行當(dāng)前cell
  • Shift+Enter:執(zhí)行當(dāng)前cell,并移到下一個cell,沒有下一個就創(chuàng)建一個新的cell

可以通過Help->Keybord Shortcuts菜單,將常用快捷鍵設(shè)置成你習(xí)慣的樣子。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容