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文件和目录操作函数小结
Jul 11 Python
python中pycurl库的用法实例
Sep 30 Python
Python中使用插入排序算法的简单分析与代码示例
May 04 Python
Python数据结构与算法之图的基本实现及迭代器实例详解
Dec 12 Python
使用Django启动命令行及执行脚本的方法
May 29 Python
pandas通过loc生成新的列方法
Nov 28 Python
想学python 这5本书籍你必看!
Dec 11 Python
python操作kafka实践的示例代码
Jun 19 Python
Python将列表中的元素转化为数字并排序的示例
Dec 25 Python
python中resample函数实现重采样和降采样代码
Feb 25 Python
python实现超级玛丽游戏
Mar 18 Python
地图可视化神器kepler.gl python接口的使用方法
Dec 22 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
php 无法加载mcrypt.dll的解决办法
2013/04/03 PHP
PHP中$_SERVER的详细参数与说明介绍
2013/10/26 PHP
html 锁定页面(js遮罩层弹出div效果)
2009/10/27 Javascript
json 入门基础教程 推荐
2009/10/31 Javascript
Jquery 高亮显示文本中重要的关键字
2009/12/24 Javascript
Js setInterval与setTimeout(定时执行与循环执行)的代码(可以传入参数)
2010/06/11 Javascript
异步加载script的代码
2011/01/12 Javascript
jquery的键盘事件修改代码
2011/02/24 Javascript
JQuery防止退格键网页后退的实现代码
2012/03/23 Javascript
JS简单实现文件上传实例代码(无需插件)
2013/11/15 Javascript
js实现数组去重、判断数组以及对象中的内容是否相同
2013/11/29 Javascript
js实现格式化金额,字符,时间的方法
2015/02/26 Javascript
原生JS实现-星级评分系统的简单实例
2016/08/21 Javascript
JS实现的图片预览插件与用法示例【不上传图片】
2016/11/25 Javascript
Node接收电子邮件的实例代码
2017/07/21 Javascript
用node开发并发布一个cli工具的方法步骤
2019/01/03 Javascript
原来JS还可以这样拆箱转换详解
2019/02/01 Javascript
了解javascript中的Dom操作
2019/05/27 Javascript
手把手教你如何编译打包video.js
2020/12/09 Javascript
swiper实现导航滚动效果
2020/12/13 Javascript
Python中字典映射类型的学习教程
2015/08/20 Python
python爬虫获取小区经纬度以及结构化地址
2018/12/30 Python
Python设计模式之原型模式实例详解
2019/01/18 Python
pyqt5 lineEdit设置密码隐藏,删除lineEdit已输入的内容等属性方法
2019/06/24 Python
python matplotlib折线图样式实现过程
2019/11/04 Python
Python将二维列表list的数据输出(TXT,Excel)
2020/04/23 Python
Python类super()及私有属性原理解析
2020/06/15 Python
Python偏函数Partial function使用方法实例详解
2020/06/17 Python
深入浅析python 中的self和cls的区别
2020/06/20 Python
美国真皮手袋品牌:GiGi New York
2017/03/10 全球购物
尤为Wconcept中国官网:韩国设计师品牌服饰
2019/01/10 全球购物
J2EE中的容器都包括哪些
2013/08/21 面试题
数控技术应届生求职信
2013/11/13 职场文书
摘录式读书笔记
2015/07/01 职场文书
煤矿安全生产工作总结
2015/08/13 职场文书
微前端qiankun改造日渐庞大的项目教程
2022/06/21 Javascript