ipython notebook


 

介紹ipython notebook

1.簡單介紹ipython notebook的安裝和使用,在ubuntu上:
sudo apt-get install ipython
但是並不是所有的版本都支持notebook功能,本人的系統安裝的是0.13的版本有
notebook,但是有個重要的功能沒有,什么功能等會再說,所以本人手動安裝的
ipython 1.1.0版本,你可以“ipython -V”查看版本號。
http://ipython.org/ 此網址可以下載最新的ipython版本

2.使用python的你也許對ipython有所耳聞或者使用過,簡單的介紹ipython:
ipython是一個強大而交互式運算架構:
(1).強大的交互式shell(終端運行);
(2).一個基於瀏覽器的notbook,支持代碼、文本、數學運算、內嵌plots等;
(3).支持交互式的數據可視化和GUI工具包的使用;
(4).靈活、內嵌的解釋器加載到自己的項目;
(5).支持並行運算.

3.運行ipython notebook,在終端輸入:
ipython notebook
如果你使用matplotlib內嵌進網頁中,那么需要運行:
ipython notebook --matplotlib inline
OK,程序會自動在瀏覽器上新建一個標簽窗口。
所以ipython notebook就是一個后端服務和一個前端表現,服務默認端口8888,
前端也就是你在瀏覽器中看到的,如下圖:

In [5]:
from IPython.display import Image
Image(filename='/home/chaofan/Desktop/firstpage.png') #press shift+enter 
Out[5]:

上圖即是控制窗口,我們可以按"New Notebook"新建一個,本人已經見了5個。
你現在所讀的頁面即是上圖 Advence打開后本人編輯 成現在的效果。

基本的操作

1.每次運行按shift-enter

In [7]:
i=0
print i #按shift+enter
 
0

可以看到輸出了0,我們可以直接對上面的程序做修改,再運行。

2.ipython提供個很多魔數,以%或者%%開始

In [1]:
%matplotlib inline

%matplotlib就是一個魔數,如果你在命令行加入--matplotlib inline
運行此命令一樣可以達到內嵌的效果。

下面是獲得連接信息

In [30]:
%connect_info
 
{
  "stdin_port": 41438, 
  "ip": "127.0.0.1", 
  "control_port": 42233, 
  "hb_port": 49904, 
  "signature_scheme": "hmac-sha256", 
  "key": "b6324ba0-f75a-4aec-98cc-42893b4ef790", 
  "shell_port": 52144, 
  "transport": "tcp", 
  "iopub_port": 59393
}

Paste the above JSON into a file, and connect with:
    $> ipython <app> --existing <file>
or, if you are local, you can connect with just:
    $> ipython <app> --existing kernel-96015ef4-abc1-40db-b408-acb9f47900f1.json 
or even just:
    $> ipython <app> --existing 
if this is the most recent IPython session you have started.

3.可以直接運行bash

In [13]:
ls -l
 
total 904
-rw-r--r-- 1 chaofan chaofan 892046 12月  9 22:04 Advance.ipynb
-rw-r--r-- 1 chaofan chaofan   6883 11月 24 13:13 python11-24.ipynb
-rw-r--r-- 1 chaofan chaofan   9928 11月 27 00:28 test.ipynb
-rw-r--r-- 1 chaofan chaofan    493 11月 27 20:54 tiny.ipynb
-rw-r--r-- 1 chaofan chaofan    290 11月 30 21:19 tmp.ipynb

In [14]:
pwd
Out[14]:
u'/home/chaofan/notebook'
In [16]:
%%bash
echo 'Hello'
date
 
Hello
2013年 12月 09日 星期一 22:21:41 CST

如果一個程序無線循環或者循環的時間太長想中斷可以
ctr-m i,如下:

In [27]:
import time
i=0
while True:
    time.sleep(1)
    print i
    i+=1
 
0
1
2
3
4
5
 
---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-27-cada1146ea44> in <module>()
      2 i=0
      3 while True:
----> 4time.sleep(1)
      5     print i
      6     i+=1

KeyboardInterrupt: 
 

4.載入圖片

上面已經使用過了載入圖片,下面載入notebook快捷鍵的圖片,
ctr-m h也會彈出幫助窗口。

In [19]:
Image(filename='/home/chaofan/Desktop/help.png')
Out[19]:

載入url圖片:

In [22]:
Image(url='http://ww1.sinaimg.cn/mw600/6a77a719jw1dyx581xf1cj.jpg')
Out[22]:

高級處理

1.matplotlib使用

In [8]:
import numpy as np
In [9]:
import matplotlib.pyplot as plt
In [10]:
x = np.linspace(0, 3*np.pi, 500)
plt.plot(x, np.sin(x**2))
plt.title('A simple chirp');
plt.show()
 

url載入代碼:

