1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
| """ 3D-CRNN: 3D CNN + RNN 联合 EEG 解码
论文核心模型: 1. 3D CNN: 提取 EEG 时空频特征 (通道×时间×频率) 2. RNN (GRU): 建模时序依赖 3. 分类头: RP + DI 双任务
输入: EEG (C×T×F) — 通道×时间×频率 输出: RP logits + DI logits """
import torch import torch.nn as nn import torch.nn.functional as F from typing import Dict, Tuple, Optional import numpy as np
class EEG3DCNN(nn.Module): """ 3D CNN: EEG 时空频特征提取 输入: (B, C, T, F) — 通道×时间×频率 输出: (B, D, T') — 时序特征 论文使用 3D 卷积捕获通道-时间-频率联合模式 """ def __init__(self, n_channels: int = 32, n_freq_bins: int = 8, hidden_dim: int = 128): super().__init__() self.conv1 = nn.Sequential( nn.Conv3d(1, 16, kernel_size=(3, 5, 3), stride=(1, 1, 1), padding=(1, 2, 1)), nn.BatchNorm3d(16), nn.ELU(), nn.MaxPool3d(kernel_size=(1, 2, 1)) ) self.conv2 = nn.Sequential( nn.Conv3d(16, 32, kernel_size=(3, 3, 3), stride=(1, 1, 1), padding=(1, 1, 1)), nn.BatchNorm3d(32), nn.ELU(), nn.MaxPool3d(kernel_size=(1, 2, 1)) ) self.conv3 = nn.Sequential( nn.Conv3d(32, hidden_dim, kernel_size=(3, 3, 1), stride=(1, 1, 1), padding=(1, 1, 0)), nn.BatchNorm3d(hidden_dim), nn.ELU(), nn.AdaptiveAvgPool3d((1, None, 1)) ) def forward(self, x: torch.Tensor) -> torch.Tensor: """ Args: x: (B, 1, C, T, F) — 批×通道×时间×频率 Returns: features: (B, D, T') — 时序特征 """ x = self.conv1(x) x = self.conv2(x) x = self.conv3(x) return x.squeeze(2).squeeze(-1)
class TemporalRNN(nn.Module): """GRU 时序建模""" def __init__(self, hidden_dim: int = 128, n_layers: int = 2): super().__init__() self.gru = nn.GRU( hidden_dim, hidden_dim, num_layers=n_layers, batch_first=True, dropout=0.3 if n_layers > 1 else 0 ) def forward(self, x: torch.Tensor) -> torch.Tensor: """x: (B, D, T) → (B, T, D)""" x = x.transpose(1, 2) out, _ = self.gru(x) return out
class RiskAwareSequentialLabeling(nn.Module): """ RSL: 风险感知序列标注 论文核心改进: 利用时间序列标签 - 标准 DI: 每个时间点独立分类 - RSL: 利用前后时序上下文修正标签 DI 从 80.9% → 85.0% BA """ def __init__(self, hidden_dim: int = 128, n_classes: int = 2): super().__init__() self.label_generator = nn.Sequential( nn.Linear(hidden_dim, hidden_dim), nn.GELU(), nn.Dropout(0.3), nn.Linear(hidden_dim, n_classes) ) self.transition = nn.Parameter( torch.randn(n_classes, n_classes) * 0.1 ) def forward(self, x: torch.Tensor) -> Dict[str, torch.Tensor]: """ Args: x: (B, T, D) Returns: logits: (B, T, n_classes) """ logits = self.label_generator(x) return {'logits': logits, 'transition': self.transition}
class ThreeDCRNN(nn.Module): """ 3D-CRNN: 完整模型 管道: 1. EEG → STFT → (C, T, F) 2. 3D CNN → 时空频特征 3. GRU → 时序依赖 4. RP 头 + DI/RSL 头 双任务: - RP (Risk Prediction): 预测未来风险 - DI (Danger Identification): 识别当前危险 """ def __init__(self, n_channels: int = 32, n_freq_bins: int = 8, hidden_dim: int = 128, n_classes: int = 2): super().__init__() self.cnn = EEG3DCNN(n_channels, n_freq_bins, hidden_dim) self.rnn = TemporalRNN(hidden_dim, n_layers=2) self.rp_head = nn.Linear(hidden_dim, n_classes) self.di_head = RiskAwareSequentialLabeling(hidden_dim, n_classes) def forward(self, eeg_stft: torch.Tensor) -> Dict[str, torch.Tensor]: """ Args: eeg_stft: (B, 1, C, T, F) — EEG STFT Returns: rp_logits: (B, n_classes) — 风险预测 di_logits: (B, T, n_classes) — 危险识别序列 """ features = self.cnn(eeg_stft) temporal = self.rnn(features) pooled = temporal.mean(dim=1) rp_logits = self.rp_head(pooled) di_output = self.di_head(temporal) return { 'rp_logits': rp_logits, 'di_logits': di_output['logits'], 'transition': di_output['transition'], 'features': temporal }
class PassengerCognitiveSupervisor: """ IMS 乘客认知辅助监督系统 基于 EEG 危险感知论文方法 应用: 1. SOTIF 辅助: 乘客 EEG 可提供额外安全监督 2. AV 决策辅助: 乘客感知到危险 → AV 减速/避让 3. 信任度评估: 乘客 EEG 反映对 AV 的信任 4. 个性化: 不同乘客的风险感知阈值不同 非侵入式 EEG 方案: - 头靠嵌入式 EEG 电极 (无需佩戴头套) - 耳道 EEG (消费级耳塞) - 近期可行: 商用头靠 EEG 已有 """ def __init__(self): self.model = ThreeDCRNN(n_channels=8, n_freq_bins=8, hidden_dim=64) self.rp_threshold = 0.7 self.di_threshold = 0.6 def monitor(self, eeg_stft: np.ndarray) -> dict: """ 监控乘客认知状态 Args: eeg_stft: (1, 1, C, T, F) EEG STFT Returns: cognitive_state: { 'risk_prediction': float, # 0-1 'danger_identification': list, # T 个时间点 'risk_level': int, 'action': str, 'av_supervision': str # AV 辅助建议 } """ with torch.no_grad(): output = self.model(torch.from_numpy(eeg_stft).float()) rp_prob = F.softmax(output['rp_logits'], dim=-1)[0, 1].item() di_probs = F.softmax(output['di_logits'], dim=-1) di_sequence = di_probs[0, :, 1].tolist() if rp_prob > 0.8: risk_level = 3 action = '紧急: 乘客感知高风险, AV 应立即减速' elif rp_prob > self.rp_threshold: risk_level = 2 action = '警告: 乘客感知风险, AV 应提高警惕' elif rp_prob > 0.5: risk_level = 1 action = '注意: 乘客轻度不安, 记录' else: risk_level = 0 action = '正常: 乘客认知状态平稳' if risk_level >= 2: av_supervision = 'SOTIF: 乘客认知信号触发额外安全检查' else: av_supervision = '正常模式' return { 'risk_prediction': rp_prob, 'danger_identification': di_sequence, 'risk_level': risk_level, 'action': action, 'av_supervision': av_supervision }
if __name__ == "__main__": print("=== 3D-CRNN EEG 模型测试 ===") model = ThreeDCRNN(n_channels=32, n_freq_bins=8, hidden_dim=128) B, C, T, F = 4, 32, 100, 8 eeg_stft = torch.randn(B, 1, C, T, F) output = model(eeg_stft) print(f"输入: EEG STFT {eeg_stft.shape}") print(f"RP logits: {output['rp_logits'].shape}") print(f"DI logits: {output['di_logits'].shape}") total = sum(p.numel() for p in model.parameters()) print(f"参数量: {total:,}") supervisor = PassengerCognitiveSupervisor() scenarios = { '正常驾驶': np.random.randn(1, 1, 8, 50, 8) * 0.3, '前车急刹': np.random.randn(1, 1, 8, 50, 8) * 1.5 + 0.8, '行人横穿': np.random.randn(1, 1, 8, 50, 8) * 1.2 + 0.5, } print(f"\n=== 乘客认知监控测试 ===") for name, eeg in scenarios.items(): result = supervisor.monitor(eeg) print(f"\n{name}:") print(f" 风险预测: {result['risk_prediction']:.2f}") print(f" 风险等级: {result['risk_level']}") print(f" 动作: {result['action']}") print(f" AV 辅助: {result['av_supervision']}") print(f"\n=== 论文性能报告 ===") print(f"{'任务':<25} {'方法':<15} {'BA':<10} {'±'}") print(f"{'RP (Risk Prediction)':<25} {'3D-CRNN':<15} {'95.3%':<10} {'2.7%'}") print(f"{'DI (单标签)':<25} {'3D-CRNN':<15} {'80.9%':<10} {'3.9%'}") print(f"{'DI + RSL':<25} {'3D-CRNN+RSL':<15} {'85.0%':<10} {'3.2%'}") print(f"{'跨会话 DI':<25} {'3D-CRNN':<15} {'77.0%':<10} {'5.3%'}") print(f"{'跨被试 (已见)':<25} {'3D-CRNN':<15} {'77.4%':<10} {'1.1%'}") print(f"{'跨被试 (未见)':<25} {'3D-CRNN':<15} {'64.9%':<10} {'8.5%'}")
|