0
我正在學習如何使用scikit-learn使用python v3.6做機器學習的決策樹。用graphwiz顯示這個決策樹
這是代碼;
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import mglearn
import graphviz
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
cancer = load_breast_cancer()
X_train, X_test, y_train, y_test = train_test_split(cancer.data, cancer.target, stratify=cancer.target, random_state=42)
tree = DecisionTreeClassifier(random_state=0)
tree.fit(X_train, y_train)
tree = DecisionTreeClassifier(max_depth=4, random_state=0)
tree.fit(X_train, y_train)
from sklearn.tree import export_graphviz
export_graphviz(tree, out_file="tree.dot", class_names=["malignant", "benign"],feature_names=cancer.feature_names, impurity=False, filled=True)
import graphviz
with open("tree.dot") as f:
dot_graph = f.read()
graphviz.Source(dot_graph)
如何使用graphviz查看dot_graph內部是什麼?據推測,它應該看起來像這樣;
檢查[export_graphviz](http://scikit-learn.org/stable/modules/generated/sklearn.tree.export_graphviz.html)函數,您可以使用該函數將.dot轉換爲其他格式,例如.png –