gpt4 book ai didi

python - 使用 pydot 绘制决策树

转载 作者:太空狗 更新时间:2023-10-30 01:15:06 26 4
gpt4 key购买 nike

我训练了一个决策(Python字典)如下。现在我正在尝试使用 pydot 绘制它.在定义树的每个节点(pydot 图)时,我为它指定了一个唯一(且冗长)的名称和一个简短的标签。

我的问题是,在我通过写入 .png 得到的结果图中,我看到了冗长的节点名称,而不是节点标签

我遵循了@Martijn Pieters 的回答 here .我不知道我错过了什么,有什么想法吗?

import pydot

tree= {'salary': {'41k-45k': 'junior', '46k-50k': {'department': {'marketing': 'senior', 'sales': 'senior', 'systems': 'junior'}}, '36k-40k': 'senior', '26k-30k': 'junior', '31k-35k': 'junior', '66k-70k': 'senior'}}

def walk_dictionaryv2(graph, dictionary, parent_node=None):
'''
Recursive plotting function for the decision tree stored as a dictionary
'''

for k in dictionary.keys():

if parent_node is not None:

from_name = parent_node.get_name().replace("\"", "") + '_' + str(k)
from_label = str(k)

node_from = pydot.Node(from_name, label=from_label)

graph.add_edge( pydot.Edge(parent_node, node_from) )

if isinstance(dictionary[k], dict): # if interim node


walk_dictionaryv2(graph, dictionary[k], node_from)

else: # if leaf node
to_name = str(k) + '_' + str(dictionary[k]) # unique name
to_label = str(dictionary[k])

node_to = pydot.Node(to_name, label=to_label, shape='box')
graph.add_edge(pydot.Edge(node_from, node_to))

#node_from.set_name(to_name)

else:

from_name = str(k)
from_label = str(k)

node_from = pydot.Node(from_name, label=from_label)
walk_dictionaryv2(graph, dictionary[k], node_from)


def plot_tree(tree, name):

# first you create a new graph, you do that with pydot.Dot()
graph = pydot.Dot(graph_type='graph')

walk_dictionaryv2(graph, tree)

graph.write_png(name+'.png')


plot_tree(tree,'name')

这是我用上面的代码得到的(不需要的)输出:

enter image description here

最佳答案

您需要明确地将您创建的节点添加到图中:

node_from = pydot.Node(from_name, label=from_label)
graph.add_node(node_from)

node_to = pydot.Node(to_name, label=to_label, shape='box')
graph.add_node(node_to)

否则渲染器将看不到名称。 graph.add_node() 在生成的 .dot 文件中包含节点元数据。

添加了 graph.add_node() 行后,结果是:

name.png

关于python - 使用 pydot 绘制决策树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24657384/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com