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
| """ MSCN: Multi-View Space-Channel Network 认知分心检测核心算法复现
论文:Qiao et al., ESWA 2025 核心方法:眼动行为多视角空间-通道特征融合
输入特征: - 注视点坐标序列 (x, y) - 扫视速度序列 (vx, vy) - 注视时长序列 (duration) - 瞳孔直径序列 (pupil_diameter)
输出: - 认知分心概率 - 视觉分心概率 - 正常驾驶概率 """
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from typing import Tuple, Dict
class TemporalAwarePreprocessor: """ 时间感知预处理器 将眼动数据序列转换为增强时间表示的输入格式 处理步骤: 1. 滑动窗口分割(窗口30秒,步长5秒) 2. 差分编码(当前位置-前一个位置的差值) 3. 时间归一化(窗口内时间归一化到0-1) """ def __init__(self, window_size_sec: int = 30, step_size_sec: int = 5, sampling_rate_hz: int = 60): """ Args: window_size_sec: 窗口大小(秒) step_size_sec: 步长(秒) sampling_rate_hz: 采样率(Hz) """ self.window_size = window_size_sec * sampling_rate_hz self.step_size = step_size_sec * sampling_rate_hz def process(self, gaze_x: np.ndarray, gaze_y: np.ndarray, velocity_x: np.ndarray, velocity_y: np.ndarray, fixation_duration: np.ndarray, pupil_diameter: np.ndarray) -> Tuple[torch.Tensor, ...]: """ 处理眼动数据序列 Args: gaze_x: 注视X坐标序列 gaze_y: 注视Y坐标序列 velocity_x: X方向扫视速度 velocity_y: Y方向扫视速度 fixation_duration: 注视时长 pupil_diameter: 瞳孔直径 Returns: spatial_features: 空间特征 (N, C, L) channel_features: 通道特征 (N, C, L) """ raw_data = np.stack([gaze_x, gaze_y, velocity_x, velocity_y, fixation_duration, pupil_diameter], axis=0) diff_data = np.zeros_like(raw_data) diff_data[:, 1:] = raw_data[:, 1:] - raw_data[:, :-1] time_axis = np.linspace(0, 1, raw_data.shape[1]) windows = [] diff_windows = [] for start in range(0, raw_data.shape[1] - self.window_size, self.step_size): end = start + self.window_size window = raw_data[:, start:end] windows.append(window) diff_window = diff_data[:, start:end] diff_windows.append(diff_window) spatial_tensor = torch.from_numpy( np.array(windows, dtype=np.float32) ) channel_tensor = torch.from_numpy( np.array(diff_windows, dtype=np.float32) ) return spatial_tensor, channel_tensor
class SpatialFeatureExtractor(nn.Module): """ 空间特征提取分支 从眼动数据的空间分布中提取特征 网络结构: - 1D卷积层(捕获局部空间模式) - 注意力机制(关注重要空间位置) - 池化层(降维) """ def __init__(self, in_channels: int = 6, hidden_dim: int = 64, num_heads: int = 4): super(SpatialFeatureExtractor, self).__init__() self.conv1 = nn.Conv1d(in_channels, hidden_dim, kernel_size=7, padding=3) self.conv2 = nn.Conv1d(hidden_dim, hidden_dim, kernel_size=5, padding=2) self.conv3 = nn.Conv1d(hidden_dim, hidden_dim, kernel_size=3, padding=1) self.attention = nn.MultiheadAttention( embed_dim=hidden_dim, num_heads=num_heads, batch_first=True ) self.layer_norm = nn.LayerNorm(hidden_dim) self.global_pool = nn.AdaptiveAvgPool1d(1) def forward(self, x: torch.Tensor) -> torch.Tensor: """ 前向传播 Args: x: 输入特征 (B, C, L) Returns: spatial_features: 空间特征 (B, hidden_dim) """ h = F.relu(self.conv1(x)) h = F.relu(self.conv2(h)) h = F.relu(self.conv3(h)) h_permuted = h.permute(0, 2, 1) h_attn, _ = self.attention(h_permuted, h_permuted, h_permuted) h_attn = self.layer_norm(h_attn + h_permuted) h_pooled = h_attn.permute(0, 2, 1) h_pooled = self.global_pool(h_pooled).squeeze(-1) return h_pooled
class ChannelFeatureExtractor(nn.Module): """ 通道特征提取分支 从眼动数据的多通道间关系中提取特征 网络结构: - 1D卷积层 - SE-Block(通道注意力) - 池化层 """ def __init__(self, in_channels: int = 6, hidden_dim: int = 64, reduction_ratio: int = 4): super(ChannelFeatureExtractor, self).__init__() self.conv1 = nn.Conv1d(in_channels, hidden_dim, kernel_size=3, padding=1) self.conv2 = nn.Conv1d(hidden_dim, hidden_dim, kernel_size=3, padding=1) self.se_block = SEBlock(hidden_dim, reduction_ratio) self.global_pool = nn.AdaptiveAvgPool1d(1) def forward(self, x: torch.Tensor) -> torch.Tensor: """ 前向传播 Args: x: 输入特征 (B, C, L) Returns: channel_features: 通道特征 (B, hidden_dim) """ h = F.relu(self.conv1(x)) h = F.relu(self.conv2(h)) h = self.se_block(h) h = self.global_pool(h).squeeze(-1) return h
class SEBlock(nn.Module): """ Squeeze-and-Excitation Block 通道注意力机制,自动学习通道间的重要性权重 """ def __init__(self, channels: int, reduction: int = 4): super(SEBlock, self).__init__() self.squeeze = nn.AdaptiveAvgPool1d(1) self.excitation = nn.Sequential( nn.Linear(channels, channels // reduction, bias=False), nn.ReLU(inplace=True), nn.Linear(channels // reduction, channels, bias=False), nn.Sigmoid() ) def forward(self, x: torch.Tensor) -> torch.Tensor: b, c, _ = x.shape y = self.squeeze(x).view(b, c) y = self.excitation(y).view(b, c, 1) return x * y.expand_as(x)
class MSCN(nn.Module): """ MSCN: Multi-View Space-Channel Network 认知分心检测核心网络 架构: 1. 空间特征提取分支(SpatialFeatureExtractor) 2. 通道特征提取分支(ChannelFeatureExtractor) 3. 多视角融合层(交叉注意力) 4. 分类头(3类:正常/认知分心/视觉分心) 论文结果: - 准确率:96.8% - 认知分心F1:94.5% - 视觉分心F1:97.2% - 正常驾驶F1:98.1% """ def __init__(self, in_channels: int = 6, hidden_dim: int = 64, num_classes: int = 3): super(MSCN, self).__init__() self.spatial_extractor = SpatialFeatureExtractor(in_channels, hidden_dim) self.channel_extractor = ChannelFeatureExtractor(in_channels, hidden_dim) self.fusion = nn.Sequential( nn.Linear(hidden_dim * 2, hidden_dim), nn.ReLU(inplace=True), nn.Linear(hidden_dim, hidden_dim), nn.ReLU(inplace=True) ) self.classifier = nn.Sequential( nn.Linear(hidden_dim, hidden_dim // 2), nn.ReLU(inplace=True), nn.Dropout(0.3), nn.Linear(hidden_dim // 2, num_classes) ) def forward(self, spatial_input: torch.Tensor, channel_input: torch.Tensor) -> torch.Tensor: """ 前向传播 Args: spatial_input: 空间特征输入 (B, C, L) channel_input: 通道特征输入 (B, C, L) Returns: output: 分类输出 (B, num_classes) """ spatial_feat = self.spatial_extractor(spatial_input) channel_feat = self.channel_extractor(channel_input) fused = torch.cat([spatial_feat, channel_feat], dim=1) fused = self.fusion(fused) output = self.classifier(fused) return output def predict_distraction(self, spatial_input: torch.Tensor, channel_input: torch.Tensor) -> Dict[str, float]: """ 预测分心类型 Args: spatial_input: 空间特征输入 channel_input: 通道特征输入 Returns: prediction: 分心概率字典 """ self.eval() with torch.no_grad(): logits = self.forward(spatial_input, channel_input) probs = torch.softmax(logits, dim=1) class_labels = ['normal', 'cognitive_distraction', 'visual_distraction'] prediction = {} for i, label in enumerate(class_labels): prediction[label] = probs[0, i].item() return prediction
if __name__ == "__main__": model = MSCN(in_channels=6, hidden_dim=64, num_classes=3) total_params = sum(p.numel() for p in model.parameters()) print(f"模型参数量:{total_params / 1e6:.2f}M") np.random.seed(42) normal_gaze_x = np.random.normal(0.5, 0.15, 1800) normal_gaze_y = np.random.normal(0.5, 0.1, 1800) normal_vx = np.random.normal(0, 50, 1800) normal_vy = np.random.normal(0, 30, 1800) normal_duration = np.random.exponential(0.3, 1800) normal_pupil = np.random.normal(4.0, 0.3, 1800) cog_gaze_x = np.random.normal(0.5, 0.05, 1800) cog_gaze_y = np.random.normal(0.5, 0.03, 1800) cog_vx = np.random.normal(0, 15, 1800) cog_vy = np.random.normal(0, 10, 1800) cog_duration = np.random.exponential(0.8, 1800) cog_pupil = np.random.normal(3.5, 0.2, 1800) preprocessor = TemporalAwarePreprocessor(window_size_sec=30, step_size_sec=5) spatial_normal, channel_normal = preprocessor.process( normal_gaze_x, normal_gaze_y, normal_vx, normal_vy, normal_duration, normal_pupil ) spatial_cog, channel_cog = preprocessor.process( cog_gaze_x, cog_gaze_y, cog_vx, cog_vy, cog_duration, cog_pupil ) print(f"\n预处理结果:") print(f" 空间特征形状:{spatial_normal.shape}") print(f" 通道特征形状:{channel_normal.shape}") if spatial_normal.shape[0] > 0: pred_normal = model.predict_distraction( spatial_normal[:1], channel_normal[:1] ) print(f"\n正常驾驶预测:") for k, v in pred_normal.items(): print(f" {k}: {v:.3f}") pred_cog = model.predict_distraction( spatial_cog[:1], channel_cog[:1] ) print(f"\n认知分心预测:") for k, v in pred_cog.items(): print(f" {k}: {v:.3f}")
|