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
| """ Self-Distillation Transformer (SDT) + 三项改进
基础: 文本 + 音频 + 视觉 → intra-modal Transformer → inter-modal Transformer → sigmoid 门 → softmax 门 → 分类
改进1: 视觉 = 外观(ViT) + 几何(FACS) 改进2: softmax 门 → 类别自适应门 改进3: + Valence-Arousal 先验 """
import torch import torch.nn as nn import torch.nn.functional as F from typing import Dict, Tuple, List import numpy as np
class GeometryEnhancedVisualEncoder(nn.Module): """ 几何增强视觉编码器 论文核心改进1: 外观特征 + 面部几何描述符 外观: ViT 提取全局面部表征 几何: FACS Action Unit 描述面部结构变化 """ def __init__(self, appearance_dim: int = 768, geometry_dim: int = 51, hidden_dim: int = 256): super().__init__() self.appearance_proj = nn.Linear(appearance_dim, hidden_dim) self.geometry_encoder = nn.Sequential( nn.Linear(geometry_dim, 128), nn.ReLU(), nn.Linear(128, hidden_dim), nn.ReLU() ) self.fusion = nn.Sequential( nn.Linear(hidden_dim * 2, hidden_dim), nn.LayerNorm(hidden_dim), nn.GELU() ) def forward(self, appearance_feat: torch.Tensor, geometry_feat: torch.Tensor) -> torch.Tensor: """ Args: appearance_feat: ViT 特征, shape=(B, T, 768) geometry_feat: FACS AU, shape=(B, T, 51) Returns: visual_repr: 增强视觉表征, shape=(B, T, hidden_dim) """ app = self.appearance_proj(appearance_feat) geo = self.geometry_encoder(geometry_feat) return self.fusion(torch.cat([app, geo], dim=-1))
class ClassWiseAdaptiveFusion(nn.Module): """ 类别自适应模态融合 论文核心改进2: 不同情绪类别下,文本/音频/视觉权重不同 例如: - 愤怒: 音频权重高(语气强烈) - 悲伤: 视觉权重高(面部表情) - 中性: 文本权重高 """ def __init__(self, n_modalities: int = 3, n_classes: int = 7, hidden_dim: int = 256): super().__init__() self.class_modality_weights = nn.Parameter( torch.randn(n_classes, n_modalities) * 0.1 + 1.0 ) def forward(self, modalities: Dict[str, torch.Tensor], class_logits: torch.Tensor) -> torch.Tensor: """ Args: modalities: {'text': (B,T,D), 'audio': (B,T,D), 'visual': (B,T,D)} class_logits: 当前预测 logits, shape=(B, n_classes) Returns: fused: 融合表征, shape=(B, T, D) """ class_probs = F.softmax(class_logits, dim=-1) weights = torch.einsum('bc,cm->bm', class_probs, self.class_modality_weights) weights = F.softmax(weights, dim=-1) mod_tensor = torch.stack([ modalities['text'], modalities['audio'], modalities['visual'] ], dim=1) weights = weights.unsqueeze(-1).unsqueeze(-1) fused = (mod_tensor * weights).sum(dim=1) return fused
class ValenceArousalPrior(nn.Module): """ Valence-Arousal 先验 论文核心改进3: 利用情感在 VA 空间的结构 情感转移 utterance (如 sad→joy) 分类困难 VA 先验: 将类别映射到 VA 空间,对转移 utterance 施加修正 """ EMOTION_VA_CENTERS = { 'neutral': (0.0, 0.0), 'happy': (0.8, 0.5), 'sad': (-0.7, -0.4), 'angry': (0.2, 0.8), 'fearful': (-0.6, 0.7), 'disgust': (-0.5, 0.3), 'surprised': (0.6, 0.9), } def __init__(self, n_classes: int = 7, va_dim: int = 2): super().__init__() self.va_projection = nn.Linear(n_classes, va_dim) self.shift_correction = nn.Linear(va_dim * 2, n_classes) def forward(self, class_logits: torch.Tensor, prev_logits: torch.Tensor = None) -> torch.Tensor: """ Args: class_logits: 当前 utterance logits, shape=(B, C) prev_logits: 上一 utterance logits (情感转移), shape=(B, C) Returns: corrected_logits: 修正后 logits """ if prev_logits is None: return class_logits curr_va = self.va_projection(class_logits) prev_va = self.va_projection(prev_logits) va_shift = torch.cat([curr_va, prev_va], dim=-1) correction = self.shift_correction(va_shift) return class_logits + 0.1 * correction
class EnhancedSDT(nn.Module): """ 增强版 SDT: 三项改进集成 完整管道: 1. 文本编码 (RoBERTa) 2. 音频编码 (WavLM) 3. 视觉编码 (ViT + FACS) ← 改进1 4. Intra-modal Transformer 5. Inter-modal Transformer 6. Sigmoid 门 → 模态增强 7. 类别自适应融合 ← 改进2 8. 分类 + VA 先验修正 ← 改进3 """ def __init__(self, n_classes: int = 7, hidden_dim: int = 256): super().__init__() self.n_classes = n_classes self.text_encoder = nn.Linear(1024, hidden_dim) self.audio_encoder = nn.Linear(1024, hidden_dim) self.visual_encoder = GeometryEnhancedVisualEncoder( appearance_dim=768, geometry_dim=51, hidden_dim=hidden_dim ) self.intra_modal = nn.TransformerEncoder( nn.TransformerEncoderLayer(hidden_dim, nhead=4, batch_first=True), num_layers=2 ) self.cross_attn = nn.MultiheadAttention(hidden_dim, 4, batch_first=True) self.adaptive_fusion = ClassWiseAdaptiveFusion( n_modalities=3, n_classes=n_classes, hidden_dim=hidden_dim ) self.classifier = nn.Linear(hidden_dim, n_classes) self.va_prior = ValenceArousalPrior(n_classes=n_classes) def forward(self, text_feat, audio_feat, appearance_feat, geometry_feat, prev_logits=None) -> Dict[str, torch.Tensor]: """ Args: text_feat: (B, T, 1024) audio_feat: (B, T, 1024) appearance_feat: (B, T, 768) ViT geometry_feat: (B, T, 51) FACS AU prev_logits: (B, C) 上一轮分类 Returns: logits, fused_repr """ t = self.text_encoder(text_feat) a = self.audio_encoder(audio_feat) v = self.visual_encoder(appearance_feat, geometry_feat) t = self.intra_modal(t) a = self.intra_modal(a) v = self.intra_modal(v) t_attended, _ = self.cross_attn(t, torch.cat([a, v], dim=1), torch.cat([a, v], dim=1)) a_attended, _ = self.cross_attn(a, torch.cat([t, v], dim=1), torch.cat([t, v], dim=1)) v_attended, _ = self.cross_attn(v, torch.cat([t, a], dim=1), torch.cat([t, a], dim=1)) pooled = torch.cat([t_attended.mean(1), a_attended.mean(1), v_attended.mean(1)], dim=-1) initial_logits = self.classifier(pooled[:, :256]) fused = self.adaptive_fusion({ 'text': t_attended, 'audio': a_attended, 'visual': v_attended }, initial_logits) logits = self.classifier(fused.mean(1)) if prev_logits is not None: logits = self.va_prior(logits, prev_logits) return {'logits': logits, 'fused_repr': fused}
class DriverEmotionDetector: """ IMS 驾驶员情绪检测器 基于 ECCV 2026 论文方法 应用场景: 1. 路怒症检测 (angry + 高 arousal) 2. 疲劳情绪 (sad + 低 arousal) 3. 焦虑检测 (fearful + 中 arousal) 4. 满意/愉悦 (happy + 中 arousal) 输入: DMS 摄像头 + 麦克风 """ def __init__(self): self.model = EnhancedSDT(n_classes=7) self.emotion_actions = { 'angry': {'risk': 3, 'action': '路怒警告', 'threshold': 0.7}, 'sad': {'risk': 2, 'action': '疲劳情绪', 'threshold': 0.6}, 'fearful': {'risk': 2, 'action': '焦虑检测', 'threshold': 0.6}, 'happy': {'risk': 0, 'action': '正常', 'threshold': 0.5}, 'neutral': {'risk': 0, 'action': '正常', 'threshold': 0.5}, 'disgust': {'risk': 1, 'action': '不适', 'threshold': 0.6}, 'surprised': {'risk': 1, 'action': '惊讶', 'threshold': 0.7}, } def classify(self, appearance_feat, geometry_feat, audio_feat, text_feat=None, prev_emotion=None) -> dict: """ 分类驾驶员情绪 Args: appearance_feat: 面部 ViT 特征 (B, T, 768) geometry_feat: FACS AU (B, T, 51) — 51 个 Action Unit audio_feat: 语音特征 (B, T, 1024) text_feat: 转录文本特征 (可选) prev_emotion: 上一帧情绪 logits """ if text_feat is None: text_feat = torch.zeros(appearance_feat.shape[0], appearance_feat.shape[1], 1024) output = self.model(text_feat, audio_feat, appearance_feat, geometry_feat, prev_emotion) logits = output['logits'] probs = F.softmax(logits, dim=-1) emotions = list(self.emotion_actions.keys()) risk_scores = torch.zeros_like(probs) for i, emo in enumerate(emotions): risk_scores[:, i] = self.emotion_actions[emo]['risk'] total_risk = (probs * risk_scores).sum(dim=-1) return { 'emotions': {emotions[i]: probs[0, i].item() for i in range(len(emotions))}, 'dominant_emotion': emotions[probs[0].argmax().item()], 'risk_score': total_risk[0].item(), 'logits': logits }
if __name__ == "__main__": print("=== 增强版 SDT 测试 ===") model = EnhancedSDT(n_classes=7, hidden_dim=256) B, T = 2, 5 text_feat = torch.randn(B, T, 1024) audio_feat = torch.randn(B, T, 1024) appearance_feat = torch.randn(B, T, 768) geometry_feat = torch.randn(B, T, 51) output = model(text_feat, audio_feat, appearance_feat, geometry_feat) print(f"输入: text={text_feat.shape}, audio={audio_feat.shape}") print(f" appearance={appearance_feat.shape}, geometry={geometry_feat.shape}") print(f"输出: logits={output['logits'].shape}") prev_logits = torch.randn(B, 7) output_shift = model(text_feat, audio_feat, appearance_feat, geometry_feat, prev_logits) print(f"VA 先验: 转移 utterance logits={output_shift['logits'].shape}") detector = DriverEmotionDetector() result = detector.classify(appearance_feat, geometry_feat, audio_feat) print(f"\n=== 驾驶员情绪检测结果 ===") print(f"主导情绪: {result['dominant_emotion']}") print(f"风险评分: {result['risk_score']:.2f}") for emo, prob in sorted(result['emotions'].items(), key=lambda x: -x[1]): print(f" {emo}: {prob:.1%}") print(f"\n=== 论文性能报告 ===") print(f"{'数据集':<12} {'改进1(几何)':<15} {'改进2(融合)':<15} {'改进3(VA)'}") print(f"{'MELD':<12} {'+0.27 F1':<15} {'+0.17 F1':<15} {'+0.30 acc'}") print(f"{'IEMOCAP':<12} {'+4.36 F1':<15} {'+0.25 F1':<15} {'+0.74 acc'}") print(f"\n关键: 三项改进互补, 可叠加使用")
|