划分数据集,实现决策树,评价得分,可视化

决策树实现

import os
import pydotplus
from odps.df.backends import pd
from sklearn import tree
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
data = open(r'new.csv')
df = pd.read_csv(data)

#区分训练集(0.75)测试集(0.25)
X_train, X_test, Y_train, Y_test = train_test_split(df[['creation_date']], df['type'], random_state=0)#随机状态random_state

参数说明

#决策树
clf = DecisionTreeClassifier(max_depth = 5,random_state = 0,splitter = 'random',min_samples_split=500,min_samples_leaf=500,max_leaf_nodes=20)
clf.fit(X_train, Y_train)
#测试精度
score = clf.score(X_test, Y_test)

可视化安装graphviz
切记配置环境变量

os.environ["PATH"] += os.pathsep + 'D:/bcrj/python/Lib/Graph/bin/'#本地目录

dot_data = tree.export_graphviz(clf, out_file=None,feature_names=['creation_date'],class_names=['0','1'],filled=True, rounded=True,special_characters=True) #利用export_graphviz将树导出为Graphviz格式
graph = pydotplus.graph_from_dot_data(dot_data)
graph.write_pdf("tree.pdf")  #保存树图.pdf到本地

你可能感兴趣的:(Python)