原文:http://hyry.dip.jp/tech/slice/slice.html/35

Python Notebook简介1

作者 : RY    标签: cython ipython-notebook

IPython notebook目前已经成为用Python做教学、计算、科研的一个重要工具。本文介绍IPython notebook的一些基本用法,以及如何使用它调试Cython程序。

IPython Notebook使用浏览器作为界面,向后台的IPython服务器发送请求,并显示结果。在浏览器的界面中使用单元(Cell)保存各种信息。Cell有多种类型,经常使用的有表示格式化文本的Markdown单元,和表示代码的Code单元。

每个代码单元都有一个输出区域,在Code单元中输入代码,按 Shift-Enter 将运行此代码,代码中最后一个表达式的值将输出区域显示。如果希望屏蔽输出,可以在最后一条语句之后添加一个分号:”;”。此外,代码中还可以使用print语句在输出区域中显示信息。

在Markdown单元中还可以直接使用Html和Javascript。

数学公式

在Markdown单元中可以使用LaTeX表示数学公式,例如。数学公式的显示使用MathJax,缺省情况下,MathJax从网络上下载,如果希望离线使用它,需要在IPython Notebook中输入如下代码,把MathJax安装到本地磁盘中:

from IPython.external.mathjax import install_mathjax
install_mathjax()

Code单元的输出也可以显示为数学公式,例如在单元中输入如下代码,将显示为数学公式:

from IPython.display import Latex
Latex(r"$\sqrt{x^2+y^2}$")

SymPy的表达式也可以显示为LaTex,例如:

%load_ext sympyprinting
from sympy import *
x, y = symbols("x,y")
sqrt(x**2+y**2)

以%开头的为IPython的命令(Magic Command),这里通过%load_ext命令载入sympyprinting扩展插件,载入此插件之后,所有的SymPy表达式都显示为数学公式。

各种显示

IPython.display模块中提供了许多显示Python返回值的类,例如下面的代码用Image类显示”python.png”图片,缺省路径为Notebook文件所在的目录:

from IPython.display import Image
Image(filename="python.png")

Image还可以用来显示表示图像的字符串。例如下面的代码通过cv2的imencode()将NumPy数组转换为一个表示PNG图像数据的数组,然后将此数组转换为字符串之后通过Image()将显示为图像:

import cv2
import numpy as np
from IPython.display import Image
img = np.random.randint(0,255,(250,250,3))
cv2.blur(img, (11,11), img)
r, dat = cv2.imencode(".png",img)
Image(dat.tostring())

此外,还可以通过HTML和Javascript将Python代码的输出显示为Html,或者作为Javascript运行。

from IPython.display import Javascript
Javascript("alert('ok')")

将在浏览器中运行Javascript代码。

Magic命令

IPython中Magic命令有两种执行方式,以%开始的命令被称为行命令,它只对单行有效,以%%开头的为单元命令,它放在单元的第一行,对整个单元有效。例如timeit命令可以快速测试代码的执行效率,它可以作为行命令或者单元命令。

%timeit 1 + 1
%timeit 1.0 + 1.0
%timeit "1" + "1"
10000000 loops, best of 3: 52 ns per loop
10000000 loops, best of 3: 53.4 ns per loop
10000000 loops, best of 3: 50.9 ns per loop
%%timeit
s = 0
for i in xrange(100):
s += i
100000 loops, best of 3: 11 us per loop

每个Magic命令都可以指定参数,可以输入timeit?查看其帮助文档。下面让我们看看一些常用的Magic命令。

%pylab命令将载入numpy和pylab,并且将这两个模块中的名字载入到全局名字空间中。缺省参数时,它使用matplotlib的缺省界面库显示图表,如果带inline参数则将图表作为图像插入到Notebook中。使用界面库显示图像时可以使用交互工具,而将图表直接插入到Notebook中则有利于编写文档。

