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 27 Python
Python内置数据结构与操作符的练习题集锦
Jul 01 Python
Python 字符串大小写转换的简单实例
Jan 21 Python
Python生成随机密码的方法
Jun 16 Python
利用PyCharm Profile分析异步爬虫效率详解
May 08 Python
python图形工具turtle绘制国际象棋棋盘
May 23 Python
java中的控制结构(if,循环)详解
Jun 26 Python
解决Jupyter无法导入已安装的 module问题
Apr 17 Python
详解python tcp编程
Aug 24 Python
Python识别验证码的实现示例
Sep 30 Python
Python常用扩展插件使用教程解析
Nov 02 Python
python基础入门之字典和集合
Jun 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
php中通过正则表达式下载内容中的远程图片的函数代码
2012/01/10 PHP
深入理解PHP几个算法:PHP冒泡、PHP二分法、PHP求素数、PHP乘法表
2013/06/06 PHP
PHP中使用addslashes函数转义的安全性原理分析
2014/11/03 PHP
php实现用已经过去多长时间的方式显示时间
2015/06/05 PHP
Javascript 日期处理之时区问题
2009/10/08 Javascript
jQuery过滤选择器详解
2015/01/13 Javascript
jQuery检测滚动条是否到达底部
2015/12/15 Javascript
Javascript中prototype的使用详解
2016/06/18 Javascript
解析JavaScript实现DDoS攻击原理与保护措施
2016/12/26 Javascript
Angular实现点击按钮后在上方显示输入内容的方法
2017/12/27 Javascript
解决vue项目中遇到 Cannot find module ‘chalk‘ 报错的问题
2020/11/05 Javascript
[03:15]2014DOTA2国际邀请赛 专访国士无双信心满满
2014/07/12 DOTA
Python编写屏幕截图程序方法
2015/02/18 Python
详细介绍Python函数中的默认参数
2015/03/30 Python
Python matplotlib绘图可视化知识点整理(小结)
2018/03/16 Python
和孩子一起学习python之变量命名规则
2018/05/27 Python
使用Python实现微信提醒备忘录功能
2018/12/04 Python
Python3爬虫之自动查询天气并实现语音播报
2019/02/21 Python
python 计算平均平方误差(MSE)的实例
2019/06/29 Python
Tensorflow 实现分批量读取数据
2020/01/04 Python
python 爬取古诗文存入mysql数据库的方法
2020/01/08 Python
Python字符串hashlib加密模块使用案例
2020/03/10 Python
python能否java成为主流语言吗
2020/06/22 Python
编辑找工作求职信分享
2014/01/03 职场文书
高一地理教学反思
2014/01/18 职场文书
一年级家长会邀请函
2014/01/25 职场文书
2014年元旦活动方案
2014/02/15 职场文书
房屋出租协议书范本(标准版)
2014/09/24 职场文书
学校运动会广播稿范文
2014/10/02 职场文书
模范教师材料大全
2014/12/16 职场文书
典型事迹材料范文
2014/12/29 职场文书
学校光盘行动倡议书
2015/04/28 职场文书
电力安全教育培训心得体会
2016/01/11 职场文书
《角的初步认识》教学反思
2016/02/17 职场文书
Python爬虫之自动爬取某车之家各车销售数据
2021/06/02 Python
【海涛教你打DOTA】黑鸟第一视角解说
2022/04/01 DOTA