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

Python 数据分析与可视化 Day 14 - 建模复盘 + 多模型评估对比(逻辑回归 vs 决策树)

✅ 今日目标

  • 回顾整个本周数据分析 & 建模流程
  • 学会训练第二种模型:决策树(Decision Tree)
  • 掌握多模型对比评估的方法与实践
  • 输出综合对比报告:准确率、精确率、召回率、F1 等指标
  • 为后续模型调优与扩展打下基础

🪜 一、本周流程快速回顾

步骤内容
第1天高级数据操作(索引、透视、变形)
第2天缺失值和异常值处理
第3天多表合并与连接
第4天特征工程(编码、归一化、时间)
第5天数据集拆分(训练集 / 测试集)
第6天逻辑回归模型构建与评估
第7天🤖 多模型对比评估(今天)

🌲 二、训练决策树分类器

from sklearn.tree import DecisionTreeClassifiertree = DecisionTreeClassifier(random_state=42)
tree.fit(X_train, y_train)
y_pred_tree = tree.predict(X_test)

⚖️ 三、模型对比评估

from sklearn.metrics import classification_reportprint("📋 Logistic 回归:")
print(classification_report(y_test, y_pred_log))print("📋 决策树模型:")
print(classification_report(y_test, y_pred_tree))

📊 可视化对比(可选)

import matplotlib.pyplot as pltmodels = ["Logistic", "DecisionTree"]
accuracies = [accuracy_score(y_test, y_pred_log),accuracy_score(y_test, y_pred_tree),
]plt.bar(models, accuracies, color=["skyblue", "lightgreen"])
plt.title("模型准确率对比")
plt.ylabel("Accuracy")
plt.show()

🧪 今日练习建议(脚本名:compare_models.py

  1. 读取本周生成的训练 / 测试数据

  2. 同时训练逻辑回归与决策树模型

  3. 输出各自的评估指标(Accuracy、Precision、Recall、F1)

  4. (可选)将结果写入一个 CSV 或图表可视化

  5. 思考不同模型优劣,以及如何选择合适模型

    # compare_models.py
    import pandas as pd
    from sklearn.linear_model import LogisticRegression
    from sklearn.tree import DecisionTreeClassifier
    from sklearn.metrics import (accuracy_score,classification_report,confusion_matrix
    )
    import matplotlib.pyplot as plt
    import seaborn as sns
    import osplt.rcParams['font.family'] = 'Arial Unicode MS'  # Mac 用户可用
    plt.rcParams['axes.unicode_minus'] = False# 1. 加载训练与测试数据
    data_dir = "data/model"
    X_train = pd.read_csv(os.path.join(data_dir, "X_train.csv"))
    X_test = pd.read_csv(os.path.join(data_dir, "X_test.csv"))
    y_train = pd.read_csv(os.path.join(data_dir, "y_train.csv")).values.ravel()
    y_test = pd.read_csv(os.path.join(data_dir, "y_test.csv")).values.ravel()# 2. 初始化模型
    log_model = LogisticRegression()
    tree_model = DecisionTreeClassifier(random_state=42)# 3. 模型训练
    log_model.fit(X_train, y_train)
    tree_model.fit(X_train, y_train)# 4. 模型预测
    y_pred_log = log_model.predict(X_test)
    y_pred_tree = tree_model.predict(X_test)# 5. 评估结果
    print("📋 Logistic 回归评估报告:")
    print(classification_report(y_test, y_pred_log))print("\n🌳 决策树评估报告:")
    print(classification_report(y_test, y_pred_tree))# 6. 准确率对比
    acc_log = accuracy_score(y_test, y_pred_log)
    acc_tree = accuracy_score(y_test, y_pred_tree)# 7. 可视化混淆矩阵
    plt.figure(figsize=(10, 4))plt.subplot(1, 2, 1)
    sns.heatmap(confusion_matrix(y_test, y_pred_log, labels=[0, 1]), annot=True, fmt="d", cmap="Blues",xticklabels=["0", "1"], yticklabels=["0", "1"])
    plt.title("Logistic 回归 - 混淆矩阵")
    plt.xlabel("预测", fontproperties="Arial Unicode MS")
    plt.ylabel("真实", fontproperties="Arial Unicode MS")plt.subplot(1, 2, 2)
    sns.heatmap(confusion_matrix(y_test, y_pred_tree, labels=[0, 1]), annot=True, fmt="d", cmap="Greens",xticklabels=["0", "1"], yticklabels=["0", "1"])
    plt.title("决策树 - 混淆矩阵")
    plt.xlabel("预测", fontproperties="Arial Unicode MS")
    plt.ylabel("真实", fontproperties="Arial Unicode MS")plt.tight_layout()
    plt.show()# 8. 准确率柱状图
    plt.figure(figsize=(5, 4))
    plt.bar(["Logistic", "Decision Tree"], [acc_log, acc_tree], color=["skyblue", "lightgreen"])
    plt.title("模型准确率对比")
    plt.ylabel("Accuracy")
    plt.ylim(0, 1)
    plt.grid(axis='y', linestyle='--', alpha=0.7)
    plt.tight_layout()
    plt.show()# 9. 汇总结果(可选保存)
    results_df = pd.DataFrame({"模型": ["Logistic", "Decision Tree"],"准确率": [acc_log, acc_tree]
    })
    os.makedirs("data/result", exist_ok=True)
    results_df.to_csv("data/result/model_comparison.csv", index=False)
    print("\n✅ 对比结果已保存:data/result/model_comparison.csv")
    

    结果输出:

    📋 Logistic 回归评估报告:precision    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🌳 决策树评估报告:precision    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✅ 对比结果已保存:data/result/model_comparison.csv
    

    可视化混淆矩阵:
    在这里插入图片描述

    准确率柱状图:
    在这里插入图片描述

    data/result/model_comparison.csv:
    在这里插入图片描述
    PS:可以使用下面的代码生成训练/测试集:

    import pandas as pd
    import numpy as np
    from sklearn.model_selection import train_test_split
    import os# 构造示例数据
    np.random.seed(42)
    size = 100
    df = pd.DataFrame({"成绩": np.random.randint(40, 100, size=size),"性别": np.random.choice(["男", "女"], size=size)
    })# 增加派生特征
    df["成绩_标准化"] = (df["成绩"] - df["成绩"].mean()) / df["成绩"].std()
    df["是否及格_数值"] = (df["成绩"] >= 60).astype(int)
    df["性别_男"] = (df["性别"] == "男").astype(int)
    df["性别_女"] = (df["性别"] == "女").astype(int)# 特征与标签
    X = df[["成绩_标准化", "性别_男", "性别_女", "是否及格_数值"]]
    y = df["是否及格_数值"]# 拆分数据
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)# 保存路径
    os.makedirs("data/model", exist_ok=True)
    X_train.to_csv("data/model/X_train.csv", index=False)
    X_test.to_csv("data/model/X_test.csv", index=False)
    y_train.to_csv("data/model/y_train.csv", index=False)
    y_test.to_csv("data/model/y_test.csv", index=False)
    

