在 2025 年 JupyterBook 中,如何嵌入 NumPy 示例并支持交互式运行

解读

国内技术面试常把“能不能把算法库跑起来”升级为“能不能把算法库跑在可交互、可复现、可上线的文档里”。JupyterBook 已成为高校、国企、大厂对外交付算法方案的标准载体,面试官问“如何嵌入 NumPy 并支持交互”,实质在考察三点:

  1. 你是否理解 JupyterBook 的构建链(MyST-NB、Sphinx、Binder/JupyterHub)。
  2. 你是否能把 NumPy 的向量化演示写成“可一键运行”的单元,并保证版本、依赖、性能可复现。
  3. 你是否能在国内网络与合规环境下,给出离线/私有化交付方案,而不是只会“!pip install”。

知识点

  1. MyST 语法:{code-cell} 指令与 ipython 魔法。
  2. 交互后端:Binder(公网)、JupyterHub(私网)、JupyterLite(纯前端 WASM)。
  3. 依赖锁定:requirements.txt、environment.yml、conda-lock、dockerfile、apt.txt。
  4. 性能优化:numpy.config.show() 查看 BLAS/LAPACK 后端;在 notebook 内用 %timeit 对比向量化与循环。
  5. 国内加速:清华镜像、华为云、阿里云容器镜像服务,以及 GitHub 代理(gitee 同步)。
  6. 合规细节:离线 bundle 需包含开源许可证;禁止公网传输数据时需关闭 Binder 的 Git 推送权限。
  7. 版本兼容性:2025 年主流 Python 3.12,NumPy 2.x 默认采用 NEP-50 的 dtype 系统,需演示旧代码迁移。
  8. 缓存与构建:JupyterBook 的 jb build --overwrite 与 sphinx-proof、sphinx-exercise 插件,避免每次全量重跑。

答案

步骤一:项目骨架
numpy_book/
├─ _config.yml
├─ _toc.yml
├─ requirements.txt
├─ environment.yml
├─ Dockerfile
└─ docs/
└─ numpy_demo.md

步骤二:锁定依赖(国内镜像)
requirements.txt 示例:
--index-url https://pypi.tuna.tsinghua.edu.cn/simple
numpy==2.1.0
jupyter-book==1.0.0
matplotlib==3.9.2
numba==0.60 # 用于 JIT 加速对比

步骤三:编写 MyST 文档 docs/numpy_demo.md

# NumPy 向量化交互示例  

```{code-cell} ipython3  
:tags: [remove-output]  

import numpy as np  
np.__config__.show()   # 验证 MKL/OpenBLAS 后端  
```  

```{code-cell} ipython3  
# 生成 1 亿数据,演示内存布局  
a = np.random.rand(10_000_000).astype(np.float32)  
b = np.random.rand(10_000_000).astype(np.float32)  
```  

```{code-cell} ipython3  
# 向量化 vs Python 循环  
%timeit c = a + b        # 向量化  
%timeit c = np.fromiter((x+y for x,y in zip(a,b)), dtype=np.float32)  # 循环  
```  

```{code-cell} ipython3  
# 广播机制可视化  
import matplotlib.pyplot as plt  
x = np.linspace(0, 2*np.pi, 400)  
y = np.sin(x[np.newaxis, :] + np.arange(0, 4)[:, np.newaxis])  
plt.plot(x, y.T);  
plt.title("广播 shape=(4,400)");  
```  

步骤四:本地构建与测试

jb build . --path-output _build/html  

打开 _build/html/index.html,确认代码单元已渲染为“点击运行”按钮。

步骤五:公网交互(可选)

  1. 仓库推送到 GitHub;
  2. 在 mybinder.org 填写 https://github.com/yourname/numpy_book;
  3. 在 _config.yml 顶部添加:
    launch_buttons:
    binderhub_url: "https://mybinder.org"
    构建后每篇 notebook 右上角出现“Launch Binder”按钮,用户零安装即可交互。

步骤六:私有化交付(国企/银行常见)

  1. 构建 docker 镜像:
    FROM jupyter/scipy-notebook:python-3.12  
    COPY requirements.txt /tmp/  
    RUN pip install -r /tmp/requirements.txt  
    COPY . /home/jovyan/numpy_book  
    WORKDIR /home/jovyan/numpy_book  
    CMD ["jb", "build", ".", "--path-output", "/home/jovyan/numpy_book/_build"]  
    
  2. 推送至阿里云 ACR;
  3. 在内网 JupyterHub 中挂载该镜像,用户点击即可启动容器,实现“文档即环境”。

步骤七:版本迁移提示(加分项)
在文档顶部增加警告单元:

import numpy as np  
if np.lib.NumpyVersion(np.__version__) >= "2.0.0":  
    print("提示:NumPy 2.x 默认使用宽 dtype,旧代码需显式 dtype=np.float64 以保持精度一致")  

拓展思考

  1. 如果数据涉密,Binder 公网方案被禁用,可考虑 JupyterLite:把 NumPy 编译为 WebAssembly,实现“纯前端交互”,但体积大、BLAS 加速缺失,需要提前评估性能。
  2. 对于超大规模矩阵(>50 GB),单机构建会 OOM,可在 _config.yml 中设置 execute: timeout: 3600 与 run_in_temp: false,并把数据挂载到只读分布式文件系统,通过 Dask 延迟计算,再回写小型结果到文档。
  3. 面试追问:“如何让用户在文档里改参数并实时看到加速比?”——可把 ipywidgets 与 numba 并行:
    import ipywidgets as wg  
    @wg.interact(n=wg.IntSlider(1_000_000, min=1e5, max=1e8, step=1e6))  
    def bench(n):  
        a = np.random.rand(n)  
        %timeit a + a  
    
    此交互单元在 JupyterBook 中需加 thebe 插件,才能“就地运行”。
  4. 国内 2025 年信创环境可能使用 ARM+麒麟+OpenBLAS,需在 Dockerfile 中判断架构并切换 numpy 包名(numpy-openblas-arm64),否则面试会被质疑“只会在 x86 上跑”。