python实现决策树和可视化决策树

一.python实现决策树

from sklearn import tree
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split

导入数据集,这里用的是自带的酒的数据

wine=load_wine()#数据集

拆分数据集(前面的几个变量是不能交换位置的,test_size意思是拆分后训练集和测试集的比例)

Xtrain,Xtest,Ytrain,Ytest=train_test_split(wine.data,wine.target,test_size=0.3)

训练并查看一下准确度

#训练
clf=tree.DecisionTreeClassifier(criterion='entropy')
clf=clf.fit(Xtrain,Ytrain)
#查看一下准确度
score=clf.score(Xtest,Ytest)

训练结果:
在这里插入图片描述
二.可视化决策树
首先需要安装graphviz包

import graphviz

然后需要对特征值赋予列名

f_name=['酒精','苹果酸','灰','灰的碱性','镁','总酚','类黄酮','非黄烷类酚类','花青素','颜色强度','色调','稀释葡萄酒','脯氨酸']

作图:


dot_data=tree.export_graphviz(clf
                              ,feature_names=f_name
                              ,class_names=['茅台','啤酒','黄酒']
                              ,filled=True
                              ,rounded=True,
                              out_file=None
                             )
graph=graphviz.Source(dot_data)
graph

在这里插入图片描述
三.决策树的优化
1.增加随机性:
random_state=30
splitter=’random’
2.剪枝策略
max_depth一般从3开始尝试
min_ samples_ leaf 一般和max_depth搭配使用,一般从5开始尝试
样本数量小于min_ samples_ leaf的分支将会被剪掉
3.简单实现使用代码查看max_depth的最好参数,这里只是简单看一下,因为不可能这么多参数都用这个方法一个个列出来

import matplotlib.pyplot as plt
test = []
for i in range(10):
    clf=tree.DecisionTreeClassifier(max_depth=i+1,criterion='entropy',random_state=30)
    clf=clf.fit(Xtrain,Ytrain)
    score = clf.score(Xtest, Ytest)
    test.append(score)
plt.plot(range(1, 11),test ,color='red',label='max_depth')
plt.legend()
plt.show()

在这里插入图片描述
在如上所示的图中可以得出结论,在这个数据中,max_depth=3是最好的,因为在3的时候已经达到了最高点,并且是最高点中计算容量最小的点

  • 1
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值