In [28]:
%load http://matplotlib.sourceforge.net/mpl_examples/pylab_examples/integral_demo.py
In [29]:
#!/usr/bin/env python

# implement the example graphs/integral from pyx
from pylab import *
from matplotlib.patches import Polygon

def func(x):
    return (x-3)*(x-5)*(x-7)+85

ax = subplot(111)

a, b = 2, 9 # integral area
x = arange(0, 10, 0.01)
y = func(x)
plot(x, y, linewidth=1)

# make the shaded region
ix = arange(a, b, 0.01)
iy = func(ix)
verts = [(a,0)] + list(zip(ix,iy)) + [(b,0)]
poly = Polygon(verts, facecolor='0.8', edgecolor='k')
ax.add_patch(poly)

text(0.5 * (a + b), 30,
     r"$\int_a^b f(x)\mathrm{d}x$", horizontalalignment='center',
     fontsize=20)

axis([0,10, 0, 180])
figtext(0.9, 0.05, 'x')
figtext(0.1, 0.9, 'y')
ax.set_xticks((a,b))
ax.set_xticklabels(('a','b'))
ax.set_yticks([])
show()
 

 

3.在來些matplotlib的例子

In [1]:
from pylab import *
In [2]:
x = linspace(0, 5, 10)
y = x ** 2
In [3]:
figure()
plot(x, y, 'r')
xlabel('x')
ylabel('y')
title('title')
show()
 
In [4]:
subplot(1,2,1)
plot(x, y, 'r--')
subplot(1,2,2)
plot(y, x, 'g*-');
 
In [5]:
fig = plt.figure()

axes1 = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # main axes
axes2 = fig.add_axes([0.2, 0.5, 0.4, 0.3]) # inset axes

# main figure
axes1.plot(x, y, 'r')
axes1.set_xlabel('x')
axes1.set_ylabel('y')
axes1.set_title('title')

# insert
axes2.plot(y, x, 'g')
axes2.set_xlabel('y')
axes2.set_ylabel('x')
axes2.set_title('insert title');
 
In [6]:
fig, ax = plt.subplots()

ax.plot(x, x**2, label=r"$y = \alpha^2$")
ax.plot(x, x**3, label=r"$y = \alpha^3$")
ax.set_xlabel(r'$\alpha$', fontsize=18)
ax.set_ylabel(r'$y$', fontsize=18)
ax.set_title('title')
ax.legend(loc=2); # upper left corner
Out[6]:
<matplotlib.legend.Legend at 0xacff72c>
 
In [7]:
fig, ax = plt.subplots(figsize=(12,6))

ax.plot(x, x+1, color="blue", linewidth=0.25)
ax.plot(x, x+2, color="blue", linewidth=0.50)
ax.plot(x, x+3, color="blue", linewidth=1.00)
ax.plot(x, x+4, color="blue", linewidth=2.00)

# possible linestype options ‘-‘, ‘–’, ‘-.’, ‘:’, ‘steps’
ax.plot(x, x+5, color="red", lw=2, linestyle='-')
ax.plot(x, x+6, color="red", lw=2, ls='-.')
ax.plot(x, x+7, color="red", lw=2, ls=':')

# custom dash
line, = ax.plot(x, x+8, color="black", lw=1.50)
line.set_dashes([5, 10, 15, 10]) # format: line length, space length, ...

# possible marker symbols: marker = '+', 'o', '*', 's', ',', '.', '1', '2', '3', '4', ...
ax.plot(x, x+ 9, color="green", lw=2, ls='*', marker='+')
ax.plot(x, x+10, color="green", lw=2, ls='*', marker='o')
ax.plot(x, x+11, color="green", lw=2, ls='*', marker='s')
ax.plot(x, x+12, color="green", lw=2, ls='*', marker='1')

# marker size and color
ax.plot(x, x+13, color="purple", lw=1, ls='-', marker='o', markersize=2)
ax.plot(x, x+14, color="purple", lw=1, ls='-', marker='o', markersize=4)
ax.plot(x, x+15, color="purple", lw=1, ls='-', marker='o', markersize=8, markerfacecolor="red")
ax.plot(x, x+16, color="purple", lw=1, ls='-', marker='s', markersize=8, 
        markerfacecolor="yellow", markeredgewidth=2, markeredgecolor="blue");
 
In [8]:
fig, ax1 = plt.subplots()

ax1.plot(x, x**2, lw=2, color="blue")
ax1.set_ylabel(r"area $(m^2)$", fontsize=18, color="blue")
for label in ax1.get_yticklabels():
    label.set_color("blue")
    
ax2 = ax1.twinx()
ax2.plot(x, x**3, lw=2, color="red")
ax2.set_ylabel(r"volume $(m^3)$", fontsize=18, color="red")
for label in ax2.get_yticklabels():
    label.set_color("red")
 
