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
| import torch import torch.nn as nn import torch.nn.functional as F
class CausalGazeForecaster(nn.Module): """ 因果视线预测器 核心思路: 1. 只用当前和过去的信息(因果性) 2. 上下文信息门控(不是所有历史都重要) 3. 预测中断期间的gaze值 输入:历史gaze序列 + 上下文(头部姿态、车辆状态等) 输出:预测的gaze值 + 置信度 """ def __init__(self, gaze_dim=2, context_dim=16, d_model=128, n_heads=4, n_layers=3, seq_len=30): super().__init__() self.seq_len = seq_len self.d_model = d_model self.gaze_encoder = nn.Linear(gaze_dim, d_model) self.context_encoder = nn.Linear(context_dim, d_model) self.causal_attention = nn.MultiheadAttention( d_model, n_heads, batch_first=True ) self.context_gate = nn.Sequential( nn.Linear(d_model * 2, d_model), nn.Sigmoid() ) self.gaze_predictor = nn.Sequential( nn.Linear(d_model, d_model // 2), nn.ReLU(), nn.Linear(d_model // 2, gaze_dim) ) self.confidence_head = nn.Sequential( nn.Linear(d_model, d_model // 2), nn.ReLU(), nn.Linear(d_model // 2, 1), nn.Sigmoid() ) self.register_buffer( 'causal_mask', torch.triu(torch.ones(seq_len, seq_len) * float('-inf'), diagonal=1) ) def forward(self, gaze_history, context_history): """ Args: gaze_history: (B, T, 2) 历史gaze [pitch, yaw] 度 context_history: (B, T, C) 上下文历史 Returns: predicted_gaze: (B, 2) 预测的gaze confidence: (B, 1) 预测置信度 """ B, T, _ = gaze_history.shape gaze_emb = self.gaze_encoder(gaze_history) ctx_emb = self.context_encoder(context_history) gate = self.context_gate(torch.cat([gaze_emb, ctx_emb], dim=-1)) fused = gaze_emb * gate + ctx_emb * (1 - gate) attended, _ = self.causal_attention( fused, fused, fused, attn_mask=self.causal_mask[:T, :T] ) last = attended[:, -1, :] predicted_gaze = self.gaze_predictor(last) confidence = self.confidence_head(last) return predicted_gaze, confidence def predict_dropout(self, gaze_history, context_history, dropout_duration=10): """ 预测眼动追踪中断期间的gaze Args: dropout_duration: 中断持续帧数 Returns: predictions: (B, dropout_duration, 2) confidences: (B, dropout_duration, 1) """ predictions = [] confidences = [] current_gaze = gaze_history current_ctx = context_history for t in range(dropout_duration): pred_gaze, conf = self.forward(current_gaze, current_ctx) predictions.append(pred_gaze) confidences.append(conf) pred_gaze = pred_gaze.unsqueeze(1) current_gaze = torch.cat([current_gaze[:, 1:], pred_gaze], dim=1) current_ctx = torch.cat([ current_ctx[:, 1:], current_ctx[:, -1:].clone() ], dim=1) return ( torch.stack(predictions, dim=1), torch.stack(confidences, dim=1) )
class DMSTrackingRecovery: """DMS眼动追踪中断恢复模块""" def __init__(self): self.forecaster = CausalGazeForecaster( gaze_dim=2, context_dim=16, d_model=128, n_heads=4, n_layers=3, seq_len=30 ) self.context_sources = { 'head_pose': 3, 'vehicle_speed': 1, 'steering_angle': 1, 'lane_deviation': 1, 'brake_status': 1, 'turn_signal': 1, 'time_of_day': 1, 'weather': 1, 'traffic_density': 1, 'nav_instruction': 1, 'audio_active': 1, 'phone_detected': 1, 'gaze_velocity': 2, } def __call__(self, tracker_status, gaze_history, context_history): """ Args: tracker_status: 'tracking' | 'lost' gaze_history: (1, 30, 2) 最近30帧gaze context_history: (1, 30, 16) 上下文 Returns: gaze_output: (2,) gaze值 confidence: float source: 'tracker' | 'predicted' """ if tracker_status == 'tracking': return gaze_history[0, -1], 1.0, 'tracker' else: with torch.no_grad(): pred, conf = self.forecaster.predict_dropout( gaze_history, context_history, dropout_duration=1 ) return pred[0, 0], conf[0, 0].item(), 'predicted'
if __name__ == "__main__": model = CausalGazeForecaster(gaze_dim=2, context_dim=16, d_model=64) B, T = 4, 30 gaze = torch.randn(B, T, 2) ctx = torch.randn(B, T, 16) pred, conf = model(gaze, ctx) print(f"输入: gaze {gaze.shape}, context {ctx.shape}") print(f"预测gaze: {pred.shape}, 置信度: {conf.shape}") preds, confs = model.predict_dropout(gaze, ctx, dropout_duration=10) print(f"中断预测: {preds.shape}, 置信度: {confs.shape}") print(f"参数量: {sum(p.numel() for p in model.parameters())/1e6:.2f}M") recovery = DMSTrackingRecovery() status = 'lost' g, c, s = recovery(status, gaze[:1], ctx[:1]) print(f"\nDMS恢复: gaze={g.numpy()}, conf={c:.3f}, source={s}")
|