分享

Jupyter Notebook的27个窍门,技巧和快捷键

 candidacy 2019-07-25

10.Jupyter Magic-%who:列出所有的全局变量

不加任何参数, %who 命令可以列出所有的全局变量。加上参数 str 将只列出字符串型的全局变量。

In [1]: one = "for the money"
two = "for the show"
three = "to get ready now go cat go"
%who str
one three two

11.Jupyter Magic-计时

有两种用于计时的jupyter magic命令: %%time 和 %timeit.当你有一些很耗时的代码,想要查清楚问题出在哪时,这两个命令非常给力。

仔细体会下我的描述哦。

%%time 会告诉你cell内代码的单次运行时间信息。

In [4]: %%time
import time
for _ in range(1000):
time.sleep(0.01)# sleep for 0.01 seconds
CPU times: user 21.5 ms, sys: 14.8 ms, total: 36.3 ms
Wall time: 11.6 s

%%timeit 使用了Python的 timeit 模块,该模块运行某语句100,000次(默认值),然后提供最快的3次的平均值作为结果。

In [3]: import numpy
%timeit numpy.random.normal(size=100)
The slowest run took 7.29 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 5.5 µs per loop

12.Jupyter Magic-writefile and %pycat:导出cell内容/显示外部脚本的内容

使用%%writefile magic可以保存cell的内容到外部文件。 而%pycat功能相反,把外部文件语法高亮显示(以弹出窗方式)。

In [7]: %%writefile pythoncode.py
import numpy
def append_if_not_exists(arr, x):
if x not in arr:
arr.append(x)
def some_useless_slow_function():
arr = list()
for i in range(10000):
x = numpy.random.randint(0, 10000)
append_if_not_exists(arr, x)
Writing pythoncode.py
In [8]: %pycat pythoncode.py
import numpy
def append_if_not_exists(arr, x):
if x not in arr:
arr.append(x)
def some_useless_slow_function():
arr = list()
for i in range(10000):
x = numpy.random.randint(0, 10000)
append_if_not_exists(arr, x)

13.Jupyter Magic-%prun:告诉你程序中每个函数消耗的时间

使用%prun+函数声明会给你一个按顺序排列的表格,显示每个内部函数的耗时情况,每次调用函数的耗时情况,以及累计耗时。

In [47]: %prun some_useless_slow_function()
26324 function calls in 0.556 seconds
Ordered by: internal time
ncalls tottime percall cumtime percall filename:lineno(function)
10000 0.527 0.000 0.528 0.000 :2(append_if_not_exists)
10000 0.022 0.000 0.022 0.000 {method 'randint' of 'mtrand.RandomState' objects}
1 0.006 0.006 0.556 0.556 :6(some_useless_slow_function)
6320 0.001 0.000 0.001 0.000 {method 'append' of 'list' objects}
1 0.000 0.000 0.556 0.556 :1()
1 0.000 0.000 0.556 0.556 {built-in method exec}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}

14.Jupyter Magic-用%pdb调试程序

Jupyter 有自己的调试界面The Python Debugger (pdb),使得进入函数内部检查错误成为可能。

Pdb中可使用的命令见链接

In [ ]: %pdb
def pick_and_take():
picked = numpy.random.randint(0, 1000)
raise NotImplementedError()
pick_and_take()
Automatic pdb calling has been turned ON

---------------------------------------------------------------------------

NotImplementedError Traceback (most recent call last)
in ()
5 raise NotImplementedError()
6
----> 7 pick_and_take()
in pick_and_take()
3 def pick_and_take():
4 picked = numpy.random.randint(0, 1000)
----> 5 raise NotImplementedError()
6
7 pick_and_take()
NotImplementedError:
> (5)pick_and_take()
3 def pick_and_take():
4 picked = numpy.random.randint(0, 1000)
----> 5 raise NotImplementedError()
6
7 pick_and_take()
ipdb>

15.末句函数不输出

有时候不让末句的函数输出结果比较方便,比如在作图的时候,此时,只需在该函数末尾加上一个分号即可。

In [4]: %matplotlib inline
from matplotlib import pyplot as plt
import numpy
x = numpy.linspace(0, 1, 1000)**1.5
In [5]: # Here you get the output of the function
plt.hist(x)
Out[5]:
(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. ]),
)

 

 

In [6]: # By adding a semicolon at the end, the output is suppressed.
plt.hist(x);

 

 

16.运行Shell命令

在notebook内部运行shell命令很简单,这样你就可以看到你的工作文件夹里有哪些数据集。

In [7]: !ls *.csv
nba_2016.csv titanic.csv
pixar_movies.csv whitehouse_employees.csv

17.用LaTex写公式

当你在一个Markdown单元格里写LaTex时,它将用MathJax呈现公式:如

$$ P(A \mid B) = \frac{P(B \mid A) , P(A)}{P(B)} $$

会变成

 

 

18.在notebook内用不同的内核运行代码

如果你想要,其实可以把不同内核的代码结合到一个notebook里运行。

只需在每个单元格的起始,用Jupyter magics调用kernal的名称:

%%bash
%%HTML
%%python2
%%python3
%%ruby
%%perl
In [6]: %%bash
for i in {1..5}
do
echo "i is $i"
done
i is 1
i is 2
i is 3
i is 4
i is 5

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多