diff --git a/src/unmanned_vehicle_safety_and_operation/README.md b/src/unmanned_vehicle_safety_and_operation/README.md new file mode 100644 index 0000000000..e36f5a84a6 --- /dev/null +++ b/src/unmanned_vehicle_safety_and_operation/README.md @@ -0,0 +1,15 @@ +# 无人车安全运维模块 - 环境配置与运行手册 + +## 一、环境设置 +运行本项目安全运维模块代码前,需确保开发环境满足以下依赖版本要求: +- Python 3.8 及以上版本(适配运维数据处理与实时监控需求) +- PyTorch 1.8 及以上版本(支持异常检测模型训练推理) +- CARLA 模拟器 0.9.13 版本(适配无人车全场景运维仿真) +- OpenCV 4.5 及以上版本(用于传感器数据可视化与异常识别) +- 其余 Python 依赖项详见项目根目录下的 'requirements_ops.txt' 文件 + +## 二、依赖安装步骤 +### 1. 克隆项目仓库 +```bash +git clone https://github.com/yourusername/unmanned_vehicle_safety_and_operation.git +cd av_safety_operation \ No newline at end of file diff --git a/src/unmanned_vehicle_safety_and_operation/anomaly_event_detection.py b/src/unmanned_vehicle_safety_and_operation/anomaly_event_detection.py new file mode 100644 index 0000000000..7dc869e05e --- /dev/null +++ b/src/unmanned_vehicle_safety_and_operation/anomaly_event_detection.py @@ -0,0 +1,303 @@ +import numpy as np +import matplotlib.pyplot as plt +from datetime import datetime, timedelta +import warnings + +warnings.filterwarnings('ignore') + + +# ===================== 1. 纯NumPy实现孤立森林 ===================== +class IsolationForestPure: + def __init__(self, n_estimators=100, max_samples='auto', contamination=0.05, random_state=42): + self.n_estimators = n_estimators + self.max_samples = max_samples + self.contamination = contamination + self.random_state = random_state + np.random.seed(random_state) + self.trees = [] # 存储所有孤立树 + self.max_depth = None # 树的最大深度 + self.sample_size = None # 每棵树的采样数量 + + def _init_params(self, X): + """初始化参数:采样数量、最大树深度""" + n_samples = X.shape[0] + # 确定采样数量 + if self.max_samples == 'auto': + self.sample_size = min(256, n_samples) + elif isinstance(self.max_samples, int): + self.sample_size = min(self.max_samples, n_samples) + else: # 浮点数(比例) + self.sample_size = int(self.max_samples * n_samples) + # 最大深度:log2(采样数量) + self.max_depth = int(np.ceil(np.log2(max(2, self.sample_size)))) + + def _build_tree(self, X): + """构建单棵孤立树""" + # 随机采样 + sample_idx = np.random.choice(X.shape[0], self.sample_size, replace=False) + X_sample = X[sample_idx] + + # 递归构建树节点 + def build_node(X_node, depth): + if depth >= self.max_depth or X_node.shape[0] <= 1: + return {'is_leaf': True, 'size': X_node.shape[0]} + + # 随机选择特征和分割点 + n_features = X_node.shape[1] + feature_idx = np.random.choice(n_features) + feature_vals = X_node[:, feature_idx] + min_val, max_val = np.min(feature_vals), np.max(feature_vals) + + if min_val == max_val: # 特征值无差异,无法分割 + return {'is_leaf': True, 'size': X_node.shape[0]} + + # 随机选择分割点 + split_val = np.random.uniform(min_val, max_val) + + # 分割数据 + left_idx = X_node[:, feature_idx] < split_val + X_left = X_node[left_idx] + X_right = X_node[~left_idx] + + return { + 'is_leaf': False, + 'feature_idx': feature_idx, + 'split_val': split_val, + 'left': build_node(X_left, depth + 1), + 'right': build_node(X_right, depth + 1) + } + + return build_node(X_sample, depth=0) + + def fit(self, X): + """训练孤立森林""" + X = np.array(X, dtype=np.float64) + self._init_params(X) + # 构建多棵树 + for _ in range(self.n_estimators): + tree = self._build_tree(X) + self.trees.append(tree) + + def _path_length(self, x, tree): + """计算单个样本在单棵树中的路径长度""" + + def traverse(node, depth): + if node['is_leaf']: + # 叶子节点:路径长度 += 调整项(针对小样本) + n = node['size'] + if n <= 1: + return depth + # 调和数近似:H(n-1) + 0.5772156649(欧拉常数) + h = np.log(n - 1) + 0.5772156649 + return depth + h + # 非叶子节点:继续遍历 + feature_val = x[node['feature_idx']] + if feature_val < node['split_val']: + return traverse(node['left'], depth + 1) + else: + return traverse(node['right'], depth + 1) + + return traverse(tree, depth=0) + + def decision_function(self, X): + """计算异常评分(越低越异常)""" + X = np.array(X, dtype=np.float64) + # 计算所有样本在所有树中的平均路径长度 + path_lengths = [] + for x in X: + lengths = [self._path_length(x, tree) for tree in self.trees] + avg_length = np.mean(lengths) + path_lengths.append(avg_length) + + # 归一化路径长度(转换为异常评分,范围[-1,1]) + c = self._average_path_length(self.sample_size) # 平均路径长度基准 + scores = 2 ** (-np.array(path_lengths) / c) + # 调整评分范围为[-1,1](与sklearn对齐) + scores = - (scores - np.percentile(scores, 100 * (1 - self.contamination))) + return scores + + def predict(self, X): + """预测异常标签(-1=异常,1=正常)""" + scores = self.decision_function(X) + # 根据异常比例确定阈值 + threshold = np.percentile(scores, 100 * self.contamination) + return np.where(scores < threshold, -1, 1) + + def _average_path_length(self, n): + """计算n个样本的平均路径长度(基准值)""" + if n <= 1: + return 0 + h = np.log(n - 1) + 0.5772156649 # 调和数+欧拉常数 + return 2 * h - 2 * (n - 1) / n + + +# ===================== 2. 数据生成模块 ===================== +def generate_abnormal_data(n_normal=1000, n_abnormal=50, random_state=42): + np.random.seed(random_state) + # 正常数据(正态分布) + normal_features = np.random.normal(loc=0, scale=1, size=(n_normal, 3)) + normal_labels = np.zeros(n_normal, dtype=int) + # 异常数据(偏离正态分布) + abnormal_features = np.random.normal(loc=5, scale=2, size=(n_abnormal, 3)) + abnormal_labels = np.ones(n_abnormal, dtype=int) + # 合并并打乱 + all_features = np.vstack([normal_features, abnormal_features]) + all_labels = np.hstack([normal_labels, abnormal_labels]) + shuffle_idx = np.random.permutation(len(all_features)) + all_features = all_features[shuffle_idx] + all_labels = all_labels[shuffle_idx] + # 生成时间戳 + start_time = datetime(2025, 1, 1) + timestamps = [start_time + timedelta(minutes=i) for i in range(len(all_features))] + return all_features, all_labels, timestamps + + +# ===================== 3. 数据预处理模块 ===================== +def preprocess_data(features): + """标准化(无sklearn的StandardScaler)""" + # 均值填充缺失值 + mask = np.random.choice([0, 1], size=features.shape, p=[0.01, 0.99]) + features_with_nan = np.where(mask == 0, np.nan, features) + mean_vals = np.nanmean(features_with_nan, axis=0) + for i in range(features_with_nan.shape[1]): + nan_idx = np.isnan(features_with_nan[:, i]) + features_with_nan[nan_idx, i] = mean_vals[i] + # 手动标准化(均值0,方差1) + mean = np.mean(features_with_nan, axis=0) + std = np.std(features_with_nan, axis=0) + std[std == 0] = 1 # 避免除以0 + scaled_features = (features_with_nan - mean) / std + return scaled_features, (mean, std) + + +# ===================== 4. 模型封装 ===================== +class AnomalyDetector: + def __init__(self, contamination=0.05, random_state=42): + self.contamination = contamination + self.random_state = random_state + self.model = IsolationForestPure( + n_estimators=100, + contamination=contamination, + random_state=random_state + ) + + def train(self, features): + self.model.fit(features) + + def detect(self, features): + anomaly_labels = self.model.predict(features) + anomaly_scores = self.model.decision_function(features) + return anomaly_labels, anomaly_scores + + +# ===================== 5. 结果分析(无sklearn metrics) ===================== +def analyze_results(true_labels, pred_labels, anomaly_scores): + """手动计算评估指标""" + pred_labels_converted = np.where(pred_labels == -1, 1, 0) + + # 手动计算TP/TN/FP/FN + TP = np.sum((true_labels == 1) & (pred_labels_converted == 1)) + TN = np.sum((true_labels == 0) & (pred_labels_converted == 0)) + FP = np.sum((true_labels == 0) & (pred_labels_converted == 1)) + FN = np.sum((true_labels == 1) & (pred_labels_converted == 0)) + + # 计算指标 + accuracy = (TP + TN) / (TP + TN + FP + FN) if (TP + TN + FP + FN) > 0 else 0 + recall = TP / (TP + FN) if (TP + FN) > 0 else 0 + precision = TP / (TP + FP) if (TP + FP) > 0 else 0 + f1 = 2 * precision * recall / (precision + recall) if (precision + recall) > 0 else 0 + + print("===== 检测结果评估 =====") + print(f"准确率(Accuracy): {accuracy:.4f}") + print(f"召回率(Recall): {recall:.4f}") + print(f"精确率(Precision): {precision:.4f}") + print(f"F1分数(F1-Score): {f1:.4f}") + + n_true_anomalies = np.sum(true_labels == 1) + n_pred_anomalies = np.sum(pred_labels_converted == 1) + print(f"\n真实异常数: {n_true_anomalies} | 检测出的异常数: {n_pred_anomalies}") + + return pred_labels_converted, anomaly_scores + + +# ===================== 6. 可视化模块 ===================== +def plot_results(timestamps, features, true_labels, pred_labels, anomaly_scores): + fig, axes = plt.subplots(2, 1, figsize=(12, 10)) + + # 子图1:特征时序+异常标注 + ax1 = axes[0] + feature1 = features[:, 0] + timestamps_plt = [ts for ts in timestamps] + ax1.plot(timestamps_plt, feature1, color='blue', alpha=0.6, label='Feature 1') + + # 真实异常 + true_anomaly_idx = np.where(true_labels == 1)[0] + ax1.scatter( + [timestamps_plt[i] for i in true_anomaly_idx], + [feature1[i] for i in true_anomaly_idx], + color='red', s=50, label='True Anomaly', zorder=5 + ) + + # 检测异常 + pred_anomaly_idx = np.where(pred_labels == 1)[0] + ax1.scatter( + [timestamps_plt[i] for i in pred_anomaly_idx], + [feature1[i] for i in pred_anomaly_idx], + color='orange', s=30, marker='x', label='Detected Anomaly', zorder=4 + ) + + ax1.set_title('Feature Time Series with Anomaly Labels', fontsize=12) + ax1.set_ylabel('Feature 1 Value') + ax1.legend() + ax1.grid(True, alpha=0.3) + + # 子图2:异常评分分布 + ax2 = axes[1] + normal_scores = anomaly_scores[true_labels == 0] + anomaly_score_values = anomaly_scores[true_labels == 1] + ax2.hist(normal_scores, bins=30, alpha=0.6, label='Normal Samples', color='blue') + ax2.hist(anomaly_score_values, bins=30, alpha=0.6, label='Anomaly Samples', color='red') + ax2.axvline(x=0, color='black', linestyle='--', label='Threshold (0)') + ax2.set_title('Anomaly Score Distribution', fontsize=12) + ax2.set_xlabel('Anomaly Score (Lower = More Anomalous)') + ax2.set_ylabel('Count') + ax2.legend() + ax2.grid(True, alpha=0.3) + + plt.tight_layout() + plt.show() + + +# ===================== 7. 主函数 ===================== +def main(): + # 1. 生成数据11 + raw_features, true_labels, timestamps = generate_abnormal_data(n_normal=1000, n_abnormal=50) + # 2. 预处理 + scaled_features, scaler_params = preprocess_data(raw_features) + # 3. 划分训练/测试集(手动实现,无sklearn) + np.random.seed(42) + test_size = 0.2 + n_samples = len(scaled_features) + test_idx = np.random.choice(n_samples, int(n_samples * test_size), replace=False) + train_idx = np.setdiff1d(np.arange(n_samples), test_idx) + + X_train = scaled_features[train_idx] + X_test = scaled_features[test_idx] + y_train = true_labels[train_idx] + y_test = true_labels[test_idx] + ts_train = [timestamps[i] for i in train_idx] + ts_test = [timestamps[i] for i in test_idx] + + # 4. 训练模型 + detector = AnomalyDetector(contamination=0.05) + detector.train(X_train) + # 5. 检测 + pred_labels, anomaly_scores = detector.detect(X_test) + # 6. 分析 + pred_labels_converted, anomaly_scores = analyze_results(y_test, pred_labels, anomaly_scores) + # 7. 11可视化 + plot_results(ts_test, X_test, y_test, pred_labels_converted, anomaly_scores) + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/src/unmanned_vehicle_safety_and_operation/efficiency_detection.py b/src/unmanned_vehicle_safety_and_operation/efficiency_detection.py new file mode 100644 index 0000000000..611be138fa --- /dev/null +++ b/src/unmanned_vehicle_safety_and_operation/efficiency_detection.py @@ -0,0 +1,494 @@ +import random +import math +import sys +import time +import os +from collections import defaultdict +import tkinter as tk +from tkinter import ttk, Canvas +import threading + +# ===================== 全局配置(PyCharm适配)===================== +# 创建图片保存目录(模拟保存,实际为tkinter绘图窗口) +if not os.path.exists('efficiency_plots'): + os.makedirs('efficiency_plots') +random.seed(42) + + +# ===================== 1. 数据生成与预处理(纯原生)===================== +class DataPreprocessor: + def __init__(self): + self.feature_means = {} # 特征均值(填充缺失值) + self.feature_stds = {} # 特征标准差(标准化) + + def generate_simulation_data(self, n_samples=1000): + """生成无人车模拟数据(纯原生)""" + data = [] + self.feature_names = [ + '规划路径长度(km)', '实际路径长度(km)', '路径偏差(km)', + '航点完成率', '能耗(kWh/100km)', '平均速度(km/h)', + '加减速频率(次/分)', '安全距离违规次数', + '紧急制动次数', '车道保持准确率', + '红绿灯等待时间(秒)', '平均车流量(辆/公里)', '行程耗时(分钟)' + ] + + for _ in range(n_samples): + # 单条样本数据 + sample = { + '规划路径长度(km)': random.uniform(5, 50), + '实际路径长度(km)': random.uniform(5, 55), + '路径偏差(km)': abs(random.uniform(0, 5)), + '航点完成率': random.uniform(0.8, 1.0), + '能耗(kWh/100km)': random.uniform(15, 35), + '平均速度(km/h)': random.uniform(20, 80), + '加减速频率(次/分)': random.uniform(0.1, 1.0), + '安全距离违规次数': random.randint(0, 5), + '紧急制动次数': random.randint(0, 3), + '车道保持准确率': random.uniform(0.85, 1.0), + '红绿灯等待时间(秒)': random.uniform(0, 120), + '平均车流量(辆/公里)': random.uniform(20, 100), + '行程耗时(分钟)': random.uniform(10, 120) + } + + # 计算效率得分(0-100) + 路径效率 = (1 - sample['路径偏差(km)'] / sample['规划路径长度(km)']) * 100 + 能耗效率 = (1 - (sample['能耗(kWh/100km)'] - 15) / 20) * 100 + 安全效率 = (1 - (sample['安全距离违规次数'] + sample['紧急制动次数']) / 8) * 100 + 通行效率 = (1 - sample['行程耗时(分钟)'] / 120) * 100 + 效率得分 = (路径效率 + 能耗效率 + 安全效率 + 通行效率) / 4 + sample['效率得分'] = max(0, min(100, 效率得分)) + data.append(sample) + + return data + + def preprocess_data(self, data): + """数据预处理:缺失值填充+标准化(纯原生)""" + # 1. 统计特征均值和标准差 + feature_sums = defaultdict(float) + feature_sq_sums = defaultdict(float) # 平方和(计算标准差) + feature_counts = defaultdict(int) + + # 模拟5%缺失值 + 统计基础值 + for sample in data: + for feat in self.feature_names: + # 模拟缺失值 + if random.random() < 0.05: + sample[feat] = None + # 统计非缺失值 + if sample[feat] is not None: + feature_sums[feat] += sample[feat] + feature_sq_sums[feat] += sample[feat] ** 2 + feature_counts[feat] += 1 + + # 计算均值和标准差 + for feat in self.feature_names: + self.feature_means[feat] = feature_sums[feat] / feature_counts[feat] if feature_counts[feat] > 0 else 0 + # 标准差 = sqrt( (Σx²/N) - (均值)² ) + variance = (feature_sq_sums[feat] / feature_counts[feat]) - (self.feature_means[feat] ** 2) if \ + feature_counts[feat] > 0 else 0 + self.feature_stds[feat] = math.sqrt(variance) if variance > 0 else 1 + + # 2. 填充缺失值+标准化 + X = [] + y = [] + for sample in data: + features = [] + for feat in self.feature_names: + # 填充缺失值 + val = sample[feat] if sample[feat] is not None else self.feature_means[feat] + # 标准化 (x-mean)/std + scaled_val = (val - self.feature_means[feat]) / self.feature_stds[feat] + features.append(scaled_val) + X.append(features) + y.append(sample['效率得分']) + + return X, y + + +# ===================== 2. 简化版随机森林(纯原生)===================== +class SimpleRandomForest: + def __init__(self, n_estimators=10, max_depth=5): + self.n_estimators = n_estimators + self.max_depth = max_depth + self.trees = [] + self.feature_importance = defaultdict(int) + + def _bootstrap_sample(self, X, y): + """自助采样""" + n_samples = len(X) + indices = [random.randint(0, n_samples - 1) for _ in range(n_samples)] + return [X[i] for i in indices], [y[i] for i in indices] + + def _split_data(self, X, y, feature_idx, threshold): + """划分数据集""" + left_X, left_y = [], [] + right_X, right_y = [], [] + for i in range(len(X)): + if X[i][feature_idx] <= threshold: + left_X.append(X[i]) + left_y.append(y[i]) + else: + right_X.append(X[i]) + right_y.append(y[i]) + return left_X, left_y, right_X, right_y + + def _mse(self, y): + """计算均方误差""" + if not y: + return 0 + mean = sum(y) / len(y) + return sum([(val - mean) ** 2 for val in y]) / len(y) + + def _find_best_split(self, X, y): + """寻找最优划分""" + best_mse = float('inf') + best_feature = -1 + best_threshold = None + n_features = len(X[0]) if X else 0 + + for feature_idx in range(n_features): + # 提取特征值并去重 + feature_vals = list(set([X[i][feature_idx] for i in range(len(X))])) + feature_vals.sort() + + for threshold in feature_vals: + left_X, left_y, right_X, right_y = self._split_data(X, y, feature_idx, threshold) + if not left_y or not right_y: + continue + # 计算划分后MSE + mse = (len(left_y) * self._mse(left_y) + len(right_y) * self._mse(right_y)) / len(y) + if mse < best_mse: + best_mse = mse + best_feature = feature_idx + best_threshold = threshold + + return best_feature, best_threshold + + def _build_tree(self, X, y, depth=0): + """递归构建决策树""" + if depth >= self.max_depth or len(y) < 5: + return {'value': sum(y) / len(y) if y else 0} + + feature_idx, threshold = self._find_best_split(X, y) + if feature_idx == -1: + return {'value': sum(y) / len(y) if y else 0} + + # 统计特征重要性 + self.feature_importance[feature_idx] += 1 + + left_X, left_y, right_X, right_y = self._split_data(X, y, feature_idx, threshold) + left_tree = self._build_tree(left_X, left_y, depth + 1) + right_tree = self._build_tree(right_X, right_y, depth + 1) + + return { + 'feature_idx': feature_idx, + 'threshold': threshold, + 'left': left_tree, + 'right': right_tree + } + + def train(self, X, y): + """训练随机森林""" + for _ in range(self.n_estimators): + X_sample, y_sample = self._bootstrap_sample(X, y) + tree = self._build_tree(X_sample, y_sample) + self.trees.append(tree) + + def predict(self, X): + """预测效率得分""" + predictions = [] + for sample in X: + tree_preds = [self._predict_tree(sample, tree) for tree in self.trees] + predictions.append(sum(tree_preds) / len(tree_preds)) + return predictions + + def _predict_tree(self, sample, tree): + """单棵树预测""" + if 'value' in tree: + return tree['value'] + if sample[tree['feature_idx']] <= tree['threshold']: + return self._predict_tree(sample, tree['left']) + else: + return self._predict_tree(sample, tree['right']) + + +# ===================== 3. 异常检测(纯原生)===================== +class SimpleIsolationForest: + def __init__(self, contamination=0.05): + self.contamination = contamination + self.trees = [] + + def _build_tree(self, X, depth=0, max_depth=10): + """构建孤立树""" + if depth >= max_depth or len(X) <= 1: + return {'depth': depth} + + # 随机选特征和阈值 + n_features = len(X[0]) if X else 0 + feature_idx = random.randint(0, n_features - 1) + feature_vals = [x[feature_idx] for x in X] + min_val, max_val = min(feature_vals), max(feature_vals) + threshold = random.uniform(min_val, max_val) + + # 划分数据 + left_X = [x for x in X if x[feature_idx] <= threshold] + right_X = [x for x in X if x[feature_idx] > threshold] + + return { + 'feature_idx': feature_idx, + 'threshold': threshold, + 'left': self._build_tree(left_X, depth + 1, max_depth), + 'right': self._build_tree(right_X, depth + 1, max_depth) + } + + def _path_length(self, sample, tree, depth=0): + """计算路径长度""" + if 'depth' in tree: + return depth + self._avg_path(len(self.X_train)) + if sample[tree['feature_idx']] <= tree['threshold']: + return self._path_length(sample, tree['left'], depth + 1) + else: + return self._path_length(sample, tree['right'], depth + 1) + + def _avg_path(self, n): + """平均路径长度""" + if n <= 1: + return 0 + return 2 * (math.log(n - 1) + 0.5772156649) - 2 * (n - 1) / n + + def train(self, X): + """训练孤立森林""" + self.X_train = X + for _ in range(10): # 10棵树 + sample_size = min(256, len(X)) + sample_indices = [random.randint(0, len(X) - 1) for _ in range(sample_size)] + X_sample = [X[i] for i in sample_indices] + self.trees.append(self._build_tree(X_sample)) + + def detect_anomalies(self, X): + """检测异常(-1=异常,1=正常)""" + avg_lengths = [] + for sample in X: + lengths = [self._path_length(sample, tree) for tree in self.trees] + avg_lengths.append(sum(lengths) / len(lengths)) + + # 按污染系数划分异常 + avg_lengths_sorted = sorted(avg_lengths) + threshold = avg_lengths_sorted[int(len(avg_lengths) * self.contamination)] + return [-1 if l < threshold else 1 for l in avg_lengths] + + +# ===================== 4. PyCharm绘图(基于tkinter纯原生)===================== +class NativePlotter: + def __init__(self, title): + self.root = tk.Tk() + self.root.title(title) + self.root.geometry("800x600") + self.canvas = Canvas(self.root, width=800, height=600, bg="white") + self.canvas.pack(fill=tk.BOTH, expand=True) + + def plot_efficiency_dist(self, scores): + """绘制效率得分分布直方图""" + # 分桶统计 + bins = [0, 20, 40, 60, 80, 100] + counts = [0] * 4 # 0-20,20-40,40-60,60-80,80-100 + for score in scores: + if 0 <= score < 20: + counts[0] += 1 + elif 20 <= score < 40: + counts[1] += 1 + elif 40 <= score < 60: + counts[2] += 1 + elif 60 <= score < 80: + counts[3] += 1 + else: + counts[4] += 1 if 80 <= score <= 100 else 0 + + # 归一化高度 + max_count = max(counts) if counts else 1 + bar_width = 100 + x_start = 100 + + # 绘制坐标轴 + self.canvas.create_line(80, 500, 720, 500, width=2) # X轴 + self.canvas.create_line(80, 100, 80, 500, width=2) # Y轴 + + # 绘制柱子 + colors = ["lightblue", "skyblue", "dodgerblue", "royalblue", "navy"] + for i in range(5): + height = (counts[i] / max_count) * 350 + x1 = x_start + i * (bar_width + 20) + y1 = 500 - height + x2 = x1 + bar_width + y2 = 500 + self.canvas.create_rectangle(x1, y1, x2, y2, fill=colors[i], outline="black") + # 标注 + self.canvas.create_text(x1 + bar_width / 2, 520, text=f"{bins[i]}-{bins[i + 1]}") + self.canvas.create_text(x1 + bar_width / 2, y1 - 10, text=str(counts[i])) + + # 标题 + self.canvas.create_text(400, 50, text="无人车效率得分分布", font=("Arial", 16, "bold")) + self.root.mainloop() + + def plot_feature_importance(self, importance, feature_names): + """绘制特征重要性条形图""" + # 排序特征 + imp_list = sorted(importance.items(), key=lambda x: x[1], reverse=True) + top_features = imp_list[:8] # 取前8个特征 + + # 绘制坐标轴 + self.canvas.create_line(150, 500, 150, 100, width=2) # Y轴 + self.canvas.create_line(150, 500, 750, 500, width=2) # X轴 + + # 绘制条形 + max_imp = max([x[1] for x in top_features]) if top_features else 1 + y_start = 120 + bar_height = 40 + for i, (feat_idx, imp) in enumerate(top_features): + width = (imp / max_imp) * 550 + x1 = 150 + y1 = y_start + i * (bar_height + 10) + x2 = 150 + width + y2 = y1 + bar_height + self.canvas.create_rectangle(x1, y1, x2, y2, fill="orange", outline="black") + # 标注特征名和重要性 + feat_name = feature_names[feat_idx] if feat_idx < len(feature_names) else f"特征{feat_idx}" + self.canvas.create_text(120, y1 + 20, text=feat_name, anchor="e", font=("Arial", 10)) + self.canvas.create_text(x2 + 10, y1 + 20, text=f"{imp}", font=("Arial", 10)) + + self.canvas.create_text(400, 50, text="特征重要性排名", font=("Arial", 16, "bold")) + self.root.mainloop() + + def plot_real_time(self, time_series, scores, anomalies): + """绘制实时效率监测曲线""" + # 绘制坐标轴 + self.canvas.create_line(80, 500, 720, 500, width=2) # X轴 + self.canvas.create_line(80, 500, 80, 100, width=2) # Y轴 + + # 绘制网格 + for x in range(180, 720, 100): + self.canvas.create_line(x, 100, x, 500, dash=(2, 2), fill="lightgray") + for y in range(200, 500, 100): + self.canvas.create_line(80, y, 720, y, dash=(2, 2), fill="lightgray") + + # 归一化坐标 + max_score = 100 + min_score = 0 + x_step = (720 - 80) / len(time_series) if time_series else 1 + + # 绘制曲线 + points = [] + for i, (t, s) in enumerate(zip(time_series, scores)): + x = 80 + i * x_step + y = 500 - ((s - min_score) / (max_score - min_score)) * 400 + points.append((x, y)) + # 标记异常点 + if anomalies[i] == -1: + self.canvas.create_oval(x - 5, y - 5, x + 5, y + 5, fill="red") + + # 连接曲线 + for i in range(len(points) - 1): + self.canvas.create_line(points[i][0], points[i][1], + points[i + 1][0], points[i + 1][1], + fill="blue", width=2) + + self.canvas.create_text(400, 50, text="实时效率得分监测", font=("Arial", 16, "bold")) + self.root.mainloop() + + +# ===================== 5. 主程序 ===================== +def main(): + # 初始化模块 + preprocessor = DataPreprocessor() + rf_model = SimpleRandomForest(n_estimators=10, max_depth=5) + anomaly_detector = SimpleIsolationForest(contamination=0.05) + + # 1. 生成数据 + print("=" * 50) + print("生成无人车模拟数据...") + data = preprocessor.generate_simulation_data(n_samples=1000) + X, y = preprocessor.preprocess_data(data) + + # 2. 划分训练/测试集 + split_idx = int(len(X) * 0.8) + X_train, X_test = X[:split_idx], X[split_idx:] + y_train, y_test = y[:split_idx], y[split_idx:] + + # 3. 训练模型 + print("训练效率检测模型...") + start_time = time.time() + rf_model.train(X_train, y_train) + anomaly_detector.train(X_train) + print(f"训练耗时: {time.time() - start_time:.2f}秒") + + # 4. 模型预测与评估 + y_pred = rf_model.predict(X_test) + # 计算MSE和R²(纯原生) + mse = sum([(y_test[i] - y_pred[i]) ** 2 for i in range(len(y_test))]) / len(y_test) + y_mean = sum(y_test) / len(y_test) + ss_total = sum([(y - y_mean) ** 2 for y in y_test]) + ss_res = sum([(y_test[i] - y_pred[i]) ** 2 for i in range(len(y_test))]) + r2 = 1 - (ss_res / ss_total) if ss_total != 0 else 0 + + print("\n=== 模型性能 ===") + print(f"均方误差(MSE): {mse:.4f}") + print(f"决定系数(R²): {r2:.4f}") + print(f"平均效率得分: {sum(y_pred) / len(y_pred):.2f}") + + # 5. 异常检测 + anomalies = anomaly_detector.detect_anomalies(X_test) + anomaly_rate = sum([1 for a in anomalies if a == -1]) / len(anomalies) + print(f"\n异常样本比例: {anomaly_rate:.2%}") + + # 6. 特征重要性 + print("\n=== 特征重要性 ===") + for feat_idx, imp in sorted(rf_model.feature_importance.items(), key=lambda x: x[1], reverse=True)[:5]: + if feat_idx < len(preprocessor.feature_names): + print(f"{preprocessor.feature_names[feat_idx]}: {imp}") + + # 7. 生成可视化图片(PyCharm中弹出tkinter窗口) + print("\n生成可视化图片(请查看弹出窗口)...") + + # 效率分布图表(子线程运行,避免阻塞) + def plot_dist(): + plotter = NativePlotter("效率得分分布") + plotter.plot_efficiency_dist(y_pred) + + threading.Thread(target=plot_dist).start() + + # 特征重要性图表 + def plot_feat(): + plotter = NativePlotter("特征重要性") + plotter.plot_feature_importance(rf_model.feature_importance, preprocessor.feature_names) + + threading.Thread(target=plot_feat).start() + + # 实时监测图表11 + def plot_realtime(): + time_series = list(range(50)) + plotter = NativePlotter("实时效率监测") + plotter.plot_real_time(time_series, y_pred[:50], anomalies[:50]) + + threading.Thread(target=plot_realtime).start() + + # 8. 实时检测示例11111 + print("\n=== 实时检测示例 ===") + test_data = preprocessor.generate_simulation_data(n_samples=10) + rt_X, _ = preprocessor.preprocess_data(test_data) + rt_scores = rf_model.predict(rt_X) + rt_anomalies = anomaly_detector.detect_anomalies(rt_X) + + print("样本ID | 效率得分 | 状态") + print("-" * 30) + for i in range(10): + status = "异常" if rt_anomalies[i] == -1 else "正常" + print(f"{i + 1:<6} | {rt_scores[i]:<8.2f} | {status}") + + print("=" * 50) + print("运行完成!可视化窗口已弹出,图片已模拟保存到 efficiency_plots 目录") + + +if __name__ == "__main__": + main() + # 保持tkinter窗口运行 + tk.mainloop() \ No newline at end of file diff --git a/src/unmanned_vehicle_safety_and_operation/emergency_brake.py b/src/unmanned_vehicle_safety_and_operation/emergency_brake.py new file mode 100644 index 0000000000..520529bf41 --- /dev/null +++ b/src/unmanned_vehicle_safety_and_operation/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.11 生成无人车刹车场景数据 111===================== +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) + # 预测并限制范围a + 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 diff --git a/src/unmanned_vehicle_safety_and_operation/human_machine_co_driving.py b/src/unmanned_vehicle_safety_and_operation/human_machine_co_driving.py new file mode 100644 index 0000000000..a19ed92e31 --- /dev/null +++ b/src/unmanned_vehicle_safety_and_operation/human_machine_co_driving.py @@ -0,0 +1,363 @@ +import math +import random +import sys + +# 强制matplotlib使用TkAgg后端(PyCharm中显示图片必备) +import matplotlib + +matplotlib.use('TkAgg') # 关键:解决PyCharm中图片不显示的问题 +import matplotlib.pyplot as plt + +# 配置中文显示(PyCharm中兼容) +plt.rcParams['font.sans-serif'] = ['DejaVu Sans', 'SimHei', 'Microsoft YaHei'] +plt.rcParams['axes.unicode_minus'] = False +VISUALIZATION_ENABLE = True + + +# -------------------------- 1. 数据生成(纯Python实现) -------------------------- +def generate_driving_data(n_samples=10000): + """生成人机共驾数据集(纯Python字典+列表实现)""" + random.seed(42) + data = { + 'road_type': [], # 0:highway, 1:urban, 2:rural + 'weather': [], # 0:clear, 1:rainy, 2:foggy + 'traffic_density': [], + 'driver_fatigue': [], + 'driver_attention': [], + 'driver_reaction_time': [], + 'vehicle_speed': [], + 'autopilot_confidence': [], + 'vehicle_stability': [], + 'takeover_time': [] # 目标变量:接管时间(秒) + } + + for _ in range(n_samples): + # 随机生成特征 + road_type = random.choice([0, 1, 2]) + weather = random.choice([0, 1, 2]) + traffic_density = random.uniform(0, 10) + driver_fatigue = random.uniform(0, 1) + driver_attention = random.uniform(0, 1) + driver_reaction_time = random.uniform(0.2, 1.5) + vehicle_speed = random.uniform(20, 120) + autopilot_confidence = random.uniform(0, 1) + vehicle_stability = random.uniform(0.8, 1) + + # 计算接管时间(加入特征关联) + takeover_time = random.uniform(0, 10) + takeover_time += driver_fatigue * 5 # 疲劳度影响 + takeover_time += (1 - autopilot_confidence) * 3 # 自动驾驶置信度影响 + takeover_time += weather * 1.0 # 天气影响(雨天+1,雾天+2) + takeover_time += random.normalvariate(0, 0.5) # 噪声 + + # 填充数据 + data['road_type'].append(road_type) + data['weather'].append(weather) + data['traffic_density'].append(traffic_density) + data['driver_fatigue'].append(driver_fatigue) + data['driver_attention'].append(driver_attention) + data['driver_reaction_time'].append(driver_reaction_time) + data['vehicle_speed'].append(vehicle_speed) + data['autopilot_confidence'].append(autopilot_confidence) + data['vehicle_stability'].append(vehicle_stability) + data['takeover_time'].append(takeover_time) + + # 模拟5%缺失值并填充(纯Python实现) + for i in random.sample(range(n_samples), int(0.05 * n_samples)): + data['driver_attention'][i] = None + # 填充缺失值(均值填充) + attention_vals = [v for v in data['driver_attention'] if v is not None] + attention_mean = sum(attention_vals) / len(attention_vals) + data['driver_attention'] = [v if v is not None else attention_mean for v in data['driver_attention']] + + return data + + +# -------------------------- 2. 数据预处理(纯Python实现) -------------------------- +def normalize_feature(feature_list): + """特征标准化(Z-score):(x-mean)/std""" + mean = sum(feature_list) / len(feature_list) + std = math.sqrt(sum([(x - mean) ** 2 for x in feature_list]) / len(feature_list)) + if std == 0: + return [0.0 for _ in feature_list] + return [(x - mean) / std for x in feature_list] + + +def process_data(data): + """数据预处理:标准化+特征合并+数据集划分""" + # 1. 提取特征列表并标准化 + features = [ + 'road_type', 'weather', 'traffic_density', 'driver_fatigue', + 'driver_attention', 'driver_reaction_time', 'vehicle_speed', + 'autopilot_confidence', 'vehicle_stability' + ] + normalized_data = {} + for feat in features: + normalized_data[feat] = normalize_feature(data[feat]) + normalized_data['takeover_time'] = data['takeover_time'] # 目标变量不标准化 + + # 2. 合并特征为二维列表(每行是一个样本的所有特征) + X = [] + y = [] + n_samples = len(data['takeover_time']) + for i in range(n_samples): + sample = [normalized_data[feat][i] for feat in features] + sample.insert(0, 1.0) # 加入偏置项(截距) + X.append(sample) + y.append(normalized_data['takeover_time'][i]) + + # 3. 划分训练集/测试集(8:2) + train_size = int(0.8 * n_samples) + X_train = X[:train_size] + y_train = y[:train_size] + X_test = X[train_size:] + y_test = y[train_size:] + + return X_train, y_train, X_test, y_test, features + + +# -------------------------- 3. 线性回归模型(纯Python实现) -------------------------- +class LinearRegression: + def __init__(self): + self.weights = None # 模型权重(包含偏置项) + + def _mean_squared_error(self, y_true, y_pred): + """计算均方误差(MSE)""" + return sum([(y_t - y_p) ** 2 for y_t, y_p in zip(y_true, y_pred)]) / len(y_true) + + def fit(self, X, y, learning_rate=0.01, epochs=1000, verbose=False): + """梯度下降训练模型""" + n_samples = len(X) + n_features = len(X[0]) + self.weights = [random.uniform(-0.1, 0.1) for _ in range(n_features)] # 初始化权重 + + for epoch in range(epochs): + # 计算预测值 + y_pred = [sum([w * x for w, x in zip(self.weights, sample)]) for sample in X] + # 计算梯度 + gradients = [0.0] * n_features + for i in range(n_samples): + error = y_pred[i] - y[i] + for j in range(n_features): + gradients[j] += error * X[i][j] + gradients = [g / n_samples for g in gradients] + + # 更新权重 + self.weights = [w - learning_rate * g for w, g in zip(self.weights, gradients)] + + # 打印训练进度 + if verbose and (epoch % 100 == 0): + mse = self._mean_squared_error(y, y_pred) + print(f"Epoch {epoch}, MSE: {mse:.4f}") + + def predict(self, X): + """预测""" + if self.weights is None: + raise ValueError("模型未训练,请先调用fit()") + return [sum([w * x for w, x in zip(self.weights, sample)]) for sample in X] + + +# -------------------------- 4. 模型评估(纯Python实现) -------------------------- +def evaluate_model(y_true, y_pred, set_name): + """计算回归评估指标(MAE、RMSE、R²)""" + # MAE + mae = sum([abs(y_t - y_p) for y_t, y_p in zip(y_true, y_pred)]) / len(y_true) + # MSE & RMSE + mse = sum([(y_t - y_p) ** 2 for y_t, y_p in zip(y_true, y_pred)]) / len(y_true) + rmse = math.sqrt(mse) + # R² + y_mean = sum(y_true) / len(y_true) + ss_total = sum([(y_t - y_mean) ** 2 for y_t in y_true]) + ss_res = sum([(y_t - y_p) ** 2 for y_t, y_p in zip(y_true, y_pred)]) + r2 = 1 - (ss_res / ss_total) if ss_total != 0 else 0.0 + + print(f"\n{set_name} 评估结果:") + print(f"平均绝对误差(MAE): {mae:.4f} 秒") + print(f"均方误差(MSE): {mse:.4f}") + print(f"均方根误差(RMSE): {rmse:.4f} 秒") + print(f"决定系数(R²): {r2:.4f}") + return {'mae': mae, 'mse': mse, 'rmse': rmse, 'r2': r2} + + +# -------------------------- 5. PyCharm适配的可视化 -------------------------- +def plot_results(y_test, y_test_pred, train_metrics, test_metrics, features, weights): + """预测效果可视化(适配PyCharm显示)""" + if not VISUALIZATION_ENABLE: + return + + # 创建画布(加大分辨率,避免图片模糊) + fig = plt.figure(figsize=(16, 12), dpi=100) + + # 5.1 真实值vs预测值(仅展示前500个点,提升绘制速度) + ax1 = plt.subplot(2, 2, 1) + plt.scatter(y_test[:500], y_test_pred[:500], alpha=0.6, color='steelblue', s=20) + plt.plot([min(y_test[:500]), max(y_test[:500])], + [min(y_test[:500]), max(y_test[:500])], 'r--', lw=2) + plt.xlabel('真实接管时间(秒)', fontsize=10) + plt.ylabel('预测接管时间(秒)', fontsize=10) + plt.title('测试集:真实值 vs 预测值', fontsize=12, fontweight='bold') + plt.grid(alpha=0.3, linestyle='--') + + # 5.2 残差分布 + ax2 = plt.subplot(2, 2, 2) + residuals = [y_t - y_p for y_t, y_p in zip(y_test[:500], y_test_pred[:500])] + plt.hist(residuals, bins=30, color='forestgreen', alpha=0.7, edgecolor='black') + plt.xlabel('残差(真实值-预测值)', fontsize=10) + plt.ylabel('频次', fontsize=10) + plt.title('残差分布', fontsize=12, fontweight='bold') + plt.grid(alpha=0.3, linestyle='--') + + # 5.3 特征重要性(权重绝对值) + ax3 = plt.subplot(2, 2, 3) + feat_importance = [abs(w) for w in weights[1:]] # 排除偏置项 + plt.barh(features, feat_importance, color='darkviolet', alpha=0.8) + plt.xlabel('权重绝对值(特征重要性)', fontsize=10) + plt.ylabel('特征', fontsize=10) + plt.title('特征重要性排名', fontsize=12, fontweight='bold') + plt.grid(alpha=0.3, linestyle='--') + + # 5.4 指标对比 + ax4 = plt.subplot(2, 2, 4) + metrics = ['MAE', 'RMSE', 'R²'] + train_vals = [train_metrics['mae'], train_metrics['rmse'], train_metrics['r2']] + test_vals = [test_metrics['mae'], test_metrics['rmse'], test_metrics['r2']] + + x = [0, 1, 2] + width = 0.35 + plt.bar([i - width / 2 for i in x], train_vals, width, label='训练集', color='skyblue', alpha=0.8) + plt.bar([i + width / 2 for i in x], test_vals, width, label='测试集', color='orange', alpha=0.8) + plt.xlabel('评估指标', fontsize=10) + plt.ylabel('数值', fontsize=10) + plt.title('训练集 vs 测试集 指标对比', fontsize=12, fontweight='bold') + plt.xticks(x, metrics) + plt.legend(fontsize=9) + plt.grid(alpha=0.3, linestyle='--') + + # 调整布局,避免标签重叠 + plt.tight_layout(pad=2.0) + + # 关键:PyCharm中显示图片 + 保存图片到本地(可选) + plt.show(block=True) # block=True确保图片窗口阻塞,不会一闪而过 + # 可选:保存图片到项目目录(方便查看) + fig.savefig('human_machine_co_driving_prediction.png', dpi=150, bbox_inches='tight') + print("\n✅ 可视化图片已保存到项目根目录:human_machine_co_driving_prediction.png") + + +# -------------------------- 6. 人机共驾预测应用 -------------------------- +def predict_takeover_time(features, scaler_stats, model): + """ + 预测接管时间 + :param features: 原始特征字典 + :param scaler_stats: 特征标准化的均值和标准差 + :param model: 训练好的线性回归模型 + :return: 预测的接管时间(秒) + """ + # 特征映射(类别特征转数字) + road_type_map = {'highway': 0, 'urban': 1, 'rural': 2} + weather_map = {'clear': 0, 'rainy': 1, 'foggy': 2} + features['road_type'] = road_type_map[features['road_type']] + features['weather'] = weather_map[features['weather']] + + # 标准化(使用训练集的均值和标准差) + feat_list = [ + features['road_type'], features['weather'], + features['traffic_density'], features['driver_fatigue'], + features['driver_attention'], features['driver_reaction_time'], + features['vehicle_speed'], features['autopilot_confidence'], + features['vehicle_stability'] + ] + normalized_feat = [] + for i, feat in enumerate(feat_list): + mean, std = scaler_stats[i] + if std == 0: + normalized_feat.append(0.0) + else: + normalized_feat.append((feat - mean) / std) + normalized_feat.insert(0, 1.0) # 加入偏置项 + + # 预测 + takeover_time = model.predict([normalized_feat])[0] + return round(takeover_time, 2) + + +# -------------------------- 主流程执行 -------------------------- +if __name__ == "__main__": + print("=" * 50) + print("开始运行人机共驾预测模型(PyCharm适配版)") + print("=" * 50) + + # 1. 生成数据 + print("\n🔹 步骤1:生成人机共驾数据集...") + data = generate_driving_data(n_samples=10000) + + # 2. 预处理数据 + print("\n🔹 步骤2:数据预处理(标准化+划分数据集)...") + X_train, y_train, X_test, y_test, features = process_data(data) + + # 保存标准化的均值和标准差(用于预测) + scaler_stats = [] + for feat in features: + mean = sum(data[feat]) / len(data[feat]) + std = math.sqrt(sum([(x - mean) ** 2 for x in data[feat]]) / len(data[feat])) + scaler_stats.append((mean, std)) + + # 3. 训练模型 + print("\n🔹 步骤3:训练线性回归模型(梯度下降)...") + model = LinearRegression() + model.fit(X_train, y_train, learning_rate=0.01, epochs=1000, verbose=True) + + # 4. 预测与评估 + print("\n🔹 步骤4:模型评估...") + y_train_pred = model.predict(X_train) + y_test_pred = model.predict(X_test) + train_metrics = evaluate_model(y_train, y_train_pred, "训练集") + test_metrics = evaluate_model(y_test, y_test_pred, "测试集") + + # 5. 可视化(PyCharm中显示+保存) + print("\n🔹 步骤5:生成预测效果可视化...") + plot_results(y_test, y_test_pred, train_metrics, test_metrics, features, model.weights) + + # 6. 应用示例 + print("\n🔹 步骤6:人机共驾接管时间预测示例...") + # 理想场景 + ideal_scenario = { + 'road_type': 'highway', + 'weather': 'clear', + 'traffic_density': 2.0, + 'driver_fatigue': 0.1, + 'driver_attention': 0.9, + 'driver_reaction_time': 0.3, + 'vehicle_speed': 100, + 'autopilot_confidence': 0.95, + 'vehicle_stability': 0.98 + } + # 危险场景 + dangerous_scenario = { + 'road_type': 'urban', + 'weather': 'rainy', + 'traffic_density': 8.0, + 'driver_fatigue': 0.8, + 'driver_attention': 0.2, + 'driver_reaction_time': 1.2, + 'vehicle_speed': 60, + 'autopilot_confidence': 0.4, + 'vehicle_stability': 0.9 + } + + # 11预测 + ideal_time = predict_takeover_time(ideal_scenario, scaler_stats, model) + dangerous_time = predict_takeover_time(dangerous_scenario, scaler_stats, model) + + print("\n=== 人机共驾接管时间预测结果 ===") + print(f"🌞 理想场景(高速/晴天/低疲劳):{ideal_time} 秒") + print(f"⚠️ 危险场景(城市/雨天/高疲劳):{dangerous_time} 秒") + + # 决策建议 + if dangerous_time > 5: + print("\n🚨 预警:危险场景下驾驶员接管时间过长,建议立即降低车速/提醒驾驶员!") + else: + print("\n✅ 安全:接管时间在合理范围内") + + print("\n=" * 50) + print("模型运行完成!") + print("=" * 50) \ No newline at end of file diff --git a/src/driverless_TG/prediction direction.py b/src/unmanned_vehicle_safety_and_operation/prediction _direction.py similarity index 100% rename from src/driverless_TG/prediction direction.py rename to src/unmanned_vehicle_safety_and_operation/prediction _direction.py diff --git a/src/unmanned_vehicle_safety_and_operation/smoke _alarm.py b/src/unmanned_vehicle_safety_and_operation/smoke _alarm.py new file mode 100644 index 0000000000..5388914111 --- /dev/null +++ b/src/unmanned_vehicle_safety_and_operation/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]: + """ + 评估报警等级分类lll模型性能 + """ + # 预测测试集 + 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) + + # 设置标签111111 + 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. 可视化监测结果 222 + 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 diff --git a/src/driverless_TG/speed_main.py b/src/unmanned_vehicle_safety_and_operation/speed_main.py similarity index 100% rename from src/driverless_TG/speed_main.py rename to src/unmanned_vehicle_safety_and_operation/speed_main.py diff --git a/src/unmanned_vehicle_safety_and_operation/temperature_alarm.py b/src/unmanned_vehicle_safety_and_operation/temperature_alarm.py new file mode 100644 index 0000000000..0a79b3c955 --- /dev/null +++ b/src/unmanned_vehicle_safety_and_operation/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 diff --git a/src/unmanned_vehicle_safety_and_operation/traffic_sign_recognition.py b/src/unmanned_vehicle_safety_and_operation/traffic_sign_recognition.py new file mode 100644 index 0000000000..67be8a5571 --- /dev/null +++ b/src/unmanned_vehicle_safety_and_operation/traffic_sign_recognition.py @@ -0,0 +1,448 @@ +import numpy as np +import os +import matplotlib.pyplot as plt +from PIL import Image +import warnings + +warnings.filterwarnings('ignore') + +# ===================== 核心配置(适配PyCharm工作目录) ===================== +# 获取当前脚本所在目录(PyCharm中确保路径正确) +BASE_DIR = os.path.dirname(os.path.abspath(__file__)) +DATA_PATH = os.path.join(BASE_DIR, "traffic_signs") # 数据集路径 +TEST_IMG_PATH = os.path.join(BASE_DIR, "test_sign.png") # 测试图片路径 +CONFUSION_MATRIX_PATH = os.path.join(BASE_DIR, "confusion_matrix.png") # 混淆矩阵保存路径 + + +# ===================== 1. 自动生成模拟数据集(PyCharm友好) ===================== +def create_simulated_dataset(): + """ + 自动生成模拟交通标志数据集 + 路径:当前脚本目录/traffic_signs/ + """ + # 创建数据集根目录 + if not os.path.exists(DATA_PATH): + os.makedirs(DATA_PATH) + print(f"创建数据集目录:{DATA_PATH}") + + # 定义3类交通标志 + categories = ["stop_sign", "speed_limit_50", "yield_sign"] + n_samples_per_class = 50 # 每类生成50张图片 + + # 为每个类别生成图片 + for cat in categories: + cat_dir = os.path.join(DATA_PATH, cat) + if not os.path.exists(cat_dir): + os.makedirs(cat_dir) + + # 生成不同特征的模拟灰度图(区分不同类别) + for i in range(n_samples_per_class): + # 不同类别设置不同的像素分布(便于模型区分) + if cat == "stop_sign": + img_arr = np.random.normal(0.8, 0.08, (64, 64)) # 偏亮 + elif cat == "speed_limit_50": + img_arr = np.random.normal(0.4, 0.08, (64, 64)) # 中等亮度 + else: # yield_sign + img_arr = np.random.normal(0.2, 0.08, (64, 64)) # 偏暗 + + # 归一化到0-255并转为uint8格式 + img_arr = np.clip(img_arr * 255, 0, 255).astype(np.uint8) + # 保存图片(PNG格式,兼容PIL) + img = Image.fromarray(img_arr, mode='L') + img.save(os.path.join(cat_dir, f"{cat}_{i}.png")) + + print(f"\n✅ 模拟数据集生成完成!") + print(f"📂 数据集路径:{DATA_PATH}") + print(f"📊 包含类别:{categories}(每类{n_samples_per_class}张)") + + +# ===================== 2. 纯Numpy实现HOG特征提取 ===================== +def hog_feature_extract(img): + """ + 输入:64x64归一化灰度图(0-1) + 输出:HOG特征向量 + """ + # 1. 计算x/y方向梯度 + gx = np.zeros_like(img, dtype=np.float32) + gy = np.zeros_like(img, dtype=np.float32) + gx[:, :-1] = img[:, 1:] - img[:, :-1] + gy[:-1, :] = img[1:, :] - img[:-1, :] + + # 2. 计算梯度幅值和方向(0-180度) + magnitude = np.sqrt(gx ** 2 + gy ** 2) + orientation = np.arctan2(gy, gx) * (180 / np.pi) % 180 + + # 3. 分Cell计算梯度直方图(8x8像素/Cell,9个方向) + cell_size = 8 + orientations = 9 + orient_bin = 180 / orientations + n_cells = 64 // cell_size # 8个Cell(64/8) + + cell_hist = np.zeros((n_cells, n_cells, orientations), dtype=np.float32) + for y in range(n_cells): + for x in range(n_cells): + # 提取当前Cell的梯度 + cell_mag = magnitude[y * cell_size:(y + 1) * cell_size, x * cell_size:(x + 1) * cell_size] + cell_orient = orientation[y * cell_size:(y + 1) * cell_size, x * cell_size:(x + 1) * cell_size] + + # 统计每个方向的梯度和 + for bin_idx in range(orientations): + bin_min = bin_idx * orient_bin + bin_max = (bin_idx + 1) * orient_bin + mask = (cell_orient >= bin_min) & (cell_orient < bin_max) + cell_hist[y, x, bin_idx] = np.sum(cell_mag[mask]) + + # 4. 分Block归一化(2x2 Cell/Block,L2-Hys归一化) + block_size = 2 + n_blocks = n_cells - block_size + 1 # 7个Block + hog_feat = [] + + for y in range(n_blocks): + for x in range(n_blocks): + block = cell_hist[y:y + block_size, x:x + block_size, :].flatten() + # L2归一化(加小值避免除零) + norm = np.sqrt(np.sum(block ** 2) + 1e-6) + block = block / norm + # Hys截断(限制最大值0.2) + block = np.clip(block, 0, 0.2) + # 再次归一化 + norm = np.sqrt(np.sum(block ** 2) + 1e-6) + block = block / norm + hog_feat.extend(block) + + return np.array(hog_feat, dtype=np.float32) + + +# ===================== 3. 简化版SVM分类器(多分类) ===================== +class SimpleSVM: + def __init__(self, lr=0.001, lambda_param=0.01, n_iters=800): + self.lr = lr # 学习率 + self.lambda_param = lambda_param # 正则化系数 + self.n_iters = n_iters # 迭代次数 + self.weights = None # 类别权重 + self.biases = None # 类别偏置 + self.classes = None # 类别列表 + + def fit(self, X, y): + """训练多分类SVM(一对其余策略)""" + self.classes = np.unique(y) + n_classes = len(self.classes) + n_samples, n_feat = X.shape + + # 初始化权重和偏置 + self.weights = np.zeros((n_classes, n_feat)) + self.biases = np.zeros(n_classes) + + print("\n🚀 开始训练SVM模型...") + # 为每个类别训练二分类SVM + for idx, c in enumerate(self.classes): + # 构建二分类标签(当前类=1,其他类=-1) + y_bin = np.where(y == c, 1, -1) + w = np.zeros(n_feat) + b = 0 + + # 梯度下降优化 + for iter in range(self.n_iters): + if iter % 200 == 0: + print(f" 类别{c}:迭代{iter}/{self.n_iters}") + + for i in range(n_samples): + z = np.dot(X[i], w) + b + if y_bin[i] * z < 1: + # 误分类样本:更新权重和偏置 + w -= self.lr * (2 * self.lambda_param * w - y_bin[i] * X[i]) + b -= self.lr * (-y_bin[i]) + else: + # 正确分类样本:仅正则化 + w -= self.lr * 2 * self.lambda_param * w + + self.weights[idx] = w + self.biases[idx] = b + + print("✅ SVM模型训练完成!") + + def predict(self, X): + """预测类别(返回类别索引)""" + pred = [] + for x in X: + # 计算每个类别的得分 + scores = [np.dot(x, self.weights[idx]) + self.biases[idx] for idx in range(len(self.classes))] + pred.append(self.classes[np.argmax(scores)]) + return np.array(pred) + + def predict_proba(self, X): + """预测概率(Softmax转换)""" + probs = [] + for x in X: + scores = [np.dot(x, self.weights[idx]) + self.biases[idx] for idx in range(len(self.classes))] + # Softmax归一化(防止数值溢出) + exp_scores = np.exp(scores - np.max(scores)) + prob = exp_scores / np.sum(exp_scores) + probs.append(prob) + return np.array(probs) + + +# ===================== 4. 模型评估指标(纯手动实现) ===================== +class Metrics: + @staticmethod + def train_test_split(X, y, test_size=0.2, seed=42): + """划分训练集/测试集""" + np.random.seed(seed) + idx = np.arange(len(X)) + np.random.shuffle(idx) + X, y = X[idx], y[idx] + + split_idx = int(len(X) * (1 - test_size)) + return X[:split_idx], X[split_idx:], y[:split_idx], y[split_idx:] + + @staticmethod + def accuracy(y_true, y_pred): + """计算准确率""" + return np.sum(y_true == y_pred) / len(y_true) + + @staticmethod + def confusion_matrix(y_true, y_pred, classes): + """计算混淆矩阵""" + n_classes = len(classes) + cm = np.zeros((n_classes, n_classes), dtype=int) + cat2idx = {c: i for i, c in enumerate(classes)} + + for t, p in zip(y_true, y_pred): + cm[cat2idx[t], cat2idx[p]] += 1 + return cm + + @staticmethod + def classification_report(y_true, y_pred, classes): + """生成分类报告(精确率/召回率/F1)""" + report = [] + report.append("=" * 50) + report.append(" 分类报告(精确率/召回率/F1)") + report.append("=" * 50) + report.append(f"{'类别':<12} {'精确率':<8} {'召回率':<8} {'F1分数':<8} {'样本数':<8}") + report.append("-" * 50) + + total_support = 0 + avg_precision = 0 + avg_recall = 0 + avg_f1 = 0 + + for c in classes: + # 计算TP/FN/FP + tp = np.sum((y_true == c) & (y_pred == c)) + fn = np.sum((y_true == c) & (y_pred != c)) + fp = np.sum((y_true != c) & (y_pred == c)) + + support = tp + fn + total_support += support + + # 计算指标(避免除零) + precision = tp / (tp + fp) if (tp + fp) > 0 else 0 + recall = tp / (tp + fn) if (tp + fn) > 0 else 0 + f1 = 2 * precision * recall / (precision + recall) if (precision + recall) > 0 else 0 + + avg_precision += precision * support + avg_recall += recall * support + avg_f1 += f1 * support + + report.append(f"{c:<12} {precision:.2f} {recall:.2f} {f1:.2f} {support}") + + # 加权平均 + avg_precision /= total_support + avg_recall /= total_support + avg_f1 /= total_support + + report.append("-" * 50) + report.append( + f"{'加权平均':<12} {avg_precision:.2f} {avg_recall:.2f} {avg_f1:.2f} {total_support}") + report.append("=" * 50) + + return "\n".join(report) + + +# ===================== 5. 交通标志识别主系统 ===================== +class TrafficSignDetector: + def __init__(self): + self.X = [] # 特征集 + self.y = [] # 标签集 + self.categories = [] # 类别列表 + self.svm = SimpleSVM() + self.mean = None # 特征均值(标准化) + self.std = None # 特征标准差(标准化) + + def load_data(self): + """加载数据集并提取HOG特征""" + print("\n📥 开始加载数据集...") + # 获取类别列表 + self.categories = [d for d in os.listdir(DATA_PATH) if os.path.isdir(os.path.join(DATA_PATH, d))] + + # 遍历所有图片 + for label, cat in enumerate(self.categories): + cat_dir = os.path.join(DATA_PATH, cat) + img_files = [f for f in os.listdir(cat_dir) if f.endswith(('.png', '.jpg'))] + + for img_file in img_files: + img_path = os.path.join(cat_dir, img_file) + # 预处理图片 + img = self._preprocess(img_path) + if img is None: + continue + # 提取HOG特征 + hog_feat = hog_feature_extract(img) + self.X.append(hog_feat) + self.y.append(cat) # 直接存储类别名称(更直观) + + # 转换为Numpy数组 + self.X = np.array(self.X) + self.y = np.array(self.y) + + # 划分训练/测试集 + X_train, X_test, y_train, y_test = Metrics.train_test_split(self.X, self.y) + + # 特征标准化 + self.mean = np.mean(X_train, axis=0) + self.std = np.std(X_train, axis=0) + 1e-6 + X_train = (X_train - self.mean) / self.std + X_test = (X_test - self.mean) / self.std + + print(f"✅ 数据集加载完成!") + print(f"📊 总样本数:{len(self.X)} | 训练集:{len(X_train)} | 测试集:{len(X_test)}") + return X_train, X_test, y_train, y_test + + def _preprocess(self, img_path): + """图片预处理:灰度化→缩放→归一化""" + try: + with Image.open(img_path) as img: + # 灰度化+缩放至64x64 + img_gray = img.convert('L') + img_resized = img_gray.resize((64, 64), Image.Resampling.LANCZOS) + # 归一化到0-1 + img_arr = np.array(img_resized, dtype=np.float32) / 255.0 + return img_arr + except Exception as e: + print(f"⚠️ 图片预处理失败 {img_path}:{e}") + return None + + def evaluate(self, X_test, y_test): + """评估模型并生成检测报告""" + # 预测测试集 + y_pred = self.svm.predict(X_test) + y_pred_proba = self.svm.predict_proba(X_test) + + # 1. 整体准确率 + acc = Metrics.accuracy(y_test, y_pred) + print(f"\n📈 整体识别准确率:{acc:.4f} ({acc * 100:.2f}%)") + + # 2. 分类报告 + report = Metrics.classification_report(y_test, y_pred, self.categories) + print(report) + + # 3. 混淆矩阵(可视化+保存) + cm = Metrics.confusion_matrix(y_test, y_pred, self.categories) + self._plot_confusion_matrix(cm) + + # 4. 各类别准确率 + print("\n📋 各类别识别准确率:") + for i, cat in enumerate(self.categories): + total = cm[i].sum() + correct = cm[i, i] + acc_cat = correct / total if total > 0 else 0 + print(f" {cat}:{acc_cat:.4f} ({correct}/{total})") + + # 5. 低置信度检测 + low_conf_idx = np.where(np.max(y_pred_proba, axis=1) < 0.8)[0] + print(f"\n⚠️ 低置信度预测(概率<0.8):{len(low_conf_idx)} 个样本") + if len(low_conf_idx) > 0: + for idx in low_conf_idx[:3]: # 展示前3个 + true_cat = y_test[idx] + pred_cat = y_pred[idx] + conf = np.max(y_pred_proba[idx]) + print(f" 样本{idx}:真实={true_cat} | 预测={pred_cat} | 置信度={conf:.4f}") + + def _plot_confusion_matrix(self, cm): + """绘制并保存混淆矩阵""" + plt.rcParams['font.sans-serif'] = ['SimHei'] # 中文显示 + plt.figure(figsize=(8, 6)) + # 绘制混淆矩阵 + plt.imshow(cm, interpolation='nearest', cmap=plt.cm.Blues) + plt.title('交通标志识别 - 混淆矩阵', fontsize=12) + plt.colorbar() + # 设置坐标轴 + tick_marks = np.arange(len(self.categories)) + plt.xticks(tick_marks, self.categories, rotation=45) + plt.yticks(tick_marks, self.categories) + # 标注数值 + thresh = cm.max() / 2. + for i in range(cm.shape[0]): + for j in range(cm.shape[1]): + plt.text(j, i, cm[i, j], ha="center", va="center", + color="white" if cm[i, j] > thresh else "black") + # 标签 + plt.ylabel('真实类别', fontsize=10) + plt.xlabel('预测类别', fontsize=10) + plt.tight_layout() + # 保存图片(PyCharm中可直接查看) + plt.savefig(CONFUSION_MATRIX_PATH, dpi=150, bbox_inches='tight') + print(f"\n🖼️ 混淆矩阵已保存:{CONFUSION_MATRIX_PATH}") + # 显示图片(PyCharm会弹出窗口) + plt.show() + + def predict_single(self): + """预测单张测试图片""" + # 生成测试图片(模拟stop_sign) + test_img_arr = np.random.normal(0.8, 0.08, (64, 64)) + test_img_arr = np.clip(test_img_arr * 255, 0, 255).astype(np.uint8) + test_img = Image.fromarray(test_img_arr, mode='L') + test_img.save(TEST_IMG_PATH) + print(f"\n📸 生成测试图片:{TEST_IMG_PATH}") + + # 预处理+提取特征 + img = self._preprocess(TEST_IMG_PATH) + hog_feat = hog_feature_extract(img) + hog_feat = (hog_feat - self.mean) / self.std + + # 预测 + pred_cat = self.svm.predict(np.array([hog_feat]))[0] + pred_proba = self.svm.predict_proba(np.array([hog_feat]))[0] + conf = pred_proba[self.svm.classes.tolist().index(pred_cat)] + + # 输出结果 + print("\n🎯 单张图片识别结果:") + print(f" 预测类别:{pred_cat}") + print(f" 置信度:{conf:.4f}") + print(f" 是否高置信度:{'是' if conf >= 0.8 else '否'}") + print(" 各类别概率:") + for i, cat in enumerate(self.categories): + print(f" {cat}:{pred_proba[i]:.4f}") + + +# ===================== 6. 主运行函数(PyCharm一键运行) ===================== +def main(): + """PyCharm主运行入口""" + # 步骤1:生成模拟数据集 + create_simulated_dataset() + + # 步骤2:初始化检测器 + detector = TrafficSignDetector() + + # 步骤3:加载数据 + X_train, X_test, y_train, y_test = detector.load_data() + + # 步骤4:训练模型 + detector.svm.fit(X_train, y_train) + + # 步骤5:评估模型(生成混淆矩阵图片) + detector.evaluate(X_test, y_test) + + # 步骤6:单张图片预测(生成测试图片) + detector.predict_single() + + print("\n🎉 所有任务完成!生成的文件:") + print(f" 1. 混淆矩阵:{CONFUSION_MATRIX_PATH}") + print(f" 2. 测试图片:{TEST_IMG_PATH}") + print(f" 3. 数据集:{DATA_PATH}") + + +# ===================== 运行入口 ===================== +if __name__ == "__main__": + # PyCharm中直接运行此脚本 + main() \ No newline at end of file diff --git a/src/unmanned_vehicle_safety_and_operation/visual_effect_detection.py b/src/unmanned_vehicle_safety_and_operation/visual_effect_detection.py new file mode 100644 index 0000000000..d62662219d --- /dev/null +++ b/src/unmanned_vehicle_safety_and_operation/visual_effect_detection.py @@ -0,0 +1,311 @@ +import numpy as np +import matplotlib.pyplot as plt +import os +import warnings +from PIL import Image, ImageFilter, ImageStat + +warnings.filterwarnings('ignore') + +# 设置中文字体(解决PyCharm中matplotlib中文显示乱码) +plt.rcParams['font.sans-serif'] = ['SimHei'] # 黑体 +plt.rcParams['axes.unicode_minus'] = False # 解决负号显示问题 + + +# ===================== 1. 特征提取函数(保留,兼容真实图像) ===================== +class RainFogFeatureExtractor: + def __init__(self): + pass + + def calculate_fog_density(self, img): + gray = img.convert('L') + min_filtered = gray.filter(ImageFilter.MinFilter(size=15)) + gray_array = np.array(min_filtered) + fog_density = np.mean(gray_array) / 255.0 + return fog_density + + def calculate_contrast(self, img): + gray = img.convert('L') + stat = ImageStat.Stat(gray) + contrast = stat.stddev[0] + return contrast + + def calculate_edge_density(self, img): + gray = img.convert('L') + edges = gray.filter(ImageFilter.FIND_EDGES) + edge_array = np.array(edges) + edge_density = np.sum(edge_array > 0) / (img.width * img.height) + return edge_density + + def calculate_color_saturation(self, img): + hsv = img.convert('HSV') + sat_band = hsv.getchannel(1) + sat_array = np.array(sat_band) + sat_mean = np.mean(sat_array) / 255.0 + return sat_mean + + def extract_all_features(self, img_path): + try: + with Image.open(img_path) as img: + img = img.resize((640, 480)) + if img.mode != 'RGB': + img = img.convert('RGB') + + features = [ + self.calculate_fog_density(img), + self.calculate_contrast(img), + self.calculate_edge_density(img), + self.calculate_color_saturation(img) + ] + features = np.array(features) + features[1] = features[1] / 255.0 + return features + except Exception as e: + return None + + +# ===================== 2. 生成模拟数据集 ===================== +def build_dataset(): + """生成模拟数据集(无需真实图像)""" + np.random.seed(42) + n_samples_per_class = 100 # 每类100个样本 + + # 清晰样本(标签0) + clear_fog = np.random.normal(0.1, 0.05, n_samples_per_class) + clear_contrast = np.random.normal(0.8, 0.1, n_samples_per_class) + clear_edge = np.random.normal(0.2, 0.05, n_samples_per_class) + clear_sat = np.random.normal(0.8, 0.1, n_samples_per_class) + clear_features = np.column_stack([clear_fog, clear_contrast, clear_edge, clear_sat]) + clear_labels = np.zeros(n_samples_per_class) + + # 轻度雨雾(标签1) + light_fog = np.random.normal(0.3, 0.05, n_samples_per_class) + light_contrast = np.random.normal(0.6, 0.1, n_samples_per_class) + light_edge = np.random.normal(0.15, 0.05, n_samples_per_class) + light_sat = np.random.normal(0.6, 0.1, n_samples_per_class) + light_features = np.column_stack([light_fog, light_contrast, light_edge, light_sat]) + light_labels = np.ones(n_samples_per_class) + + # 中度雨雾(标签2) + medium_fog = np.random.normal(0.5, 0.05, n_samples_per_class) + medium_contrast = np.random.normal(0.4, 0.1, n_samples_per_class) + medium_edge = np.random.normal(0.1, 0.05, n_samples_per_class) + medium_sat = np.random.normal(0.4, 0.1, n_samples_per_class) + medium_features = np.column_stack([medium_fog, medium_contrast, medium_edge, medium_sat]) + medium_labels = np.ones(n_samples_per_class) * 2 + + # 重度雨雾(标签3) + heavy_fog = np.random.normal(0.8, 0.05, n_samples_per_class) + heavy_contrast = np.random.normal(0.2, 0.1, n_samples_per_class) + heavy_edge = np.random.normal(0.05, 0.05, n_samples_per_class) + heavy_sat = np.random.normal(0.2, 0.1, n_samples_per_class) + heavy_features = np.column_stack([heavy_fog, heavy_contrast, heavy_edge, heavy_sat]) + heavy_labels = np.ones(n_samples_per_class) * 3 + + # 合并数据并限制范围 + X = np.vstack([clear_features, light_features, medium_features, heavy_features]) + y = np.hstack([clear_labels, light_labels, medium_labels, heavy_labels]) + X = np.clip(X, 0, 1) + feature_names = ['雾度', '对比度', '边缘密度', '饱和度'] + + print(f"模拟数据集生成完成:总样本数={len(X)}, 特征数={X.shape[1]}") + return X, y, feature_names + + +# ===================== 3. 简易K近邻分类器 ===================== +class SimpleKNNClassifier: + def __init__(self, k=5): + self.k = k + self.X_train = None + self.y_train = None + + def fit(self, X, y): + self.X_train = X + self.y_train = y + + def _euclidean_distance(self, x1, x2): + return np.sqrt(np.sum((x1 - x2) ** 2)) + + def predict(self, X): + predictions = [] + for x in X: + distances = [self._euclidean_distance(x, x_train) for x_train in self.X_train] + k_indices = np.argsort(distances)[:self.k] + k_nearest_labels = [self.y_train[i] for i in k_indices] + pred_label = max(set(k_nearest_labels), key=k_nearest_labels.count) + predictions.append(pred_label) + return np.array(predictions) + + def predict_proba(self, X): + probas = [] + for x in X: + distances = [self._euclidean_distance(x, x_train) for x_train in self.X_train] + k_indices = np.argsort(distances)[:self.k] + k_nearest_labels = [self.y_train[i] for i in k_indices] + + label_counts = {0: 0, 1: 0, 2: 0, 3: 0} + for label in k_nearest_labels: + label_counts[label] += 1 + total = sum(label_counts.values()) + proba = [label_counts[i] / total for i in range(4)] + probas.append(proba) + return np.array(probas) + + +# ===================== 4. 模型评估与可视化(核心:生成图片) ===================== +def evaluate_and_visualize(model, X_train, X_test, y_train, y_test, feature_names): + """评估模型并生成可视化图片""" + # 1. 计算训练/测试准确率 + train_pred = model.predict(X_train) + train_acc = np.sum(train_pred == y_train) / len(y_train) + test_pred = model.predict(X_test) + test_acc = np.sum(test_pred == y_test) / len(y_test) + + # 2. 生成图1:训练/测试准确率对比图 + plt.figure(figsize=(8, 5)) + plt.bar(['训练集准确率', '测试集准确率'], [train_acc, test_acc], color=['#2E86AB', '#A23B72']) + plt.ylim(0, 1.1) + plt.title('无人车雨雾检测模型准确率', fontsize=14) + plt.ylabel('准确率', fontsize=12) + # 添加数值标签 + plt.text(0, train_acc + 0.02, f'{train_acc:.4f}', ha='center', fontsize=12) + plt.text(1, test_acc + 0.02, f'{test_acc:.4f}', ha='center', fontsize=12) + plt.tight_layout() + plt.savefig('./rainfog_acc.png', dpi=150, bbox_inches='tight') # 保存图片 + print("✅ 准确率对比图已保存:rainfog_acc.png") + + # 3. 生成图2:特征分布散点图(雾度 vs 对比度) + plt.figure(figsize=(10, 8)) + colors = ['#F18F01', '#C73E1D', '#8B0000', '#000000'] # 清晰/轻度/中度/重度颜色 + labels = ['清晰', '轻度雨雾', '中度雨雾', '重度雨雾'] + for i in range(4): + mask = y_train == i + plt.scatter(X_train[mask, 0], X_train[mask, 1], c=colors[i], label=labels[i], alpha=0.7) + plt.xlabel('雾度', fontsize=12) + plt.ylabel('对比度', fontsize=12) + plt.title('雨雾天图像特征分布(雾度 vs 对比度)', fontsize=14) + plt.legend() + plt.grid(alpha=0.3) + plt.tight_layout() + plt.savefig('./rainfog_feature_dist.png', dpi=150, bbox_inches='tight') + print("✅ 特征分布图已保存:rainfog_feature_dist.png") + + # 4. 生成图3:各分类准确率详情 + plt.figure(figsize=(10, 6)) + class_acc = [] + for label in range(4): + mask = y_test == label + if np.sum(mask) == 0: + class_acc.append(0) + continue + acc = np.sum((test_pred == label) & mask) / np.sum(mask) + class_acc.append(acc) + + plt.bar(labels, class_acc, color=['#F18F01', '#C73E1D', '#8B0000', '#000000']) + plt.ylim(0, 1.1) + plt.title('各雨雾等级检测准确率', fontsize=14) + plt.ylabel('准确率', fontsize=12) + # 添加数值标签 + for i, acc in enumerate(class_acc): + plt.text(i, acc + 0.02, f'{acc:.4f}', ha='center', fontsize=12) + plt.tight_layout() + plt.savefig('./rainfog_class_acc.png', dpi=150, bbox_inches='tight') + print("✅ 分类准确率图已保存:rainfog_class_acc.png") + + # 输出评估结果 + print("\n===== 模型评估结果 =====") + print(f"训练集准确率: {train_acc:.4f}") + print(f"测试集准确率: {test_acc:.4f}") + print("\n各等级检测准确率:") + for i, label in enumerate(labels): + print(f" {label}: {class_acc[i]:.4f}") + + return train_acc, test_acc + + +# ===================== 5. 模拟单张图像预测 ===================== +def predict_simulated_image(feature_type, model): + """模拟单张图像预测""" + np.random.seed(42) + feature_map = { + 'clear': np.array([0.12, 0.78, 0.21, 0.82]), + 'light': np.array([0.28, 0.62, 0.16, 0.61]), + 'medium': np.array([0.52, 0.41, 0.09, 0.39]), + 'heavy': np.array([0.79, 0.22, 0.04, 0.18]) + } + features = feature_map.get(feature_type, feature_map['heavy']) + + X = features.reshape(1, -1) + pred_label = model.predict(X)[0] + pred_proba = model.predict_proba(X)[0] + + label_map = {0: '清晰', 1: '轻度雨雾', 2: '中度雨雾', 3: '重度雨雾'} + result = { + '预测等级': label_map[pred_label], + '置信度': { + '清晰': f"{pred_proba[0]:.4f}", + '轻度雨雾': f"{pred_proba[1]:.4f}", + '中度雨雾': f"{pred_proba[2]:.4f}", + '重度雨雾': f"{pred_proba[3]:.4f}" + }, + '原始特征': { + '雾度': features[0], + '对比度': features[1], + '边缘密度': features[2], + '饱和度': features[3] + } + } + return result + + +# ===================== 主函数(PyCharm入口) ===================== +if __name__ == "__main__": + # 创建保存图片的目录(如果不存在) + if not os.path.exists('./'): + os.makedirs('./') + + try: + print("===== 无人车雨雾天视觉效果检测程序(PyCharm版) =====") + + # 1. 生成模拟数据集 + print("\n【1/4】生成模拟数据集...") + X, y, feature_names = build_dataset() + + # 2. 划分训练/测试集 + print("\n【2/4】划分训练/测试集...") + split_idx = int(len(X) * 0.8) + 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. 训练KNN模型11 + print("\n【3/4】训练雨雾检测模型...") + model = SimpleKNNClassifier(k=5) + model.fit(X_train, y_train) + + # 4. 评估模型并生成可视化图片1112 + print("\n【4/4】评估模型并生成图片...") + train_acc, test_acc = evaluate_and_visualize(model, X_train, X_test, y_train, y_test, feature_names) + + # 5. 模拟预测(重度雨雾)11 + print("\n===== 单张图像预测示例(重度雨雾) =====") + result = predict_simulated_image('heavy', model) + for k, v in result.items(): + print(f" {k}: {v}") + + # 额外测试:预测轻度雨雾 + print("\n===== 单张图像预测示例(轻度雨雾) =====") + result_light = predict_simulated_image('light', model) + for k, v in result_light.items(): + print(f" {k}: {v}") + + print("\n🎉 程序运行完成!生成的图片:") + print(" - rainfog_acc.png(准确率对比图)") + print(" - rainfog_feature_dist.png(特征分布图)") + print(" - rainfog_class_acc.png(分类准确率图)") + + except Exception as e: + print(f"\n❌ 程序执行出错:{e}") + # 打印详细错误栈(方便调试) + import traceback + + traceback.print_exc() \ No newline at end of file