python机器学习实现决策树


Posted in Python onNovember 11, 2019

本文实例为大家分享了python机器学习实现决策树的具体代码,供大家参考,具体内容如下

# -*- coding: utf-8 -*-
"""
Created on Sat Nov 9 10:42:38 2019

@author: asus
"""
"""
决策树
目的:
1. 使用决策树模型
2. 了解决策树模型的参数
3. 初步了解调参数
要求:
基于乳腺癌数据集完成以下任务:
1.调整参数criterion,使用不同算法信息熵(entropy)和基尼不纯度算法(gini)
2.调整max_depth参数值,查看不同的精度
3.根据参数criterion和max_depth得出你初步的结论。
"""

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import mglearn 
from sklearn.model_selection import train_test_split
#导入乳腺癌数据集
from sklearn.datasets import load_breast_cancer
from sklearn.tree import DecisionTreeClassifier


#决策树并非深度越大越好,考虑过拟合的问题
#mglearn.plots.plot_animal_tree()
#mglearn.plots.plot_tree_progressive()

#获取数据集
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)
#查看训练集和测试集数据      
print('train dataset :{0} ;test dataset :{1}'.format(X_train.shape,X_test.shape))
#建立模型(基尼不纯度算法(gini)),使用不同最大深度和随机状态和不同的算法看模型评分
tree = DecisionTreeClassifier(random_state = 0,criterion = 'gini',max_depth = 5)
#训练模型
tree.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)))
print(tree)


# 参数选择 max_depth,算法选择基尼不纯度算法(gini) or 信息熵(entropy)
def Tree_score(depth = 3,criterion = 'entropy'):
 """
 参数为max_depth(默认为3)和criterion(默认为信息熵entropy),
 函数返回模型的训练精度和测试精度
 """
 tree = DecisionTreeClassifier(criterion = criterion,max_depth = depth)
 tree.fit(X_train,y_train)
 train_score = tree.score(X_train, y_train)
 test_score = tree.score(X_test, y_test)
 return (train_score,test_score)

#gini算法,深度对模型精度的影响
depths = range(2,25)#考虑到数据集有30个属性
scores = [Tree_score(d,'gini') for d in depths]
train_scores = [s[0] for s in scores]
test_scores = [s[1] for s in scores]

plt.figure(figsize = (6,6),dpi = 144)
plt.grid()
plt.xlabel("max_depth of decision Tree")
plt.ylabel("score")
plt.title("'gini'")
plt.plot(depths,train_scores,'.g-',label = 'training score')
plt.plot(depths,test_scores,'.r--',label = 'testing score')
plt.legend()


#信息熵(entropy),深度对模型精度的影响
scores = [Tree_score(d) for d in depths]
train_scores = [s[0] for s in scores]
test_scores = [s[1] for s in scores]

plt.figure(figsize = (6,6),dpi = 144)
plt.grid()
plt.xlabel("max_depth of decision Tree")
plt.ylabel("score")
plt.title("'entropy'")
plt.plot(depths,train_scores,'.g-',label = 'training score')
plt.plot(depths,test_scores,'.r--',label = 'testing score')
plt.legend()

运行结果:

python机器学习实现决策树

python机器学习实现决策树

python机器学习实现决策树

很明显看的出来,决策树深度越大,训练集拟合效果越好,但是往往面对测试集的预测效果会下降,这就是过拟合。

参考书籍: 《Python机器学习基础教程》

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python字典操作简明总结
Apr 13 Python
Python 使用os.remove删除文件夹时报错的解决方法
Jan 13 Python
python中 chr unichr ord函数的实例详解
Aug 06 Python
python3.x 将byte转成字符串的方法
Jul 17 Python
python基础知识(一)变量与简单数据类型详解
Apr 17 Python
python实现视频读取和转化图片
Dec 10 Python
Win10里python3创建虚拟环境的步骤
Jan 31 Python
PyCharm无法识别PyQt5的2种解决方法,ModuleNotFoundError: No module named 'pyqt5'
Feb 17 Python
python os模块常用的29种方法使用详解
Jun 02 Python
使用Keras预训练好的模型进行目标类别预测详解
Jun 27 Python
Python实现手绘图效果实例分享
Jul 22 Python
利用Pycharm连接服务器的全过程记录
Jul 01 Python
Python SQLAlchemy入门教程(基本用法)
Nov 11 #Python
django中间键重定向实例方法
Nov 10 #Python
Java文件与类动手动脑实例详解
Nov 10 #Python
python语言线程标准库threading.local解读总结
Nov 10 #Python
Python 脚本拉取 Docker 镜像问题
Nov 10 #Python
Python如何优雅获取本机IP方法
Nov 10 #Python
python argparser的具体使用
Nov 10 #Python
You might like
Yii2框架可逆加密简单实现方法
2017/08/25 PHP
Laravel 关联模型-关联新增和关联更新的方法
2019/10/10 PHP
使用新的消息弹出框blackbirdjs
2008/10/16 Javascript
jquery struts 验证唯一标识(公用方法)
2013/03/27 Javascript
JavaScript函数的4种调用方法详解
2014/04/22 Javascript
node.js中的socket.io入门实例
2014/04/26 Javascript
JS跨域问题详解
2014/11/25 Javascript
JavaScript字符串删除重复字符的方法
2015/12/25 Javascript
angularjs自定义ng-model标签的属性
2016/01/21 Javascript
关于cookie的初识和运用(js和jq)
2016/04/07 Javascript
微信小程序 location API实例详解
2016/10/02 Javascript
js处理层级数据结构的方法小结
2017/01/17 Javascript
echarts学习笔记之箱线图的分析与绘制详解
2017/11/22 Javascript
jQuery实现的淡入淡出图片轮播效果示例
2018/08/29 jQuery
在微信小程序中渲染HTML内容的方法示例
2018/09/28 Javascript
JS实现的点击按钮图片上下滚动效果示例
2019/01/28 Javascript
laypage+SpringMVC实现后端分页
2019/07/27 Javascript
JQuery实现ul中添加LI和删除指定的Li元素功能完整示例
2019/10/16 jQuery
微信小程序学习之自定义滚动弹窗
2020/12/20 Javascript
[02:10]探秘浦东源深体育馆 DOTA2 Supermajor不见不散
2018/05/17 DOTA
Python彩色化Linux的命令行终端界面的代码实例分享
2016/07/02 Python
python中日志logging模块的性能及多进程详解
2017/07/18 Python
Python探索之pLSA实现代码
2017/10/25 Python
对numpy.append()里的axis的用法详解
2018/06/28 Python
python如何实现数据的线性拟合
2019/07/19 Python
python获取全国城市pm2.5、臭氧等空气质量过程解析
2019/10/12 Python
获取python运行输出的数据并解析存为dataFrame实例
2020/07/07 Python
《童年》教学反思
2014/02/18 职场文书
查摆问题自我剖析材料
2014/08/18 职场文书
2014年会计工作总结
2014/11/27 职场文书
2015年效能监察工作总结
2015/04/23 职场文书
学校2015年纠风工作总结
2015/05/15 职场文书
Python爬取某拍短视频
2021/06/11 Python
Jackson 反序列化时实现大小写不敏感设置
2021/06/29 Java/Android
java objectUtils 使用可能会出现的问题
2022/02/28 Java/Android
redis protocol通信协议及使用详解
2022/07/15 Redis