Jupyter Notebook最实用的5个魔术命令

2018年08月27日 由 浅浅 发表 69867 0
Jupyter Notebook

Jupyter Notebook是一个基于Web的交互式工具,机器学习和数据科学社区都频繁使用它。它们用于快速测试,作为报告工具,甚至是在线课程中非常复杂的学习材料。我最喜欢的一个功能是魔术命令。这些快捷方式可显着扩展Notebook的功能。以下是你应首先学习的五种命令列表,以便成为更好的数据向导。

%time,%timeit和%% time


你想知道你的代码需要运行多长时间吗?不出所料,你需要使用的魔术命令是时间及其变体。我经常使用cell magic版本(%% time)。这是对代码进行基准测试的快速方法,并向其他人表明他们需要多长时间来重新运行结果。
import numpy as np
from numpy.random import randint

# A function to simulate one million dice throws.
def one_million_dice():
return randint(low=1, high=7, size=1000000)

# Let's try %time first
%time throws = one_million_dice()
%time mean = np.mean(throws)

# Outputs:
# Wall time: 20.6 ms
# Wall time: 3.01 ms

# Let's do the same with %timeit
%timeit throws = one_million_dice()
%timeit mean = np.mean(throws)

# Outputs:
# 10 loops, best of 3: 22.2 ms per loop
# 100 loops, best of 3: 2.86 ms per loop

# And finally %%time
%%time
throws = one_million_dice()
mean = np.mean(throws)

# Outputs:
# Wall time: 36.6 ms

%matplotlib


如果你之前进行过在线课程,则可能会将此魔术命令与内联参数结合使用。使用此命令可确保Jupyter Notebook显示你的绘图。对于每一个基于Notebook的报告来说,这可能是最关键的魔术命令。
from numpy.random import randint
import matplotlib.pyplot as plt

# Sample 1000 random values to create a scatterplot
x = randint(low=1, high=1000, size=100)
y = randint(low=1, high=1000, size=100)

# This will show nothing in a Jupyter Notebook
plt.scatter(x, y)
plt.show()

# Let the magic happen!
%matplotlib inline
plt.scatter(x, y)
plt.show()

%load_ext autoreload


这个神奇的命令允许你加载最重要的扩展名:autoreload。没有它,每次更改引用代码中的内容时都必须重新加载内核。以下代码段为你提供了如何使用它的简短示例:
# load the autoreload extension
%load_ext autoreload
# Set extension to reload modules every time before executing code
%autoreload 2

from helperfunctions import complicated_function_to_return_a_number

complicated_function_to_return_a_number()
# Output: 123

# Go to helperfunctions.py and change something withing the function

complicated_function_to_return_a_number()
# Output: 321

%system


如果你想使用shell,这个魔术命令可以帮到你。它非常适合快速检查当前目录和类似的东西。它看起来并不复杂,但是它是一个很好的工具。
# Easy to read version
%system date

# Shorthand with "!!" instead of "%system" works equally well
!!date

%who_ls


这个神奇的命令可以很好地向你展示环境中的变量列表。你还可以添加参数来定义要查看的变量类型,例如函数。
# Outputs a list of all interactive variables in your environment
%who_ls

# Reduces the output to interactive variables of type "function"
%who_ls function

 
欢迎关注ATYUN官方公众号
商务合作及内容投稿请联系邮箱:bd@atyun.com
评论 登录
热门职位
Maluuba
20000~40000/月
Cisco
25000~30000/月 深圳市
PilotAILabs
30000~60000/年 深圳市
写评论取消
回复取消