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
| """ EyeCue: 视线增强的认知分心检测 """
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np
class EyeCue(nn.Module): """ EyeCue: Gaze-Empowered Egocentric Video Understanding for Cognitive Distraction Detection """ def __init__(self, config: dict): super().__init__() self.config = config self.video_encoder = VideoEncoder( d_model=config['video_dim'], num_frames=config['num_frames'] ) self.gaze_encoder = GazeEncoder( d_model=config['gaze_dim'], num_points=config['num_gaze_points'] ) self.cross_attention = CrossModalAttention( video_dim=config['video_dim'], gaze_dim=config['gaze_dim'], fusion_dim=config['fusion_dim'] ) self.classifier = nn.Sequential( nn.Linear(config['fusion_dim'], config['fusion_dim'] // 2), nn.ReLU(), nn.Dropout(config['dropout']), nn.Linear(config['fusion_dim'] // 2, config['num_classes']) ) def forward(self, video, gaze_sequence, gaze_heatmap=None): """ Args: video: [B, T, C, H, W] 第一人称视频 gaze_sequence: [B, T, 2] 注视点序列 gaze_heatmap: [B, T, H, W] 注视点热力图(可选) Returns: logits: [B, num_classes] 认知状态 """ video_feat = self.video_encoder(video) gaze_feat = self.gaze_encoder(gaze_sequence, gaze_heatmap) fused_feat = self.cross_attention(video_feat, gaze_feat) logits = self.classifier(fused_feat) return logits
class VideoEncoder(nn.Module): """视频编码器""" def __init__(self, d_model=256, num_frames=16): super().__init__() self.conv3d = nn.Sequential( nn.Conv3d(3, 64, kernel_size=(3, 5, 5), stride=(1, 2, 2), padding=(1, 2, 2)), nn.BatchNorm3d(64), nn.ReLU(), nn.MaxPool3d((1, 2, 2)), nn.Conv3d(64, 128, kernel_size=(3, 3, 3), stride=(1, 2, 2), padding=(1, 1, 1)), nn.BatchNorm3d(128), nn.ReLU(), nn.AdaptiveAvgPool3d((num_frames, 1, 1)) ) self.proj = nn.Linear(128, d_model) encoder_layer = nn.TransformerEncoderLayer(d_model=d_model, nhead=8, batch_first=True) self.transformer = nn.TransformerEncoder(encoder_layer, num_layers=2) def forward(self, x): """ Args: x: [B, T, C, H, W] Returns: feat: [B, T, d_model] """ B, T, C, H, W = x.shape x = x.permute(0, 2, 1, 3, 4) x = self.conv3d(x) x = x.squeeze(-1).squeeze(-1).permute(0, 2, 1) x = self.proj(x) x = self.transformer(x) return x
class GazeEncoder(nn.Module): """注视点编码器""" def __init__(self, d_model=128, num_points=16): super().__init__() self.gaze_embed = nn.Linear(2, d_model) self.pos_encoding = nn.Parameter(torch.randn(1, num_points, d_model)) encoder_layer = nn.TransformerEncoderLayer(d_model=d_model, nhead=4, batch_first=True) self.transformer = nn.TransformerEncoder(encoder_layer, num_layers=2) self.heatmap_encoder = nn.Sequential( nn.Conv2d(1, 32, kernel_size=7, stride=2, padding=3), nn.ReLU(), nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(32, d_model // 2) ) def forward(self, gaze_sequence, gaze_heatmap=None): """ Args: gaze_sequence: [B, T, 2] gaze_heatmap: [B, T, H, W](可选) Returns: feat: [B, T, d_model] """ x = self.gaze_embed(gaze_sequence) x = x + self.pos_encoding[:, :x.size(1)] x = self.transformer(x) if gaze_heatmap is not None: B, T, H, W = gaze_heatmap.shape heatmap_feat = self.heatmap_encoder(gaze_heatmap.view(B*T, 1, H, W)) heatmap_feat = heatmap_feat.view(B, T, -1) x = x + F.pad(heatmap_feat, (0, x.size(-1) - heatmap_feat.size(-1))) return x
class CrossModalAttention(nn.Module): """交叉模态注意力""" def __init__(self, video_dim=256, gaze_dim=128, fusion_dim=256): super().__init__() self.video_proj = nn.Linear(video_dim, fusion_dim) self.gaze_proj = nn.Linear(gaze_dim, fusion_dim) self.cross_attn = nn.MultiheadAttention(fusion_dim, num_heads=8, batch_first=True) self.output = nn.Sequential( nn.LayerNorm(fusion_dim), nn.Linear(fusion_dim, fusion_dim), nn.ReLU() ) def forward(self, video_feat, gaze_feat): """ Args: video_feat: [B, T_v, D_v] gaze_feat: [B, T_g, D_g] Returns: fused: [B, D_f] """ video = self.video_proj(video_feat) gaze = self.gaze_proj(gaze_feat) attn_out, _ = self.cross_attn( query=video, key=gaze, value=gaze ) fused = self.output(video + attn_out) fused = fused.mean(dim=1) return fused
def analyze_cognitive_distraction_features(): """分析认知分心的注视特征""" features = { '专注驾驶': { 'gaze_variance': 0.3, 'fixation_duration': 0.5, 'saccade_frequency': 0.8, 'gaze_road_ratio': 0.9, }, '认知分心': { 'gaze_variance': 0.1, 'fixation_duration': 2.0, 'saccade_frequency': 0.2, 'gaze_road_ratio': 0.95, }, '视觉分心': { 'gaze_variance': 0.4, 'fixation_duration': 1.5, 'saccade_frequency': 0.6, 'gaze_road_ratio': 0.3, } } print("=" * 70) print("Cognitive Distraction Gaze Features") print("=" * 70) print(f"{'状态':<15} | {'视线方差':>8} | {'注视时长':>8} | {'扫视频率':>8} | {'道路比例':>8}") print("-" * 70) for state, metrics in features.items(): print(f"{state:<15} | {metrics['gaze_variance']:>8.2f} | {metrics['fixation_duration']:>8.1f}s | " f"{metrics['saccade_frequency']:>8.2f} | {metrics['gaze_road_ratio']:>7.0%}") return features
if __name__ == "__main__": config = { 'video_dim': 256, 'gaze_dim': 128, 'fusion_dim': 256, 'num_frames': 16, 'num_gaze_points': 16, 'num_classes': 3, 'dropout': 0.1 } model = EyeCue(config) B = 4 video = torch.randn(B, 16, 3, 224, 224) gaze = torch.randn(B, 16, 2) output = model(video, gaze) print(f"Video shape: {video.shape}") print(f"Gaze shape: {gaze.shape}") print(f"Output shape: {output.shape}") print(f"Model parameters: {sum(p.numel() for p in model.parameters()):,}") print("\n") analyze_cognitive_distraction_features()
|