You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将eli5展示的sklearn决策树渲染为图片或PDF?

将eli5生成的决策树HTML转为图片/PDF的方法

下面是几种可行的解决方案,帮你把eli5输出的决策树HTML可视化内容转为图片或PDF格式:

方法1:浏览器打印功能快速转换

  • 在Jupyter Notebook中用display(explanation)渲染出决策树HTML
  • 右键页面空白处选择「打印」(或按Ctrl+P/Command+P)
  • 在打印设置面板中:
    • 若要存PDF,选择「另存为PDF」,调整页面方向为横向,勾选「背景图形」确保样式完整,再保存
    • 若要存图片,可在打印预览界面用系统截图工具截取完整树图,或部分浏览器支持直接选择保存为图片格式

方法2:用Python库批量转换HTML为图片/PDF

这类方法依赖wkhtmltopdf工具,需先安装:

  • Windows:下载安装包后添加到系统环境变量
  • macOS:brew install wkhtmltopdf
  • Linux:sudo apt-get install wkhtmltopdf

转为图片(使用imgkit)

  1. 安装依赖库:
    pip install imgkit
    
  2. 代码实现:
    import imgkit
    from eli5 import show_weights
    from sklearn.tree import DecisionTreeClassifier
    
    # 假设已训练好决策树模型clf,并有特征名列表feature_names
    explanation = show_weights(clf, feature_names=feature_names)
    # 提取HTML字符串
    html_content = explanation.data
    # 保存为图片
    imgkit.from_string(html_content, 'decision_tree_eli5.png')
    

转为PDF(使用pdfkit)

  1. 安装依赖库:
    pip install pdfkit
    
  2. 代码实现:
    import pdfkit
    
    html_content = explanation.data
    # 保存为PDF,可通过options参数调整页面大小、方向
    options = {'orientation': 'Landscape'}
    pdfkit.from_string(html_content, 'decision_tree_eli5.pdf', options=options)
    

方法3:用sklearn原生工具生成图片/PDF

如果不需要eli5的特定样式,也可以直接用sklearn自带的可视化工具生成并保存:

from sklearn.tree import plot_tree
import matplotlib.pyplot as plt

# 设置画布大小,确保树结构完整显示
plt.figure(figsize=(25, 12))
# 绘制决策树,filled参数填充节点颜色,rounded参数美化节点边角
plot_tree(clf, feature_names=feature_names, filled=True, rounded=True, fontsize=10)
# 保存为高清图片
plt.savefig('decision_tree_sklearn.png', dpi=300, bbox_inches='tight')
# 保存为PDF
plt.savefig('decision_tree_sklearn.pdf', bbox_inches='tight')
plt.close()

内容的提问来源于stack exchange,提问作者Marc Bacvanski

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 06:10:14