在 png 或 pdf 中可视化 scikit-learn/sklearn 多输出决策树回归

Visualizing scikit-learn/ sklearn multi-output decision tree regression in png or pdf

这是我在 Whosebug 上发布的第一个问题,因此对于布局等方面的任何错误,我深表歉意(欢迎提出建议)。非常感谢您的帮助!

我正在尝试使用 pydot 以 png 或 pdf 格式可视化具有多个输出的 DecisionTreeRegressor 的输出(如 http://scikit-learn.org/stable/auto_examples/tree/plot_tree_regression_multioutput.html#example-tree-plot-tree-regression-multioutput-py 中所述)。

我试过的代码是这样的:

...
dtreg = tree.DecisionTreeRegressor(max_depth=3)
dtreg.fit(x,y)

tree.export_graphviz(dtreg, out_file='tree.dot') #print dotfile

dot_data = StringIO()
tree.export_graphviz(dtreg, out_file=dot_data)
print dot_data.getvalue()
pydot.graph_from_dot_data(dot_data.getvalue()).write_pdf("pydot_try.pdf") 

写pdf出现以下错误:

pydot.InvocationException: Program terminated with status: 1. stderr follows: Warning: /tmp/tmpAy7d59:7: string ran past end of line Error: /tmp/tmpAy7d59:8: syntax error near line 8 context: >>> [ <<< 0.20938667] Warning: /tmp/tmpAy7d59:18: string ran past end of line Warning: /tmp/tmpAy7d59:20: string ran past end of line

等等更多 "string ran past end of line" 错误。

我以前从未使用过 .dot,但我怀疑多输出格式可能存在问题。例如,树的一部分如下所示:

digraph Tree {
0 [label="X[0] <= 56.0000\nmse = 0.0149315126135\nsamples = 41", shape="box"] ;
1 [label="X[0] <= 40.0000\nmse = 0.0137536911947\nsamples = 25", shape="box"] ;
0 -> 1 ;
2 [label="X[0] <= 24.0000\nmse = 0.0152142545276\nsamples = 21", shape="box"] ;
1 -> 2 ;
3 [label="mse = 0.0140\nsamples = 15\nvalue = [[ 0.83384667]
 [ 0.20938667]
 [ 0.08511333]
 [ 0.04234667]
 [ 0.08158   ]
 [ 0.17948667]
 [ 0.03616   ]
 [ 0.00995333]
 [ 0.99529333]
 [ 0.13715333]
 [ 0.10294667]
 [ 0.06632667]]", shape="box"] ;
2 -> 3 ;
4 [label="mse = 0.0170\nsamples = 6\nvalue = [[ 0.69588333]
 [ 0.20275   ]
 [ 0.0953    ]
 [ 0.0436    ]
 [ 0.1216    ]
 [ 0.17248333]
 [ 0.04393333]
 [ 0.01178333]
 [ 0.99913333]
 [ 0.12348333]
 [ 0.10838333]
 [ 0.06973333]]", shape="box"] ;
2 -> 4 ;
}

我不知道如何解决这个问题,因为那只是我从 DecisionTreeRegressor 获得的输出。

我也试过转换点文件:

dot -Tpng tree.dot -o tree.png

但这给出了相同的错误(字符串 运行 超过行尾) 我还尝试使用 xdot 可视化 tree.dot,结果出现了同样的错误。

错误消息似乎是在告诉您多行字符串(标签)存在问题。如图here, to specify multiline labels in dot you can use \n, or alternatively as described in the DOT language documentation:

As another aid for readability, dot allows double-quoted strings to span multiple physical lines using the standard C convention of a backslash immediately preceding a newline character.

就是说,当我尝试在 Graphviz 版本 2.39.20141007.0445 上使用 dot 生成您的图时,它工作得非常好:

我找不到关于格式更改的参考,但是可能值得再次尝试安装最新版本的 Graphviz。

按照以下说明查看决策树。

•使用sklearn,我们可以以点格式导出树。 “点”格式文件是文本文件。

•可以使用“graphviz”实用程序将“点”文件转换为图像文件

•从网站下载‘graphviz.msi’ - http://www.graphviz.org/Download_windows.php

•确保将“\graphviz\bin”添加到环境变量中的“路径”。

可以在以下命令的帮助下使用 sklearn 模块提取“点”文件

from sklearn import tree
tree.export_graphviz(clf,out_file='tree.dot')

在命令提示符下执行以下命令将“.dot”文件转换为“.png”文件。

 dot -Tpng tree.dot -o tree.png