Jupyter介绍及使用技巧

官方文档: Jupyter Project Documentation — Jupyter Documentation latest documentation

Jupyter Notebook

Jupyter Notebook(此前被称为 IPython notebook) 是一个基于 Web 的交互式笔记本,便于创建和共享文学化程序文档,支持实时代码,数学方程,可视化和 markdown。 用途包括:数据清理和转换,数值模拟,统计建模,机器学习等等 。支持运行 40 多种编程语言。

机器学习和数据科学社区都频繁使用它。用于快速测试,作为报告工具,甚至是在线课程中的学习环境。

Jupyter Notebook 需要与内核互动,内核是 Jupyter 与其它编程语言的交互编程协议。Python 的 Jupyter 内核使用 IPython。

安装

# pip 安装
pip install notebook

# conda 安装
conda install -c conda-forge notebook

推荐在虚拟环境中安装。

运行

jupyter notebook

参数:
--no-browser:不自动打开浏览器,运行后用显示的链接访问。

notebook界面截图
当保存 notebook 时,会创建一个后缀名为 .ipynb 的文件。这是一个自包含文件格式,包含当前笔记本中的所有内容(包括所有已评估的代码输出)。可以被其它用户加载和编辑。

notebook 扩展

jupyter_contrib_nbextensions
ipython-contrib/jupyter_contrib_nbextensions: A collection of various notebook extensions for Jupyter (github.com)
包含一系列扩展,这些扩展主要用 JavaScript 编写,并将在浏览器中本地加载。

安装:

# Install the python package
pip install jupyter_contrib_nbextensions
# Install javascript and css files
jupyter contrib nbextension install --user
# 添加环境变量
export PATH=~.local/bin:$PATH
# 安装后重启 jupyter 就可以看到 Nbextensions 标签页
  • 推荐插件
    • Code folding:代码折叠。
    • Code prettify:格式化代码(PEP8 规范)。
      • 依赖 Google 开发的 YAPF 模块。
      • pip install yapf -i https://pypi.tuna.tsinghua.edu.cn/simple
    • ExecuteTime:显示执行时间。
    • Highlight selected word:高亮所选词。
    • Notify:后台运行完通知。
    • Scratchpad:窗口分栏
      • Ctrl + B 打开一个新窗口,可用来对比。
    • Snippets menu:Document 快速获取
      • 在工具栏中添加 python 常见模块的 example、document 菜单。
    • Table of Contents:显示目录。
    • Toggle all line numbers:显示代码行号。
    • Variable Inspector:变量收集浮窗
      • 在浮窗表格中显示 notebook 中的变量信息。

JupyterLab

JupyterLab 是 Jupyter 主打的最新数据科学生产工具,某种意义上,它的出现是为了取代 Jupyter Notebook。包含了 Jupyter Notebook 所有功能。可以使用它编写 notebook、操作终端、编辑 markdown 文本、打开交互模式、查看 csv文件及图片等功能。如果说 Jupyter Notebook 像是一个交互式的笔记本,那么 Jupyter Lab 更像是一个交互式的 VSCode。

安装

# pip 安装
pip install jupyterlab

# conda 安装
conda install -c conda-forge jupyterlab

推荐在虚拟环境中安装。

运行

jupyter-lab

参数:
--no-browser:不自动打开浏览器,运行后用显示的链接访问。

插件配置

1) 工具栏点击 「Settings」–> 「Advanced Settings Editor」 ,将 「Extension Manager」里的 enabled 的 false 改成 true(在右边的里面改),如下图:
jupyterlab插件配置1

2)启用插件后,界面左侧可以看到一个插件管理的图标,如下图:
jupyterlab插件配置2

注:一些插件需安装 nodejs

pip install nodejs

推荐插件

  • Autopep8:pep8 标准格式化代码。
  • execute-time:显示单元格运行完成时间和时长。
  • toc:按标题显示目录结构。
  • jupyterlab-drawio:画流程图。
  • jupyterlab_voyager:Voyager 数据优化浏览。
  • pylantern:数据绘图加强。

使用技巧

修改默认工作路径

修改进入 notebook 的默认工作路径:

# cmd 命令行模式
$ jupyter notebook --generate-config
# 输入 y 生成配置文件
Writing default config to: C:\Users\xxx\.jupyter\jupyter_notebook_config.py

编辑 jupyter_notebook_config.py

## The directory to use for notebooks and kernels. 
c.NotebookApp.notebook_dir = 'C:YOURPATH' # YOURPATH 必须存在,否则会闪退

重新打开 notebook 就会自动跳转到设置的路径下。

windows 通过快捷方式打开 notebook 的默认工作路径:
右键快捷方式 → 属性 → “目标”栏后添加路径,如图:
jupyter快捷方式属性

快捷键

代码补全
输入函数的时候按下 Tab 按钮能够自动补全函数

显示当前函数的用法
shift + tab

查看已安装内核

jupyter kernelspec list

显示帮助文档

在库、方法 或 变量前 加 “?”,如:

In [1]: ?str.replace
Signature: str.replace(self, old, new, count=-1, /)
Docstring:
Return a copy with all occurrences of substring old replaced by new.

  count
    Maximum number of occurrences to replace.
    -1 (the default value) means replace all occurrences.

If the optional argument count is given, only the first count occurrences are
replaced.
Type:      method_descriptor
...

自动显示变量

默认只显示最后一个变量,修改内核选项 ast_node_interactivity 后可自动显示独占一行的所有变量或者语句:

from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all" 

魔术命令

IPython 中特殊的命令(Python中没有)被称作“魔术”命令。这些命令可以使普通任务更便捷,更容易控制 IPython系统。魔术命令是在指令前添加百分号 % 前缀。

列出所有可用的 IPython magics:

%lsmagic

%env

环境变量:

# 设置环境变量
%env TEMP = 4
# 显示环境变量
%env

%time,%timeit

显示运行时间:

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)

# 代码单次运行时间
%time throws = one_million_dice()
%time mean = np.mean(throws)

# Outputs:
# CPU times: user 10.1 ms, sys: 0 ns, total: 10.1 ms
# Wall time: 9.24 ms
# CPU times: user 1.05 ms, sys: 0 ns, total: 1.05 ms
# Wall time: 825 µs

# 运行 100 次, 然后提供最快的 3 次平均值作为结果
%timeit throws = one_million_dice()
%timeit mean = np.mean(throws)
# Outputs:
# 8.2 ms ± 59.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
# 762 µs ± 8.42 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%matplotlib

使用此命令可确保 Jupyter Notebook 正常显示你的绘图:

import matplotlib.pyplot as plt

# Let the magic happen!
%matplotlib inline

%load_ext autoreload

修改引用代码中的内容后,自动重新加载内核:

# load the autoreload extension
%load_ext autoreload
# Set extension to reload modules every time before executing code
%autoreload 2

%system

执行 shell 命令,适合快速检查当前目录和类似的东西:

# Easy to read version
%system date

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

%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

%%writefile %pycat

保存 cell 内容到外部文件:

%%writefile test1.py
print("hello world!")

显示外部文件:

%pycat test1.py

%run

运行.py 格式的 python 代码:

%run xxx.py

– END –


版权声明:本文为hunter1000原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。