《机器学习(周志华)》笔记--决策树(6)--决策树构造代码实现
八、决策树构造
from sklearn import tree #决策树生成 clf = tree.DecisionTreeClassifier(criterion='entropy') clf = tree.DecisionTreeClassifier(criterion='gini') clf.fit(X,Y) dot_data = StringIO() tree.export_graphviz(clf, out_file = dot_data, feature_names=['color','root','sound','texture','navel','feeling'], class_names=['good','bad']) #决策树可视化 graph = pydotplus.graph_from_dot_data(dot_data.getvalue()) graph.write_pdf("tree.pdf")
具体代码实现:
import pandas as pd from sklearn import tree import pydotplus from sklearn.externals.six import StringIO df = pd.read_csv('ex4.csv',header=None) data = df.values X=data[:,:-1] Y=data[:,-1] clf = tree.DecisionTreeClassifier(criterion='entropy') clf.fit(X,Y) dot_data = StringIO() tree.export_graphviz(clf, out_file = dot_data,\ feature_names=['color','root','sound','texture','navel','feeling'],\ class_names=['good','bad']) graph = pydotplus.graph_from_dot_data(dot_data.getvalue()) graph.write_pdf("tree.pdf")