python決策樹(二叉樹、樹)的可視化

問題描述

在我學(xué)習(xí)機(jī)器學(xué)習(xí)實(shí)戰(zhàn)-決策樹部分,欲可視化決策樹結(jié)構(gòu)。最終可視化結(jié)果:

在這里插入圖片描述
在這里插入圖片描述

解決方案

決策樹由嵌套字典組成,如:

{"no surfacing": {0: "no", 1: {"flippers": {0: "no", 1: "yes"}}}}

{'tearRate': {'reduced': 'no lenses', 'normal': {'astigmatic': {'no': {'age': {'young': 'soft', 'presbyopic': {'prescript': {'myope': 'no lenses', 'hyper': 'soft'}}, 'pre': 'soft'}}, 'yes': {'prescript': {'myope': 'hard', 'hyper': {'age': {'young': 'hard', 'presbyopic': 'no lenses', 'pre': 'no lenses'}}}}}}}}

使用graphviz包中的畫點(diǎn)和連線。代碼如下:

"""
@author: lishihang
@software: PyCharm
@file: TreeVis.py
@time: 2018/11/29 22:20
"""
from graphviz import Digraph


def plot_model(tree, name):
    g = Digraph("G", filename=name, format='png', strict=False)
    first_label = list(tree.keys())[0]
    g.node("0", first_label)
    _sub_plot(g, tree, "0")
    g.view()


root = "0"


def _sub_plot(g, tree, inc):
    global root

    first_label = list(tree.keys())[0]
    ts = tree[first_label]
    for i in ts.keys():
        if isinstance(tree[first_label][i], dict):
            root = str(int(root) + 1)
            g.node(root, list(tree[first_label][i].keys())[0])
            g.edge(inc, root, str(i))
            _sub_plot(g, tree[first_label][i], root)
        else:
            root = str(int(root) + 1)
            g.node(root, tree[first_label][i])
            g.edge(inc, root, str(i))


d1 = {"no surfacing": {0: "no", 1: {"flippers": {0: "no", 1: "yes"}}}}

d2 = {'tearRate': {'reduced': 'no lenses', 'normal': {'astigmatic': {'yes': {
    'prescript': {'myope': 'hard', 'hyper': {'age': {'young': 'hard', 'presbyopic': 'no lenses', 'pre': 'no lenses'}}}},
    'no': {'age': {'young': 'soft', 'presbyopic': {
        'prescript': {'myope': 'no lenses',
                      'hyper': 'soft'}},
                   'pre': 'soft'}}}}}}

plot_model(d1, "hello.gv")
plot_model(d2, "hello2.gv")

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,854評論 0 10
  • 一夜秋雨終落盡 黃了幾樹葉 撫一把新添的哀思 呆看這一地凌亂 停落在殘瓣上的生命 已被洗去了茁壯的猖狂 掙扎在雨后...
    玉棲青梧閱讀 187評論 0 0
  • 【0210讀書感悟】曉陽 書名:《周國平論閱讀》 作者:周國平 金句:做一個(gè)真正的讀者,就是加入到人類精神文明的傳...
    阿凌_ee52閱讀 189評論 0 0
  • 以后無聊就有事情做了 好啦好啦 開始午睡
    邱了了閱讀 273評論 5 6
  • 最近不少大咖,都愛上了一個(gè)演員。 劉燁愛他。 宋丹丹愛他。 章子怡也愛他。 三位大咖都陶醉到?jīng)]辦法睜眼睛說話了.....
    Sir電影閱讀 14,105評論 38 258

友情鏈接更多精彩內(nèi)容