前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Jupyter Notebook(下篇)

Jupyter Notebook(下篇)

作者头像
MeteoAI
发布2019-07-22 18:09:22
1.5K0
发布2019-07-22 18:09:22
举报
文章被收录于专栏:MeteoAIMeteoAI

Jupyter Notebook是一个基于Web的交互式工具,数据科学领域正在频繁的使用它。

在上篇文章中,我们介绍了如何安装使用Jupyter Notebook来快快乐乐的编程,以及一些快捷键sao操作、如何搭建一个开放的notebook让大家一起使用,最后我们介绍了怎样修改Jupyter Notebook的风格,让它更酷炫。

还没学过的同学快戳:Jupyter Notebook介绍(上篇)

补完课再回来啊!!!

通过上篇的介绍,相信大家已经可以自如的使用Jupyter了,今天我们继续介绍一下Jupyter Notebook的一些更酷的扩展功能。

魔术命令magics

魔术命令是ipython中的特殊命令,常以%作为前缀符号开头,用于方便我们的日常使用。

  • %:行魔法函数,只对本行代码生效。
  • %%:Cell魔法函数,在整个Cell中生效,必须放于Cell首行。 下面我们来介绍一下常用的magics。

(完整的magics命令:大家可以打开jupyter后可以在cell中输入%quickref显示快速参考卡,%lsmagic:列出所有的魔法函数,以及%magic命令可以显示魔术命令的详细文档)

  • %matplotlib inline: 这个命令可能是大家最常用的一个魔术命令。这个命令用于将matplotlib的输出图嵌入到notebook中,如果不加这条命令,在用matplotlib绘图时可能会出现不显示的情况,举个我们在介绍seaborn中的例子:
代码语言:javascript
复制
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
sns.set()
x = np.linspace(0,20,8)
y_bar = np.random.randint(5,20,8)
y_line = y_bar 
plt.figure(figsize=(8,6))
plt.bar(x, y_bar, color='r')
plt.plot(x, y_line, '-o', color='g')
plt.tick_params(labelsize='15', width=1)
plt.show()
  • %time, %timeit和 %%time, %%timeit:可以用来记录程序运行的时间,以便于后期对代码逻辑进行优化。

%time可以输出单个语句的运行时间,而%timeit会自动多次执行语句以产生一个更具代表性的平均执行时间, %%time可以输出整个cell中语句的执行时间。

代码语言:javascript
复制
import time
import numpy as np

def time_test():
    arr = np.random.rand(5,6)
    for i in range(10000):
        arr += (-1)**i
    return arr

%time time_test()

# OUTPUT:
"""
CPU times: user 26 ms, sys: 2.16 ms, total: 28.2 ms
Wall time: 27 ms
array([[0.9002168 , 0.3041222 , 0.44203939, 0.17079689, 0.94881637,
        0.3497185 ],
       [0.3253366 , 0.94237406, 0.94394366, 0.45562757, 0.13917467,
        0.34043364],
       [0.17794278, 0.51184239, 0.30619056, 0.17429579, 0.92800944,
        0.4405044 ],
       [0.30972439, 0.02095686, 0.31532945, 0.65237745, 0.03647221,
        0.54834167],
       [0.9697625 , 0.52372474, 0.12283473, 0.46851531, 0.09019544,
        0.41063005]])
"""
%timeit time_test()

# OUTPUT:
"""
17.1 ms ± 187 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
"""
代码语言:javascript
复制
%%time 
import time
import numpy as np

def time_test():
    arr = np.random.rand(5,6)
    for i in range(10000):
        arr += (-1)**i
    return arr

time_test()
# OUTPUT:
"""
CPU times: user 24.5 ms, sys: 914 µs, total: 25.4 ms
Wall time: 25 ms
"""
  • %xdel:删除一个变量,清除相关的引用。
  • %prun, %lprun, %memit, %mprun:程序性能分析。
    • %prun: Run code with the profiler
    • %lprun: Run code with the line-by-line profiler
    • %memit: Measure the memory use of a single statement
    • %mprun: Run code with the line-by-line memory profiler`

注:后面三个magics命令不是jupyter自带的,需要先进行安装和导入才可以使用。

代码语言:javascript
复制
$ pip install line_profiler
%load_ext line_profiler 
$ pip install memory_profiler
%load_ext memory_profiler
  • %load_ext:导入ipython的拓展工具。

Load an IPython extension by its module name.

  • %run:运行python脚本:
代码语言:javascript
复制
%run script.py
  • %system date, !date 和 !!date: 都可用于在cell中执行shell命令。
  • %who_ls, %who, %whos:输出环境中的变量列表。%who_ls function仅仅输入函数类型的变量列表。
代码语言:javascript
复制
%whos

#OUTPUT
"""
Variable    Type        Data/Info
---------------------------------
np          module      <module 'numpy' from '/Us<...>kages/numpy/__init__.py'>
time        module      <module 'time' (built-in)>
time_test   function    <function time_test at 0x10f433620>
"""
  • %debug, %pdb:可用于调试debug
  • %env:列出全部环境变量
  • %reset:清除全部变量
  • %%: Cell magics:在每个cell的开头使用的以%%开头的魔法命令,可以在一个notebook中用不同的内核运行代码,例如:
代码语言:javascript
复制
%%bash
%%markdown
%%time
%%HTML
%%python2
%%python3
%%latex
%%javascript
%%ruby
%%perl

扩展功能

安装方法:

代码语言:javascript
复制
!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

安装完成后打开jupyter可以看到多了Nbextensions这个选项卡:

安装了之后便多了很多便捷的小工具可以选择,可以直接在上图显示的Nbextensions这个选项卡中直接打开相应的功能。下面介绍一些常见的:

  • Hinterland:代码输入提示工具,非常好用。
  • Autopep8:一键美化代码。
  • Table of Contents:生成目录。
  • Split Cells Notebook:拆分单元格。
  • Codefolding:代码折叠。
  • table_beautifier:美化表格。

更多的扩展功能大家可以自行探索啊。

其他

  • ?,??:可以在jupyter中实现help的功能。
代码语言:javascript
复制
np.random.rand??

# OUTPUT:
"""
Docstring:
rand(d0, d1, ..., dn)

Random values in a given shape.

Create an array of the given shape and populate it with
random samples from a uniform distribution
over ``[0, 1)``.

Parameters
----------
d0, d1, ..., dn : int, optional
    The dimensions of the returned array, should all be positive.
    If no argument is given a single Python float is returned.

Returns
-------
out : ndarray, shape ``(d0, d1, ..., dn)``
    Random values.

See Also
--------
random

Notes
-----
This is a convenience function. If you want an interface that
takes a shape-tuple as the first argument, refer to
np.random.random_sample .

Examples
--------
>>> np.random.rand(3,2)
array([[ 0.14022471,  0.96360618],  #random
       [ 0.37601032,  0.25528411],  #random
       [ 0.49313049,  0.94909878]]) #random
Type:      builtin_function_or_method
"""
  • 将Notebook转化为PPT展示: https://github.com/damianavila/RISE
  • 嵌入网页,pdf或者视频:

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-01-15,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 MeteoAI 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 魔术命令magics
  • 扩展功能
  • 其他
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档