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 fabric使用笔记
May 09 Python
在Python中处理时间之clock()方法的使用
May 22 Python
python实现在控制台输入密码不显示的方法
Jul 02 Python
浅谈python import引入不同路径下的模块
Jul 11 Python
Python实现二维曲线拟合的方法
Dec 29 Python
python 反编译exe文件为py文件的实例代码
Jun 27 Python
Python关于__name__属性的含义和作用详解
Feb 19 Python
对django 2.x版本中models.ForeignKey()外键说明介绍
Mar 30 Python
如何使用Python调整图像大小
Sep 26 Python
linux mint中搜狗输入法导致pycharm卡死的问题
Oct 28 Python
Django后端按照日期查询的方法教程
Feb 28 Python
python实现socket简单通信的示例代码
Apr 13 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
一首老MP3,致敬WAR3经典
2021/03/08 魔兽争霸
第四节--构造函数和析构函数
2006/11/16 PHP
某大型网络公司应聘时的笔试题目附答案
2008/03/27 PHP
thinkPHP使用post方式查询时分页失效的解决方法
2015/12/09 PHP
将HTML自动转为JS代码
2006/06/26 Javascript
utf8的编码算法 转载
2006/12/27 Javascript
javascript 学习之旅 (1)
2009/02/05 Javascript
浅析JavaScript中的常用算法与函数
2013/11/21 Javascript
基于JavaScript实现定时跳转到指定页面
2016/01/01 Javascript
设计模式中的facade外观模式在JavaScript开发中的运用
2016/05/18 Javascript
结合代码图文讲解JavaScript中的作用域与作用域链
2016/07/05 Javascript
封装的dialog插件 基于bootstrap模态对话框的简单扩展
2016/08/10 Javascript
vue 中自定义指令改变data中的值
2017/06/02 Javascript
jQuery常见面试题之DOM操作详析
2017/07/05 jQuery
实例详解BootStrap的动态模态框及静态模态框
2018/08/13 Javascript
js实现登录时记住密码的方法分析
2020/04/05 Javascript
Vue管理系统前端之组件拆分封装详解
2020/08/23 Javascript
[05:20]卡尔工作室_DOTA2新手教学_DOTA2超强新手功能
2013/04/22 DOTA
Python常用列表数据结构小结
2014/08/06 Python
Python简单计算文件MD5值的方法示例
2018/04/11 Python
一行代码让 Python 的运行速度提高100倍
2018/10/08 Python
Python matplotlib画曲线例题解析
2020/02/07 Python
python使用Thread的setDaemon启动后台线程教程
2020/04/25 Python
One.com挪威:北欧成长最快的网络托管公司
2016/11/19 全球购物
携程英文网站:Trip.com
2017/02/07 全球购物
一家外企的面试题目(C/C++面试题,C语言面试题)
2014/03/24 面试题
写给女朋友的检讨书
2014/01/28 职场文书
大学生军训感想
2014/02/16 职场文书
竞聘书怎么写,如何写?
2014/03/31 职场文书
廉洁校园实施方案
2014/05/25 职场文书
计生专干事迹
2014/05/28 职场文书
金融与证券专业求职信
2014/06/22 职场文书
农业局党的群众路线教育实践活动整改方案
2014/09/20 职场文书
在职证明书模板
2015/06/15 职场文书
MySQL中distinct与group by之间的性能进行比较
2021/05/26 MySQL
Python 实现绘制子图及子图刻度的变换等问题
2021/05/31 Python