🧾 今日总结

  • 理解模型评估不止准确率,更要看精确率与召回率
  • 决策树可捕捉非线性关系,但易过拟合
  • 模型选择应结合业务背景、样本数量、可解释性等因素
http://www.dtcms.com/a/264957.html

相关文章:

  • JavaEE==网站开发
  • Liunx 安装 MySQL 8.0
  • Selenium使用教程-爬虫版(超详细)
  • 数学建模_图论
  • 重塑智能体决策路径:深入理解 ReAct 框架
  • 【前端进阶】【实战】【性能优化】前端开发中的事件监听与DOM操作优化实践
  • Linux基本命令篇 —— whereis命令
  • 利用 Claude Opus 4 自动化 GitHub 工作流:从安装到实战详解
  • 新版本AI数字人全能管家,即将推出,还是开源免费。
  • [附源码+数据库+毕业论文+答辩PPT]基于Spring+MyBatis+MySQL+Maven+vue实现的中小型企业财务管理系统,推荐!
  • 多个单片机简单通讯框架
  • GO Web 框架 Gin 完全解析与实践
  • 数据结构与算法 第三章 栈和队列
  • 第一章 快速入门
  • DPI深度检索原理和架构
  • 人脸活体识别3:C/C++实现人脸眨眼 张嘴 点头 摇头识别(可实时检测)
  • 创客匠人解构知识付费爆单密码:产品力打造与 IP 变现的深度耦合
  • Kafka高级特性深度解析:构建企业级流处理平台的核心技术
  • IP地理定位技术综述:理论、方法与应用创新(三)
  • pdf 合并 python实现(已解决)
  • Qt Quick 与 QML(五)qml中的布局
  • 基于图神经网络的ALS候选药物预测模型设计与实现
  • Point Transformer V3(PTv3)
  • AI:什么是Agent
  • mysql查看数据库
  • 自主/智能的本质内涵及其相互关系
  • QT6 源(145)模型视图架构里的表格视图 QTableView 篇一:先学习属性,再 public 权限的成员函数
  • 胡兵全新时尚生活频道上线,开启多维生活美学新篇
  • 胡兵创立时尚生活频道《HUBING SELECTS胡兵智选》担任主编深耕智选生活
  • Ragflow 前后端登录逻辑