From 8fb069fb47634807abd62c7b4a5d39bf5d65679b Mon Sep 17 00:00:00 2001 From: aliangabc Date: Thu, 18 Dec 2025 16:59:30 +0800 Subject: [PATCH 01/10] =?UTF-8?q?=E4=BA=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/driverless_TG/speed_main.py | 266 ++++++++++++++++++++++++++++++++ 1 file changed, 266 insertions(+) create mode 100644 src/driverless_TG/speed_main.py diff --git a/src/driverless_TG/speed_main.py b/src/driverless_TG/speed_main.py new file mode 100644 index 0000000000..ab7726cc9e --- /dev/null +++ b/src/driverless_TG/speed_main.py @@ -0,0 +1,266 @@ +import numpy as np +import matplotlib.pyplot as plt +import random +from typing import Tuple, Dict, List +from sklearn.linear_model import LinearRegression +from sklearn.ensemble import IsolationForest, RandomForestClassifier +from sklearn.model_selection import train_test_split +from sklearn.metrics import mean_absolute_error, accuracy_score, classification_report +import warnings + +warnings.filterwarnings("ignore") # 忽略无关警告 + + +# ===================== 基础数据生成 ===================== +def generate_velocity_data( + test_duration: int = 60, + sample_freq: int = 1, + max_velocity: float = 30.0, + noise_level: float = 0.5, + add_abnormal: bool = True # 是否加入异常值(模拟故障) +) -> Tuple[np.ndarray, np.ndarray]: + """生成模拟无人车速度数据(含可选异常值)""" + time_steps = np.arange(0, test_duration, 1 / sample_freq) + num_samples = len(time_steps) + velocity = np.zeros(num_samples) + + # 模拟加速→匀速→减速 + for i, t in enumerate(time_steps): + if t < 10: + v = (max_velocity / 10) * t + elif 10 <= t < 40: + v = max_velocity + else: + v = max_velocity - (max_velocity / 20) * (t - 40) + + # 加入噪声 + v += random.uniform(-noise_level, noise_level) + velocity[i] = max(v, 0.0) + + # 随机加入2-3个异常值(模拟传感器故障/急刹) + if add_abnormal: + abnormal_idx = random.sample(range(num_samples), random.randint(2, 3)) + for idx in abnormal_idx: + velocity[idx] = velocity[idx] * random.uniform(2, 3) # 异常飙升 + if random.random() > 0.5: + velocity[idx] = 0 # 异常归零 + + return time_steps, velocity + + +# ===================== 机器学习:速度预测 ===================== +def velocity_prediction( + time_steps: np.ndarray, + velocity: np.ndarray, + predict_ratio: float = 0.2 # 预测未来20%的数据 +) -> Tuple[np.ndarray, np.ndarray, float]: + """ + 基于线性回归预测未来速度 + :param time_steps: 时间戳数组 + :param velocity: 速度数组 + :param predict_ratio: 预测未来数据占比 + :return: 预测时间戳、预测速度、MAE误差 + """ + # 数据预处理:划分训练/预测时间范围 + total_len = len(time_steps) + train_len = int(total_len * (1 - predict_ratio)) + train_time = time_steps[:train_len].reshape(-1, 1) # 回归要求特征为2D + train_vel = velocity[:train_len] + predict_time = time_steps[train_len:].reshape(-1, 1) + + # 训练线性回归模型 + model = LinearRegression() + model.fit(train_time, train_vel) + + # 预测未来速度 + predict_vel = model.predict(predict_time) + + # 计算预测误差(仅当有真实值时) + if len(predict_vel) == len(velocity[train_len:]): + mae = mean_absolute_error(velocity[train_len:], predict_vel) + else: + mae = 0.0 + + return predict_time.flatten(), predict_vel, mae + + +# ===================== 机器学习:异常检测 ===================== +def detect_abnormal_velocity( + velocity: np.ndarray, + contamination: float = 0.05 # 异常值占比(默认5%) +) -> np.ndarray: + """ + 基于孤立森林检测速度异常值 + :param velocity: 速度数组 + :param contamination: 异常值比例 + :return: 异常标记数组(1=正常,-1=异常) + """ + # 数据预处理:重塑为2D数组 + vel_2d = velocity.reshape(-1, 1) + + # 训练孤立森林模型 + model = IsolationForest( + n_estimators=100, + contamination=contamination, + random_state=42 + ) + abnormal_label = model.fit_predict(vel_2d) # 1=正常,-1=异常 + + return abnormal_label + + +# ===================== 机器学习:驾驶模式分类 ===================== +def classify_driving_mode( + time_steps: np.ndarray, + velocity: np.ndarray +) -> Tuple[np.ndarray, float]: + """ + 基于随机森林分类驾驶模式(0=减速,1=匀速,2=加速) + :param time_steps: 时间戳数组 + :param velocity: 速度数组 + :return: 模式标签数组、分类准确率 + """ + # 特征工程:计算加速度(速度差分/时间差分)作为核心特征 + vel_diff = np.diff(velocity) + time_diff = np.diff(time_steps) + acceleration = vel_diff / time_diff + + # 构建标签:根据加速度分类 + # 加速度>0.5 → 加速(2);-0.5<加速度<0.5 → 匀速(1);加速度<-0.5 → 减速(0) + labels = [] + for acc in acceleration: + if acc > 0.5: + labels.append(2) + elif acc > -0.5: + labels.append(1) + else: + labels.append(0) + labels = np.array(labels) + + # 构建特征集:加速度+当前速度(需对齐长度) + features = np.column_stack([ + acceleration, + velocity[:-1] # 差分后长度减1 + ]) + + # 划分训练/测试集 + X_train, X_test, y_train, y_test = train_test_split( + features, labels, test_size=0.3, random_state=42 + ) + + # 训练随机森林分类器 + model = RandomForestClassifier(n_estimators=100, random_state=42) + model.fit(X_train, y_train) + + # 预测并计算准确率 + y_pred = model.predict(X_test) + accuracy = accuracy_score(y_test, y_pred) + + # 预测全量数据的模式标签(补全最后一个点的标签) + full_pred = model.predict(features) + full_pred = np.append(full_pred, full_pred[-1]) # 补全长度 + + return full_pred, accuracy + + +# ===================== 可视化整合 ===================== +def plot_ml_results( + time_steps: np.ndarray, + velocity: np.ndarray, + predict_time: np.ndarray, + predict_vel: np.ndarray, + abnormal_label: np.ndarray, + mode_labels: np.ndarray +): + """可视化机器学习分析结果""" + plt.rcParams["font.sans-serif"] = ["SimHei"] + plt.rcParams["axes.unicode_minus"] = False + + # 创建2行1列的子图 + fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 10)) + + # -------- 子图1:速度预测+异常检测 -------- + # 绘制原始速度 + ax1.plot(time_steps, velocity, color="#2E86AB", linewidth=2, label="原始速度") + # 绘制预测速度 + ax1.plot(predict_time, predict_vel, color="#F18F01", linestyle="--", linewidth=2, label="预测速度") + # 标注异常点 + abnormal_idx = np.where(abnormal_label == -1)[0] + ax1.scatter(time_steps[abnormal_idx], velocity[abnormal_idx], + color="#E63946", s=100, label="异常速度点", zorder=5) + + ax1.set_xlabel("时间 (秒)", fontsize=12) + ax1.set_ylabel("速度 (km/h)", fontsize=12) + ax1.set_title("无人车速度预测 + 异常检测", fontsize=14, fontweight="bold") + ax1.legend(loc="upper right") + ax1.grid(True, alpha=0.3) + + # -------- 子图2:驾驶模式分类 -------- + # 定义模式颜色和标签 + mode_colors = {0: "#A23B72", 1: "#2E86AB", 2: "#F18F01"} + mode_names = {0: "减速", 1: "匀速", 2: "加速"} + + # 绘制分类结果 + for mode in [0, 1, 2]: + mode_idx = np.where(mode_labels == mode)[0] + ax2.scatter(time_steps[mode_idx], velocity[mode_idx], + color=mode_colors[mode], label=mode_names[mode], s=50, alpha=0.7) + + ax2.set_xlabel("时间 (秒)", fontsize=12) + ax2.set_ylabel("速度 (km/h)", fontsize=12) + ax2.set_title("无人车驾驶模式分类", fontsize=14, fontweight="bold") + ax2.legend(loc="upper right") + ax2.grid(True, alpha=0.3) + + plt.tight_layout() + plt.show() + + +# ===================== 主函数 ===================== +def main(): + # 1. 配置参数 + TEST_DURATION = 60 + SAMPLE_FREQ = 2 # 提高采样频率(每秒2次) + MAX_VELOCITY = 30 + NOISE_LEVEL = 0.5 + + # 2. 生成测试数据 + print("===== 生成无人车速度测试数据 =====") + time_steps, velocity = generate_velocity_data( + test_duration=TEST_DURATION, + sample_freq=SAMPLE_FREQ, + max_velocity=MAX_VELOCITY, + noise_level=NOISE_LEVEL, + add_abnormal=True + ) + + # 3. 速度预测 + print("\n===== 速度预测(线性回归) =====") + predict_time, predict_vel, mae = velocity_prediction(time_steps, velocity) + print(f"预测未来{len(predict_time)}个时间点的速度") + print(f"预测平均绝对误差(MAE):{mae:.2f} km/h") + + # 4. 异常检测 + print("\n===== 异常检测(孤立森林) =====") + abnormal_label = detect_abnormal_velocity(velocity) + abnormal_num = len(np.where(abnormal_label == -1)[0]) + print(f"检测到异常速度点数量:{abnormal_num} 个") + abnormal_time = time_steps[abnormal_label == -1] + print(f"异常点时间戳:{abnormal_time.round(2)}") + + # 5. 驾驶模式分类 + print("\n===== 驾驶模式分类(随机森林) =====") + mode_labels, accuracy = classify_driving_mode(time_steps, velocity) + print(f"分类准确率:{accuracy:.2%}") + mode_count = {0: 0, 1: 0, 2: 0} + for label in mode_labels: + mode_count[label] += 1 + print(f"减速模式次数:{mode_count[0]} | 匀速模式次数:{mode_count[1]} | 加速模式次数:{mode_count[2]}") + + # 6. 可视化结果 + print("\n===== 可视化分析结果 =====") + plot_ml_results(time_steps, velocity, predict_time, predict_vel, abnormal_label, mode_labels) + + +if __name__ == "__main__": + main() \ No newline at end of file From 9c0b1bbfb76e208cc3dd4c409f45e5bde748fbe6 Mon Sep 17 00:00:00 2001 From: aliangabc Date: Thu, 18 Dec 2025 19:49:02 +0800 Subject: [PATCH 02/10] =?UTF-8?q?=E4=BA=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/driverless_TG/prediction direction.py | 309 ++++++++++++++++++++++ 1 file changed, 309 insertions(+) create mode 100644 src/driverless_TG/prediction direction.py diff --git a/src/driverless_TG/prediction direction.py b/src/driverless_TG/prediction direction.py new file mode 100644 index 0000000000..8596152b31 --- /dev/null +++ b/src/driverless_TG/prediction direction.py @@ -0,0 +1,309 @@ +import numpy as np +import matplotlib.pyplot as plt +from typing import Tuple, Dict, List +from sklearn.model_selection import train_test_split +from sklearn.ensemble import RandomForestClassifier +from sklearn.preprocessing import StandardScaler +from sklearn.metrics import ( + accuracy_score, classification_report, confusion_matrix +) +from sklearn.linear_model import LogisticRegression +import warnings + +warnings.filterwarnings("ignore") + + +# ===================== 1. 数据生成(纯numpy+内置库) ===================== +def generate_vehicle_motion_data( + sample_num: int = 1000, # 样本数量 + noise_level: float = 0.1 # 传感器噪声 +) -> Tuple[np.ndarray, np.ndarray]: + """ + 生成无人车运动数据(纯numpy实现) + 特征:速度(km/h)、加速度(km/h/s)、方向盘角度(°)、偏航角(°)、角速度(°/s) + 标签:运动方向(0=直行,1=左转,2=右转) + """ + # 初始化特征矩阵(sample_num行 × 5列)和标签数组 + features = np.zeros((sample_num, 5), dtype=np.float32) + labels = np.zeros(sample_num, dtype=np.int32) + + # 随机生成数据 + for i in range(sample_num): + # 基础特征(速度、加速度) + speed = np.random.uniform(0, 40) # 0-40km/h + acceleration = np.random.uniform(-2, 2) # -2~2 km/h/s + + # 随机选择运动方向(直行60%、左转20%、右转20%) + direction = np.random.choice([0, 1, 2], p=[0.6, 0.2, 0.2]) + + # 根据方向生成核心特征 + if direction == 0: # 直行 + steering_angle = np.random.normal(0, 1) # 方向盘角度接近0° + yaw_angle = np.random.normal(0, 0.5) # 偏航角接近0° + angular_velocity = np.random.normal(0, 0.3) # 角速度接近0°/s + elif direction == 1: # 左转 + steering_angle = np.random.uniform(10, 30) # 方向盘左偏10-30° + yaw_angle = np.random.uniform(5, 15) # 偏航角左偏5-15° + angular_velocity = np.random.uniform(1, 3) # 左转角速度1-3°/s + else: # 右转 + steering_angle = np.random.uniform(-30, -10) # 方向盘右偏10-30° + yaw_angle = np.random.uniform(-15, -5) # 偏航角右偏5-15° + angular_velocity = np.random.uniform(-3, -1) # 右转角速度1-3°/s + + # 加入传感器噪声 + steering_angle += np.random.normal(0, noise_level) + yaw_angle += np.random.normal(0, noise_level) + angular_velocity += np.random.normal(0, noise_level) + + # 赋值到特征矩阵(保留2位小数) + features[i] = [ + round(speed, 2), + round(acceleration, 2), + round(steering_angle, 2), + round(yaw_angle, 2), + round(angular_velocity, 2) + ] + labels[i] = direction + + return features, labels + + +# ===================== 2. 数据预处理 ===================== +def preprocess_data(features: np.ndarray, labels: np.ndarray) -> Tuple[ + np.ndarray, np.ndarray, np.ndarray, np.ndarray, StandardScaler]: + """ + 数据预处理:标准化 + 划分训练/测试集 + """ + # 划分训练集(80%)和测试集(20%),保证标签分布均匀 + X_train, X_test, y_train, y_test = train_test_split( + features, labels, test_size=0.2, random_state=42, stratify=labels + ) + + # 特征标准化(提升模型性能) + scaler = StandardScaler() + X_train_scaled = scaler.fit_transform(X_train) + X_test_scaled = scaler.transform(X_test) + + return X_train_scaled, X_test_scaled, y_train, y_test, scaler + + +# ===================== 3. 模型训练 ===================== +def train_direction_model( + X_train: np.ndarray, + y_train: np.ndarray, + model_type: str = "random_forest" # 可选:random_forest / logistic_regression +) -> object: + """ + 训练运动方向预测模型 + """ + if model_type == "random_forest": + # 随机森林(核心模型,鲁棒性强) + model = RandomForestClassifier( + n_estimators=100, # 决策树数量 + max_depth=8, # 防止过拟合 + random_state=42 + ) + elif model_type == "logistic_regression": + # 逻辑回归(基准模型,易解释) + model = LogisticRegression(max_iter=200, random_state=42) + else: + raise ValueError("仅支持 random_forest / logistic_regression 模型") + + # 训练模型 + model.fit(X_train, y_train) + return model + + +# ===================== 4. 模型评估(无pandas可视化) ===================== +def evaluate_model( + model: object, + X_test: np.ndarray, + y_test: np.ndarray, + feature_names: List[str] +) -> Dict[str, float]: + """ + 评估模型性能,输出指标并绘制混淆矩阵(纯matplotlib实现) + """ + # 预测测试集 + y_pred = model.predict(X_test) + + # 计算核心指标 + accuracy = accuracy_score(y_test, y_pred) + + # 输出分类报告 + print("\n===== 分类详细报告 =====") + print(classification_report( + y_test, y_pred, + target_names=["直行", "左转", "右转"] + )) + + # 输出特征重要性(仅随机森林支持) + if hasattr(model, "feature_importances_"): + print("\n===== 特征重要性 =====") + importance = model.feature_importances_ + for name, imp in zip(feature_names, importance): + print(f"{name}: {imp:.4f}") + + # 绘制混淆矩阵(纯matplotlib,无pandas依赖) + plt.rcParams["font.sans-serif"] = ["SimHei"] + plt.rcParams["axes.unicode_minus"] = False + + cm = confusion_matrix(y_test, y_pred) + fig, ax = plt.subplots(figsize=(8, 6)) + im = ax.imshow(cm, interpolation='nearest', cmap=plt.cm.Blues) + ax.figure.colorbar(im, ax=ax) + + # 设置坐标轴标签 + ax.set(xticks=np.arange(cm.shape[1]), + yticks=np.arange(cm.shape[0]), + xticklabels=["直行", "左转", "右转"], + yticklabels=["直行", "左转", "右转"], + title="混淆矩阵(运动方向预测)", + ylabel="真实标签", + xlabel="预测标签") + + # 标注数值 + thresh = cm.max() / 2. + for i in range(cm.shape[0]): + for j in range(cm.shape[1]): + ax.text(j, i, format(cm[i, j], 'd'), + ha="center", va="center", + color="white" if cm[i, j] > thresh else "black") + + fig.tight_layout() + plt.show() + + return {"accuracy": accuracy} + + +# ===================== 5. 特征关系可视化(纯matplotlib) ===================== +def visualize_feature_relationship(features: np.ndarray, labels: np.ndarray): + """ + 可视化核心特征与运动方向的关系(无pandas依赖) + """ + plt.rcParams["font.sans-serif"] = ["SimHei"] + plt.rcParams["axes.unicode_minus"] = False + + # 特征名称映射 + feature_idx = { + "speed": 0, + "steering_angle": 2, + "yaw_angle": 3, + "angular_velocity": 4 + } + + # 创建2x1子图 + fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(10, 8)) + + # 子图1:方向盘角度 vs 速度(散点图) + # 直行(绿)、左转(红)、右转(蓝) + ax1.scatter( + features[labels == 0, feature_idx["steering_angle"]], + features[labels == 0, feature_idx["speed"]], + label="直行", alpha=0.6, s=30, color="green" + ) + ax1.scatter( + features[labels == 1, feature_idx["steering_angle"]], + features[labels == 1, feature_idx["speed"]], + label="左转", alpha=0.6, s=30, color="red" + ) + ax1.scatter( + features[labels == 2, feature_idx["steering_angle"]], + features[labels == 2, feature_idx["speed"]], + label="右转", alpha=0.6, s=30, color="blue" + ) + ax1.set_xlabel("方向盘角度 (°)") + ax1.set_ylabel("速度 (km/h)") + ax1.set_title("方向盘角度 vs 速度 vs 运动方向") + ax1.legend() + ax1.grid(alpha=0.3) + + # 子图2:角速度分布(直方图) + ax2.hist( + [features[labels == 0, feature_idx["angular_velocity"]], + features[labels == 1, feature_idx["angular_velocity"]], + features[labels == 2, feature_idx["angular_velocity"]]], + bins=20, label=["直行", "左转", "右转"], + color=["green", "red", "blue"], alpha=0.6 + ) + ax2.set_xlabel("角速度 (°/s)") + ax2.set_ylabel("样本数量") + ax2.set_title("角速度分布 vs 运动方向") + ax2.legend() + ax2.grid(alpha=0.3) + + plt.tight_layout() + plt.show() + + +# ===================== 6. 单样本实时预测 ===================== +def predict_single_sample( + model: object, + scaler: object, + sample: List[float] # [speed, acceleration, steering_angle, yaw_angle, angular_velocity] +) -> Tuple[int, str]: + """ + 预测单个样本的运动方向(模拟无人车在线推理) + """ + # 特征标准化 + sample_scaled = scaler.transform([sample]) + + # 预测方向 + pred_label = model.predict(sample_scaled)[0] + + # 标签转名称 + direction_map = {0: "直行", 1: "左转", 2: "右转"} + pred_name = direction_map[pred_label] + + return pred_label, pred_name + + +# ===================== 主函数(整合全流程) ===================== +def main(): + # 1. 生成模拟数据 + print("===== 1. 生成无人车运动数据 =====") + features, labels = generate_vehicle_motion_data(sample_num=1000, noise_level=0.1) + print(f"生成样本数量:{len(features)} 条") + print("前5条特征数据:") + print(features[:5]) + print("前5条标签(0=直行,1=左转,2=右转):", labels[:5]) + + # 2. 可视化特征关系 + print("\n===== 2. 可视化特征与运动方向的关系 =====") + visualize_feature_relationship(features, labels) + + # 3. 数据预处理 + print("\n===== 3. 数据预处理 =====") + feature_names = ["speed", "acceleration", "steering_angle", "yaw_angle", "angular_velocity"] + X_train, X_test, y_train, y_test, scaler = preprocess_data(features, labels) + print(f"训练集数量:{len(X_train)} 条,测试集数量:{len(X_test)} 条") + + # 4. 训练模型 + print("\n===== 4. 训练运动方向预测模型 =====") + model = train_direction_model(X_train, y_train, model_type="random_forest") + + # 5. 评估模型 + print("\n===== 5. 模型评估 =====") + eval_metrics = evaluate_model(model, X_test, y_test, feature_names) + print(f"模型整体准确率:{eval_metrics['accuracy']:.2%}") + + # 6. 单样本实时预测 + print("\n===== 6. 单样本实时预测 =====") + # 示例1:直行样本 + sample1 = [20.0, 0.5, 0.2, 0.1, 0.05] + pred_label1, pred_name1 = predict_single_sample(model, scaler, sample1) + print(f"样本1特征:{sample1} → 预测结果:{pred_name1}(标签:{pred_label1})") + + # 示例2:左转样本 + sample2 = [15.0, 0.3, 20.0, 10.0, 2.0] + pred_label2, pred_name2 = predict_single_sample(model, scaler, sample2) + print(f"样本2特征:{sample2} → 预测结果:{pred_name2}(标签:{pred_label2})") + + # 示例3:右转样本 + sample3 = [18.0, 0.2, -18.0, -8.0, -1.5] + pred_label3, pred_name3 = predict_single_sample(model, scaler, sample3) + print(f"样本3特征:{sample3} → 预测结果:{pred_name3}(标签:{pred_label3})") + + +if __name__ == "__main__": + main() \ No newline at end of file From 999f6a8fcdb9f5817490503c41a790302a45b1f0 Mon Sep 17 00:00:00 2001 From: aliangabc Date: Thu, 18 Dec 2025 20:26:50 +0800 Subject: [PATCH 03/10] =?UTF-8?q?=E4=BA=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/driverless_TG/smoke _alarm.py | 355 ++++++++++++++++++++++++++++++ 1 file changed, 355 insertions(+) create mode 100644 src/driverless_TG/smoke _alarm.py diff --git a/src/driverless_TG/smoke _alarm.py b/src/driverless_TG/smoke _alarm.py new file mode 100644 index 0000000000..c15adea2a1 --- /dev/null +++ b/src/driverless_TG/smoke _alarm.py @@ -0,0 +1,355 @@ +import numpy as np +import matplotlib.pyplot as plt +from typing import Tuple, Dict, List +from sklearn.ensemble import IsolationForest, RandomForestClassifier +from sklearn.model_selection import train_test_split +from sklearn.preprocessing import StandardScaler +from sklearn.metrics import ( + accuracy_score, classification_report, confusion_matrix +) +import warnings + +warnings.filterwarnings("ignore") + + +# ===================== 1. 烟雾传感器数据生成(模拟无人车场景) ===================== +def generate_smoke_sensor_data( + sample_num: int = 1000, # 采样点数(对应时间序列) + sample_freq: int = 1, # 采样频率(Hz) + noise_level: float = 0.05, # 传感器噪声(ppm) + add_abnormal: bool = True # 是否加入烟雾异常值 +) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: + """ + 生成无人车烟雾传感器数据(时间戳+烟雾浓度+报警标签) + 烟雾浓度单位:ppm(百万分之一) + 标签定义:0=无报警(0-5ppm),1=低风险(5-20ppm),2=高风险(>20ppm) + """ + # 生成时间戳(模拟连续采样) + time_steps = np.arange(0, sample_num / sample_freq, 1 / sample_freq) + + # 初始化烟雾浓度数组(默认正常浓度) + smoke_conc = np.zeros(sample_num, dtype=np.float32) + + # 生成基础浓度(正常场景:0-5ppm随机波动) + base_conc = np.random.uniform(0, 5, sample_num) + + # 随机插入低风险/高风险烟雾段(模拟局部烟雾) + # 低风险段(5-20ppm):占比15% + low_risk_idx = np.random.choice(sample_num, int(sample_num * 0.15), replace=False) + smoke_conc[low_risk_idx] = np.random.uniform(5, 20, len(low_risk_idx)) + + # 高风险段(>20ppm):占比5% + high_risk_idx = np.random.choice(sample_num, int(sample_num * 0.05), replace=False) + smoke_conc[high_risk_idx] = np.random.uniform(20, 50, len(high_risk_idx)) + + # 正常段赋值 + normal_idx = np.setdiff1d(np.arange(sample_num), np.union1d(low_risk_idx, high_risk_idx)) + smoke_conc[normal_idx] = base_conc[normal_idx] + + # 加入传感器噪声(模拟真实采样误差) + smoke_conc += np.random.normal(0, noise_level, sample_num) + smoke_conc = np.maximum(smoke_conc, 0) # 浓度非负 + + # 加入突发异常值(模拟传感器故障/瞬时浓烟) + if add_abnormal: + abnormal_idx = np.random.choice(sample_num, np.random.randint(3, 8), replace=False) + smoke_conc[abnormal_idx] = np.random.uniform(60, 100, len(abnormal_idx)) + + # 生成报警标签(基于浓度阈值) + labels = np.zeros(sample_num, dtype=np.int32) + labels[(smoke_conc >= 5) & (smoke_conc < 20)] = 1 # 低风险 + labels[smoke_conc >= 20] = 2 # 高风险 + + # 保留2位小数 + smoke_conc = np.round(smoke_conc, 2) + + return time_steps, smoke_conc, labels + + +# ===================== 2. 数据预处理(修复sample_freq未定义问题) ===================== +def preprocess_smoke_data(smoke_conc: np.ndarray, labels: np.ndarray, sample_freq: int = 1) -> Tuple[ + np.ndarray, np.ndarray, np.ndarray, np.ndarray, StandardScaler, np.ndarray]: + """ + 数据预处理:构建时序特征 + 标准化 + 划分训练/测试集 + 特征:当前浓度 + 前1帧浓度 + 浓度变化率(差分) + :param sample_freq: 采样频率(Hz),用于计算浓度变化率 + """ + # 构建时序特征(适配时间序列监测) + # 前1帧浓度(首帧补0) + prev_conc = np.concatenate([[0], smoke_conc[:-1]]) + # 浓度变化率(ppm/s):修复sample_freq参数传递 + conc_diff = np.diff(smoke_conc, prepend=0) * sample_freq # 乘以采样频率转速率 + + # 特征矩阵(3维特征) + features = np.column_stack([smoke_conc, prev_conc, conc_diff]) + + # 划分训练/测试集(8:2) + X_train, X_test, y_train, y_test = train_test_split( + features, labels, test_size=0.2, random_state=42, stratify=labels + ) + + # 特征标准化 + scaler = StandardScaler() + X_train_scaled = scaler.fit_transform(X_train) + X_test_scaled = scaler.transform(X_test) + + return X_train_scaled, X_test_scaled, y_train, y_test, scaler, features + + +# ===================== 3. 烟雾异常检测(报警触发) ===================== +def detect_smoke_abnormal(smoke_conc: np.ndarray, contamination: float = 0.08) -> np.ndarray: + """ + 基于孤立森林检测烟雾异常值(触发报警) + :return: 异常标记数组(1=正常,-1=异常/报警) + """ + # 重塑为2D数组(适配sklearn输入) + conc_2d = smoke_conc.reshape(-1, 1) + + # 训练孤立森林模型(无监督异常检测) + iso_forest = IsolationForest( + n_estimators=100, + contamination=contamination, # 异常值占比(8%) + random_state=42 + ) + abnormal_label = iso_forest.fit_predict(conc_2d) + + return abnormal_label + + +# ===================== 4. 报警等级分类模型训练 ===================== +def train_smoke_alarm_model( + X_train: np.ndarray, + y_train: np.ndarray, + model_type: str = "random_forest" +) -> object: + """ + 训练烟雾报警等级分类模型 + """ + if model_type == "random_forest": + model = RandomForestClassifier( + n_estimators=100, + max_depth=6, + random_state=42 + ) + else: + raise ValueError("仅支持 random_forest 模型") + + model.fit(X_train, y_train) + return model + + +# ===================== 5. 模型评估 ===================== +def evaluate_alarm_model( + model: object, + X_test: np.ndarray, + y_test: np.ndarray +) -> Dict[str, float]: + """ + 评估报警等级分类模型性能 + """ + # 预测测试集 + y_pred = model.predict(X_test) + + # 计算准确率 + accuracy = accuracy_score(y_test, y_pred) + + # 输出分类报告 + print("\n===== 报警等级分类报告 =====") + print(classification_report( + y_test, y_pred, + target_names=["无报警", "低风险", "高风险"] + )) + + # 绘制混淆矩阵 + plt.rcParams["font.sans-serif"] = ["SimHei"] + plt.rcParams["axes.unicode_minus"] = False + + cm = confusion_matrix(y_test, y_pred) + fig, ax = plt.subplots(figsize=(8, 6)) + im = ax.imshow(cm, interpolation='nearest', cmap=plt.cm.Reds) + ax.figure.colorbar(im, ax=ax) + + # 设置标签 + ax.set( + xticks=np.arange(cm.shape[1]), + yticks=np.arange(cm.shape[0]), + xticklabels=["无报警", "低风险", "高风险"], + yticklabels=["无报警", "低风险", "高风险"], + title="烟雾报警等级混淆矩阵", + ylabel="真实等级", + xlabel="预测等级" + ) + + # 标注数值 + thresh = cm.max() / 2. + for i in range(cm.shape[0]): + for j in range(cm.shape[1]): + ax.text(j, i, format(cm[i, j], 'd'), + ha="center", va="center", + color="white" if cm[i, j] > thresh else "black") + + fig.tight_layout() + plt.show() + + return {"accuracy": accuracy} + + +# ===================== 6. 实时监测可视化 ===================== +def visualize_smoke_alarm( + time_steps: np.ndarray, + smoke_conc: np.ndarray, + abnormal_label: np.ndarray, + alarm_level: np.ndarray +): + """ + 可视化烟雾监测结果:浓度曲线 + 异常报警标记 + 等级分类 + """ + plt.rcParams["font.sans-serif"] = ["SimHei"] + plt.rcParams["axes.unicode_minus"] = False + + # 创建2行1列子图 + fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 10)) + + # 子图1:烟雾浓度曲线 + 异常报警标记 + ax1.plot(time_steps, smoke_conc, color="#1f77b4", linewidth=1.5, label="烟雾浓度") + # 标注异常报警点(红色散点) + alarm_idx = np.where(abnormal_label == -1)[0] + ax1.scatter( + time_steps[alarm_idx], smoke_conc[alarm_idx], + color="#d62728", s=80, label="报警触发点", zorder=5 + ) + # 绘制阈值线 + ax1.axhline(y=5, color="#ff7f0e", linestyle="--", label="低风险阈值(5ppm)") + ax1.axhline(y=20, color="#d62728", linestyle="--", label="高风险阈值(20ppm)") + + ax1.set_xlabel("时间 (秒)") + ax1.set_ylabel("烟雾浓度 (ppm)") + ax1.set_title("无人车烟雾浓度监测曲线 + 报警标记") + ax1.legend(loc="upper right") + ax1.grid(alpha=0.3) + + # 子图2:报警等级分类结果 + # 等级颜色映射:0=绿色(无报警),1=黄色(低风险),2=红色(高风险) + colors = np.array(["#2ca02c", "#ff7f0e", "#d62728"])[alarm_level] + ax2.scatter( + time_steps, smoke_conc, + c=colors, s=20, alpha=0.7, label="报警等级" + ) + # 手动添加图例 + ax2.scatter([], [], color="#2ca02c", s=50, label="无报警") + ax2.scatter([], [], color="#ff7f0e", s=50, label="低风险") + ax2.scatter([], [], color="#d62728", s=50, label="高风险") + + ax2.set_xlabel("时间 (秒)") + ax2.set_ylabel("烟雾浓度 (ppm)") + ax2.set_title("无人车烟雾报警等级分类") + ax2.legend(loc="upper right") + ax2.grid(alpha=0.3) + + plt.tight_layout() + plt.show() + + +# ===================== 7. 单样本实时监测(车载场景) ===================== +def realtime_smoke_monitor( + model: object, + scaler: object, + current_conc: float, + prev_conc: float, + sample_freq: int = 1 +) -> Tuple[int, str]: + """ + 实时监测单样本烟雾浓度,返回报警等级 + :param current_conc: 当前浓度(ppm) + :param prev_conc: 上一帧浓度(ppm) + :return: 等级标签、等级名称 + """ + # 计算浓度变化率 + conc_diff = (current_conc - prev_conc) * sample_freq + + # 构建特征 + features = np.array([[current_conc, prev_conc, conc_diff]]) + # 标准化 + features_scaled = scaler.transform(features) + # 预测等级 + level_label = model.predict(features_scaled)[0] + + # 等级映射 + level_map = {0: "无报警", 1: "低风险", 2: "高风险"} + level_name = level_map[level_label] + + return level_label, level_name + + +# ===================== 主函数(修复参数传递) ===================== +def main(): + # 全局参数 + SAMPLE_NUM = 1000 # 采样点数 + SAMPLE_FREQ = 1 # 采样频率(1Hz) + NOISE_LEVEL = 0.05 # 传感器噪声 + + # 1. 生成烟雾传感器数据 + print("===== 1. 生成无人车烟雾传感器数据 =====") + time_steps, smoke_conc, labels = generate_smoke_sensor_data( + sample_num=SAMPLE_NUM, + sample_freq=SAMPLE_FREQ, + noise_level=NOISE_LEVEL + ) + print(f"生成采样点数:{len(smoke_conc)} 个") + print(f"时间范围:0 ~ {time_steps[-1]:.1f} 秒") + print(f"浓度范围:{smoke_conc.min():.2f} ~ {smoke_conc.max():.2f} ppm") + + # 2. 烟雾异常检测(触发报警) + print("\n===== 2. 烟雾异常检测(报警触发) =====") + abnormal_label = detect_smoke_abnormal(smoke_conc) + alarm_count = len(np.where(abnormal_label == -1)[0]) + print(f"检测到报警触发点数量:{alarm_count} 个") + alarm_time = time_steps[abnormal_label == -1][:5] # 打印前5个报警时间 + print(f"前5个报警时间戳:{alarm_time.round(2)} 秒") + + # 3. 数据预处理(修复:传递sample_freq参数) + print("\n===== 3. 数据预处理 =====") + X_train, X_test, y_train, y_test, scaler, features = preprocess_smoke_data( + smoke_conc, labels, sample_freq=SAMPLE_FREQ # 补充sample_freq参数 + ) + print(f"训练集数量:{len(X_train)} 条,测试集数量:{len(X_test)} 条") + + # 4. 训练报警等级分类模型 + print("\n===== 4. 训练烟雾报警等级模型 =====") + alarm_model = train_smoke_alarm_model(X_train, y_train) + + # 5. 评估模型 + print("\n===== 5. 模型评估 =====") + eval_metrics = evaluate_alarm_model(alarm_model, X_test, y_test) + print(f"报警等级分类准确率:{eval_metrics['accuracy']:.2%}") + + # 6. 全量数据等级预测 + print("\n===== 6. 全量数据报警等级预测 =====") + features_scaled = scaler.transform(features) + alarm_level = alarm_model.predict(features_scaled) + level_count = {0: 0, 1: 0, 2: 0} + for level in alarm_level: + level_count[level] += 1 + print(f"无报警样本数:{level_count[0]} | 低风险样本数:{level_count[1]} | 高风险样本数:{level_count[2]}") + + # 7. 可视化监测结果 + print("\n===== 7. 可视化烟雾监测结果 =====") + visualize_smoke_alarm(time_steps, smoke_conc, abnormal_label, alarm_level) + + # 8. 实时监测示例(模拟车载传感器) + print("\n===== 8. 实时烟雾监测示例 =====") + # 示例1:正常浓度(3ppm) + level1, name1 = realtime_smoke_monitor(alarm_model, scaler, 3.0, 2.8, SAMPLE_FREQ) + print(f"实时样本1:当前浓度3.0ppm → 报警等级:{name1}") + + # 示例2:低风险(10ppm) + level2, name2 = realtime_smoke_monitor(alarm_model, scaler, 10.0, 8.5, SAMPLE_FREQ) + print(f"实时样本2:当前浓度10.0ppm → 报警等级:{name2}") + + # 示例3:高风险(25ppm) + level3, name3 = realtime_smoke_monitor(alarm_model, scaler, 25.0, 20.0, SAMPLE_FREQ) + print(f"实时样本3:当前浓度25.0ppm → 报警等级:{name3}") + + +if __name__ == "__main__": + main() \ No newline at end of file From 62db7ff5e9438abd8e003149efe48cb8d58c372c Mon Sep 17 00:00:00 2001 From: aliangabc Date: Thu, 18 Dec 2025 20:27:31 +0800 Subject: [PATCH 04/10] =?UTF-8?q?=E4=BA=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../{prediction direction.py => prediction _direction.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename src/driverless_TG/{prediction direction.py => prediction _direction.py} (100%) diff --git a/src/driverless_TG/prediction direction.py b/src/driverless_TG/prediction _direction.py similarity index 100% rename from src/driverless_TG/prediction direction.py rename to src/driverless_TG/prediction _direction.py From 3ce9fc9053cce4c00cd8e8d7fb4ef5db900c12c7 Mon Sep 17 00:00:00 2001 From: aliangabc Date: Thu, 18 Dec 2025 20:28:28 +0800 Subject: [PATCH 05/10] =?UTF-8?q?=E4=BA=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/driverless_TG/smoke _alarm.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/driverless_TG/smoke _alarm.py b/src/driverless_TG/smoke _alarm.py index c15adea2a1..ed140966bf 100644 --- a/src/driverless_TG/smoke _alarm.py +++ b/src/driverless_TG/smoke _alarm.py @@ -332,7 +332,7 @@ def main(): level_count[level] += 1 print(f"无报警样本数:{level_count[0]} | 低风险样本数:{level_count[1]} | 高风险样本数:{level_count[2]}") - # 7. 可视化监测结果 + # 7. 可视化监测结果 222 print("\n===== 7. 可视化烟雾监测结果 =====") visualize_smoke_alarm(time_steps, smoke_conc, abnormal_label, alarm_level) From 6341d317961e3431d5f316ac3124ff3d875d7704 Mon Sep 17 00:00:00 2001 From: aliangabc Date: Thu, 18 Dec 2025 20:33:01 +0800 Subject: [PATCH 06/10] =?UTF-8?q?=E4=BA=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/driverless_TG/smoke _alarm.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/driverless_TG/smoke _alarm.py b/src/driverless_TG/smoke _alarm.py index ed140966bf..c3794afa4c 100644 --- a/src/driverless_TG/smoke _alarm.py +++ b/src/driverless_TG/smoke _alarm.py @@ -169,7 +169,7 @@ def evaluate_alarm_model( im = ax.imshow(cm, interpolation='nearest', cmap=plt.cm.Reds) ax.figure.colorbar(im, ax=ax) - # 设置标签 + # 设置标签111111 ax.set( xticks=np.arange(cm.shape[1]), yticks=np.arange(cm.shape[0]), From 1faee976247afbd90280140aaf0b710e3acbac78 Mon Sep 17 00:00:00 2001 From: aliangabc Date: Thu, 18 Dec 2025 20:40:43 +0800 Subject: [PATCH 07/10] =?UTF-8?q?=E4=BA=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/driverless_TG/prediction direction.py | 309 ---------------------- src/driverless_TG/smoke _alarm.py | 2 +- 2 files changed, 1 insertion(+), 310 deletions(-) delete mode 100644 src/driverless_TG/prediction direction.py diff --git a/src/driverless_TG/prediction direction.py b/src/driverless_TG/prediction direction.py deleted file mode 100644 index 8596152b31..0000000000 --- a/src/driverless_TG/prediction direction.py +++ /dev/null @@ -1,309 +0,0 @@ -import numpy as np -import matplotlib.pyplot as plt -from typing import Tuple, Dict, List -from sklearn.model_selection import train_test_split -from sklearn.ensemble import RandomForestClassifier -from sklearn.preprocessing import StandardScaler -from sklearn.metrics import ( - accuracy_score, classification_report, confusion_matrix -) -from sklearn.linear_model import LogisticRegression -import warnings - -warnings.filterwarnings("ignore") - - -# ===================== 1. 数据生成(纯numpy+内置库) ===================== -def generate_vehicle_motion_data( - sample_num: int = 1000, # 样本数量 - noise_level: float = 0.1 # 传感器噪声 -) -> Tuple[np.ndarray, np.ndarray]: - """ - 生成无人车运动数据(纯numpy实现) - 特征:速度(km/h)、加速度(km/h/s)、方向盘角度(°)、偏航角(°)、角速度(°/s) - 标签:运动方向(0=直行,1=左转,2=右转) - """ - # 初始化特征矩阵(sample_num行 × 5列)和标签数组 - features = np.zeros((sample_num, 5), dtype=np.float32) - labels = np.zeros(sample_num, dtype=np.int32) - - # 随机生成数据 - for i in range(sample_num): - # 基础特征(速度、加速度) - speed = np.random.uniform(0, 40) # 0-40km/h - acceleration = np.random.uniform(-2, 2) # -2~2 km/h/s - - # 随机选择运动方向(直行60%、左转20%、右转20%) - direction = np.random.choice([0, 1, 2], p=[0.6, 0.2, 0.2]) - - # 根据方向生成核心特征 - if direction == 0: # 直行 - steering_angle = np.random.normal(0, 1) # 方向盘角度接近0° - yaw_angle = np.random.normal(0, 0.5) # 偏航角接近0° - angular_velocity = np.random.normal(0, 0.3) # 角速度接近0°/s - elif direction == 1: # 左转 - steering_angle = np.random.uniform(10, 30) # 方向盘左偏10-30° - yaw_angle = np.random.uniform(5, 15) # 偏航角左偏5-15° - angular_velocity = np.random.uniform(1, 3) # 左转角速度1-3°/s - else: # 右转 - steering_angle = np.random.uniform(-30, -10) # 方向盘右偏10-30° - yaw_angle = np.random.uniform(-15, -5) # 偏航角右偏5-15° - angular_velocity = np.random.uniform(-3, -1) # 右转角速度1-3°/s - - # 加入传感器噪声 - steering_angle += np.random.normal(0, noise_level) - yaw_angle += np.random.normal(0, noise_level) - angular_velocity += np.random.normal(0, noise_level) - - # 赋值到特征矩阵(保留2位小数) - features[i] = [ - round(speed, 2), - round(acceleration, 2), - round(steering_angle, 2), - round(yaw_angle, 2), - round(angular_velocity, 2) - ] - labels[i] = direction - - return features, labels - - -# ===================== 2. 数据预处理 ===================== -def preprocess_data(features: np.ndarray, labels: np.ndarray) -> Tuple[ - np.ndarray, np.ndarray, np.ndarray, np.ndarray, StandardScaler]: - """ - 数据预处理:标准化 + 划分训练/测试集 - """ - # 划分训练集(80%)和测试集(20%),保证标签分布均匀 - X_train, X_test, y_train, y_test = train_test_split( - features, labels, test_size=0.2, random_state=42, stratify=labels - ) - - # 特征标准化(提升模型性能) - scaler = StandardScaler() - X_train_scaled = scaler.fit_transform(X_train) - X_test_scaled = scaler.transform(X_test) - - return X_train_scaled, X_test_scaled, y_train, y_test, scaler - - -# ===================== 3. 模型训练 ===================== -def train_direction_model( - X_train: np.ndarray, - y_train: np.ndarray, - model_type: str = "random_forest" # 可选:random_forest / logistic_regression -) -> object: - """ - 训练运动方向预测模型 - """ - if model_type == "random_forest": - # 随机森林(核心模型,鲁棒性强) - model = RandomForestClassifier( - n_estimators=100, # 决策树数量 - max_depth=8, # 防止过拟合 - random_state=42 - ) - elif model_type == "logistic_regression": - # 逻辑回归(基准模型,易解释) - model = LogisticRegression(max_iter=200, random_state=42) - else: - raise ValueError("仅支持 random_forest / logistic_regression 模型") - - # 训练模型 - model.fit(X_train, y_train) - return model - - -# ===================== 4. 模型评估(无pandas可视化) ===================== -def evaluate_model( - model: object, - X_test: np.ndarray, - y_test: np.ndarray, - feature_names: List[str] -) -> Dict[str, float]: - """ - 评估模型性能,输出指标并绘制混淆矩阵(纯matplotlib实现) - """ - # 预测测试集 - y_pred = model.predict(X_test) - - # 计算核心指标 - accuracy = accuracy_score(y_test, y_pred) - - # 输出分类报告 - print("\n===== 分类详细报告 =====") - print(classification_report( - y_test, y_pred, - target_names=["直行", "左转", "右转"] - )) - - # 输出特征重要性(仅随机森林支持) - if hasattr(model, "feature_importances_"): - print("\n===== 特征重要性 =====") - importance = model.feature_importances_ - for name, imp in zip(feature_names, importance): - print(f"{name}: {imp:.4f}") - - # 绘制混淆矩阵(纯matplotlib,无pandas依赖) - plt.rcParams["font.sans-serif"] = ["SimHei"] - plt.rcParams["axes.unicode_minus"] = False - - cm = confusion_matrix(y_test, y_pred) - fig, ax = plt.subplots(figsize=(8, 6)) - im = ax.imshow(cm, interpolation='nearest', cmap=plt.cm.Blues) - ax.figure.colorbar(im, ax=ax) - - # 设置坐标轴标签 - ax.set(xticks=np.arange(cm.shape[1]), - yticks=np.arange(cm.shape[0]), - xticklabels=["直行", "左转", "右转"], - yticklabels=["直行", "左转", "右转"], - title="混淆矩阵(运动方向预测)", - ylabel="真实标签", - xlabel="预测标签") - - # 标注数值 - thresh = cm.max() / 2. - for i in range(cm.shape[0]): - for j in range(cm.shape[1]): - ax.text(j, i, format(cm[i, j], 'd'), - ha="center", va="center", - color="white" if cm[i, j] > thresh else "black") - - fig.tight_layout() - plt.show() - - return {"accuracy": accuracy} - - -# ===================== 5. 特征关系可视化(纯matplotlib) ===================== -def visualize_feature_relationship(features: np.ndarray, labels: np.ndarray): - """ - 可视化核心特征与运动方向的关系(无pandas依赖) - """ - plt.rcParams["font.sans-serif"] = ["SimHei"] - plt.rcParams["axes.unicode_minus"] = False - - # 特征名称映射 - feature_idx = { - "speed": 0, - "steering_angle": 2, - "yaw_angle": 3, - "angular_velocity": 4 - } - - # 创建2x1子图 - fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(10, 8)) - - # 子图1:方向盘角度 vs 速度(散点图) - # 直行(绿)、左转(红)、右转(蓝) - ax1.scatter( - features[labels == 0, feature_idx["steering_angle"]], - features[labels == 0, feature_idx["speed"]], - label="直行", alpha=0.6, s=30, color="green" - ) - ax1.scatter( - features[labels == 1, feature_idx["steering_angle"]], - features[labels == 1, feature_idx["speed"]], - label="左转", alpha=0.6, s=30, color="red" - ) - ax1.scatter( - features[labels == 2, feature_idx["steering_angle"]], - features[labels == 2, feature_idx["speed"]], - label="右转", alpha=0.6, s=30, color="blue" - ) - ax1.set_xlabel("方向盘角度 (°)") - ax1.set_ylabel("速度 (km/h)") - ax1.set_title("方向盘角度 vs 速度 vs 运动方向") - ax1.legend() - ax1.grid(alpha=0.3) - - # 子图2:角速度分布(直方图) - ax2.hist( - [features[labels == 0, feature_idx["angular_velocity"]], - features[labels == 1, feature_idx["angular_velocity"]], - features[labels == 2, feature_idx["angular_velocity"]]], - bins=20, label=["直行", "左转", "右转"], - color=["green", "red", "blue"], alpha=0.6 - ) - ax2.set_xlabel("角速度 (°/s)") - ax2.set_ylabel("样本数量") - ax2.set_title("角速度分布 vs 运动方向") - ax2.legend() - ax2.grid(alpha=0.3) - - plt.tight_layout() - plt.show() - - -# ===================== 6. 单样本实时预测 ===================== -def predict_single_sample( - model: object, - scaler: object, - sample: List[float] # [speed, acceleration, steering_angle, yaw_angle, angular_velocity] -) -> Tuple[int, str]: - """ - 预测单个样本的运动方向(模拟无人车在线推理) - """ - # 特征标准化 - sample_scaled = scaler.transform([sample]) - - # 预测方向 - pred_label = model.predict(sample_scaled)[0] - - # 标签转名称 - direction_map = {0: "直行", 1: "左转", 2: "右转"} - pred_name = direction_map[pred_label] - - return pred_label, pred_name - - -# ===================== 主函数(整合全流程) ===================== -def main(): - # 1. 生成模拟数据 - print("===== 1. 生成无人车运动数据 =====") - features, labels = generate_vehicle_motion_data(sample_num=1000, noise_level=0.1) - print(f"生成样本数量:{len(features)} 条") - print("前5条特征数据:") - print(features[:5]) - print("前5条标签(0=直行,1=左转,2=右转):", labels[:5]) - - # 2. 可视化特征关系 - print("\n===== 2. 可视化特征与运动方向的关系 =====") - visualize_feature_relationship(features, labels) - - # 3. 数据预处理 - print("\n===== 3. 数据预处理 =====") - feature_names = ["speed", "acceleration", "steering_angle", "yaw_angle", "angular_velocity"] - X_train, X_test, y_train, y_test, scaler = preprocess_data(features, labels) - print(f"训练集数量:{len(X_train)} 条,测试集数量:{len(X_test)} 条") - - # 4. 训练模型 - print("\n===== 4. 训练运动方向预测模型 =====") - model = train_direction_model(X_train, y_train, model_type="random_forest") - - # 5. 评估模型 - print("\n===== 5. 模型评估 =====") - eval_metrics = evaluate_model(model, X_test, y_test, feature_names) - print(f"模型整体准确率:{eval_metrics['accuracy']:.2%}") - - # 6. 单样本实时预测 - print("\n===== 6. 单样本实时预测 =====") - # 示例1:直行样本 - sample1 = [20.0, 0.5, 0.2, 0.1, 0.05] - pred_label1, pred_name1 = predict_single_sample(model, scaler, sample1) - print(f"样本1特征:{sample1} → 预测结果:{pred_name1}(标签:{pred_label1})") - - # 示例2:左转样本 - sample2 = [15.0, 0.3, 20.0, 10.0, 2.0] - pred_label2, pred_name2 = predict_single_sample(model, scaler, sample2) - print(f"样本2特征:{sample2} → 预测结果:{pred_name2}(标签:{pred_label2})") - - # 示例3:右转样本 - sample3 = [18.0, 0.2, -18.0, -8.0, -1.5] - pred_label3, pred_name3 = predict_single_sample(model, scaler, sample3) - print(f"样本3特征:{sample3} → 预测结果:{pred_name3}(标签:{pred_label3})") - - -if __name__ == "__main__": - main() \ No newline at end of file diff --git a/src/driverless_TG/smoke _alarm.py b/src/driverless_TG/smoke _alarm.py index c3794afa4c..5388914111 100644 --- a/src/driverless_TG/smoke _alarm.py +++ b/src/driverless_TG/smoke _alarm.py @@ -145,7 +145,7 @@ def evaluate_alarm_model( y_test: np.ndarray ) -> Dict[str, float]: """ - 评估报警等级分类模型性能 + 评估报警等级分类lll模型性能 """ # 预测测试集 y_pred = model.predict(X_test) From c4fa41d62df3bbf6322624933ec78d82f7031ec8 Mon Sep 17 00:00:00 2001 From: aliangabc Date: Fri, 19 Dec 2025 09:14:40 +0800 Subject: [PATCH 08/10] =?UTF-8?q?=E5=92=8C=E6=94=B9=E5=96=84=E6=94=B9?= =?UTF-8?q?=E5=96=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/driverless_TG/temperature_alarm.py | 517 +++++++++++++++++++++++++ 1 file changed, 517 insertions(+) create mode 100644 src/driverless_TG/temperature_alarm.py diff --git a/src/driverless_TG/temperature_alarm.py b/src/driverless_TG/temperature_alarm.py new file mode 100644 index 0000000000..0a79b3c955 --- /dev/null +++ b/src/driverless_TG/temperature_alarm.py @@ -0,0 +1,517 @@ +import numpy as np +import time +import random +from collections import defaultdict +import matplotlib.pyplot as plt + +# 解决PyCharm中文显示问题 +plt.rcParams['font.sans-serif'] = ['SimHei'] # 黑体 +plt.rcParams['axes.unicode_minus'] = False # 解决负号显示问题 + + +# ===================== 1. 数据生成模块 ===================== +def generate_temperature_data(n_samples=10000): + """生成模拟的无人车温度数据集""" + np.random.seed(42) + # 基础特征 + motor_temp = np.random.normal(60, 10, n_samples) + battery_temp = np.random.normal(45, 8, n_samples) + controller_temp = np.random.normal(50, 9, n_samples) + runtime = np.random.uniform(0, 10, n_samples) + speed = np.random.normal(40, 15, n_samples) + + # 构造异常数据 + anomaly_idx = np.random.choice(n_samples, size=int(n_samples * 0.3), replace=False) + mild_idx = anomaly_idx[:int(len(anomaly_idx) * 0.5)] + moderate_idx = anomaly_idx[int(len(anomaly_idx) * 0.5):int(len(anomaly_idx) * 0.8)] + severe_idx = anomaly_idx[int(len(anomaly_idx) * 0.8):] + + motor_temp[mild_idx] += np.random.uniform(5, 10, len(mild_idx)) + battery_temp[mild_idx] += np.random.uniform(3, 7, len(mild_idx)) + + motor_temp[moderate_idx] += np.random.uniform(10, 20, len(moderate_idx)) + battery_temp[moderate_idx] += np.random.uniform(7, 15, len(moderate_idx)) + controller_temp[moderate_idx] += np.random.uniform(8, 12, len(moderate_idx)) + + motor_temp[severe_idx] += np.random.uniform(20, 35, len(severe_idx)) + battery_temp[severe_idx] += np.random.uniform(15, 25, len(severe_idx)) + controller_temp[severe_idx] += np.random.uniform(12, 20, len(severe_idx)) + runtime[severe_idx] = np.random.uniform(8, 12, len(severe_idx)) + + # 生成标签 + labels = np.zeros(n_samples) + labels[mild_idx] = 1 + labels[moderate_idx] = 2 + labels[severe_idx] = 3 + + # 限制数值合理性 + motor_temp = np.clip(motor_temp, 0, 120) + battery_temp = np.clip(battery_temp, 0, 80) + controller_temp = np.clip(controller_temp, 0, 100) + runtime = np.clip(runtime, 0, 12) + speed = np.clip(speed, 0, 120) + + features = np.column_stack([motor_temp, battery_temp, controller_temp, runtime, speed]) + return features, labels + + +# ===================== 2. 数据预处理 ===================== +def standard_scaler(X): + """手动实现标准化""" + mean = np.mean(X, axis=0) + std = np.std(X, axis=0) + std[std == 0] = 1e-8 + X_scaled = (X - mean) / std + return X_scaled, mean, std + + +def train_test_split(X, y, test_size=0.2, random_state=42): + """手动实现数据集划分""" + np.random.seed(random_state) + n_samples = X.shape[0] + test_samples = int(n_samples * test_size) + + indices = np.arange(n_samples) + np.random.shuffle(indices) + + test_indices = indices[:test_samples] + train_indices = indices[test_samples:] + + X_train = X[train_indices] + X_test = X[test_indices] + y_train = y[train_indices] + y_test = y[test_indices] + + return X_train, X_test, y_train, y_test + + +# ===================== 3. 决策树分类器 ===================== +class DecisionTreeClassifier: + """手动实现决策树分类器""" + + def __init__(self, max_depth=10, min_samples_split=5): + self.max_depth = max_depth + self.min_samples_split = min_samples_split + self.tree = {} + + def _gini_impurity(self, y): + """计算基尼不纯度""" + classes, counts = np.unique(y, return_counts=True) + impurity = 1.0 + for count in counts: + p = count / len(y) + impurity -= p * p + return impurity + + def _best_split(self, X, y): + """寻找最优划分特征和阈值""" + n_features = X.shape[1] + best_gini = float('inf') + best_feature = None + best_threshold = None + + for feature in range(n_features): + values = X[:, feature] + unique_values = np.unique(values) + + for threshold in unique_values: + left_mask = values <= threshold + right_mask = values > threshold + + if len(y[left_mask]) < 1 or len(y[right_mask]) < 1: + continue + + gini_left = self._gini_impurity(y[left_mask]) + gini_right = self._gini_impurity(y[right_mask]) + gini = (len(y[left_mask]) * gini_left + len(y[right_mask]) * gini_right) / len(y) + + if gini < best_gini: + best_gini = gini + best_feature = feature + best_threshold = threshold + + return best_feature, best_threshold + + def _build_tree(self, X, y, depth=0): + """递归构建决策树""" + n_samples, n_features = X.shape + n_classes = len(np.unique(y)) + + if (depth >= self.max_depth or + n_samples < self.min_samples_split or + n_classes == 1): + classes, counts = np.unique(y, return_counts=True) + return classes[np.argmax(counts)] + + best_feature, best_threshold = self._best_split(X, y) + if best_feature is None: + classes, counts = np.unique(y, return_counts=True) + return classes[np.argmax(counts)] + + left_mask = X[:, best_feature] <= best_threshold + right_mask = X[:, best_feature] > best_threshold + + left_subtree = self._build_tree(X[left_mask], y[left_mask], depth + 1) + right_subtree = self._build_tree(X[right_mask], y[right_mask], depth + 1) + + return { + 'feature': best_feature, + 'threshold': best_threshold, + 'left': left_subtree, + 'right': right_subtree + } + + def fit(self, X, y): + """训练决策树""" + self.tree = self._build_tree(X, y) + + def _predict_sample(self, x, tree): + """预测单个样本""" + if not isinstance(tree, dict): + return tree + + feature = tree['feature'] + threshold = tree['threshold'] + + if x[feature] <= threshold: + return self._predict_sample(x, tree['left']) + else: + return self._predict_sample(x, tree['right']) + + def predict(self, X): + """预测多个样本""" + predictions = [self._predict_sample(x, self.tree) for x in X] + return np.array(predictions) + + +# ===================== 4. 模型评估与可视化 ===================== +def evaluate_model(y_true, y_pred): + """评估模型并生成可视化图表""" + classes = np.unique(y_true) + n_classes = len(classes) + + # 混淆矩阵 + conf_matrix = np.zeros((n_classes, n_classes), dtype=int) + for t, p in zip(y_true, y_pred): + conf_matrix[int(t), int(p)] += 1 + + # 计算评估指标 + overall_accuracy = np.trace(conf_matrix) / np.sum(conf_matrix) + precision = [] + recall = [] + f1 = [] + + for i in range(n_classes): + tp = conf_matrix[i, i] + fp = np.sum(conf_matrix[:, i]) - tp + fn = np.sum(conf_matrix[i, :]) - tp + + p = tp / (tp + fp) if (tp + fp) > 0 else 0.0 + r = tp / (tp + fn) if (tp + fn) > 0 else 0.0 + f = 2 * p * r / (p + r) if (p + r) > 0 else 0.0 + + precision.append(p) + recall.append(r) + f1.append(f) + + # 1. 绘制混淆矩阵热力图 + plt.figure(figsize=(8, 6)) + plt.imshow(conf_matrix, cmap='Blues') + plt.title('模型混淆矩阵', fontsize=14) + plt.xlabel('预测标签', fontsize=12) + plt.ylabel('真实标签', fontsize=12) + plt.xticks(range(n_classes), ['正常', '轻度异常', '中度异常', '重度异常']) + plt.yticks(range(n_classes), ['正常', '轻度异常', '中度异常', '重度异常']) + + # 添加数值标注 + for i in range(n_classes): + for j in range(n_classes): + plt.text(j, i, conf_matrix[i, j], ha='center', va='center', color='black', fontsize=10) + + plt.colorbar(label='样本数量') + plt.tight_layout() + plt.savefig('confusion_matrix.png', dpi=150) # 保存图片 + plt.show() # PyCharm中显示图片 + + # 2. 绘制精确率/召回率/F1对比图 + plt.figure(figsize=(10, 6)) + x = np.arange(n_classes) + width = 0.25 + + plt.bar(x - width, precision, width, label='精确率', color='#1f77b4') + plt.bar(x, recall, width, label='召回率', color='#ff7f0e') + plt.bar(x + width, f1, width, label='F1分数', color='#2ca02c') + + plt.title('模型分类性能指标', fontsize=14) + plt.xlabel('异常等级', fontsize=12) + plt.ylabel('指标值', fontsize=12) + plt.xticks(x, ['正常', '轻度异常', '中度异常', '重度异常']) + plt.ylim(0, 1.1) + plt.legend() + plt.grid(axis='y', alpha=0.3) + plt.tight_layout() + plt.savefig('classification_metrics.png', dpi=150) + plt.show() + + # 打印文本报告 + print("=== 模型性能报告 ===") + print(f"{'类别':<8} {'精确率':<8} {'召回率':<8} {'F1分数':<8}") + print("-" * 32) + for i, cls in enumerate(classes): + print(f"{int(cls):<8} {precision[i]:.4f} {recall[i]:.4f} {f1[i]:.4f}") + print(f"\n整体准确率:{overall_accuracy:.4f}") + + return conf_matrix + + +def plot_temperature_distribution(X, y): + """绘制温度特征分布直方图""" + feature_names = ['电机温度(℃)', '电池温度(℃)', '控制器温度(℃)'] + fig, axes = plt.subplots(1, 3, figsize=(15, 5)) + + for i, ax in enumerate(axes): + # 正常数据 + normal_data = X[y == 0, i] + # 异常数据 + anomaly_data = X[y != 0, i] + + ax.hist(normal_data, bins=30, alpha=0.7, label='正常', color='green', density=True) + ax.hist(anomaly_data, bins=30, alpha=0.7, label='异常', color='red', density=True) + + ax.set_title(feature_names[i], fontsize=12) + ax.set_xlabel('温度值') + ax.set_ylabel('概率密度') + ax.legend() + ax.grid(alpha=0.3) + + plt.suptitle('关键部件温度分布对比', fontsize=14) + plt.tight_layout() + plt.savefig('temperature_distribution.png', dpi=150) + plt.show() + + +# ===================== 5. 实时监测与报警系统 ===================== +class TemperatureAlarmSystem: + """无人车温度报警系统(带可视化)""" + + def __init__(self, model, mean, std): + self.model = model + self.mean = mean + self.std = std + self.alarm_config = { + 0: {"level": "正常", "msg": "各部件温度正常", "action": "持续监测", "color": 'green'}, + 1: {"level": "轻度异常", "msg": "温度略高于正常阈值", "action": "提醒驾驶员关注", "color": 'yellow'}, + 2: {"level": "中度异常", "msg": "温度明显升高", "action": "降低车速", "color": 'orange'}, + 3: {"level": "重度异常", "msg": "温度严重超标", "action": "紧急停车", "color": 'red'} + } + self.history = [] + self.hard_thresholds = {"motor": 100, "battery": 70, "controller": 90} + + def _scale_data(self, data): + """标准化数据""" + scaled = (data - self.mean) / self.std + return scaled + + def _check_hard_threshold(self, sensor_data): + """检查硬件阈值""" + motor_temp = sensor_data[0][0] + battery_temp = sensor_data[0][1] + controller_temp = sensor_data[0][2] + + if motor_temp >= self.hard_thresholds["motor"] or \ + battery_temp >= self.hard_thresholds["battery"] or \ + controller_temp >= self.hard_thresholds["controller"]: + return 3 + return None + + def simulate_sensor(self): + """模拟传感器数据""" + motor = random.uniform(50, 70) + battery = random.uniform(40, 50) + controller = random.uniform(45, 55) + runtime = random.uniform(0, 10) + speed = random.uniform(30, 50) + + anomaly_prob = random.random() + if anomaly_prob < 0.05: + motor += 30 + battery += 20 + controller += 18 + elif anomaly_prob < 0.15: + motor += 15 + battery += 10 + controller += 10 + elif anomaly_prob < 0.3: + motor += 8 + battery += 5 + controller += 5 + + motor = max(0, min(motor, 120)) + battery = max(0, min(battery, 80)) + controller = max(0, min(controller, 100)) + runtime = max(0, min(runtime, 12)) + speed = max(0, min(speed, 120)) + + return np.array([[motor, battery, controller, runtime, speed]]) + + def predict_risk(self, sensor_data): + """预测风险等级""" + hard_risk = self._check_hard_threshold(sensor_data) + if hard_risk is not None: + return hard_risk + + scaled_data = self._scale_data(sensor_data) + risk_level = self.model.predict(scaled_data)[0] + return int(risk_level) + + def trigger_alarm(self, risk_level, sensor_data): + """触发报警""" + alarm_info = self.alarm_config[risk_level] + timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + + log = { + "时间": timestamp, + "时间戳": time.time(), + "电机温度": round(sensor_data[0][0], 2), + "电池温度": round(sensor_data[0][1], 2), + "控制器温度": round(sensor_data[0][2], 2), + "运行时长": round(sensor_data[0][3], 2), + "车速": round(sensor_data[0][4], 2), + "风险等级": risk_level, + "报警级别": alarm_info["level"], + "颜色": alarm_info["color"] + } + + self.history.append(log) + + print(f"\n【{timestamp}】【{alarm_info['level']}】") + print(f"传感器数据:电机{log['电机温度']}℃ | 电池{log['电池温度']}℃ | 控制器{log['控制器温度']}℃") + print(f"报警信息:{alarm_info['msg']} | 建议操作:{alarm_info['action']}") + + return log + + def plot_monitoring_results(self): + """绘制实时监测结果可视化图表""" + if not self.history: + print("无监测数据可绘制") + return + + # 提取数据 + timestamps = [log["时间戳"] for log in self.history] + motor_temps = [log["电机温度"] for log in self.history] + battery_temps = [log["电池温度"] for log in self.history] + controller_temps = [log["控制器温度"] for log in self.history] + risk_levels = [log["风险等级"] for log in self.history] + colors = [log["颜色"] for log in self.history] + + # 归一化时间戳(便于显示) + start_ts = timestamps[0] + timestamps = [ts - start_ts for ts in timestamps] + + # 1. 温度趋势图 + plt.figure(figsize=(12, 6)) + plt.plot(timestamps, motor_temps, 'o-', label='电机温度', linewidth=2, markersize=6) + plt.plot(timestamps, battery_temps, 's-', label='电池温度', linewidth=2, markersize=6) + plt.plot(timestamps, controller_temps, '^-', label='控制器温度', linewidth=2, markersize=6) + + # 标注异常点 + for i, (t, r) in enumerate(zip(timestamps, risk_levels)): + if r > 0: + plt.scatter(t, motor_temps[i], color=colors[i], s=100, edgecolor='black', zorder=5) + plt.annotate(f'等级{r}', (t, motor_temps[i]), xytext=(5, 5), textcoords='offset points') + + plt.title('无人车温度实时监测趋势', fontsize=14) + plt.xlabel('监测时长(秒)', fontsize=12) + plt.ylabel('温度(℃)', fontsize=12) + plt.legend() + plt.grid(alpha=0.3) + plt.tight_layout() + plt.savefig('temperature_trend.png', dpi=150) + plt.show() + + # 2. 报警等级统计饼图 + alarm_counts = defaultdict(int) + for log in self.history: + alarm_counts[log["报警级别"]] += 1 + + labels = list(alarm_counts.keys()) + sizes = list(alarm_counts.values()) + colors = [self.alarm_config[0]["color"] if l == "正常" else + self.alarm_config[1]["color"] if l == "轻度异常" else + self.alarm_config[2]["color"] if l == "中度异常" else + self.alarm_config[3]["color"] for l in labels] + + plt.figure(figsize=(8, 8)) + plt.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%', startangle=90, shadow=True) + plt.title('报警等级分布统计', fontsize=14) + plt.axis('equal') + plt.tight_layout() + plt.savefig('alarm_distribution.png', dpi=150) + plt.show() + + def run_monitor(self, duration=10, interval=2): + """运行实时监测系统""" + print("\n========== 无人车温度报警系统启动 ==========") + print(f"监测时长:{duration}秒 | 采样间隔:{interval}秒") + print("===========================================\n") + + start_time = time.time() + while time.time() - start_time < duration: + sensor_data = self.simulate_sensor() + risk_level = self.predict_risk(sensor_data) + self.trigger_alarm(risk_level, sensor_data) + time.sleep(interval) + + print("\n========== 监测结束 ==========") + # 生成监测结果可视化 + self.plot_monitoring_results() + + # 输出统计信息 + anomaly_stats = defaultdict(int) + for log in self.history: + anomaly_stats[log["报警级别"]] += 1 + print("异常统计:") + for level, count in anomaly_stats.items(): + print(f"{level}:{count}次") + + +# ===================== 6. 主程序入口 ===================== +if __name__ == "__main__": + # 步骤1:生成数据并可视化分布 + print("=== 1. 生成温度数据集 ===") + X, y = generate_temperature_data(n_samples=10000) + print(f"数据集规模:特征{X.shape} | 标签{y.shape}") + print(f"标签分布:{np.bincount(y.astype(int))}") + + # 绘制温度分布 + plot_temperature_distribution(X, y) + + # 步骤2:数据预处理 + print("\n=== 2. 数据预处理 ===") + X_scaled, mean, std = standard_scaler(X) + X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2) + print(f"训练集:{X_train.shape} | 测试集:{X_test.shape}") + + # 步骤3:训练模型 + print("\n=== 3. 训练决策树模型 ===") + model = DecisionTreeClassifier(max_depth=8, min_samples_split=5) + model.fit(X_train, y_train) + print("模型训练完成!") + + # 步骤4:评估模型并可视化 + print("\n=== 4. 模型评估 ===") + y_pred = model.predict(X_test) + evaluate_model(y_test, y_pred) + + # 步骤5:启动报警系统 + print("\n=== 5. 启动温度报警系统 ===") + alarm_system = TemperatureAlarmSystem(model, mean, std) + alarm_system.run_monitor(duration=10, interval=2) + + print("\n=== 所有可视化图片已保存到当前目录 ===") + print("生成的图片:") + print("1. temperature_distribution.png - 温度分布对比图") + print("2. confusion_matrix.png - 混淆矩阵热力图") + print("3. classification_metrics.png - 分类性能指标图") + print("4. temperature_trend.png - 实时温度趋势图") + print("5. alarm_distribution.png - 报警等级统计饼图") \ No newline at end of file From 4009885d0decf46cb9f1cceb4b78816a526409f9 Mon Sep 17 00:00:00 2001 From: aliangabc Date: Fri, 19 Dec 2025 13:13:22 +0800 Subject: [PATCH 09/10] =?UTF-8?q?=E5=92=8C=E6=94=B9=E5=96=84=E6=94=B9?= =?UTF-8?q?=E5=96=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/driverless_TG/emergency_brake.py | 338 +++++++++++++++++++++++++++ 1 file changed, 338 insertions(+) create mode 100644 src/driverless_TG/emergency_brake.py diff --git a/src/driverless_TG/emergency_brake.py b/src/driverless_TG/emergency_brake.py new file mode 100644 index 0000000000..4cb017e529 --- /dev/null +++ b/src/driverless_TG/emergency_brake.py @@ -0,0 +1,338 @@ +import numpy as np +import random +import math +import matplotlib.pyplot as plt + +# ===================== 全局配置(解决PyCharm中文显示/图片样式) ===================== +plt.rcParams['font.sans-serif'] = ['Microsoft YaHei', 'SimHei', 'DejaVu Sans'] # 兼容不同系统中文 +plt.rcParams['axes.unicode_minus'] = False # 解决负号显示问题 +plt.rcParams['figure.figsize'] = (14, 9) # 图片默认尺寸 +plt.rcParams['savefig.dpi'] = 300 # 保存图片的分辨率 +plt.rcParams['figure.dpi'] = 100 # 显示图片的分辨率 + +# ===================== 1. 生成无人车刹车场景数据 ===================== +def generate_vehicle_data(n_samples=8000): + """生成模拟数据集(纯Python实现,含物理模型+噪声)""" + random.seed(42) # 固定随机种子,保证结果可复现 + features = [] + labels = [] + + for _ in range(n_samples): + # 核心特征(无人车感知数据) + vehicle_speed = random.uniform(0, 120) # 车速(km/h) + obstacle_distance = random.uniform(0, 200) # 障碍物距离(m) + obstacle_speed = random.uniform(-50, 50) # 障碍物相对速度(km/h) + road_friction = random.uniform(0.1, 1.0) # 路面摩擦系数(雨雪天低/干燥高) + weather_visibility = random.uniform(50, 1000)# 能见度(m) + brake_delay = random.uniform(0.05, 0.2) # 刹车系统延迟(s) + + # 刹车时间核心公式(物理模型) + base_time = (obstacle_distance / (vehicle_speed/3.6)) * (1/road_friction) - brake_delay + # 环境修正项 + vis_correction = 0.5 if weather_visibility < 200 else 0.1 # 低能见度需更早刹车 + obs_correction = obstacle_speed / 100 # 障碍物速度修正 + noise = random.gauss(0, 0.15) # 高斯噪声模拟真实误差 + + # 限制刹车时间合理范围(0.1~5秒) + brake_time = max(0.1, min(base_time + vis_correction + obs_correction + noise, 5.0)) + + features.append([vehicle_speed, obstacle_distance, obstacle_speed, road_friction, weather_visibility, brake_delay]) + labels.append(brake_time) + + return np.array(features), np.array(labels) + +# ===================== 2. 特征归一化(纯Python实现) ===================== +class StandardScaler: + """均值-标准差归一化,适配PyCharm运行""" + def __init__(self): + self.feature_mean = None + self.feature_std = None + + def fit(self, X): + """计算每个特征的均值和标准差""" + n_features = X.shape[1] + self.feature_mean = np.zeros(n_features) + self.feature_std = np.zeros(n_features) + + for i in range(n_features): + col_data = X[:, i] + self.feature_mean[i] = np.mean(col_data) + self.feature_std[i] = np.std(col_data) + 1e-8 # 避免除以0 + + def transform(self, X): + """应用归一化""" + return (X - self.feature_mean) / self.feature_std + +# ===================== 3. 简化版决策树回归(核心预测模型) ===================== +class SimpleDecisionTree: + """轻量级决策树,适配PyCharm低资源运行""" + def __init__(self, max_depth=3, min_samples=5): + self.max_depth = max_depth + self.min_samples = min_samples + self.tree = {} + self.feat_importance = np.zeros(6) # 特征重要性(6个特征) + + def _mse(self, y): + """计算均方误差(回归损失)""" + if len(y) == 0: + return 0.0 + mean_y = np.mean(y) + return np.mean((y - mean_y) ** 2) + + def _best_split(self, X, y): + """寻找最优分割特征和阈值""" + best_feat = -1 + best_thresh = None + best_mse = self._mse(y) + n_features = X.shape[1] + + for feat_idx in range(n_features): + # 去重阈值,减少计算量 + thresholds = np.unique(X[:, feat_idx])[:20] # 限制阈值数量,加速PyCharm运行 + for thresh in thresholds: + # 分割数据集 + left_mask = X[:, feat_idx] <= thresh + right_mask = ~left_mask + + # 跳过样本数不足的分割 + if len(y[left_mask]) < self.min_samples or len(y[right_mask]) < self.min_samples: + continue + + # 计算分割后的总MSE + mse_left = self._mse(y[left_mask]) + mse_right = self._mse(y[right_mask]) + total_mse = (len(y[left_mask]) * mse_left + len(y[right_mask]) * mse_right) / len(y) + + # 更新最优分割 + if total_mse < best_mse: + best_mse = total_mse + best_feat = feat_idx + best_thresh = thresh + + # 累计特征重要性 + if best_feat != -1: + self.feat_importance[best_feat] += (self._mse(y) - best_mse) * len(y) + return best_feat, best_thresh + + def _build_tree(self, X, y, depth): + """递归构建决策树""" + # 终止条件:深度达标/损失足够小 + if depth >= self.max_depth or self._mse(y) < 1e-5: + return {"value": np.mean(y)} + + # 寻找最优分割 + feat_idx, thresh = self._best_split(X, y) + if feat_idx == -1: + return {"value": np.mean(y)} + + # 分割数据集并递归构建子树 + left_mask = X[:, feat_idx] <= thresh + right_mask = ~left_mask + left_tree = self._build_tree(X[left_mask], y[left_mask], depth + 1) + right_tree = self._build_tree(X[right_mask], y[right_mask], depth + 1) + + return { + "feature": feat_idx, + "threshold": thresh, + "left": left_tree, + "right": right_tree + } + + def fit(self, X, y): + """训练决策树""" + self.tree = self._build_tree(X, y, depth=0) + # 归一化特征重要性 + self.feat_importance = self.feat_importance / np.sum(self.feat_importance) if np.sum(self.feat_importance) > 0 else self.feat_importance + + def _predict_single(self, x): + """预测单个样本""" + tree_node = self.tree + while "feature" in tree_node: + if x[tree_node["feature"]] <= tree_node["threshold"]: + tree_node = tree_node["left"] + else: + tree_node = tree_node["right"] + return tree_node["value"] + + def predict(self, X): + """批量预测""" + return np.array([self._predict_single(x) for x in X]) + +# ===================== 4. 梯度提升回归(集成模型) ===================== +class GradientBoostRegressor: + """简化版梯度提升,适配PyCharm快速运行""" + def __init__(self, n_trees=80, lr=0.1, max_depth=3): + self.n_trees = n_trees # 树的数量(减少数量加速运行) + self.lr = lr # 学习率 + self.max_depth = max_depth # 树深度 + self.trees = [] # 保存所有树 + self.base_pred = None # 初始预测值 + self.total_feat_importance = np.zeros(6) # 总特征重要性 + + def fit(self, X, y): + """训练梯度提升模型""" + # 初始预测:所有样本的均值 + self.base_pred = np.mean(y) + y_pred = np.full(len(y), self.base_pred) + + print("模型训练进度:") + for i in range(self.n_trees): + # 计算残差(负梯度) + residual = y - y_pred + + # 训练一棵决策树拟合残差 + tree = SimpleDecisionTree(max_depth=self.max_depth) + tree.fit(X, residual) + + # 累加特征重要性 + self.total_feat_importance += tree.feat_importance + + # 更新预测值 + tree_pred = tree.predict(X) + y_pred += self.lr * tree_pred + self.trees.append(tree) + + # 打印训练进度(PyCharm控制台可见) + if (i + 1) % 20 == 0: + mse = np.mean((y - y_pred) ** 2) + print(f" 完成 {i+1}/{self.n_trees} 棵树,当前MSE:{mse:.4f}") + + # 归一化总特征重要性 + self.total_feat_importance = self.total_feat_importance / np.sum(self.total_feat_importance) if np.sum(self.total_feat_importance) > 0 else self.total_feat_importance + + def predict(self, X): + """预测刹车时间""" + y_pred = np.full(len(X), self.base_pred) + for tree in self.trees: + y_pred += self.lr * tree.predict(X) + return y_pred + +# ===================== 5. 可视化绘图函数(PyCharm专用) ===================== +def plot_results(y_true, y_pred, feat_importance, X_test): + """生成4张子图,在PyCharm中显示并保存""" + # 创建2x2子图布局 + fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(14, 9)) + + # 子图1:真实值vs预测值散点图 + ax1.scatter(y_true, y_pred, color="#2E86AB", alpha=0.6, s=8) + ax1.plot([y_true.min(), y_true.max()], [y_true.min(), y_true.max()], "r--", linewidth=2, label="完美预测线") + ax1.set_xlabel("真实刹车时间 (秒)", fontsize=10) + ax1.set_ylabel("预测刹车时间 (秒)", fontsize=10) + ax1.set_title("刹车时间:真实值 vs 预测值", fontsize=12, fontweight="bold") + ax1.legend() + ax1.grid(alpha=0.3) + + # 子图2:特征重要性柱状图 + feat_names = ["车速", "障碍物距离", "障碍物速度", "路面摩擦", "能见度", "刹车延迟"] + ax2.bar(feat_names, feat_importance, color="#A23B72", alpha=0.8) + ax2.set_xlabel("特征名称", fontsize=10) + ax2.set_ylabel("重要性权重", fontsize=10) + ax2.set_title("特征重要性排名", fontsize=12, fontweight="bold") + ax2.tick_params(axis="x", rotation=30) # 旋转x轴标签,避免重叠 + ax2.grid(alpha=0.3, axis="y") + + # 子图3:预测误差分布直方图 + error = y_true - y_pred + ax3.hist(error, bins=40, color="#F18F01", alpha=0.7, edgecolor="black", linewidth=0.5) + ax3.axvline(x=0, color="red", linestyle="--", linewidth=2, label="无误差线") + ax3.set_xlabel("预测误差 (秒)", fontsize=10) + ax3.set_ylabel("样本数量", fontsize=10) + ax3.set_title("预测误差分布", fontsize=12, fontweight="bold") + ax3.legend() + ax3.grid(alpha=0.3) + + # 子图4:不同路面摩擦系数的刹车时间箱线图 + friction_bins = [0.1, 0.4, 0.7, 1.0] + friction_labels = ["低摩擦(雨雪)", "中摩擦", "高摩擦(干燥)"] + friction_groups = [] + for i in range(3): + mask = (X_test[:, 3] >= friction_bins[i]) & (X_test[:, 3] < friction_bins[i+1]) + friction_groups.append(y_true[mask]) + + box_plot = ax4.boxplot(friction_groups, labels=friction_labels, patch_artist=True) + for patch in box_plot["boxes"]: + patch.set_facecolor("#C73E1D") + patch.set_alpha(0.7) + ax4.set_xlabel("路面摩擦系数区间", fontsize=10) + ax4.set_ylabel("刹车时间 (秒)", fontsize=10) + ax4.set_title("不同路面摩擦的刹车时间分布", fontsize=12, fontweight="bold") + ax4.grid(alpha=0.3, axis="y") + + # 调整子图间距(避免标签重叠) + plt.tight_layout(pad=2.0) + + # 关键:在PyCharm中显示图片(内置Plot窗口) + plt.show() + + # 保存图片到本地(代码同级目录) + fig.savefig("无人车刹车时间分析图.png", dpi=300, bbox_inches="tight") + print("\n✅ 分析图片已保存为:无人车刹车时间分析图.png") + +# ===================== 6. 主函数(PyCharm运行入口) ===================== +if __name__ == "__main__": + print("="*50) + print(" 无人车紧急刹车时间预测模型(PyCharm专用) ") + print("="*50) + + # 1. 生成数据集 + print("\n📊 正在生成模拟数据集...") + X, y = generate_vehicle_data(n_samples=8000) # 减少样本数加速运行 + + # 2. 划分训练集/测试集(8:2) + split_idx = int(0.8 * len(X)) + X_train, X_test = X[:split_idx], X[split_idx:] + y_train, y_test = y[:split_idx], y[split_idx:] + print(f"✅ 数据集划分完成:训练集{len(X_train)}条,测试集{len(X_test)}条") + + # 3. 特征归一化 + print("\n🔧 正在进行特征归一化...") + scaler = StandardScaler() + scaler.fit(X_train) + X_train_scaled = scaler.transform(X_train) + X_test_scaled = scaler.transform(X_test) + + # 4. 训练模型 + print("\n🚀 正在训练梯度提升模型...") + model = GradientBoostRegressor(n_trees=80, lr=0.1, max_depth=3) + model.fit(X_train_scaled, y_train) + + # 5. 模型评估 + print("\n📈 模型评估结果:") + y_pred = model.predict(X_test_scaled) + mae = np.mean(np.abs(y_test - y_pred)) # 平均绝对误差 + r2 = 1 - (np.sum((y_test - y_pred)**2) / np.sum((y_test - np.mean(y_test))**2)) # 决定系数 + print(f" 平均绝对误差(MAE):{mae:.4f} 秒(越小越好)") + print(f" 决定系数(R²):{r2:.4f}(越接近1越好)") + + # 6. 生成可视化图片(PyCharm显示+本地保存) + print("\n🎨 正在生成分析图片...") + plot_results(y_test, y_pred, model.total_feat_importance, X_test) + + # 7. 实时预测示例(模拟无人车实时感知数据) + print("\n🔍 实时刹车时间预测示例:") + def predict_brake_time(vehicle_state): + """输入车辆状态,预测刹车时间""" + # 转换为模型输入格式 + state_arr = np.array([list(vehicle_state.values())]) + state_scaled = scaler.transform(state_arr) + # 预测并限制范围 + brake_time = model.predict(state_scaled)[0] + return max(0.1, min(brake_time, 5.0)) + + # 模拟真实场景:高速+干燥路面+近距离障碍物 + test_state = { + "vehicle_speed": 90.0, # 车速90km/h + "obstacle_distance": 70.0, # 障碍物距离70m + "obstacle_speed": 8.0, # 障碍物同向8km/h + "road_friction": 0.8, # 干燥路面摩擦系数 + "weather_visibility": 600.0, # 能见度600m + "brake_delay": 0.12 # 刹车系统延迟0.12s + } + + # 预测并输出结果 + pred_time = predict_brake_time(test_state) + print("📌 测试场景:高速干燥路面+近距离障碍物") + for k, v in test_state.items(): + print(f" {k}:{v}") + print(f"✅ 预测紧急刹车时间:{pred_time:.2f} 秒") + print("\n🎉 所有任务完成!") \ No newline at end of file From a76a6df2a4af4707af53f364284351a102d15152 Mon Sep 17 00:00:00 2001 From: aliangabc Date: Fri, 19 Dec 2025 13:19:16 +0800 Subject: [PATCH 10/10] =?UTF-8?q?=E5=92=8C=E6=94=B9=E5=96=84=E6=94=B9?= =?UTF-8?q?=E5=96=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/driverless_TG/emergency_brake.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/driverless_TG/emergency_brake.py b/src/driverless_TG/emergency_brake.py index 4cb017e529..6f351dd938 100644 --- a/src/driverless_TG/emergency_brake.py +++ b/src/driverless_TG/emergency_brake.py @@ -315,7 +315,7 @@ def predict_brake_time(vehicle_state): # 转换为模型输入格式 state_arr = np.array([list(vehicle_state.values())]) state_scaled = scaler.transform(state_arr) - # 预测并限制范围 + # 预测并限制范围a brake_time = model.predict(state_scaled)[0] return max(0.1, min(brake_time, 5.0))