2015-10-12 57 views
2

我的目標是在IPython筆記本中顯示決策樹。我的問題是,當我嘗試渲染它時,它會打開一個新窗口,但我希望它以內聯方式顯示(如matplotlib圖)。在IPython Notebook中顯示決策樹

這裏是我使用的代碼:

def show_tree(decisionTree, out_file, feature_names): 
    out_file = 'viz_tree/' + out_file 
    export_graphviz(decisionTree, out_file=out_file, feature_names=feature_names) 
    dot = '' 
    with open(out_file, 'r') as file: 
     for line in file: 
      dot += line 
    dot = Source(dot) 
    return dot 

decisionTree.fit(inputs, outputs) 
d = show_tree(decisionTree, 'tree.dot', col_names) 
d.render(view=True) 

我知道這是可能做到這一點example的是因爲。

你知道我該怎麼做嗎?

回答

6

我最終什麼事做的是從源頭上安裝pydot library(畫中畫安裝似乎打破了python3),然後使用此功能:

import io 
from scipy import misc 

def show_tree(decisionTree, file_path): 
    dotfile = io.StringIO() 
    export_graphviz(decisionTree, out_file=dotfile) 
    pydot.graph_from_dot_data(dotfile.getvalue()).write_png(file_path) 
    i = misc.imread(file_path) 
    plt.imshow(i) 

# To use it 
show_tree(decisionT, 'test.png') 

這使圖像保持其路徑被定義在文件中文件路徑。然後簡單地讀取它作爲一個PNG來顯示它。

希望它能幫助你們中的一些人!