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
| import torch import torch.nn as nn import torch.nn.functional as F
class DrowSFormerXAI(nn.Module): """ DrowSFormer-XAI: 跨注意力CNN-Transformer融合疲劳检测框架 论文: Neural Processing Letters, 2026 核心: CNN特征提取 + Transformer跨注意力融合 + XAI可解释性 输入: 驾驶员面部视频帧序列 输出: 疲劳等级 + 注意力热图(可解释性) """ def __init__(self, num_classes=3, feat_dim=256, num_heads=8, num_transformer_layers=4): super().__init__() self.eye_stream = FeatureStream(in_channels=3, feat_dim=feat_dim) self.mouth_stream = FeatureStream(in_channels=3, feat_dim=feat_dim) self.head_pose_stream = FeatureStream(in_channels=3, feat_dim=feat_dim) self.cross_attn = CrossAttentionFusion( feat_dim=feat_dim, num_heads=num_heads, num_layers=num_transformer_layers ) self.classifier = nn.Sequential( nn.Linear(feat_dim, feat_dim // 2), nn.GELU(), nn.Dropout(0.1), nn.Linear(feat_dim // 2, num_classes) ) self.xai_module = XAIModule() def forward(self, eye_img, mouth_img, head_pose_img, return_attention=False): """ Args: eye_img: (B, C, H, W) 眼部裁剪图像 mouth_img: (B, C, H, W) 嘴部裁剪图像 head_pose_img: (B, C, H, W) 头部姿态图像 return_attention: 是否返回注意力图(可解释性) Returns: logits: (B, num_classes) 疲劳等级 attention_maps: (可选) 注意力热图 """ eye_feat = self.eye_stream(eye_img) mouth_feat = self.mouth_stream(mouth_img) pose_feat = self.head_pose_stream(head_pose_img) fused, attn_weights = self.cross_attn( eye_feat, mouth_feat, pose_feat ) logits = self.classifier(fused) if return_attention: attention_maps = self.xai_module.generate_attention_map( attn_weights, eye_img, mouth_img, head_pose_img ) return logits, attention_maps return logits
class FeatureStream(nn.Module): """单流CNN特征提取器""" def __init__(self, in_channels=3, feat_dim=256): super().__init__() self.backbone = nn.Sequential( nn.Conv2d(in_channels, 32, 3, 1, 1), nn.BatchNorm2d(32), nn.ReLU(), nn.MaxPool2d(2), nn.Conv2d(32, 64, 3, 1, 1), nn.BatchNorm2d(64), nn.ReLU(), nn.MaxPool2d(2), nn.Conv2d(64, 128, 3, 1, 1), nn.BatchNorm2d(128), nn.ReLU(), nn.AdaptiveAvgPool2d(1) ) self.proj = nn.Linear(128, feat_dim) def forward(self, x): feat = self.backbone(x).flatten(1) return self.proj(feat)
class CrossAttentionFusion(nn.Module): """ 跨注意力融合模块 三个特征流之间的双向交叉注意力 """ def __init__(self, feat_dim=256, num_heads=8, num_layers=4): super().__init__() self.layers = nn.ModuleList([ CrossAttentionLayer(feat_dim, num_heads) for _ in range(num_layers) ]) self.norm = nn.LayerNorm(feat_dim) def forward(self, eye, mouth, pose): """ Args: eye, mouth, pose: (B, feat_dim) Returns: fused: (B, feat_dim) attn_weights: 注意力权重(用于可解释性) """ x = torch.stack([eye, mouth, pose], dim=1) all_attn = [] for layer in self.layers: x, attn = layer(x) all_attn.append(attn) fused = self.norm(x.mean(dim=1)) return fused, all_attn
class CrossAttentionLayer(nn.Module): """跨注意力层""" def __init__(self, dim=256, num_heads=8): super().__init__() self.attn = nn.MultiheadAttention(dim, num_heads, batch_first=True) self.norm1 = nn.LayerNorm(dim) self.norm2 = nn.LayerNorm(dim) self.ffn = nn.Sequential( nn.Linear(dim, dim * 4), nn.GELU(), nn.Linear(dim * 4, dim) ) def forward(self, x): attn_out, attn_weights = self.attn(x, x, x) x = self.norm1(x + attn_out) x = self.norm2(x + self.ffn(x)) return x, attn_weights
class XAIModule: """ 可解释性模块 生成注意力热图和特征归因 """ def generate_attention_map(self, attn_weights, eye_img, mouth_img, pose_img): """ 从Transformer注意力权重生成可视化热图 Returns: dict: 各模态的注意力权重 """ last_attn = attn_weights[-1] eye_weight = last_attn[:, 0].mean(dim=-1) mouth_weight = last_attn[:, 1].mean(dim=-1) pose_weight = last_attn[:, 2].mean(dim=-1) return { 'eye_attention': eye_weight, 'mouth_attention': mouth_weight, 'pose_attention': pose_weight, 'fatigue_indicators': { 'eye_closure': '眼部闭眼频率', 'yawning': '嘴部张开程度', 'head_nodding': '头部点头频率' } }
if __name__ == "__main__": model = DrowSFormerXAI(num_classes=3, feat_dim=256) eye = torch.randn(4, 3, 64, 64) mouth = torch.randn(4, 3, 64, 64) pose = torch.randn(4, 3, 64, 64) logits, attn = model(eye, mouth, pose, return_attention=True) print(f"Logits: {logits.shape}") print(f"Eye attention: {attn['eye_attention']}") print(f"Mouth attention: {attn['mouth_attention']}") print(f"Pose attention: {attn['pose_attention']}") print(f"Parameters: {sum(p.numel() for p in model.parameters()):,}")
|