问题
如何将graphviz.dot.Digraph
转换为networkx.Graph
(或它的任何子类)?
动机
LightGBM是一个基于树的算法的实现,它有一个函数返回一个graphviz.dot.Digraph
对象.这种类型的对象可以表示任何有向图,但我的图具体是一棵树,因此可以通过更简单的嵌套结构用JSON表示:
var tree = {
"name": "parent",
"children": [
{
"name": "child_1"
}
{
"name": "child_2"
}
[
}
上述JSON结构的另一个较长的示例是这里。我使用这种JSON格式来使用d3
在javascript
中创建树可视化。
总之,我需要将这个graphviz.dot.Digraph
对象转换成上面嵌套的-JSON格式。
如果我能够将这个graphviz.dot.Digraph
对象转换成一个networkx.Graph
对象,我可以使用这种方法将它转换成所需的JSON格式。这种中间转换对我来说是有问题的。看来我需要另一种转换为networkx
能用。
发布于 2017-12-06 19:32:11
将graphviz.dot.Digraph
转换为networkx.Graph
的一种方法是将其转换为pydotplus.graphviz.Dot
对象,并将其转换为继承自graph
的networkx.classes.multidigraph.MultiDiGraph
对象。
#--------------------
# Do whatever it is you do to create the graphviz.Digraph object
import lightgbm as lgbm
# .......
digraph = lgbm.create_tree_digraph(model)
print(type(digraph)) # prints <class 'graphviz.dot.Digraph'>
#--------------------
# Perform the conversion to networkx
import pydotplus
import networkx
dotplus = pydotplus.graph_from_dot_data(digraph.source)
print(type(dotplus)) # prints <class 'pydotplus.graphviz.Dot'>
# if graph doesn't have multiedges, use dotplus.set_strict(true)
nx_graph = networkx.nx_pydot.from_pydot(dotplus)
print(type(nx_graph)) # prints <class 'networkx.classes.multidigraph.MultiDiGraph'>
其余部分只供考虑转换为JSON的人使用
#--------------------
# Optionally, convert to json
import json
# must specify whatever node is the root of the tree, here its 'split0'
# or you can try list(graph)[0] if you're not sure.
data = networkx.readwrite.json_graph.tree_data(nx_graph,root='split0')
# data is just a dictionary. Dump results in proper json format.
json.dump(data,open(file_path,'w'))
后来,我发现LightGBM实际上有一个dump_model方法,它可以快速选择所有的this...but,我将把这个放在这里。
https://stackoverflow.com/questions/47681617
复制相似问题