如何在保留图表的前提下减小大ipynb文件体积以发布至GitHub?
解决Jupyter Notebook过大无法上传GitHub且保留图表的方法
压缩内嵌图表的体积
Notebook内嵌图表多为Base64编码的高清图片,是文件体积过大的主要原因之一。可以用以下Python脚本遍历并压缩输出中的图片:import base64 import json from io import BytesIO from PIL import Image def compress_notebook_images(notebook_path, quality=70, target_format="JPEG"): with open(notebook_path, "r", encoding="utf-8") as f: nb = json.load(f) for cell in nb.get("cells", []): if "outputs" in cell: for output in cell["outputs"]: if "data" in output and "image/png" in output["data"]: # 解码PNG图片 img_data = base64.b64decode(output["data"]["image/png"]) img = Image.open(BytesIO(img_data)) # 转换格式并压缩 buffer = BytesIO() img.convert("RGB").save(buffer, format=target_format, quality=quality) compressed_data = base64.b64encode(buffer.getvalue()).decode("utf-8") # 替换为压缩后的图片数据 output["data"][f"image/{target_format.lower()}"] = compressed_data # 移除原PNG数据(可选) del output["data"]["image/png"] # 保存压缩后的Notebook with open(f"compressed_{notebook_path}", "w", encoding="utf-8") as f: json.dump(nb, f, indent=2) # 调用示例 compress_notebook_images("your_notebook.ipynb", quality=60)若需保留图表透明度,可将
target_format改为WebP,需提前安装pillow-webp依赖。将图表外置,用相对路径引用
避免将图表内嵌到Notebook,而是生成图表时保存到本地文件夹(如images/),再用Markdown引用:# 生成并保存图表到本地 import matplotlib.pyplot as plt plt.figure(figsize=(10,6)) plt.plot([1,2,3,4]) plt.savefig("images/plot.png", dpi=100, bbox_inches="tight") plt.close()在Markdown单元格中添加引用:
上传时将Notebook与
images/文件夹一并推送到GitHub,既能大幅减小Notebook体积,又能正常显示图表。使用Git LFS托管大文件
GitHub官方的Git LFS支持单个最大5GB的文件,适合内嵌大量图表的大体积Notebook:- 安装Git LFS(根据系统选择对应安装方式)
- 在本地仓库初始化LFS:
git lfs install - 跟踪.ipynb文件:
git lfs track "*.ipynb" - 提交并推送:
git add .gitattributes your_notebook.ipynb,随后执行git commit -m "Add notebook via Git LFS"和git push
尝试替代压缩工具
若ipynbcompress无效,可试用nbcompress工具:- 安装工具:
pip install nbcompress - 执行压缩:
nbcompress your_notebook.ipynb --output compressed_notebook.ipynb
该工具会自动压缩内嵌图片和冗余的Notebook数据。
- 安装工具:
内容的提问来源于stack exchange,提问作者Júnior Luz
相关产品推荐
相关产品推荐

