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

Python 机器学习核心入门与实战进阶 Day 3 - 决策树 随机森林模型实战

✅ 今日目标

  • 理解决策树(Decision Tree)的基本原理
  • 掌握信息熵、基尼系数等分裂标准
  • 使用 DecisionTreeClassifierRandomForestClassifier 构建模型
  • 学会可视化决策树与查看特征重要性
  • 对比单棵树与集成模型(随机森林)的泛化能力

📘 一、决策树模型简介

特性描述
本质以“特征条件”划分决策路径,形成一棵判断树
优点逻辑清晰、可解释性强、不需归一化
缺点易过拟合、对噪声敏感
应用信用评分、规则建模、分类可视化

🧠 二、常用模型 API

决策树:

from sklearn.tree import DecisionTreeClassifierclf = DecisionTreeClassifier(max_depth=3, criterion='gini')
clf.fit(X_train, y_train)

随机森林:

from sklearn.ensemble import RandomForestClassifierrf = RandomForestClassifier(n_estimators=100, random_state=42)
rf.fit(X_train, y_train)

📊 三、评估方式建议

模型适合场景可解释性精度表现
决策树可视化逻辑、规则推理✅ 强中等
随机森林提高精度、降低过拟合中等✅ 强

📈 四、可视化与分析

from sklearn.tree import plot_tree
import matplotlib.pyplot as pltplt.figure(figsize=(10, 6))
plot_tree(clf, feature_names=["成绩", "性别"], class_names=["不及格", "及格"], filled=True)
plt.show()
# 特征重要性
import pandas as pd
importance = rf.feature_importances_
pd.DataFrame({"特征": ["成绩", "性别"], "重要性": importance})

💡 今日思路建议

  1. 构建同样的“是否及格预测”分类数据集
  2. 训练决策树模型,尝试调节 max_depth 查看影响
  3. 训练随机森林模型,查看是否提升性能
  4. 输出特征重要性对比
  5. 可视化决策树结构图

📁 练习脚本:decision_tree_forest_demo.py

# 决策树 & 随机森林实战:预测学生是否及格from sklearn.tree import DecisionTreeClassifier, plot_tree
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report, accuracy_score
import matplotlib.pyplot as plt
import numpy as np
import pandas as pdplt.rcParams['font.family'] = 'Arial Unicode MS'  # Mac 用户可用
plt.rcParams['axes.unicode_minus'] = False
# 1. 构造数据
np.random.seed(42)
size = 100
scores = np.random.randint(40, 100, size)
genders = np.random.choice([0, 1], size=size)
labels = (scores >= 60).astype(int)# 标准化成绩 + 性别作为特征
X = np.column_stack(((scores - scores.mean()) / scores.std(), genders))
y = labelsX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)# 2. 决策树模型
dt_model = DecisionTreeClassifier(max_depth=3, criterion='gini', random_state=42)
dt_model.fit(X_train, y_train)
y_pred_dt = dt_model.predict(X_test)print("=== 决策树模型评估 ===")
print("准确率:", accuracy_score(y_test, y_pred_dt))
print(classification_report(y_test, y_pred_dt))# 决策树可视化
plt.figure(figsize=(10, 6))
plot_tree(dt_model, feature_names=["成绩", "性别"], class_names=["不及格", "及格"], filled=True)
plt.title("决策树可视化")
plt.tight_layout()
plt.show()# 3. 随机森林模型
rf_model = RandomForestClassifier(n_estimators=100, random_state=42)
rf_model.fit(X_train, y_train)
y_pred_rf = rf_model.predict(X_test)print("\n=== 随机森林模型评估 ===")
print("准确率:", accuracy_score(y_test, y_pred_rf))
print(classification_report(y_test, y_pred_rf))# 特征重要性对比
feature_importance = rf_model.feature_importances_
features = ["成绩", "性别"]
importance_df = pd.DataFrame({"特征": features, "重要性": feature_importance})
print("\n=== 特征重要性(随机森林) ===")
print(importance_df)

运行输出:
在这里插入图片描述

=== 决策树模型评估 ===
准确率: 1.0precision    recall  f1-score   support0       1.00      1.00      1.00         71       1.00      1.00      1.00        13accuracy                           1.00        20macro avg       1.00      1.00      1.00        20
weighted avg       1.00      1.00      1.00        20
http://www.dtcms.com/a/267245.html

相关文章:

  • TailWind CSS Intellisense 插件在VSCode 上不生效
  • 蓝桥杯51单片机设计
  • 在VMware虚拟机中安装Windows 98时,Explorer提示“该程序执行了非法操作,即将关闭”的解决办法
  • PADS交互式布局
  • SwiftUI 7(iOS 26)中玻璃化工具栏的艺术
  • Qt开发:QListWidget的介绍和使用
  • Java面试宝典:BIO、NIO、AIO原理演进与实际应用深度实践
  • Ubuntu 安装 etcd 与 etcd-cpp-apiv3
  • 开发三维CAD:实现框选和反选功能
  • 翻译《The Old New Thing》- Windows 媒体目录中 onestop.mid 文件的故事
  • mybatis-plus-01-环境初始化及简单应用
  • 基于uni-app的书法学习管理小程序的设计与实现
  • Java IO相关技术小结
  • SpringCloud系列(51)--SpringCloud Stream之使用分组解决消息重复消费问题
  • 你的Prompt还有很大提升
  • PyTorch中 item()、tolist()使用详解和实战示例
  • 企业微信iPad协议端强制拉群漏洞深度分析
  • Scrapy进阶封装(第四阶段:中间件设置,动态UA,ip代理池)
  • 【STM32实践篇】:GPIO 详解
  • 【深度学习新浪潮】基于扩散模型的图像编辑加速方法
  • 传输层 udptcp
  • 【性能优化与架构调优(二)】高性能数据库设计与优化
  • 【科普】Keil5软件使用教程、小技巧学习笔记:11个知识点。DIY机器人工房
  • 【数据结构】排序算法:归并与堆
  • Python入门Day4
  • Cortex-M 异常处理的 C 实现、栈帧以及 EXC_RETURN
  • 操作符详解(上)
  • 深入解析Redis 7.0中每种数据类型的底层实现
  • 【Qt】QStringLiteral 介绍
  • 2025最新Telegram快读助手:一款智能Telegram链接摘要机器人