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
| import torch import torch.nn as nn
class AttentiveEyeEncoder(nn.Module): """ AttentiveGaze眼部特征编码器 创新:空间注意力+通道注意力双重加权 作用:在眼镜反光/遮挡时自动降权受损区域 """ def __init__(self, in_channels=3, d_model=128): super().__init__() self.backbone = nn.Sequential( nn.Conv2d(in_channels, 32, 3, padding=1), nn.BatchNorm2d(32), nn.GELU(), nn.MaxPool2d(2), nn.Conv2d(32, 64, 3, padding=1), nn.BatchNorm2d(64), nn.GELU(), nn.MaxPool2d(2), nn.Conv2d(64, d_model, 3, padding=1), nn.BatchNorm2d(d_model), nn.GELU(), nn.AdaptiveAvgPool2d((4, 4)) ) self.spatial_attn = nn.Sequential( nn.Conv2d(d_model, d_model // 8, 1), nn.GELU(), nn.Conv2d(d_model // 8, 1, 1), nn.Sigmoid() ) self.channel_attn = nn.Sequential( nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(d_model, d_model // 8), nn.GELU(), nn.Linear(d_model // 8, d_model), nn.Sigmoid() ) self.flatten = nn.Flatten() self.proj = nn.Linear(d_model * 4 * 4, d_model) def forward(self, eye_image): """ Args: eye_image: (B, 3, H, W) 眼部裁剪图 Returns: features: (B, d_model) 注意力增强的眼部特征 """ feat = self.backbone(eye_image) spatial_w = self.spatial_attn(feat) feat = feat * spatial_w channel_w = self.channel_attn(feat) feat = feat * channel_w.unsqueeze(-1).unsqueeze(-1) feat = self.flatten(feat) feat = self.proj(feat) return feat, spatial_w
class CrossModalFusion(nn.Module): """ 跨模态注意力融合 眼部、全脸、头姿三个模态互相查询 可学习门控决定最终融合权重 """ def __init__(self, d_model=128, n_heads=4): super().__init__() self.eye_to_face = nn.MultiheadAttention(d_model, n_heads, batch_first=True) self.eye_to_head = nn.MultiheadAttention(d_model, n_heads, batch_first=True) self.gate = nn.Sequential( nn.Linear(d_model * 3, d_model), nn.GELU(), nn.Linear(d_model, 3), nn.Softmax(dim=-1) ) def forward(self, eye_feat, face_feat, head_feat): """ Returns: fused: (B, d_model) 融合特征 weights: (B, 3) 各模态权重 """ eye_enhanced = eye_feat.unsqueeze(1) face_enhanced = face_feat.unsqueeze(1) head_enhanced = head_feat.unsqueeze(1) eye_from_face, _ = self.eye_to_face( eye_enhanced, face_enhanced, face_enhanced ) eye_from_head, _ = self.eye_to_head( eye_enhanced, head_enhanced, head_feat.unsqueeze(1) ) concat = torch.cat([ eye_feat, eye_from_face.squeeze(1), eye_from_head.squeeze(1) ], dim=-1) weights = self.gate(concat) fused = ( weights[:, 0:1] * eye_feat + weights[:, 1:2] * eye_from_face.squeeze(1) + weights[:, 2:3] * eye_from_head.squeeze(1) ) return fused, weights
class UncertaintyGazeHead(nn.Module): """ 不确定性感知视线回归头 输出:视线方向(pitch, yaw) + 不确定性(variance) 基于Nix & Weigend的异方差回归 """ def __init__(self, d_model=128, n_heads=4): super().__init__() self.multi_head = nn.ModuleList([ nn.Linear(d_model, d_model // n_heads) for _ in range(n_heads) ]) self.gaze_regressor = nn.Linear(d_model, 2) self.uncertainty_regressor = nn.Sequential( nn.Linear(d_model, d_model // 2), nn.GELU(), nn.Linear(d_model // 2, 2), nn.Softplus() ) def forward(self, fused_feat): """ Returns: gaze: (B, 2) pitch, yaw in radians variance: (B, 2) per-dimension uncertainty """ head_outputs = [] for head in self.multi_head: head_outputs.append(head(fused_feat)) multi_embed = torch.cat(head_outputs, dim=-1) gaze = self.gaze_regressor(fused_feat) variance = self.uncertainty_regressor(fused_feat) return gaze, variance
class AttentiveGaze(nn.Module): """AttentiveGaze完整模型""" def __init__(self): super().__init__() self.eye_encoder = AttentiveEyeEncoder() self.face_encoder = nn.Sequential( nn.Conv2d(3, 32, 3, stride=2, padding=1), nn.GELU(), nn.Conv2d(32, 64, 3, stride=2, padding=1), nn.GELU(), nn.AdaptiveAvgPool2d((4, 4)), nn.Flatten(), nn.Linear(64 * 4 * 4, 128) ) self.head_pose_encoder = nn.Linear(6, 128) self.fusion = CrossModalFusion() self.gaze_head = UncertaintyGazeHead() def forward(self, eye_img, face_img, head_pose): eye_feat, attn_map = self.eye_encoder(eye_img) face_feat = self.face_encoder(face_img) head_feat = self.head_pose_encoder(head_pose) fused, weights = self.fusion(eye_feat, face_feat, head_feat) gaze, variance = self.gaze_head(fused) return { 'gaze': gaze, 'uncertainty': variance, 'fusion_weights': weights, 'attention_map': attn_map }
if __name__ == "__main__": model = AttentiveGaze() B = 2 eye_img = torch.randn(B, 3, 64, 32) face_img = torch.randn(B, 3, 224, 224) head_pose = torch.randn(B, 6) output = model(eye_img, face_img, head_pose) print("AttentiveGaze 输出:") print(f" 视线方向: {output['gaze'].shape} (pitch, yaw)") print(f" 不确定性: {output['uncertainty'].shape} (每维度方差)") print(f" 融合权重: {output['fusion_weights'].shape} (眼/脸/头)") print(f" 注意力图: {output['attention_map'].shape}") print(f"\n示例输出:") for i in range(B): g = output['gaze'][i].detach().numpy() u = output['uncertainty'][i].detach().numpy() w = output['fusion_weights'][i].detach().numpy() print(f" 样本{i}: gaze=({g[0]:.2f}°, {g[1]:.2f}°) " f"unc=({u[0]:.3f}, {u[1]:.3f}) " f"weights=(eye:{w[0]:.2f}, face:{w[1]:.2f}, head:{w[2]:.2f})")
|