《python机器学习基础教程》代码实现 随机森林--分类

DecisionTreeClassifier

from sklearn.tree import DecisionTreeClassifier
from sklearn.tree import export_graphviz
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
import graphviz
import matplotlib.pyplot as plt
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(max_depth=4,random_state=0).fit(X_train,y_train)
print("Accuracy on training set: {:.3f}".format(tree.score(X_train,y_train)))
print("Accuracy on test set:{:.3f}".format(tree.score(X_test,y_test)))
export_graphviz(tree,out_file="tree.dot",class_names=['malignant','benign'],feature_names=cancer.feature_names,impurity=False,filled=True)

with open("tree.dot") as f:
    dot_graph = f.read()
t = graphviz.Source(dot_graph)
plt.switch_backend('agg')
t.view()

你可能感兴趣的:(python机器学习基础教程,机器学习,python,回归)