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 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
| """ SAHQNN: 自注意力混合量子神经网络 驾驶员认知分心检测
论文复现: Electronics (MDPI), 2025 DOI: 10.3390/electronics15153342
包含: 1. ECG/RSP 信号预处理与特征提取 2. 自注意力机制 3. 参数化量子电路 (PQC) 模拟 4. 混合分类器
注意: 量子部分使用模拟器 (无真实量子硬件) 依赖: pip install numpy scipy torch pennylane scikit-learn matplotlib """
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from scipy.signal import butter, filtfilt, find_peaks from typing import Tuple, Optional from sklearn.metrics import classification_report, accuracy_score import warnings warnings.filterwarnings('ignore')
try: import pennylane as qml QUA_MISSING = False except ImportError: QUA_MISSING = True
class ECGPreprocessor: """ECG 信号预处理""" def __init__(self, sample_rate: int = 256): self.fs = sample_rate def bandpass_filter(self, signal: np.ndarray, low: float = 0.5, high: float = 40.0) -> np.ndarray: """带通滤波: 0.5-40 Hz (保留心电主成分)""" nyq = self.fs / 2 b, a = butter(4, [low/nyq, high/nyq], btype='band') return filtfilt(b, a, signal) def extract_hrv_features(self, ecg: np.ndarray) -> np.ndarray: """ 提取心率变异性特征 Returns: features: shape=(10,) HRV特征向量 """ filtered = self.bandpass_filter(ecg) peaks, _ = find_peaks(filtered, height=0.5*np.max(filtered), distance=0.6*self.fs) if len(peaks) < 3: return np.zeros(10) rr = np.diff(peaks) / self.fs mean_rr = np.mean(rr) sdnn = np.std(rr) rmssd = np.sqrt(np.mean(np.diff(rr) ** 2)) pnn50 = np.sum(np.abs(np.diff(rr)) > 0.05) / len(rr) * 100 rr_interp = np.interp( np.linspace(0, len(rr)/mean_rr, 256), np.arange(len(rr))/mean_rr, rr ) fft = np.abs(np.fft.rfft(rr_interp)) freqs = np.fft.rfftfreq(256, d=1/mean_rr) lf = np.sum(fft[(freqs >= 0.04) & (freqs < 0.15)]) hf = np.sum(fft[(freqs >= 0.15) & (freqs < 0.4)]) lf_hf = lf / (hf + 1e-8) sd1 = np.sqrt(0.5 * np.var(rr[1:] - rr[:-1])) sd2 = np.sqrt(0.5 * np.var(rr[1:] + rr[:-1])) return np.array([ mean_rr, sdnn, rmssd, pnn50, lf, hf, lf_hf, sd1, sd2, len(peaks) ])
class RSPPreprocessor: """呼吸信号预处理""" def __init__(self, sample_rate: int = 128): self.fs = sample_rate def extract_features(self, rsp: np.ndarray) -> np.ndarray: """提取呼吸特征""" nyq = self.fs / 2 b, a = butter(4, [0.1/nyq, 0.5/nyq], btype='band') filtered = filtfilt(b, a, rsp) fft = np.abs(np.fft.rfft(filtered)) freqs = np.fft.rfftfreq(len(filtered), d=1/self.fs) peak_idx = np.argmax(fft) resp_rate = freqs[peak_idx] * 60 amplitude = np.std(filtered) peaks, _ = find_peaks(filtered, distance=2*self.fs) if len(peaks) > 2: rr_var = np.std(np.diff(peaks)) else: rr_var = 0 return np.array([resp_rate, amplitude, rr_var, np.mean(filtered)])
class SelfAttention(nn.Module): """自注意力模块""" def __init__(self, dim: int, heads: int = 4): super().__init__() self.heads = heads self.scale = dim ** -0.5 self.q = nn.Linear(dim, dim) self.k = nn.Linear(dim, dim) self.v = nn.Linear(dim, dim) self.out = nn.Linear(dim, dim) def forward(self, x): B, T, D = x.shape H = self.heads q = self.q(x).reshape(B, T, H, D//H).transpose(1, 2) k = self.k(x).reshape(B, T, H, D//H).transpose(1, 2) v = self.v(x).reshape(B, T, H, D//H).transpose(1, 2) attn = (q @ k.transpose(-2, -1)) * self.scale attn = F.softmax(attn, dim=-1) out = (attn @ v).transpose(1, 2).reshape(B, T, D) return self.out(out)
class PQCQuantumLayer: """ 参数化量子电路 (PQC) 模拟层 使用 PennyLane 模拟量子电路 无量子硬件时回退到经典近似 """ def __init__(self, n_qubits: int = 4, n_layers: int = 2): self.n_qubits = n_qubits self.n_layers = n_layers self.n_params = n_qubits * n_layers + (n_layers - 1) * n_qubits if not QUA_MISSING: self.dev = qml.device('default.qubit', wires=n_qubits) self.circuit = self._build_circuit() else: np.random.seed(42) self.proj = np.random.randn(self.n_params, n_qubits) * 0.1 def _build_circuit(self): @qml.qnode(self.dev) def circuit(inputs, params): for i in range(self.n_qubits): qml.RY(inputs[i], wires=i) for layer in range(self.n_layers): for i in range(self.n_qubits): qml.RY(params[layer * self.n_qubits + i], wires=i) for i in range(self.n_qubits - 1): qml.CNOT(wires=[i, i + 1]) if self.n_qubits > 2: qml.CNOT(wires=[self.n_qubits - 1, 0]) return [qml.expval(qml.PauliZ(i)) for i in range(self.n_qubits)] return circuit def forward(self, x: np.ndarray, params: np.ndarray = None) -> np.ndarray: """ 量子电路前向传播 Args: x: 输入特征 (n_qubits,) params: PQC参数 Returns: quantum_features: (n_qubits,) 测量值 """ if params is None: params = np.random.uniform(0, 2*np.pi, self.n_params) if not QUA_MISSING: result = self.circuit(x, params) return np.array(result) else: return np.tanh(self.proj.T @ x[:min(len(x), self.n_params)])
class SAHQNN(nn.Module): """ 自注意力混合量子神经网络 (SAHQNN) 架构: 1. CNN 特征提取 (ECG/RSP) 2. 自注意力时序加权 3. 降维到量子编码维度 4. PQC 量子特征提取 5. 经典分类器 """ def __init__(self, input_channels: int = 2, feature_dim: int = 64, hidden_dim: int = 128, n_classes: int = 3, n_qubits: int = 4, use_quantum: bool = True): super().__init__() self.use_quantum = use_quantum self.cnn = nn.Sequential( nn.Conv1d(input_channels, 32, 7, stride=2, padding=3), nn.BatchNorm1d(32), nn.ReLU(), nn.MaxPool1d(2), nn.Conv1d(32, 64, 5, stride=2, padding=2), nn.BatchNorm1d(64), nn.ReLU(), nn.MaxPool1d(2), nn.Conv1d(64, feature_dim, 3, padding=1), nn.BatchNorm1d(feature_dim), nn.ReLU(), nn.AdaptiveAvgPool1d(16), ) self.attention = SelfAttention(feature_dim, heads=4) self.norm = nn.LayerNorm(feature_dim) self.feature_reduce = nn.Sequential( nn.Linear(feature_dim, hidden_dim), nn.ReLU(), nn.Linear(hidden_dim, n_qubits), ) if use_quantum: self.pqc = PQCQuantumLayer(n_qubits=n_qubits, n_layers=2) quantum_out_dim = n_qubits else: quantum_out_dim = n_qubits self.classifier = nn.Sequential( nn.Linear(quantum_out_dim + hidden_dim, 64), nn.ReLU(), nn.Dropout(0.3), nn.Linear(64, n_classes) ) if use_quantum and hasattr(self, 'pqc'): self.pqc_params = nn.Parameter( torch.uniform(0, 2*np.pi, (self.pqc.n_params,)) ) def forward(self, x): """ Args: x: (B, C, L) 多通道时序信号 Returns: logits: (B, n_classes) """ feat = self.cnn(x) feat = feat.transpose(1, 2) attn_out = self.attention(feat) feat = self.norm(feat + attn_out) feat_flat = feat.mean(dim=1) reduced = self.feature_reduce(feat_flat) if self.use_quantum: quantum_features = [] for b in range(x.shape[0]): qf = self.pqc.forward( reduced[b].detach().cpu().numpy(), self.pqc_params.detach().cpu().numpy() ) quantum_features.append(qf) quantum_features = torch.tensor(quantum_features, device=x.device, dtype=torch.float32) else: quantum_features = torch.tanh(reduced) combined = torch.cat([quantum_features, feat_flat], dim=1) logits = self.classifier(combined) return logits
if __name__ == "__main__": print("=" * 70) print("SAHQNN: 量子神经网络驾驶员认知分心检测") print("论文: Electronics (MDPI), 2025") print("DOI: 10.3390/electronics15153342") print("=" * 70) print("\n=== 信号预处理测试 ===") ecg_pre = ECGPreprocessor(sample_rate=256) rsp_pre = RSPPreprocessor(sample_rate=128) t = np.linspace(0, 10, 2560) normal_ecg = 0.5 * np.sin(2 * np.pi * 1.2 * t) normal_ecg += 0.1 * np.random.randn(2560) normal_ecg[np.arange(0, 2560, int(256/1.2))] += 2.0 distracted_ecg = 0.5 * np.sin(2 * np.pi * 1.4 * t) distracted_ecg += 0.15 * np.random.randn(2560) distracted_ecg[np.arange(0, 2560, int(256/1.4))] += 2.0 normal_rsp = 0.3 * np.sin(2 * np.pi * 0.25 * np.linspace(0, 10, 1280)) distracted_rsp = 0.4 * np.sin(2 * np.pi * 0.30 * np.linspace(0, 10, 1280)) normal_hrv = ecg_pre.extract_hrv_features(normal_ecg) distracted_hrv = ecg_pre.extract_hrv_features(distracted_ecg) normal_rsp_f = rsp_pre.extract_features(normal_rsp) distracted_rsp_f = rsp_pre.extract_features(distracted_rsp) print(f"正常: HRV特征 = {normal_hrv[:4]}") print(f" RSP特征 = {normal_rsp_f}") print(f"分心: HRV特征 = {distracted_hrv[:4]}") print(f" RSP特征 = {distracted_rsp_f}") print(f"\n=== 量子电路 (PQC) 测试 ===") if not QUA_MISSING: print(f"PennyLane 量子模拟器: 可用") pqc = PQCQuantumLayer(n_qubits=4, n_layers=2) print(f"量子比特数: {pqc.n_qubits}") print(f"参数数: {pqc.n_params}") test_input = np.array([0.1, 0.2, -0.1, 0.3]) output = pqc.forward(test_input) print(f"输入: {test_input}") print(f"量子输出: {output}") print(f"输出范围: [{output.min():.3f}, {output.max():.3f}]") else: print(f"PennyLane 不可用, 使用经典近似") pqc = PQCQuantumLayer(n_qubits=4, n_layers=2) output = pqc.forward(np.array([0.1, 0.2, -0.1, 0.3])) print(f"近似输出: {output}") print(f"\n=== SAHQNN 完整模型测试 ===") model = SAHQNN( input_channels=2, feature_dim=64, hidden_dim=128, n_classes=3, n_qubits=4, use_quantum=not QUA_MISSING ) batch_size = 8 seq_len = 2560 X_normal = torch.randn(batch_size, 2, seq_len) * 0.5 X_distracted = torch.randn(batch_size, 2, seq_len) * 0.5 + 0.3 with torch.no_grad(): out_normal = model(X_normal) out_distracted = model(X_distracted) print(f"输入: {X_normal.shape}") print(f"输出: {out_normal.shape}") print(f"正常驾驶 logits: {out_normal[0]}") print(f"分心驾驶 logits: {out_distracted[0]}") total = sum(p.numel() for p in model.parameters()) trainable = sum(p.numel() for p in model.parameters() if p.requires_grad) print(f"\n模型参数量: {total:,} ({total/1e6:.2f}M)") print(f"可训练参数: {trainable:,} ({trainable/1e6:.2f}M)") print(f"\n=== 分类性能 (论文报告) ===") print(f"{'方法':<25s} {'准确率':>8s} {'F1':>8s} {'AUC':>8s}") print(f"{'SAHQNN (本文)':<25s} {'92.3%':>8s} {'91.5%':>8s} {'0.95':>8s}") print(f"{'CNN + Self-Attention':<25s} {'88.7%':>8s} {'87.2%':>8s} {'0.92':>8s}") print(f"{'经典 CNN':<25s} {'85.1%':>8s} {'83.8%':>8s} {'0.89':>8s}") print(f"{'SVM + 手工特征':<25s} {'78.4%':>8s} {'77.1%':>8s} {'0.82':>8s}") print(f"\n量子优势: +3.6pp (vs CNN+Attention), +7.2pp (vs CNN)")
|