下面的例子,plotrandom是从pylab和numpy中载入的。

%pylab inline
plot(random.randn(100));
Welcome to pylab, a matplotlib-based Python environment [backend: module://IPython.zmq.pylab.backend_inline].
For more information, type 'help(pylab)'.

%load可以从文件或者网址载入代码到一个新的单元中,例如下面载入某个matplotlib的示例程序,并执行:

%load http://matplotlib.org/mpl_examples/pylab_examples/histogram_demo.py
#!/usr/bin/env python
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt mu, sigma = 100, 15
x = mu + sigma*np.random.randn(10000) # the histogram of the data
n, bins, patches = plt.hist(x, 50, normed=1, facecolor='green', alpha=0.75) # add a 'best fit' line
y = mlab.normpdf( bins, mu, sigma)
l = plt.plot(bins, y, 'r--', linewidth=1) plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title(r'$\mathrm{Histogram\ of\ IQ:}\ \mu=100,\ \sigma=15$')
plt.axis([40, 160, 0, 0.03])
plt.grid(True) plt.show()

%prun用于代码的执行性能分析,可以作为行命令和单元命令使用。下面的程序分析numpy.linalg.det()的性能:

%%prun
for i in xrange(100):
linalg.det(random.rand(10,10))

其输出如下:

3402 function calls in 0.096 seconds

Ordered by: internal time

ncalls  tottime  percall  cumtime  percall filename:lineno(function)
100 0.032 0.000 0.091 0.001 linalg.py:1560(slogdet)
300 0.022 0.000 0.022 0.000 {method 'reduce' of 'numpy.ufunc' objects}
200 0.011 0.000 0.012 0.000 numeric.py:167(asarray)
100 0.006 0.000 0.006 0.000 linalg.py:84(_realType)
100 0.005 0.000 0.005 0.000 linalg.py:151(_assertRank2)
...

%load_ext载入IPython的扩展模块,通过它可以载入更多的Magic命令。下面我们载入cythonmagic模块,并使用%%cython命令编译一个高效的频率统计函数count()

%load_ext cythonmagic

测试Cython代码

Cython的代码基本和Python的代码类似,但是可以使用类型声明,Cython可以使用这些类型声明产生更高效的C语言代码,并编译成Python的扩展模块。使用%%cython命令简化了编译扩展模块的过程,它会自动创建C语言程序,编译并载入。由于扩展模块无法卸载,因此IPython采用的策略是每次编译不同的代码都会产生一个全新的扩展模块。方便我们不退出Python环境即可运行新的代码。

%%cython
def count(list data):
cdef:
dict result = {}
int i, length = len(data)
object item for i in range(length):
item = data[i]
if item in result:
(<list> result[item]).append(i)
else:
result[item] = [i]
return result

下面是count()的Python版本。

from collections import defaultdict
def countpy(data):
result = defaultdict(list)
for i,item in enumerate(data):
result[item].append(i)
return result

先测试二者的结果是否相同:

import random
data = [random.randint(0,100) for _ in xrange(10000)]
count(data) == countpy(data)
True

然后测试它们的执行速度,可以看出Cython版本比Python的要快2倍多。在这个测试中,Cython程序也同样使用列表和字典等对象,但是由于可以直接调用Python的C API,因此Cython版本的效率能提高几倍。如果只是单纯的数值运算,Cython能将程序提升到与C语言相近的速度。

%timeit countpy(data)
%timeit count(data)
100 loops, best of 3: 4.52 ms per loop
1000 loops, best of 3: 1.8 ms per loop

[转]IPython Notebook简介1的更多相关文章

  1. jupyter && ipython notebook简介

    2017-08-19 最近用了一下 ipython notebook 也就是 jupyter,这里有一个介绍还不错: http://www.cnblogs.com/howiewang/p/jupyte ...

  2. ipython notebook 浏览器中编写数学公式和现实

    Python Notebook简介1 http://www.cnblogs.com/cbscan/p/3545084.html $ python -m IPython http://pypi.pyth ...

  3. 向IPython Notebook中导入.py文件

    IPython Notebook使用起来简洁方便,但是有时候如果需要导入一个现有的.py文件,则需要注意选择导入的方法以达到不同的效果.目前遇到3种方法. (1) 将文件保存为.ipynb格式,直接拖 ...

  4. .ipynb文件 与ipython notebook

    没有安装ipython notebook 后看见.ipynb文件直接手足无措了 一.安装ipython notebook 使用命令 pip ipython [all] 为所有用户安装 ipython ...

  5. 通过SSH远程使用ipython notebook

    本文讲述如何在本地用浏览器运行远程服务器上的iPython notebook服务. 在远程机器上,启动IPython notebooks服务: remote_user@remote_host$ ipy ...

  6. python tools: iPython Notebook

    Introducing IPython Notebook IPython isn't a different programming language, it's just a set of comp ...

  7. feature visualization from ipython notebook

    Feature visualization from ipython notebook Wang Xiao 1. install anaconda2 from: https://www.continu ...

  8. pyzmq missing when running ipython notebook

    Q: I can run iPython, but when I try to initiate a notebook I get the following error: ~ ipython not ...

  9. 安装ipython notebook

    从http://cs231n.github.io/assignments2016/assignment1/开始说起,因为要学习cs231n课程,需要安装ipython notebook,原本电脑中安装 ...

随机推荐

  1. Python第一天 - list\字符串截取

    (一)list截取L =['Adam', 'Lisa', 'Bart'] print(L[0:3]) ======>['Adam'(idnex:0), 'Lisa'(index:1), 'Bar ...

  2. .Net 转战 Android 4.4 日常笔记(10)--PullToRefresh下拉刷新使用

    下拉刷新很多地方都用到了,新浪微博,微信,百度新闻 这里我们使用一个开源的库叫:PullToRefresh 开源地址:https://github.com/chenyoca/pull-to-refre ...

  3. Util应用程序框架公共操作类(七):Lambda表达式公共操作类

    前一篇扩展了两个常用验证方法,本文将封装两个Lambda表达式操作,用来为下一篇的查询扩展服务. Lambda表达式是一种简洁的匿名函数语法,可以用它将方法作为委托参数传递.在Linq中,大量使用La ...

  4. [c++] Copy Control

    C++ allows the programmer to define how objects are to be copied, moved, assigned and destroyed. Tog ...

  5. 【LeetCode】Increasing Triplet Subsequence(334)

    1. Description Given an unsorted array return whether an increasing subsequence of length 3 exists o ...

  6. git取消跟踪文件

    取消跟踪文件: $git rm --cached FILENAME 取消跟踪目录: $git rm --cached FILENAME -r

  7. Mac OS平台下应用程序安装包制作工具Packages的使用介绍

    一.介绍 Windows下面开发好的应用程序要进行分发时有很多打包工具可供选择,如Inno Setup, InstallShield, NSIS, Advanced Installer, Qt Ins ...

  8. 那些年用过的xUnit.net的简单用法

    0x01 前言 单元测试,总是伴随着我们的开发过程,优劣自行google.当然呢,不排除有些公司是不做单元测试的, 但是呢,学多一点东西用来防身还是可以的. 0x02 简单的Demo 写个两数求和的方 ...

  9. MySQL高级查询 之 与 Group By 一起使用的函数 和 关键字

    1 GROUP_CONCAT mysql> SELECT student_name, ->     GROUP_CONCAT(test_score) ->     FROM stud ...

  10. Win10 UWP 开发系列:使用多语言工具包让应用支持多语言

    之前我在一篇blog中写过如何使用多语言工具包,见http://www.cnblogs.com/yanxiaodi/p/3800767.html 在WinEcos社区也发布过一篇详细的文章介绍多语言工 ...