def printtree(root,temp):
global countleaf
spaces = temp.level * 10
if temp.leaf:
print(" " *(spaces) + "=>If it is ", end=" ")
print(temp.when)
print(" "*spaces,end=" "),
print("Did he/she will play:"+str(temp.ans)+" Level("+str(temp.level)+")")
return
if root!=temp:
print(" " * spaces+"=>If it is ",end=" ")
print(temp.when)
print(" "*spaces,end=" ")
print("Class:"+str(temp.question)+" Level("+str(temp.level)+")")
for i in range(len(temp.children)):
if temp.children[i].question!=None:
G.add_edges_from([(str(temp.question),str(temp.children[i].question))],label=str(temp.children[i].when))
else:
countleaf = countleaf + 1
G.add_edges_from([(str(temp.question), str(temp.children[i].ans+"("+str(countleaf)+")"))], label=str(temp.children[i].when))
printtree(root,temp.children[i])
pos=nx.spring_layout(G)
edge_labels=dict([((u,v,),d['label'])
for u,v,d in G.edges(data=True)])
nx.draw_networkx_nodes(G,pos,cmap=None,node_size=2500)
nx.draw_networkx_labels(G, pos)
nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_labels)
nx.draw_networkx_edges(G,pos,arrows=True,arrowsize=70,width=6,style='dashed',alpha=0.5)
plt.show()
制作决策树图(可视化)。每次我运行程序图时,外观都会有所不同。
如何更改代码,使图形看起来像决策树?
我正在根据这些数据制作决策树:
|----------+------+----------+-------+------|
| Outlook | Temp | Humidity | Windy | Play |
| Rainy | Hot | High | FALSE | No |
| Rainy | Hot | High | TRUE | No |
| Overcast | Hot | High | FALSE | Yes |
| Sunny | Mild | High | FALSE | Yes |
| Sunny | Cool | Normal | FALSE | Yes |
| Sunny | Cool | Normal | TRUE | No |
| Overcast | Cool | Normal | TRUE | Yes |
| Rainy | Mild | High | FALSE | No |
| Rainy | Cool | Normal | FALSE | Yes |
| Sunny | Mild | Normal | FALSE | Yes |
| Rainy | Mild | Normal | TRUE | Yes |
| Overcast | Mild | High | TRUE | Yes |
| Overcast | Hot | Normal | FALSE | Yes |
| Sunny | Mild | High | TRUE | No |
|----------+------+----------+-------+------|
以下是该图的示例: