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

使用subprocess.call生成随机森林树图失败:无法创建PNG文件

问题:Windows下Anaconda环境中调用dot命令转换决策树dot文件为PNG失败

我使用Anaconda运行以下Python代码,已成功在指定路径生成tree.dot文件:

RESULTS_PATH = 'C:\...\results\'

from sklearn.tree import export_graphviz
# Export as dot file
export_graphviz(estimator, 
            out_file=RESULTS_PATH+'tree.dot', 
            feature_names = features,
            class_names = target_names,
            rounded = True, proportion = False, 
            precision = 2, filled = True)

但执行以下转换PNG的代码时出现异常:

# Convert to png
from subprocess import call
call(['dot', '-Tpng', RESULTS_PATH+'tree.dot', '-o', RESULTS_PATH+'tree.png', '-Gdpi=600']) #, shell=True)

报错信息如下:

FileNotFoundError: [WinError 2] The system cannot find the file specified

若启用shell=True选项,命令返回码为1(表示执行失败),且PNG文件未生成。请问问题出在哪里?


替代解决方案

我未查明具体问题根源,但推测是Windows环境下执行dot -Tpng tree.dot -o tree.png命令导致的问题。于是改用以下代码实现决策树可视化并保存为PNG文件:

fig, axes = plt.subplots(nrows = 1,ncols = 1,figsize = (4,4), dpi=800)
tree.plot_tree(model_WD.estimators_[0],
           feature_names = features, 
           class_names=target_names,
           filled = True);
fig.savefig(RESULTS_PATH+'rf_individualtree.png')

希望能帮助到遇到同样问题的人。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 22:25:24