python机器学习实现决策树
作者:晒冷- 发布时间:2021-04-21 07:44:34
标签:python,决策树
本文实例为大家分享了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机器学习基础教程》
来源:https://blog.csdn.net/huangjiaaaaa/article/details/102987183


猜你喜欢
- 百度贴吧的爬虫制作和糗百的爬虫制作原理基本相同,都是通过查看源码扣出关键数据,然后将其存储到本地txt文件。项目内容:用Python写的百度
- 1. 换源,sohu的相当好用。 1.1备份CentOS-Base.repo cd /etc/yum.repos.d/ cp CentOS-
- 写在之前命名空间,又名 namesapce,是在很多的编程语言中都会出现的术语,估计很多人都知道这个词,但是让你真的来说这是个什么,估计就歇
- 1, 创建pytorch 的Tensor张量:torch.rand((3,224,224)) #创建随机值的三维张量,大小为(3,224,2
- 一、数据可视化1.pyecharts介绍官方网址:https://pyecharts.org/#/zh-cn/intro📣 概况:Echar
- 本文实例讲述了Python基于分水岭算法解决走迷宫游戏。分享给大家供大家参考,具体如下:#Solving maze with morphol
- 本文实例讲述了C#简单访问SQLite数据库的方法。分享给大家供大家参考,具体如下:下载最新版SQLite(http://www.sqlit
- 前言本文主要给大家介绍了关于Golang map生成有序json数据的相关内容,分享出来供大家参考学习,下面来一起看看详细的介绍:先来看一段
- 本文实例为大家分享了python3磁盘空间监控的具体代码,供大家参考,具体内容如下软硬件环境python3apscheduler前言在做频繁
- 如何引入同级包和模块工程项目结构如下包AnimalShow和Class_test是同级包,AnimalShow是父类,Gound,Sea,S
- 何为样本分布不均:样本分布不均衡就是指样本差异非常大,例如共1000条数据样本的数据集中,其中占有10条样本分类,其特征无论如何你和也无法实
- 最近买了个腾讯云服务器,搭建环境。该笔记用于系统上未装过mysql的干净系统第一次安装mysql。自己指定安装目录,指定数据文件目录。lin
- 一、效果展示在介绍代码之前,先来看下本文的实现效果。可以参考下面步骤把Python文件转化成exe,发给未安装Python的他/她。Pins
- 路由跳转了但界面不显示没有在父路由加上router-view,加上下面的代码即可。<!-- 路由匹配到的组件将显示在这里 -->
- 本文介绍机器学习中的Logistic回归算法,我们使用这个算法来给数据进行分类。Logistic回归算法同样是需要通过样本空间学习的监督学习
- 个人使用样例及部分翻译自官方文档,并详细介绍chart的使用一:基础应用1.创建pptx文档类并插入一页幻灯片from pptx impor
- 最近学习了一点python,那就试着做一做简单的编程练习。 首先是这个编程的指导图,如下:对的,类似一个简单区块链的模拟。 代码如下:cla
- 6月初,Python之父Guido van Rossum在今天的PyCon US大会上作了名为“Python Language”的演讲。近日
- 背景在我的 《Vue 3 开发企业级音乐 App》课程问答区,有个同学提了个问题,在歌手列表到歌手详情页面到转场动画中,只有进入动画,却没有
- 我们工作中经常需要将数据转化成柱状图,饼图等,以方便直观的分析数据, 这里给大家介绍一个ASP中制作饼图、柱状图的组件:csDra