In [11]:
n = array([0,1,2,3,4,5])
xx = np.linspace(-0.75, 1., 100)
In [12]:
fig, axes = plt.subplots(1, 4, figsize=(12,3))

axes[0].scatter(xx, xx + 0.25*randn(len(xx)))

axes[1].step(n, n**2, lw=2)

axes[2].bar(n, n**2, align="center", width=0.5, alpha=0.5)

axes[3].fill_between(x, x**2, x**3, color="green", alpha=0.5);
 
In [13]:
fig = plt.figure()
ax = fig.add_axes([0.0, 0.0, .6, .6], polar=True)
t = linspace(0, 2 * pi, 100)
ax.plot(t, t, color='blue', lw=3);
 
In [31]:
import matplotlib.gridspec as gridspec
In [32]:
fig = plt.figure()

gs = gridspec.GridSpec(2, 3, height_ratios=[2,1], width_ratios=[1,2,1])
for g in gs:
    ax = fig.add_subplot(g)
    
fig.tight_layout()
 
In [33]:
alpha = 0.7
phi_ext = 2 * pi * 0.5

def flux_qubit_potential(phi_m, phi_p):
    return 2 + alpha - 2 * cos(phi_p)*cos(phi_m) \
- alpha * cos(phi_ext - 2*phi_p)
In [34]:
phi_m = linspace(0, 2*pi, 100)
phi_p = linspace(0, 2*pi, 100)
X,Y = meshgrid(phi_p, phi_m)
Z = flux_qubit_potential(X, Y).T
In [35]:
fig, ax = plt.subplots()

p = ax.pcolor(X/(2*pi), Y/(2*pi), Z, cmap=cm.RdBu,\
              vmin=abs(Z).min(), vmax=abs(Z).max())
cb = fig.colorbar(p, ax=ax)
 
In [36]:
fig, ax = plt.subplots()

im = imshow(Z, cmap=cm.RdBu, vmin=abs(Z).min(),\
            vmax=abs(Z).max(), extent=[0, 1, 0, 1])
im.set_interpolation('bilinear')

cb = fig.colorbar(im, ax=ax)
 
In [37]:
fig, ax = plt.subplots()

cnt = contour(Z, cmap=cm.RdBu, vmin=abs(Z).min(),\
              vmax=abs(Z).max(), extent=[0, 1, 0, 1])
 

4.matplotlib 3D效果

In [38]:
from mpl_toolkits.mplot3d.axes3d import Axes3D
In [39]:
fig = plt.figure(figsize=(14,6))

# `ax` is a 3D-aware axis instance, because of the projection='3d' keyword argument to add_subplot
ax = fig.add_subplot(1, 2, 1, projection='3d')

p = ax.plot_surface(X, Y, Z, rstride=4, cstride=4, linewidth=0)

# surface_plot with color grading and color bar
ax = fig.add_subplot(1, 2, 2, projection='3d')
p = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, \
                    cmap=cm.coolwarm, linewidth=0, antialiased=False)
cb = fig.colorbar(p, shrink=0.5)
 
In [23]:
fig = plt.figure(figsize=(8,6))

ax = fig.add_subplot(1, 1, 1, projection='3d')

p = ax.plot_wireframe(X, Y, Z, rstride=4, cstride=4)
 
In [24]:
fig = plt.figure(figsize=(8,6))

ax = fig.add_subplot(1,1,1, projection='3d')

ax.plot_surface(X, Y, Z, rstride=4, cstride=4, alpha=0.25)
cset = ax.contour(X, Y, Z, zdir='z', offset=-pi, cmap=cm.coolwarm)
cset = ax.contour(X, Y, Z, zdir='x', offset=-pi, cmap=cm.coolwarm)
cset = ax.contour(X, Y, Z, zdir='y', offset=3*pi, cmap=cm.coolwarm)

ax.set_xlim3d(-pi, 2*pi);
ax.set_ylim3d(0, 3*pi);
ax.set_zlim3d(-pi, 2*pi);
 

  就演示這么多吧,本文所有內容全是在notebook上編輯的,可以看出對於教育、科研、

開發具有很強的運算處理,同時很好的記錄,
也可以很好的演示給他人。寫代碼時也在寫博客。ipython已經非常流行了,再此介紹給
熱愛python的伙伴們.今年8月微軟捐贈10萬美元給ipython為支持其開發,足見其能量。

最后說一下為何ipython版本要高,因為在1.0+版本后有一個nbconvert功能,由於我們看到的
這個網頁本身並不是html的,默認是ipynb格式的文件,存儲的也都是json格式的內容,我們需要
把它轉成html頁面。
ipython nbconvert --to html Advance.ipynb

 注:在博客園上顯示科學計算效果很不好(也許是本人不知怎么弄),所以給個完整鏈接:

http://wuchaofan.github.io/blogsource/python/Advance.html此鏈接是完整的,博客園上的

把這部分刪了。


免責聲明!

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



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