python机器学习实现决策树

作者:晒冷- 时间:2021-04-21 07:44:34 

本文实例为大家分享了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机器学习基础教程》

来源:https://blog.csdn.net/huangjiaaaaa/article/details/102987183

标签:python,决策树
0
投稿

猜你喜欢

  • 英文罚抄引发的艺术创意

    2008-05-13 12:02:00
  • 剖析网页设计中的几何圆

    2010-10-19 12:27:00
  • Python实现多任务进程示例

    2023-03-04 21:42:09
  • 从一个项目中来看三层架构

    2008-08-06 12:50:00
  • 树莓派升级python的具体步骤

    2023-08-04 00:28:49
  • asp如何计算下载一个文件需要多长时间?

    2009-11-25 20:17:00
  • pygame多种方式实现屏保操作(自动切换、鼠标切换、键盘切换)

    2022-12-08 20:39:49
  • python实现字符串和日期相互转换的方法

    2022-09-02 04:05:55
  • Python 使用tf-idf算法计算文档关键字权重并生成词云的方法

    2022-03-28 13:09:18
  • php基于curl实现随机ip地址抓取内容的方法

    2023-11-14 22:29:45
  • Python实现从多表格中随机抽取数据

    2022-07-01 01:58:18
  • Go获取与设置环境变量的方法详解

    2023-06-21 04:35:10
  • python样条插值的实现代码

    2022-05-11 16:04:05
  • 在pandas多重索引multiIndex中选定指定索引的行方法

    2023-07-07 22:04:16
  • MySQL中的字符串模式匹配

    2010-03-09 16:30:00
  • 使用python画出逻辑斯蒂映射(logistic map)中的分叉图案例

    2023-05-19 13:05:18
  • 磁盘缓存专题之一 缓存命中和缓存未命中&缓存与缓冲间的差异

    2012-10-07 11:02:46
  • 详解用python写网络爬虫-爬取新浪微博评论

    2021-09-30 22:23:11
  • python 字典(dict)按键和值排序

    2021-11-20 05:44:35
  • python2.x实现人民币转大写人民币

    2023-06-26 10:35:53
  • asp之家 网络编程 m.aspxhome.com