diff --git a/src/driverless_car/README.md b/src/driverless_car/README.md index 0b97ccb5c9..a92a7c85ee 100644 --- a/src/driverless_car/README.md +++ b/src/driverless_car/README.md @@ -48,16 +48,12 @@ python main_fg.py 该项目实现了**无人机图像分类**的深度学习Demo,使用公开数据集模拟无人机采集的图像数据,搭建轻量化卷积神经网络(CNN)完成分类任务。 ### 主要特点 -- 🚀 **无硬件依赖**:使用CIFAR-10公开数据集模拟无人机航拍图像 -- 🧠 **轻量化模型**:搭建适用于无人机端的轻量化CNN,兼顾性能与算力消耗 -- 📊 **可视化界面**:包含数据集样本展示、训练过程实时可视化、预测结果展示 -- 🐞 **兼容性修复**:解决Matplotlib中文字体缺失、PyCharm后端兼容等问题 +- 🚀 **无硬件依赖**:使用CIFAR-10数据集模拟航拍图像 +- 🧠 **轻量化模型**:轻量化CNN设计,兼顾性能与效率 +- 📊 **可视化界面**:数据展示、训练可视化、预测结果展示 +- 🐞 **兼容性强**:已处理中文显示和IDE兼容问题 -### 技术栈 -- Python + PyTorch -- torchvision (数据集处理) -- matplotlib (可视化) -- numpy (数值计算) +**技术栈**:Python + PyTorch, torchvision, matplotlib, numpy --- @@ -72,45 +68,24 @@ python main_fg.py - 实时可视化无人机的移动路径、网格环境和训练奖励变化 - 优化的可视化界面,支持坐标标注、路径方向箭头、移动平均奖励曲线 -### 技术栈 -- **环境搭建**:gymnasium(gym 的维护版)自定义网格环境 -- **强化学习算法**:Q-Learning(ε-贪心策略平衡探索与利用) -- **可视化**:matplotlib(绘制网格、路径、奖励曲线) -- **数值计算**:numpy +**技术栈**:gymnasium, PyTorch, matplotlib, numpy --- -## 环境配置 - -### 基础依赖安装 - -推荐使用国内镜像源加速安装: +## 快速安装 ```bash -# 语义分割项目依赖 -pip install torch torchvision matplotlib scikit-image pillow numpy opencv-python - -# 图像分类项目依赖 -pip install torch torchvision matplotlib numpy -i https://pypi.tuna.tsinghua.edu.cn/simple +# 安装所有项目依赖 +pip install torch torchvision matplotlib scikit-image pillow numpy opencv-python gymnasium -i https://pypi.tuna.tsinghua.edu.cn/simple -# 路径规划项目依赖 -pip install torch torchvision matplotlib numpy gymnasium -i https://pypi.tuna.tsinghua.edu.cn/simple - -# 若需要gymnasium完整版(包含额外环境,如Atari) +# 如需完整版gymnasium(可选) pip install gymnasium[all] -i https://pypi.tuna.tsinghua.edu.cn/simple -``` -### 卸载旧版依赖(可选) -```bash -# 卸载旧版 gym(如果存在冲突) +# 卸载旧版gym(如果存在冲突,可选) pip uninstall gym -y ``` -### 系统要求 -- Python 3.7+ -- 支持CUDA的GPU(可选,用于加速训练) -- 内存:建议4GB以上 -- 存储空间:至少1GB可用空间 +**系统要求**:Python 3.7+,建议4GB以上内存,支持CUDA的GPU(可选) --- @@ -164,29 +139,28 @@ pip uninstall gym -y --- -## 扩展方向 +## 优化建议 -### 语义分割项目优化方向 -- **数据增强**:在transform中添加随机裁剪、翻转、亮度调整等操作,提升模型泛化能力 -- **模型优化**:在 U-Net 中加入注意力机制(如 SE 模块)或使用 U-Net++ 模型,提升分割精度 -- **真实数据适配**:替换模拟数据生成部分,加载真实的无人机航拍道路数据集 -- **多类别分割**:修改模型输出通道数,实现建筑、植被、水体等多类地物的语义分割 +### 语义分割项目优化 +- **数据增强**:添加随机裁剪、翻转、亮度调整等操作 +- **模型优化**:加入注意力机制或使用U-Net++模型 +- **多类别分割**:实现建筑、植被、水体等多类地物分割 +- **真实数据适配**:替换模拟数据,加载真实航拍数据集 -### 通用优化建议 -- 使用更高分辨率的输入图像提升分割精度 -- 尝试不同的损失函数(如Dice Loss、Focal Loss) -- 添加数据增强技术提升模型泛化能力 +### 通用优化方向 +- 使用更高分辨率输入图像 +- 尝试不同损失函数(Dice Loss、Focal Loss等) +- 添加数据增强技术 - 使用预训练模型进行迁移学习 --- ## 注意事项 -- 项目完全基于代码仿真,无需真实无人机硬件 -- 可在普通PC上运行,建议配置支持CUDA的GPU以加速训练 -- 所有可视化界面均已优化,兼容中文显示 -- 代码已处理常见的兼容性问题,可直接在PyCharm等IDE中运行 -- 语义分割项目会在指定路径自动创建数据集文件夹,请确保有足够存储空间 +- 项目基于代码仿真,无需真实无人机硬件 +- 所有可视化界面已优化,兼容中文显示 +- 代码已处理兼容性问题,可直接在IDE中运行 +- 语义分割项目会自动创建数据集文件夹,请确保存储空间充足 --- diff --git a/src/driverless_car/main_height.py b/src/driverless_car/main_height.py index e801592db1..4a4ead4792 100644 --- a/src/driverless_car/main_height.py +++ b/src/driverless_car/main_height.py @@ -1,4 +1,4 @@ -#无人机高度保持 +# 导入必要的库 import tkinter as tk from tkinter import ttk, messagebox import numpy as np @@ -111,68 +111,79 @@ def _init_controller(self): class SimpleController: def __init__(self): - # 模拟一个经过训练的控制器(实际使用时加载PyTorch模型) - self.kp = 0.05 # 比例系数(模拟模型学到的参数) - self.kd = 0.02 # 微分系数 + # 模拟一个经过训练的控制器(实际使用时加载PyTorch/TensorFlow模型) + # 无人机高度保持:控制器的核心参数,模拟模型学到的比例和微分系数 + self.kp = 0.05 # 比例系数(对应高度误差的响应强度) + self.kd = 0.02 # 微分系数(对应误差变化率的响应强度,抑制震荡) def predict(self, error, error_rate, current_h): """ - 输入:误差e、误差变化率de、当前高度h - 输出:油门控制量(0~1) + 无人机高度保持:控制器的核心预测逻辑,输入状态输出油门控制量 + 输入:误差e(目标高度-当前高度)、误差变化率de、当前高度h + 输出:油门控制量(0~1,0为最小油门,1为最大油门) """ - # 模拟深度学习模型的输出(实际中是model(inputs)) + # 模拟深度学习模型的输出(实际中是model(inputs)的前向传播) + # 基础油门0.5为悬停基准,叠加比例和微分控制项实现高度保持 throttle = 0.5 + self.kp * error + self.kd * error_rate - # 限制油门范围 + # 限制油门范围在0~1之间,避免超出无人机的物理控制范围 return np.clip(throttle, 0.0, 1.0) return SimpleController() def _update_data(self): - """更新无人机数据(模拟或真实数据)""" + """更新无人机数据(模拟无人机的高度动力学和控制逻辑)""" # 获取当前时间 t = self.time_data[-1] + self.dt if self.time_data else 0.0 self.time_data.append(t) - # 更新目标高度(从输入框读取) + # 更新目标高度(从输入框读取,支持实时修改目标高度,测试高度保持的动态响应) + # 无人机高度保持:实时更新目标高度,模拟用户手动调整无人机的期望高度 try: new_target = float(self.target_entry.get()) self.target_h = new_target except ValueError: - pass # 忽略无效输入 + pass # 忽略无效输入,保持原有目标高度 self.target_height.append(self.target_h) - # 计算当前高度(基于物理模型模拟) + # 计算当前高度(基于简化的物理模型模拟无人机的高度变化) + # 无人机高度保持:核心的高度动力学模拟,反映油门对高度的影响 if not self.current_height: - # 初始高度 - current_h = 0.0 # 从地面开始 + # 初始高度:从地面(0米)开始,模拟无人机起飞阶段 + current_h = 0.0 else: - # 基于上一时刻高度和油门计算当前高度(简化物理模型) + # 基于上一时刻高度和油门计算当前高度(简化的无人机高度物理模型) last_h = self.current_height[-1] last_throttle = self.throttle_data[-1] if self.throttle_data else 0.5 - # 高度变化 = 油门贡献 - 重力衰减 - h_change = (last_throttle - 0.45) * 0.8 # 简化模型:油门>0.45时上升 + # 高度变化 = 油门贡献 - 重力衰减(简化模型:油门>0.45时上升,<0.45时下降) + # 无人机高度保持:油门是控制高度的核心变量,0.45为悬停临界油门 + h_change = (last_throttle - 0.45) * 0.8 # 0.8为高度变化的增益系数 - # 加入噪声(模拟气流) + # 加入噪声(模拟气流扰动,贴近真实的无人机飞行环境) + # 无人机高度保持:气流噪声是影响高度稳定的主要干扰因素 if self.simulate_noise: - h_change += random.gauss(0, 0.15) # 高斯噪声 + h_change += random.gauss(0, 0.15) # 加入高斯噪声,均值0,标准差0.15 + # 计算当前高度:上一高度 + 高度变化 * 采样时间间隔 current_h = last_h + h_change * self.dt self.current_height.append(current_h) - # 计算误差 + # 计算高度误差(目标高度 - 当前高度,是高度保持控制的核心输入) + # 无人机高度保持:误差是控制器的关键输入,误差为正表示需要上升,为负表示需要下降 error = self.target_h - current_h self.error_data.append(error) - # 计算误差变化率 + # 计算误差变化率(反映误差的变化趋势,抑制高度震荡) + # 无人机高度保持:误差变化率用于阻尼控制,避免无人机高度频繁震荡 error_rate = (error - self.error_data[-2]) / self.dt if len(self.error_data) > 1 else 0.0 - # 深度学习控制器计算油门 + # 深度学习控制器计算油门(核心的高度保持控制逻辑) + # 无人机高度保持:控制器根据误差和误差变化率输出油门,实现高度的闭环控制 throttle = self.controller.predict(error, error_rate, current_h) self.throttle_data.append(throttle) - # 限制数据长度 + # 限制数据长度,只保留最近的max_points个数据点,保证绘图的流畅性 if len(self.time_data) > self.max_points: self.time_data.pop(0) self.current_height.pop(0) @@ -181,21 +192,24 @@ def _update_data(self): self.throttle_data.pop(0) def _update_plot(self, frame): - """更新绘图""" + """更新绘图,可视化无人机高度保持的各项数据""" if self.running: self._update_data() + # 实时显示无人机的高度状态,便于监控高度保持的效果 self.status_var.set( f"运行中 | 当前高度: {self.current_height[-1]:.2f}米 | 误差: {self.error_data[-1]:.2f}米") - # 更新高度曲线 + # 更新高度曲线(可视化当前高度和目标高度的偏差,直观反映高度保持效果) + # 无人机高度保持:核心可视化项,观察当前高度是否跟踪目标高度 self.line_current.set_data(self.time_data, self.current_height) self.line_target.set_data(self.time_data, self.target_height) - # 更新误差和油门曲线 + # 更新误差和油门曲线(分析高度误差的变化和油门的控制响应) + # 无人机高度保持:误差曲线反映控制精度,油门曲线反映控制器的输出特性 self.line_error.set_data(self.time_data, self.error_data) self.line_throttle.set_data(self.time_data, self.throttle_data) - # 自动调整坐标轴范围 + # 自动调整坐标轴范围,保证数据始终在视图内 for ax in [self.ax1, self.ax2, self.ax2_twin]: ax.relim() ax.autoscale_view() @@ -203,21 +217,21 @@ def _update_plot(self, frame): return self.line_current, self.line_target, self.line_error, self.line_throttle def start(self): - """开始运行""" + """开始运行,启动无人机高度保持的模拟过程""" self.running = True self.start_btn.config(state=tk.DISABLED) self.pause_btn.config(state=tk.NORMAL) self.status_var.set("启动中...") def pause(self): - """暂停运行""" + """暂停运行,暂停无人机高度保持的模拟过程""" self.running = False self.start_btn.config(state=tk.NORMAL) self.pause_btn.config(state=tk.DISABLED) self.status_var.set("已暂停") def reset(self): - """重置数据""" + """重置数据,清空所有历史数据,恢复初始状态""" self.pause() self.time_data = [] self.current_height = [] @@ -230,7 +244,7 @@ def reset(self): self.canvas.draw() def run(self): - """启动动画""" + """启动动画,开始无人机高度保持的可视化循环""" self.ani = FuncAnimation( self.fig, self._update_plot, interval=int(self.dt * 1000), blit=True, cache_frame_data=False @@ -239,6 +253,7 @@ def run(self): if __name__ == "__main__": + # 无人机高度保持:程序入口,创建主窗口和可视化应用实例 root = tk.Tk() app = DroneHeightVisualizer(root) app.run() \ No newline at end of file diff --git a/src/driverless_car/main_pinheng.py b/src/driverless_car/main_pinheng.py index 469cc31cfe..76898a90cc 100644 --- a/src/driverless_car/main_pinheng.py +++ b/src/driverless_car/main_pinheng.py @@ -1,328 +1,435 @@ -import numpy as np -import matplotlib.pyplot as plt -from matplotlib.animation import FuncAnimation -import torch -import torch.nn as nn -import torch.optim as optim -from torch.utils.data import Dataset, DataLoader -import random -from mpl_toolkits.mplot3d import Axes3D - -# 设置中文字体 -plt.rcParams["font.family"] = ["SimHei", "WenQuanYi Micro Hei", "Heiti TC"] -plt.rcParams["axes.unicode_minus"] = False # 解决负号显示问题 - - -# 无人机物理模型参数 +# 导入必要的库 +import numpy as np # 数值计算库,用于矩阵和数组操作 +import matplotlib.pyplot as plt # 绘图库,用于静态和动态可视化 +from matplotlib.animation import FuncAnimation # 动态动画绘制工具 +import torch # PyTorch深度学习框架核心库 +import torch.nn as nn # 神经网络层定义模块 +import torch.optim as optim # 优化器模块,用于模型训练 +from torch.utils.data import Dataset, DataLoader # 数据集和数据加载器,用于批处理训练 +import random # 随机数生成器,用于初始化无人机状态 +from mpl_toolkits.mplot3d import Axes3D # 3D绘图工具包 + +# 设置matplotlib中文字体和负号显示 +plt.rcParams["font.family"] = ["SimHei", "WenQuanYi Micro Hei", "Heiti TC"] # 支持中文显示的字体列表 +plt.rcParams["axes.unicode_minus"] = False # 解决负号'-'显示为方块的问题 + + +# ===================== 无人机物理模型类 ===================== +# 功能:模拟无人机的动力学和运动学特性,实现状态重置和一步动作执行 class DroneModel: def __init__(self): - self.mass = 1.0 # 质量(kg) - self.inertia = np.array([0.1, 0.1, 0.2]) # 转动惯量 - self.gravity = 9.81 # 重力加速度 - self.dt = 0.01 # 时间步长 - self.reset() + # 无人机物理参数配置 + self.mass = 1.0 # 无人机质量,单位kg + self.inertia = np.array([0.1, 0.1, 0.2]) # 三轴转动惯量 [滚转, 俯仰, 偏航] + self.gravity = 9.81 # 重力加速度,单位m/s² + self.dt = 0.01 # 仿真时间步长,单位s,越小仿真越精确但速度越慢 + self.reset() # 初始化时重置无人机状态 def reset(self): - # 状态: [x, y, z, 滚转角, 俯仰角, 偏航角, 线速度, 角速度] - self.state = np.array([0.0, 0.0, 1.0, # 位置 - 0.05 * random.random() - 0.025, # 滚转角 - 0.05 * random.random() - 0.025, # 俯仰角 - 0.0, # 偏航角 - 0.0, 0.0, 0.0, # 线速度 - 0.0, 0.0, 0.0]) # 角速度 + """ + 重置无人机状态到初始值 + 返回值:初始化后的状态数组 + 状态数组格式(共12维): + [x, y, z, 滚转角, 俯仰角, 偏航角, 线速度vx, vy, vz, 角速度wx, wy, wz] + """ + # 位置初始化:x=0, y=0, z=1m(初始高度1米) + # 姿态初始化:滚转和俯仰角在[-0.025, 0.025]rad小范围随机扰动,偏航角为0 + # 线速度和角速度初始化为0 + self.state = np.array([ + 0.0, 0.0, 1.0, # 位置 [x, y, z] + 0.05 * random.random() - 0.025, # 滚转角 (roll) + 0.05 * random.random() - 0.025, # 俯仰角 (pitch) + 0.0, # 偏航角 (yaw) + 0.0, 0.0, 0.0, # 线速度 [vx, vy, vz] + 0.0, 0.0, 0.0 # 角速度 [wx, wy, wz] + ]) return self.state def step(self, action): - # action: 四个螺旋桨的推力 - f1, f2, f3, f4 = action - - # 计算合力和力矩 - thrust = (f1 + f2 + f3 + f4) + """ + 执行一步动作,更新无人机状态 + 参数: + action: 长度为4的数组,代表四个螺旋桨的推力大小 + 返回值: + state: 更新后的无人机状态 + reward: 本次动作的奖励值(用于强化学习训练) + done: 布尔值,是否达到终止条件(无人机失控) + """ + f1, f2, f3, f4 = action # 解包四个螺旋桨推力 + + # 1. 计算总推力和三轴力矩 + thrust = (f1 + f2 + f3 + f4) # 总推力(垂直机体坐标系z轴) + # 滚转力矩:由对角螺旋桨推力差产生,臂长系数0.1 torque_x = (f2 + f4 - f1 - f3) * 0.1 + # 俯仰力矩:由前后螺旋桨推力差产生,臂长系数0.1 torque_y = (f1 + f2 - f3 - f4) * 0.1 + # 偏航力矩:由相邻螺旋桨推力差产生,系数0.05 torque_z = (f2 + f3 - f1 - f4) * 0.05 - # 更新位置和姿态 + # 2. 解包当前姿态角 roll, pitch, yaw = self.state[3:6] - # 线加速度计算 + # 3. 计算线加速度(机体坐标系转世界坐标系) + # 基于欧拉角的坐标变换,将机体坐标系的推力转换为世界坐标系的加速度 ax = (np.cos(yaw) * np.sin(pitch) + np.sin(yaw) * np.sin(roll) * np.cos(pitch)) * thrust / self.mass ay = (np.sin(yaw) * np.sin(pitch) - np.cos(yaw) * np.sin(roll) * np.cos(pitch)) * thrust / self.mass - az = self.gravity - (np.cos(roll) * np.cos(pitch)) * thrust / self.mass - - # 角加速度计算 - angular_acc = np.array([torque_x / self.inertia[0], - torque_y / self.inertia[1], - torque_z / self.inertia[2]]) - - # 更新速度 - self.state[6:9] += np.array([ax, ay, az]) * self.dt - - # 更新位置 - self.state[0:3] += self.state[6:9] * self.dt - - # 更新角速度 - self.state[9:12] += angular_acc * self.dt - - # 更新姿态 - self.state[3:6] += self.state[9:12] * self.dt - - # 限制角度范围在[-pi, pi] + az = self.gravity - (np.cos(roll) * np.cos(pitch)) * thrust / self.mass # 重力补偿 + + # 4. 计算角加速度(力矩/转动惯量) + angular_acc = np.array([ + torque_x / self.inertia[0], + torque_y / self.inertia[1], + torque_z / self.inertia[2] + ]) + + # 5. 更新状态(欧拉积分法:状态 = 原状态 + 变化率 * 时间步长) + self.state[6:9] += np.array([ax, ay, az]) * self.dt # 更新线速度 + self.state[0:3] += self.state[6:9] * self.dt # 更新位置 + self.state[9:12] += angular_acc * self.dt # 更新角速度 + self.state[3:6] += self.state[9:12] * self.dt # 更新姿态角 + + # 6. 姿态角范围限制:将角度约束在[-π, π]范围内 self.state[3:6] = np.mod(self.state[3:6] + np.pi, 2 * np.pi) - np.pi - # 计算奖励: 越稳定奖励越高 - reward = - (np.sum(np.square(self.state[3:5])) + 0.1 * np.sum(np.square(self.state[9:11])) - + 0.01 * np.sum(np.square(self.state[0:2])) + 0.1 * np.square(self.state[2] - 1.0)) - - # 判断是否失败 - done = (abs(self.state[3]) > np.pi / 4 or # 滚转角过大 - abs(self.state[4]) > np.pi / 4 or # 俯仰角过大 - self.state[2] < 0.2) # 高度过低 + # 7. 计算奖励值:惩罚姿态倾斜、角速度过大、位置偏移和高度偏离 + # 奖励公式设计原则:越接近目标状态(悬停),奖励值越高 + reward = - ( + np.sum(np.square(self.state[3:5])) + # 惩罚滚转/俯仰角倾斜(权重1) + 0.1 * np.sum(np.square(self.state[9:11])) + # 惩罚角速度(权重0.1) + 0.01 * np.sum(np.square(self.state[0:2])) + # 惩罚xy平面位置偏移(权重0.01) + 0.1 * np.square(self.state[2] - 1.0) # 惩罚高度偏离1m目标值(权重0.1) + ) + + # 8. 判断终止条件:无人机失控 + done = ( + abs(self.state[3]) > np.pi / 4 or # 滚转角超过45度 + abs(self.state[4]) > np.pi / 4 or # 俯仰角超过45度 + self.state[2] < 0.2 # 高度低于0.2米 + ) return self.state, reward, done -# 深度学习控制器模型 +# ===================== 深度学习控制器模型 ===================== +# 功能:基于全连接神经网络的无人机控制器,输入状态输出四个螺旋桨推力 class DroneController(nn.Module): def __init__(self, state_dim=12, action_dim=4): + """ + 初始化神经网络结构 + 参数: + state_dim: 输入状态维度,默认12维 + action_dim: 输出动作维度,默认4维(四个螺旋桨推力) + """ super(DroneController, self).__init__() - self.fc1 = nn.Linear(state_dim, 64) - self.fc2 = nn.Linear(64, 64) - self.fc3 = nn.Linear(64, action_dim) - self.activation = nn.Tanh() + # 定义三层全连接神经网络 + self.fc1 = nn.Linear(state_dim, 64) # 输入层→隐藏层1:12→64 + self.fc2 = nn.Linear(64, 64) # 隐藏层1→隐藏层2:64→64 + self.fc3 = nn.Linear(64, action_dim) # 隐藏层2→输出层:64→4 + self.activation = nn.Tanh() # 激活函数:输出范围[-1, 1] def forward(self, x): - x = self.activation(self.fc1(x)) - x = self.activation(self.fc2(x)) - x = self.activation(self.fc3(x)) # 输出范围[-1,1] - return x * 15.0 # 推力范围[-15,15] - - -# 生成训练数据 + """ + 前向传播:输入状态计算输出动作 + 参数: + x: 输入状态张量,shape=(batch_size, state_dim) + 返回值: + 输出动作张量,shape=(batch_size, action_dim),推力范围[-15, 15] + """ + x = self.activation(self.fc1(x)) # 第一层+激活 + x = self.activation(self.fc2(x)) # 第二层+激活 + x = self.activation(self.fc3(x)) # 第三层+激活 + return x * 15.0 # 缩放输出范围到[-15, 15](螺旋桨最大推力15N) + + +# ===================== 无人机数据集类 ===================== +# 功能:生成训练数据,使用规则控制器生成示范动作,用于监督学习训练 class DroneDataset(Dataset): def __init__(self, size=10000): + """ + 初始化数据集 + 参数: + size: 数据集大小,默认10000条样本 + """ self.size = size - self.drone = DroneModel() - self.data = [] + self.drone = DroneModel() # 实例化无人机模型 + self.data = [] # 存储样本数据:[(state, action), ...] + # 生成size条训练样本 for _ in range(size): - state = self.drone.reset() - # 简单的规则控制器生成目标动作 - roll, pitch = state[3], state[4] - # 基于姿态误差的控制动作 + state = self.drone.reset() # 随机初始化无人机状态 + roll, pitch = state[3], state[4] # 获取当前姿态角 + + # 规则控制器生成目标动作:基于姿态误差的PD控制(简化版) + # 控制逻辑:姿态角倾斜时,调整对应螺旋桨推力以修正姿态 f1 = 5.0 + 10.0 * pitch + 10.0 * roll f2 = 5.0 + 10.0 * pitch - 10.0 * roll f3 = 5.0 - 10.0 * pitch - 10.0 * roll f4 = 5.0 - 10.0 * pitch + 10.0 * roll - action = np.clip([f1, f2, f3, f4], 0, 15) - self.data.append((state, action)) + # 推力范围限制:避免推力为负数或过大 + action = np.clip([f1, f2, f3, f4], 0, 15) + self.data.append((state, action)) # 保存状态-动作对 def __len__(self): + """返回数据集大小(必须实现)""" return self.size def __getitem__(self, idx): + """ + 获取单个样本(必须实现) + 参数: + idx: 样本索引 + 返回值: + 状态张量和动作张量(float32类型,符合PyTorch要求) + """ state, action = self.data[idx] return torch.FloatTensor(state), torch.FloatTensor(action) -# 训练模型 +# ===================== 模型训练函数 ===================== def train_model(epochs=50): - dataset = DroneDataset() + """ + 训练深度学习控制器模型 + 参数: + epochs: 训练轮数,默认50轮 + 返回值: + 训练完成的模型 + """ + # 1. 创建数据集和数据加载器 + dataset = DroneDataset() # 生成训练数据 + # 数据加载器:批大小64,打乱数据顺序 dataloader = DataLoader(dataset, batch_size=64, shuffle=True) - model = DroneController() - criterion = nn.MSELoss() - optimizer = optim.Adam(model.parameters(), lr=0.001) + # 2. 初始化模型、损失函数和优化器 + model = DroneController() # 实例化控制器模型 + criterion = nn.MSELoss() # 损失函数:均方误差(监督学习) + optimizer = optim.Adam(model.parameters(), lr=0.001) # 优化器:Adam,学习率0.001 + # 3. 开始训练循环 for epoch in range(epochs): - running_loss = 0.0 - for states, actions in dataloader: - optimizer.zero_grad() + running_loss = 0.0 # 累计每轮的损失值 + for states, actions in dataloader: # 遍历每个批次 + optimizer.zero_grad() # 清零梯度(避免梯度累积) - outputs = model(states) - loss = criterion(outputs, actions) + outputs = model(states) # 模型预测动作 + loss = criterion(outputs, actions) # 计算预测值与真实值的损失 - loss.backward() - optimizer.step() + loss.backward() # 反向传播计算梯度 + optimizer.step() # 更新模型参数 - running_loss += loss.item() + running_loss += loss.item() # 累加损失值 + # 每10轮打印一次训练进度 if (epoch + 1) % 10 == 0: - print(f'第 {epoch + 1} 轮训练, 损失: {running_loss / len(dataloader):.6f}') + avg_loss = running_loss / len(dataloader) + print(f'第 {epoch + 1:2d} 轮训练 | 平均损失: {avg_loss:.6f}') - return model + return model # 返回训练好的模型 -# 可视化无人机 +# ===================== 无人机3D可视化函数 ===================== def draw_drone(ax, state): - ax.clear() + """ + 在3D坐标轴上绘制无人机的当前姿态 + 参数: + ax: matplotlib的3D坐标轴对象 + state: 无人机当前状态数组 + 返回值: + 更新后的3D坐标轴对象 + """ + # 解包当前位置和姿态角 x, y, z = state[0], state[1], state[2] roll, pitch, yaw = state[3], state[4], state[5] - # 无人机机体尺寸 - body_length = 0.5 - arm_length = 0.3 - - # 无人机中心位置 - center = np.array([x, y, z]) + # 无人机几何参数 + body_length = 0.5 # 机身长度(米) + arm_length = 0.3 # 机臂长度(米) + center = np.array([x, y, z]) # 无人机中心位置 - # 旋转矩阵 (从机体坐标系到世界坐标系) + # 计算旋转矩阵:机体坐标系→世界坐标系(基于欧拉角) cosr, sinr = np.cos(roll), np.sin(roll) cosp, sinp = np.cos(pitch), np.sin(pitch) cosy, siny = np.cos(yaw), np.sin(yaw) - + # 欧拉角旋转矩阵(Z-Y-X顺序:偏航→俯仰→滚转) R = np.array([ [cosy * cosp, cosy * sinp * sinr - siny * cosr, cosy * sinp * cosr + siny * sinr], [siny * cosp, siny * sinp * sinr + cosy * cosr, siny * sinp * cosr - cosy * sinr], [-sinp, cosp * sinr, cosp * cosr] ]) - # 机体关键点 (机体坐标系) - front = center + R @ np.array([body_length / 2, 0, 0]) - back = center + R @ np.array([-body_length / 2, 0, 0]) - left = center + R @ np.array([0, arm_length, 0]) - right = center + R @ np.array([0, -arm_length, 0]) - top = center + R @ np.array([0, 0, 0.1]) + # 计算无人机机体关键点在世界坐标系的位置 + front = center + R @ np.array([body_length / 2, 0, 0]) # 机头 + back = center + R @ np.array([-body_length / 2, 0, 0]) # 机尾 + left = center + R @ np.array([0, arm_length, 0]) # 左侧 + right = center + R @ np.array([0, -arm_length, 0]) # 右侧 + top = center + R @ np.array([0, 0, 0.1]) # 机顶(用于绘制垂直方向) - # 绘制无人机 - ax.plot([front[0], back[0]], [front[1], back[1]], [front[2], back[2]], 'b-', linewidth=3) - ax.plot([left[0], right[0]], [left[1], right[1]], [left[2], right[2]], 'b-', linewidth=3) - ax.plot([center[0], top[0]], [center[1], top[1]], [center[2], top[2]], 'r-', linewidth=2) + # 绘制无人机结构 + ax.clear() # 清空之前的绘制内容 + ax.plot([front[0], back[0]], [front[1], back[1]], [front[2], back[2]], 'b-', linewidth=3, label='机身') + ax.plot([left[0], right[0]], [left[1], right[1]], [left[2], right[2]], 'b-', linewidth=3, label='机臂') + ax.plot([center[0], top[0]], [center[1], top[1]], [center[2], top[2]], 'r-', linewidth=2, label='垂向') - # 绘制四个螺旋桨 + # 绘制四个螺旋桨位置(绿色散点) props = [ - center + R @ np.array([body_length / 4, arm_length, 0]), - center + R @ np.array([-body_length / 4, arm_length, 0]), - center + R @ np.array([-body_length / 4, -arm_length, 0]), - center + R @ np.array([body_length / 4, -arm_length, 0]) + center + R @ np.array([body_length / 4, arm_length, 0]), # 前左 + center + R @ np.array([-body_length / 4, arm_length, 0]), # 后左 + center + R @ np.array([-body_length / 4, -arm_length, 0]), # 后右 + center + R @ np.array([body_length / 4, -arm_length, 0]) # 前右 ] - for p in props: - ax.scatter(p[0], p[1], p[2], color='g', s=50) + ax.scatter(p[0], p[1], p[2], color='g', s=50, label='螺旋桨' if p is props[0] else "") - # 设置坐标轴 + # 设置3D坐标轴范围和标签 ax.set_xlim([-1, 1]) ax.set_ylim([-1, 1]) ax.set_zlim([0, 2]) - ax.set_xlabel('X轴') - ax.set_ylabel('Y轴') - ax.set_zlabel('Z轴') + ax.set_xlabel('X轴 (m)') + ax.set_ylabel('Y轴 (m)') + ax.set_zlabel('Z轴 (m)') ax.set_title('无人机平衡控制可视化') + ax.legend(loc='upper right') return ax -# 实时可视化控制过程 +# ===================== 实时控制可视化函数 ===================== def visualize_control(model): - drone = DroneModel() - state = drone.reset() - + """ + 实时运行训练好的模型,可视化无人机控制效果 + 参数: + model: 训练完成的DroneController模型 + """ + drone = DroneModel() # 实例化无人机模型 + state = drone.reset() # 重置初始状态 + + # 创建绘图窗口,2x2子图布局 fig = plt.figure(figsize=(12, 8)) - # 3D 无人机姿态图 + # 子图1:3D无人机姿态可视化 ax3d = fig.add_subplot(221, projection='3d') - # 姿态角度图 + # 子图2:姿态角变化曲线(滚转、俯仰、偏航) ax_angles = fig.add_subplot(222) - ax_angles.set_title('姿态角度') + ax_angles.set_title('姿态角度变化') ax_angles.set_ylim([-0.8, 0.8]) ax_angles.set_ylabel('角度 (rad)') + ax_angles.grid(True, alpha=0.3) lines_angles = [] - for color in ['r', 'g', 'b']: - line, = ax_angles.plot([], [], color=color, label=['滚转角', '俯仰角', '偏航角'][len(lines_angles)]) + for color, label in zip(['r', 'g', 'b'], ['滚转角', '俯仰角', '偏航角']): + line, = ax_angles.plot([], [], color=color, label=label) lines_angles.append(line) ax_angles.legend() - # 位置图 + # 子图3:位置变化曲线(x、y、z) ax_pos = fig.add_subplot(223) - ax_pos.set_title('位置') + ax_pos.set_title('位置变化') ax_pos.set_ylim([-0.5, 1.5]) ax_pos.set_ylabel('位置 (m)') + ax_pos.set_xlabel('时间 (s)') + ax_pos.grid(True, alpha=0.3) lines_pos = [] - for color in ['r', 'g', 'b']: - line, = ax_pos.plot([], [], color=color, label=['X', 'Y', 'Z'][len(lines_pos)]) + for color, label in zip(['r', 'g', 'b'], ['X', 'Y', 'Z']): + line, = ax_pos.plot([], [], color=color, label=label) lines_pos.append(line) ax_pos.legend() - # 控制动作图 + # 子图4:四个螺旋桨推力变化曲线 ax_actions = fig.add_subplot(224) - ax_actions.set_title('螺旋桨推力') + ax_actions.set_title('螺旋桨推力变化') ax_actions.set_ylim([0, 20]) ax_actions.set_ylabel('推力 (N)') + ax_actions.set_xlabel('时间 (s)') + ax_actions.grid(True, alpha=0.3) lines_actions = [] for i in range(4): - line, = ax_actions.plot([], [], label=f'螺旋桨 {i + 1}') + line, = ax_actions.plot([], [], label=f'螺旋桨 {i+1}') lines_actions.append(line) ax_actions.legend() - # 数据缓存 + # 历史数据缓存:用于绘制曲线 history = { - 'angles': np.zeros((3, 0)), - 'pos': np.zeros((3, 0)), - 'actions': np.zeros((4, 0)), - 'time': np.array([]) + 'angles': np.zeros((3, 0)), # 姿态角历史 (3, time_steps) + 'pos': np.zeros((3, 0)), # 位置历史 (3, time_steps) + 'actions': np.zeros((4, 0)), # 推力历史 (4, time_steps) + 'time': np.array([]) # 时间戳历史 } - max_history = 100 - time = 0 + max_history = 100 # 最大缓存长度(只显示最近100个时间步) + time = 0 # 累计时间 def update(frame): - nonlocal state, time, history - - # 使用深度学习模型计算控制动作 + """ + 动画更新函数:每帧执行一次,更新无人机状态和绘图 + 参数: + frame: 动画帧数(matplotlib自动传入) + 返回值: + 所有需要更新的绘图元素 + """ + nonlocal state, time, history # 引用外部变量 + + # 1. 使用训练好的模型计算控制动作(关闭梯度计算,加快速度) with torch.no_grad(): - state_tensor = torch.FloatTensor(state) - action = model(state_tensor).numpy() + state_tensor = torch.FloatTensor(state) # numpy→tensor + action = model(state_tensor).numpy() # tensor→numpy - # 执行动作 + # 2. 执行动作,更新无人机状态 state, reward, done = drone.step(action) - # 更新历史数据 - time += drone.dt + # 3. 更新历史数据缓存 + time += drone.dt # 累计时间 history['time'] = np.append(history['time'], time) history['angles'] = np.hstack((history['angles'], state[3:6].reshape(-1, 1))) history['pos'] = np.hstack((history['pos'], state[0:3].reshape(-1, 1))) history['actions'] = np.hstack((history['actions'], action.reshape(-1, 1))) - # 保持历史数据长度 + # 4. 裁剪历史数据,只保留最近max_history个数据点 if len(history['time']) > max_history: history['time'] = history['time'][-max_history:] history['angles'] = history['angles'][:, -max_history:] history['pos'] = history['pos'][:, -max_history:] history['actions'] = history['actions'][:, -max_history:] - # 更新3D无人机图 + # 5. 更新3D无人机姿态图 draw_drone(ax3d, state) - # 更新姿态角度图 + # 6. 更新姿态角曲线 for i, line in enumerate(lines_angles): line.set_data(history['time'], history['angles'][i]) - # 更新位置图 + # 7. 更新位置曲线 for i, line in enumerate(lines_pos): line.set_data(history['time'], history['pos'][i]) - # 更新控制动作图 + # 8. 更新推力曲线 for i, line in enumerate(lines_actions): line.set_data(history['time'], history['actions'][i]) - # 自动调整X轴范围 + # 9. 自动调整x轴范围(跟随时间变化) for ax in [ax_angles, ax_pos, ax_actions]: ax.set_xlim([history['time'][0], history['time'][-1]]) + # 10. 无人机失控时停止动画 if done: - print("无人机失去平衡!") - ani.event_source.stop() + print("\n无人机失去平衡!动画停止") + ani.event_source.stop() # 停止动画 + # 返回所有更新的绘图元素(用于blitting优化) return ax3d, *lines_angles, *lines_pos, *lines_actions - ani = FuncAnimation(fig, update, interval=50, blit=False) - plt.tight_layout() - plt.show() + # 创建动画对象:每50ms更新一次,无限循环 + ani = FuncAnimation(fig, update, interval=50, blit=False, cache_frame_data=False) + plt.tight_layout() # 自动调整子图间距 + plt.show() # 显示动画窗口 +# ===================== 主函数入口 ===================== if __name__ == "__main__": - print("正在训练无人机平衡控制模型...") - model = train_model(epochs=50) - print("训练完成,开始可视化控制过程...") - visualize_control(model) \ No newline at end of file + print("=" * 50) + print("开始训练无人机平衡控制模型...") + print("=" * 50) + model = train_model(epochs=50) # 训练模型(50轮) + + print("\n" + "=" * 50) + print("训练完成!开始实时可视化控制过程...") + print("=" * 50) + visualize_control(model) # 启动可视化 \ No newline at end of file diff --git a/src/driverless_car/main_run.py b/src/driverless_car/main_run.py index de60642468..e2dc5b912d 100644 --- a/src/driverless_car/main_run.py +++ b/src/driverless_car/main_run.py @@ -1,183 +1,256 @@ -import numpy as np -import torch -import torch.nn as nn -import torch.optim as optim -from torch.utils.data import Dataset, DataLoader -import matplotlib.pyplot as plt -import random -import os +# 导入必要的库 +import numpy as np # 数值计算库,用于处理数组、矩阵和数值运算 +import torch # PyTorch核心库,用于构建和训练神经网络 +import torch.nn as nn # PyTorch的神经网络模块,包含各类层和损失函数 +import torch.optim as optim # PyTorch的优化器模块,用于模型参数优化 +from torch.utils.data import Dataset, DataLoader # 数据集和数据加载器,用于批量处理数据 +import matplotlib.pyplot as plt # 绘图库,用于可视化结果 +import random # 随机数生成库,用于生成异常区域的随机坐标 +import os # 操作系统库,用于创建目录、保存文件等操作 # -------------------------- 修复Matplotlib后端问题(核心新增代码) -------------------------- -# 方案一:强制设置Matplotlib后端,避开PyCharm的兼容问题 -plt.switch_backend('TkAgg') # 优先用TkAgg后端(需安装tkinter,大部分环境已预装) +# 方案一:强制设置Matplotlib后端,避开PyCharm等IDE的兼容问题 +# Matplotlib的后端负责图像的渲染和显示,不同环境下默认后端可能存在兼容问题 +plt.switch_backend('TkAgg') # 优先用TkAgg后端(需安装tkinter,大部分环境已预装,支持交互式显示) # 如果TkAgg报错,可替换为以下后端: -# plt.switch_backend('Agg') # 无界面后端,需配合保存图片使用 -# plt.switch_backend('Qt5Agg') # 需安装PyQt5 +# plt.switch_backend('Agg') # 无界面后端,仅支持保存图片到文件,不支持交互式显示 +# plt.switch_backend('Qt5Agg') # 需安装PyQt5,支持交互式显示 -# -------------------------- 1. 配置参数 -------------------------- +# -------------------------- 1. 配置全局参数 -------------------------- +# 设置计算设备:优先使用GPU(CUDA),若无则使用CPU device = torch.device("cuda" if torch.cuda.is_available() else "cpu") -img_size = (64, 64) -batch_size = 32 -epochs = 30 -lr = 1e-3 -threshold = 0.02 +img_size = (64, 64) # 无人机巡检图像的尺寸:高度64,宽度64 +batch_size = 32 # 批次大小:每次训练加载32个样本 +epochs = 30 # 训练轮数:整个数据集训练30次 +lr = 1e-3 # 学习率:优化器的步长,控制参数更新的幅度 +threshold = 0.02 # 异常检测的阈值:重构误差超过该值则判定为异常 -# -------------------------- 2. 代码生成模拟无人机巡检数据 -------------------------- +# -------------------------- 2. 生成模拟无人机巡检数据 -------------------------- def generate_normal_sample(): - """生成单张正常的无人机巡检图像(3通道,64x64)""" + """ + 生成单张正常的无人机巡检图像(3通道RGB,64x64分辨率) + 返回: + np.ndarray: 形状为(64, 64, 3)的浮点数组,值范围[0,1] + """ + # 初始化图像为灰度值0.5的背景(3通道) img = np.ones((img_size[0], img_size[1], 3), dtype=np.float32) * 0.5 - # 绘制网格纹理 + # 绘制网格纹理(模拟巡检图像的背景纹理,每4个像素画一条深灰色线) for i in range(0, img_size[0], 4): - img[i, :, :] = 0.1 + img[i, :, :] = 0.1 # 水平网格线 for j in range(0, img_size[1], 4): - img[:, j, :] = 0.1 - # 添加噪声 - noise = np.random.normal(0, 0.02, img.shape).astype(np.float32) - img = np.clip(img + noise, 0, 1) + img[:, j, :] = 0.1 # 垂直网格线 + # 添加高斯噪声(模拟图像的自然噪声) + noise = np.random.normal(0, 0.02, img.shape).astype(np.float32) # 均值0,标准差0.02的高斯噪声 + img = np.clip(img + noise, 0, 1) # 限制值范围在[0,1],避免超出图像像素范围 return img def generate_abnormal_sample(): - """生成单张异常的无人机巡检图像(3通道,64x64)""" + """ + 生成单张异常的无人机巡检图像(在正常图像基础上添加异常区域) + 返回: + np.ndarray: 形状为(64, 64, 3)的浮点数组,值范围[0,1] + """ + # 先生成正常图像 img = generate_normal_sample() - # 制造异常区域 + # 随机生成异常区域的左上角和右下角坐标(范围:10~50,避免超出图像边界) x1 = random.randint(10, 30) y1 = random.randint(10, 30) x2 = random.randint(30, 50) y2 = random.randint(30, 50) + # 在异常区域填充0.7~1.0的随机亮度(模拟缺陷、异物等异常) img[x1:x2, y1:y2, :] = np.random.uniform(0.7, 1.0, (x2-x1, y2-y1, 3)) return img -# 自定义数据集 +# 自定义数据集类:继承PyTorch的Dataset,用于加载模拟的无人机巡检数据 class DroneInspectionDataset(Dataset): def __init__(self, is_normal, sample_num=1000): - self.sample_num = sample_num - self.is_normal = is_normal + """ + 初始化数据集 + 参数: + is_normal (bool): True表示加载正常样本,False表示加载异常样本 + sample_num (int): 数据集的样本数量,默认1000 + """ + self.sample_num = sample_num # 样本总数 + self.is_normal = is_normal # 样本类型标记 def __len__(self): + """返回数据集的样本数量(必须实现的方法)""" return self.sample_num def __getitem__(self, idx): + """ + 根据索引获取单个样本(必须实现的方法) + 参数: + idx (int): 样本索引 + 返回: + torch.Tensor: 形状为(3, 64, 64)的张量,值范围[-1,1] + """ + # 根据标记生成对应类型的图像 if self.is_normal: img = generate_normal_sample() else: img = generate_abnormal_sample() - # 转换为张量:(H, W, C) → (C, H, W) + # 转换为张量并调整维度:(H, W, C) → (C, H, W)(PyTorch默认的图像张量格式) img_tensor = torch.from_numpy(img).permute(2, 0, 1) - img_tensor = (img_tensor - 0.5) / 0.5 # 归一化到[-1,1] + # 归一化到[-1,1]:将原[0,1]的范围转换为[-1,1],符合神经网络的输入习惯 + img_tensor = (img_tensor - 0.5) / 0.5 return img_tensor # -------------------------- 3. 定义轻量化自编码器模型 -------------------------- class LightweightAutoencoder(nn.Module): + """ + 轻量化自编码器模型,用于无人机巡检图像的重构和异常检测 + 结构:编码器(卷积层)→ 解码器(反卷积层) + 输入:3通道64x64图像张量 + 输出:3通道64x64重构图像张量 + """ def __init__(self): - super(LightweightAutoencoder, self).__init__() - # 编码器:3通道输入 + super(LightweightAutoencoder, self).__init__() # 继承父类的初始化方法 + # 编码器:通过卷积层降维,提取图像特征(3通道→64通道,64x64→8x8) self.encoder = nn.Sequential( - nn.Conv2d(3, 16, 3, stride=2, padding=1), # 3→16,64→32 + # 卷积层1:3输入通道→16输出通道,卷积核3x3,步长2,填充1 → 输出尺寸32x32 + nn.Conv2d(3, 16, 3, stride=2, padding=1), + nn.ReLU(True), # 激活函数:ReLU,inplace=True表示原地操作,节省内存 + # 卷积层2:16输入通道→32输出通道,卷积核3x3,步长2,填充1 → 输出尺寸16x16 + nn.Conv2d(16, 32, 3, stride=2, padding=1), nn.ReLU(True), - nn.Conv2d(16, 32, 3, stride=2, padding=1), # 16→32,32→16 - nn.ReLU(True), - nn.Conv2d(32, 64, 3, stride=2, padding=1), # 32→64,16→8 + # 卷积层3:32输入通道→64输出通道,卷积核3x3,步长2,填充1 → 输出尺寸8x8 + nn.Conv2d(32, 64, 3, stride=2, padding=1), nn.ReLU(True) ) - # 解码器:3通道输出 + # 解码器:通过反卷积层升维,重构图像(64通道→3通道,8x8→64x64) self.decoder = nn.Sequential( - nn.ConvTranspose2d(64, 32, 3, stride=2, padding=1, output_padding=1), # 8→16 + # 反卷积层1:64输入通道→32输出通道,卷积核3x3,步长2,填充1,输出填充1 → 输出尺寸16x16 + nn.ConvTranspose2d(64, 32, 3, stride=2, padding=1, output_padding=1), nn.ReLU(True), - nn.ConvTranspose2d(32, 16, 3, stride=2, padding=1, output_padding=1), # 16→32 + # 反卷积层2:32输入通道→16输出通道,卷积核3x3,步长2,填充1,输出填充1 → 输出尺寸32x32 + nn.ConvTranspose2d(32, 16, 3, stride=2, padding=1, output_padding=1), nn.ReLU(True), - nn.ConvTranspose2d(16, 3, 3, stride=2, padding=1, output_padding=1), # 32→64,输出3通道 - nn.Tanh() + # 反卷积层3:16输入通道→3输出通道,卷积核3x3,步长2,填充1,输出填充1 → 输出尺寸64x64 + nn.ConvTranspose2d(16, 3, 3, stride=2, padding=1, output_padding=1), + nn.Tanh() # 激活函数:Tanh,输出值范围[-1,1],与输入的归一化范围匹配 ) def forward(self, x): - # 自动处理维度:3维→4维(添加batch维度) + """ + 前向传播:输入图像经过编码器和解码器,输出重构图像 + 参数: + x (torch.Tensor): 输入张量,形状为(B, 3, 64, 64)或(3, 64, 64)(B为批次大小) + 返回: + torch.Tensor: 重构张量,形状与输入一致 + """ + # 处理单张图像的情况:如果输入是3维(C,H,W),添加batch维度变为4维(1,C,H,W) if len(x.shape) == 3: - x = x.unsqueeze(0) # (C,H,W) → (1,C,H,W) - encoded = self.encoder(x) - decoded = self.decoder(encoded) + x = x.unsqueeze(0) # 增加batch维度 + encoded = self.encoder(x) # 编码:提取特征 + decoded = self.decoder(encoded) # 解码:重构图像 return decoded -# -------------------------- 4. 训练自编码器 -------------------------- +# -------------------------- 4. 训练自编码器模型 -------------------------- def train_model(): + """ + 训练自编码器模型(仅使用正常样本训练,让模型学习正常图像的特征) + 返回: + LightweightAutoencoder: 训练好的模型 + """ + # 创建训练数据集:仅使用正常样本,数量1000 train_dataset = DroneInspectionDataset(is_normal=True, sample_num=1000) + # 创建数据加载器:批量加载数据,打乱顺序 train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True) + # 初始化模型并移至指定设备(GPU/CPU) model = LightweightAutoencoder().to(device) + # 定义损失函数:均方误差(MSE),衡量重构图像与原图像的差异 criterion = nn.MSELoss() + # 定义优化器:Adam优化器,用于更新模型参数 optimizer = optim.Adam(model.parameters(), lr=lr) - # 训练 + # 开启训练模式(启用批归一化、dropout等训练相关的层) model.train() + # 遍历训练轮数 for epoch in range(epochs): - total_loss = 0.0 + total_loss = 0.0 # 累计总损失 + # 遍历数据加载器中的每个批次 for data in train_loader: - img = data.to(device) - output = model(img) - loss = criterion(output, img) - # 反向传播 - optimizer.zero_grad() - loss.backward() - optimizer.step() - total_loss += loss.item() * data.size(0) + img = data.to(device) # 将图像移至指定设备 + output = model(img) # 前向传播,得到重构图像 + loss = criterion(output, img) # 计算损失值 + + # 反向传播与参数更新 + optimizer.zero_grad() # 清空梯度(避免梯度累积) + loss.backward() # 反向传播,计算梯度 + optimizer.step() # 更新模型参数 + + total_loss += loss.item() * data.size(0) # 累加损失(乘以批次大小,得到该批次的总损失) + # 计算该轮的平均损失 avg_loss = total_loss / len(train_loader.dataset) + # 打印训练信息 print(f"Epoch [{epoch+1}/{epochs}], Average Loss: {avg_loss:.6f}") print("训练完成!") return model # -------------------------- 5. 异常检测测试 -------------------------- def test_anomaly_detection(model): + """ + 使用训练好的模型进行异常检测测试 + 参数: + model (LightweightAutoencoder): 训练好的自编码器模型 + """ + # 开启评估模式(关闭批归一化、dropout等训练相关的层) model.eval() - # 生成测试样本:5正常+5异常 + # 生成测试样本:5个正常样本 + 5个异常样本 test_normal = DroneInspectionDataset(is_normal=True, sample_num=5) test_abnormal = DroneInspectionDataset(is_normal=False, sample_num=5) - # 拼接测试样本:(10,3,64,64) + # 拼接测试样本:形状为(10, 3, 64, 64) test_samples = torch.stack([test_normal[i] for i in range(5)] + [test_abnormal[i] for i in range(5)]) - test_labels = [0]*5 + [1]*5 # 0=正常,1=异常 + # 定义测试标签:0表示正常,1表示异常 + test_labels = [0]*5 + [1]*5 - # 计算重构误差 + # 计算每个样本的重构误差 errors = [] + # 禁用梯度计算(评估阶段不需要计算梯度,节省内存和计算资源) with torch.no_grad(): for img in test_samples: - img = img.to(device) - output = model(img) - # 还原到[0,1]计算误差 - img_01 = (img + 1) / 2 # (3,64,64) - output_01 = (output.squeeze(0) + 1) / 2 # 去掉batch维度 + img = img.to(device) # 将图像移至指定设备 + output = model(img) # 前向传播,得到重构图像 + # 将图像从[-1,1]还原到[0,1],方便计算视觉上的误差 + img_01 = (img + 1) / 2 # 原图像还原 + output_01 = (output.squeeze(0) + 1) / 2 # 重构图像还原(去掉batch维度) + # 计算重构误差(MSE) error = nn.MSELoss()(output_01, img_01).item() - errors.append(error) + errors.append(error) # 保存误差值 - # 可视化结果(修复后) - plt.figure(figsize=(15, 8)) + # 可视化结果 + plt.figure(figsize=(15, 8)) # 设置画布大小:宽15英寸,高8英寸 for i in range(len(test_samples)): - # 处理图像用于显示:(C,H,W) → (H,W,C) + # 处理图像用于显示:(C, H, W) → (H, W, C),并还原到[0,1] img = (test_samples[i].permute(1, 2, 0).cpu().numpy() + 1) / 2 error = errors[i] - is_anomaly = error > threshold - # 绘制 + is_anomaly = error > threshold # 判断是否为异常 + # 绘制子图:2行5列,第i+1个位置 plt.subplot(2, 5, i+1) - plt.imshow(img) + plt.imshow(img) # 显示图像 + # 设置标题:包含真实标签、重构误差、检测结果 plt.title(f"Label: {'Normal' if test_labels[i]==0 else 'Abnormal'}\nError: {error:.4f}\nDetect: {'Anomaly' if is_anomaly else 'Normal'}") - plt.axis('off') - plt.tight_layout() + plt.axis('off') # 关闭坐标轴显示 + plt.tight_layout() # 调整子图间距,避免重叠 - # -------------------------- 修复可视化的核心修改 -------------------------- + # 尝试显示图像,若失败则保存到本地 try: - # 尝试显示图像 - plt.show() + plt.show() # 显示图像窗口 except Exception as e: - # 如果显示失败,保存图像到本地(方案二兜底) + # 捕获异常,保存图像到本地 print(f"显示图像失败:{e},将保存图像到本地") # 创建保存目录(如果不存在) if not os.path.exists("drone_anomaly_results"): os.makedirs("drone_anomaly_results") - # 保存图像 + # 保存图像:分辨率300,保留所有内容 plt.savefig("drone_anomaly_results/anomaly_detection_result.png", dpi=300, bbox_inches='tight') print("图像已保存到:drone_anomaly_results/anomaly_detection_result.png") finally: - # 关闭画布,释放资源 - plt.close() + plt.close() # 关闭画布,释放资源 -# -------------------------- 主函数 -------------------------- +# -------------------------- 主函数:程序入口 -------------------------- if __name__ == "__main__": # 训练模型 model = train_model()