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
| import torch import torch.nn as nn import torch.nn.functional as F from typing import Tuple
class DCDDModel(nn.Module): """ DCDD: Driver Cognitive Distraction Detection Model 基于眼动行为的认知分心检测模型 参考论文: "Driver Cognitive Distraction Detection based on eye movement behavior and integration of multi-view space-channel feature" Expert Systems with Applications, 2024 """ def __init__(self, input_dim: int = 20, hidden_dim: int = 128, num_heads: int = 4, num_layers: int = 2, dropout: float = 0.1): super().__init__() self.input_dim = input_dim self.hidden_dim = hidden_dim self.input_projection = nn.Linear(input_dim, hidden_dim) self.spatial_conv = nn.ModuleList([ nn.Conv1d(hidden_dim, hidden_dim, kernel_size=k, padding=k//2) for k in [3, 5, 7] ]) self.temporal_encoder = nn.LSTM( hidden_dim, hidden_dim // 2, num_layers=num_layers, batch_first=True, bidirectional=True, dropout=dropout ) self.channel_attention = nn.Sequential( nn.Linear(hidden_dim * 3, hidden_dim), nn.ReLU(), nn.Linear(hidden_dim, hidden_dim * 3), nn.Sigmoid() ) self.self_attention = nn.MultiheadAttention( hidden_dim * 3, num_heads, dropout=dropout, batch_first=True ) self.classifier = nn.Sequential( nn.Linear(hidden_dim * 3, hidden_dim), nn.ReLU(), nn.Dropout(dropout), nn.Linear(hidden_dim, 64), nn.ReLU(), nn.Dropout(dropout), nn.Linear(64, 2) ) def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: """ 前向传播 Args: x: 输入特征, shape=(batch, seq_len, input_dim) Returns: logits: 分类 logits attention_weights: 注意力权重 """ batch_size, seq_len, _ = x.shape x = self.input_projection(x) x_transposed = x.transpose(1, 2) spatial_features = [] for conv in self.spatial_conv: spatial_features.append(conv(x_transposed)) spatial_features = torch.cat(spatial_features, dim=1) spatial_features = spatial_features.transpose(1, 2) channel_weights = self.channel_attention( spatial_features.mean(dim=1) ) spatial_features = spatial_features * channel_weights.unsqueeze(1) temporal_features, _ = self.temporal_encoder(x) fused_features = torch.cat([ spatial_features, temporal_features.unsqueeze(-1).expand(-1, -1, -1, 3).reshape(batch_size, seq_len, -1) ], dim=-1)[:, :, :self.hidden_dim * 3] attended_features, attention_weights = self.self_attention( fused_features, fused_features, fused_features ) global_features = attended_features.mean(dim=1) logits = self.classifier(global_features) return logits, attention_weights
class DCDDPipeline: """ DCDD 完整检测管道 """ def __init__(self, model_path: str = None, device: str = 'cuda' if torch.cuda.is_available() else 'cpu'): self.device = device self.feature_extractor = EyeMovementFeatureExtractor() self.model = DCDDModel() if model_path: self.model.load_state_dict(torch.load(model_path, map_location=device)) self.model.to(device) self.model.eval() self.gaze_buffer = [] self.buffer_size = 300 def update(self, gaze_point: GazePoint) -> dict: """ 更新检测状态 Args: gaze_point: 当前注视点 Returns: result: 检测结果 """ self.gaze_buffer.append(gaze_point) if len(self.gaze_buffer) > self.buffer_size: self.gaze_buffer.pop(0) if len(self.gaze_buffer) >= self.buffer_size: return self._detect() else: return { 'cognitive_distraction': False, 'confidence': 0.0, 'status': 'warming_up' } def _detect(self) -> dict: """执行检测""" with torch.no_grad(): features = self.feature_extractor.extract_features(self.gaze_buffer) if not features: return { 'cognitive_distraction': False, 'confidence': 0.0, 'status': 'insufficient_data' } feature_vector = torch.tensor( list(features.values()) ).float().unsqueeze(0).unsqueeze(0).to(self.device) logits, attention_weights = self.model(feature_vector) probs = F.softmax(logits, dim=-1) return { 'cognitive_distraction': probs[0, 1].item() > 0.5, 'confidence': probs[0, 1].item(), 'probabilities': { 'normal': probs[0, 0].item(), 'distracted': probs[0, 1].item() }, 'status': 'detected', 'features': features }
if __name__ == "__main__": np.random.seed(42) pipeline = DCDDPipeline() for i in range(300): if i < 150: x = np.random.normal(960, 200) y = np.random.normal(540, 150) else: x = np.random.normal(960, 50) y = np.random.normal(540, 30) gaze_point = GazePoint( timestamp=i / 30.0, x=x, y=y, pupil_diameter=np.random.normal(4.0, 0.5) ) result = pipeline.update(gaze_point) if i % 50 == 0: print(f"Frame {i}: Cognitive Distraction = {result['cognitive_distraction']}, " f"Confidence = {result.get('confidence', 0):.2f}") print("\n最终检测结果:") print(f"认知分心: {result['cognitive_distraction']}") print(f"置信度: {result['confidence']:.2f}")
|