当前位置: 首页 > news >正文

决策树相关案例

全流程

以下是一个更复杂、全流程的决策树和随机森林示例,不仅包括模型训练和预测,还涵盖了数据预处理、超参数调优以及模型评估的可视化。我们依旧使用鸢尾花数据集,并额外引入 GridSearchCV 进行超参数调优,使用 matplotlib 进行简单的可视化。

 

import numpy as np

import pandas as pd

import matplotlib.pyplot as plt

from sklearn.datasets import load_iris

from sklearn.model_selection import train_test_split, GridSearchCV, cross_val_score

from sklearn.preprocessing import StandardScaler

from sklearn.tree import DecisionTreeClassifier, export_graphviz

from sklearn.ensemble import RandomForestClassifier

from sklearn.metrics import accuracy_score, classification_report, confusion_matrix, roc_curve, auc

from sklearn.externals.six import StringIO  

from IPython.display import Image  

from graphviz import Source

import pydotplus

 

# 1. 加载鸢尾花数据集

iris = load_iris()

X = pd.DataFrame(iris.data, columns=iris.feature_names)

y = pd.Series(iris.target)

 

# 2. 数据预处理

# 2.1 特征标准化

scaler = StandardScaler()

X_scaled = scaler.fit_transform(X)

 

# 3. 划分训练集和测试集

X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.3, random_state=42)

 

# 4. 决策树模型

# 4.1 定义超参数搜索空间

dtc_param_grid = {

    'max_depth': [3, 5, 7, 10],

    'min_samples_split': [2, 5, 10],

    'min_samples_leaf': [1, 2, 4]

}

 

# 4.2 使用GridSearchCV进行超参数调优

dtc_grid_search = GridSearchCV(DecisionTreeClassifier(random_state=42), dtc_param_grid, cv=5)

dtc_grid_search.fit(X_train, y_train)

 

# 4.3 输出最佳超参数

print("决策树最佳超参数:", dtc_grid_search.best_params_)

 

# 4.4 使用最佳超参数构建决策树模型

dtc_best = dtc_grid_search.best_estimator_

 

# 4.5 预测并评估

y_pred_dtc = dtc_best.predict(X_test)

dtc_accuracy = accuracy_score(y_test, y_pred_dtc)

print(f"决策树模型的准确率: {dtc_accuracy}")

print("决策树分类报告:\n", classification_report(y_test, y_pred_dtc))

print("决策树混淆矩阵:\n", confusion_matrix(y_test, y_pred_dtc))

 

# 4.6 可视化决策树(需要graphviz工具支持)

dot_data = StringIO()

export_graphviz(dtc_best, out_file=dot_data,  

                filled=True, rounded=True,

                special_characters=True, feature_names=iris.feature_names, class_names=iris.target_names)

graph = pydotplus.graph_from_dot_data(dot_data.getvalue())  

Image(graph.create_png())

 

# 5. 随机森林模型

# 5.1 定义超参数搜索空间

rfc_param_grid = {

    'n_estimators': [50, 100, 200],

   'max_depth': [3, 5, 7, 10],

   'min_samples_split': [2, 5, 10],

   'min_samples_leaf': [1, 2, 4]

}

 

# 5.2 使用GridSearchCV进行超参数调优

rfc_grid_search = GridSearchCV(RandomForestClassifier(random_state=42), rfc_param_grid, cv=5)

rfc_grid_search.fit(X_train, y_train)

 

# 5.3 输出最佳超参数

print("随机森林最佳超参数:", rfc_grid_search.best_params_)

 

# 5.4 使用最佳超参数构建随机森林模型

rfc_best = rfc_grid_search.best_estimator_

 

# 5.5 预测并评估

y_pred_rfc = rfc_best.predict(X_test)

rfc_accuracy = accuracy_score(y_test, y_pred_rfc)

print(f"随机森林模型的准确率: {rfc_accuracy}")

print("随机森林分类报告:\n", classification_report(y_test, y_pred_rfc))

print("随机森林混淆矩阵:\n", confusion_matrix(y_test, y_pred_rfc))

 

# 5.6 绘制ROC曲线(以二分类为例,这里简单取其中一类演示)

fpr_rfc, tpr_rfc, thresholds_rfc = roc_curve(y_test == 0, rfc_best.predict_proba(X_test)[:, 0])

roc_auc_rfc = auc(fpr_rfc, tpr_rfc)

 

plt.figure()

plt.plot(fpr_rfc, tpr_rfc, label='Random Forest (area = %0.2f)' % roc_auc_rfc)

plt.plot([0, 1], [0, 1], 'k--')

plt.xlim([0.0, 1.0])

plt.ylim([0.0, 1.05])

plt.xlabel('False Positive Rate')

plt.ylabel('True Positive Rate')

plt.title('Receiver operating characteristic example')

plt.legend(loc="lower right")

plt.show()

 

 

代码解释:

 

1. 数据加载与预处理:加载鸢尾花数据集,将其转换为 DataFrame 和 Series 形式,并对特征进行标准化处理。

2. 数据划分:将数据集划分为训练集和测试集。

3. 决策树模型:定义超参数搜索空间,使用 GridSearchCV 进行超参数调优,得到最佳超参数后构建决策树模型,进行预测和评估,并可视化决策树。

4. 随机森林模型:类似地,定义随机森林的超参数搜索空间,进行超参数调优,构建模型,预测评估,并绘制ROC曲线进行可视化。

 

http://www.xdnf.cn/news/172387.html

相关文章:

  • 【Node.js 】在Windows 下搭建适配 DPlayer 的轻量(简陋)级弹幕后端服务
  • Linux系统之设置开机启动运行桌面环境
  • 力扣hot100_子串_python版本
  • Nginx配置文件介绍
  • 机器学习day2-seaborn绘图练习
  • 数模学习:二,MATLAB的基本语法使用
  • 跨专业自学AI人工智能学习路线图(2025版)
  • Android完整开发环境搭建/Studio安装/NDK/本地Gradle下载配置/创建AVD/运行一个Android项目/常用插件
  • 金融数据分析(Python)个人学习笔记(13):自然语言处理
  • Kubernetes学习笔记-配置Service对接第三方访问
  • 【Redis】服务端高并发分布式结构演进之路
  • 零基础小白如何上岸数模国奖
  • IDEA 连接 Oracle 数据库
  • 安卓7.0以上抓包配置--Charles
  • ​​全栈自动化:从零构建智能CI/CD流水线​
  • 手搓传染病模型(SEIR)
  • k8s的volume
  • Alibaba Cloud Linux 3.2104 LTS 64位 容器优化版安装docker docker compose记录
  • MyBatis DTD [Element type “if“ must be declared]
  • Kafka HA集群配置搭建与SpringBoot使用示例总结
  • LeetCode -- Flora -- edit 2025-04-27
  • Spring AI Alibaba - MCP连接 MySQL
  • docker--docker的基本环境配置
  • Stable Diffusion 技术全景解析与行业竞争力分析
  • 小程序发布后,不能强更的情况下,怎么通知到用户需要去更新?
  • 图论---最大流(Dinic)
  • Golang 类型方法
  • 【2025最近Java面试八股】Spring中循环依赖的问题?怎么解决的?
  • 层级时间轮的 Golang 实现原理与实践
  • 环境DNA宏条形码技术,鱼类检测引物如何选择?