LightGBM模型树图存为PNG遇问题,求解决方案及插入Excel方法
解决LightGBM树图保存与写入Excel的问题
针对你遇到的三个核心问题——plot_tree数值空白、create_tree_digraph保存失败、树图写入Excel,我整理了分步解决方案:
1. 修复plot_tree的数值空白问题
你看到的空白框通常是matplotlib渲染时的字体缺失或参数未正确设置导致的,可以通过以下代码修复:
import lightgbm as lgb import matplotlib.pyplot as plt from sklearn.datasets import load_iris X, y = load_iris(True) clf = lgb.LGBMClassifier() clf.fit(X, y) # 明确指定要显示的数值类型+调整渲染参数 ax = lgb.plot_tree(clf, tree_index=0, show_info=['split_gain', 'internal_value', 'internal_count', 'leaf_count'], figsize=(20, 10), dpi=100) # 设置字体避免空白(中文环境用SimHei,英文环境可换Arial) plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False # 保存plot_tree生成的图 plt.savefig('plot_tree_result.png', bbox_inches='tight') plt.show()
show_info参数强制指定要渲染的数值类型,确保内容不会留白;- 调整
figsize和dpi提升图的清晰度; - 字体设置解决系统渲染时的字符缺失问题。
2. 正确保存create_tree_digraph生成的树图
create_tree_digraph返回的是graphviz原生Digraph对象,直接调用它的render方法就能保存为png,无需额外的graphviz.Source操作:
import lightgbm as lgb from sklearn.datasets import load_iris X, y = load_iris(True) clf = lgb.LGBMClassifier() clf.fit(X, y) # 生成Digraph对象并指定显示信息 digraph = lgb.create_tree_digraph(clf, tree_index=0, name='Iris_LightGBM_Tree', show_info=['split_gain', 'internal_value']) # 直接保存为png,cleanup=True会自动删除中间生成的gv文件 digraph.render(filename='tree_digraph_result', format='png', cleanup=True)
这样生成的图清晰度更高,也不会和plot_tree的输出混淆。
3. 将树图写入Excel
可以用openpyxl库实现图片插入,先安装依赖:
pip install openpyxl
然后执行以下代码插入图片到Excel:
from openpyxl import Workbook from openpyxl.drawing.image import Image # 创建Excel工作簿 wb = Workbook() ws = wb.active ws.title = "LightGBM树图" # 插入plot_tree生成的图,调整尺寸避免重叠 img1 = Image('plot_tree_result.png') img1.width = 600 img1.height = 300 ws.add_image(img1, 'A1') # 插入create_tree_digraph生成的图 img2 = Image('tree_digraph_result.png') img2.width = 600 img2.height = 300 ws.add_image(img2, 'A20') # 保存Excel文件 wb.save('LightGBM_Trees.xlsx')
额外注意事项
- 如果你的graphviz 0.8.3版本仍有兼容问题,可以尝试升级:
pip install --upgrade graphviz; - 英文系统下,字体设置可改为
plt.rcParams['font.sans-serif'] = ['Arial']; create_tree_digraph生成的矢量转png图清晰度更高,更适合插入Excel文档。
内容的提问来源于stack exchange,提问作者Archana
相关产品推荐
相关产品推荐

