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
| import torch import torch.nn as nn import torch.nn.functional as F import numpy as np
class FrequencyAttentionModulation(nn.Module): """频域-空域融合模块 核心思想:频域幅度谱在光照变化下保持稳定 """ def __init__(self, spatial_channels=512, freq_channels=256): super().__init__() self.spatial_conv = nn.Sequential( nn.Conv2d(spatial_channels, 256, 1), nn.BatchNorm2d(256), nn.ReLU() ) self.freq_conv = nn.Sequential( nn.Conv2d(2, 64, 3, padding=1), nn.BatchNorm2d(64), nn.ReLU(), nn.Conv2d(64, 128, 3, padding=1), nn.BatchNorm2d(128), nn.ReLU(), nn.AdaptiveAvgPool2d(1) ) self.freq_inject = nn.Linear(128, 256) self.fusion = nn.Sequential( nn.Conv2d(256 + 256, 256, 1), nn.BatchNorm2d(256), nn.ReLU() ) self.spatial_gate = nn.Sequential( nn.Conv2d(256, 64, 1), nn.ReLU(), nn.Conv2d(64, 1, 1), nn.Sigmoid() ) def forward(self, spatial_feat, img): """ Args: spatial_feat: (B, C, H, W) 空域特征 img: (B, 3, H, W) 原始图像 Returns: fused_feat: (B, 256, H, W) 融合特征 """ B, C, H, W = spatial_feat.shape spatial_feat_proc = self.spatial_conv(spatial_feat) img_gray = img.mean(dim=1, keepdim=True) freq = torch.fft.fft2(img_gray) freq_mag = torch.abs(freq) freq_phase = torch.angle(freq) freq_mag = torch.log(freq_mag + 1e-6) freq_feat = self.freq_conv(torch.cat([freq_mag, freq_phase], dim=1)) freq_feat = freq_feat.squeeze(-1).squeeze(-1) freq_injected = self.freq_inject(freq_feat) freq_injected = freq_injected.unsqueeze(-1).unsqueeze(-1) freq_broadcast = freq_injected.expand(-1, -1, H, W) concat_feat = torch.cat([spatial_feat_proc, freq_broadcast], dim=1) fused_feat = self.fusion(concat_feat) gate = self.spatial_gate(fused_feat) gated_feat = fused_feat * gate return gated_feat
class SemanticDisentanglement(nn.Module): """语义解耦模块 使用CLIP语言嵌入分离视线特征与外观干扰 """ def __init__(self, gaze_dim=128, clip_dim=512): super().__init__() self.gaze_proj = nn.Linear(gaze_dim, clip_dim) self.distractor_texts = [ "a driver wearing sunglasses", "a driver wearing a mask", "a driver with glasses", "a driver in dim light", "a driver in bright sunlight" ] self.register_buffer('distractor_embeddings', self._precompute_distractors()) self.disentangle = nn.Sequential( nn.Linear(clip_dim, 256), nn.ReLU(), nn.Linear(256, clip_dim) ) def _precompute_distractors(self): """预计算干扰文本嵌入""" num_distractors = len(self.distractor_texts) return torch.randn(num_distractors, 512) def forward(self, gaze_feat): """ Args: gaze_feat: (B, 128) 视线特征 Returns: purified_gaze: (B, 512) 纯净化视线特征 """ gaze_clip = self.gaze_proj(gaze_feat) similarity = torch.matmul(gaze_clip, self.distractor_embeddings.T) distractor_direction = torch.matmul( similarity, self.distractor_embeddings ) / self.distractor_embeddings.size(0) purified = gaze_clip - 0.3 * distractor_direction purified = self.disentangle(purified) return purified
class LISA(nn.Module): """LISA完整模型 论文:Language-guided Interference-aware Spatial-Frequency Attention """ def __init__(self, config=None): super().__init__() self.config = config or {} import torchvision.models as models self.backbone = models.resnet18(pretrained=True) self.backbone = nn.Sequential(*list(self.backbone.children())[:-2]) self.fam = FrequencyAttentionModulation(spatial_channels=512) self.sdm = SemanticDisentanglement() self.gaze_head = nn.Sequential( nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(256, 128), nn.ReLU(), nn.Linear(128, 2) ) def forward(self, img): """ Args: img: (B, 3, 224, 224) 驾驶员图像 Returns: output: dict - gaze: (B, 2) 视线方向 - purified_feat: (B, 512) 纯净化特征 """ spatial_feat = self.backbone(img) fused_feat = self.fam(spatial_feat, img) gaze_feat = F.adaptive_avg_pool2d(fused_feat, 1).squeeze(-1).squeeze(-1) purified_feat = self.sdm(gaze_feat[:, :128]) gaze = self.gaze_head(fused_feat) return { 'gaze': gaze, 'purified_feat': purified_feat, 'fused_feat': fused_feat }
if __name__ == "__main__": model = LISA() img = torch.randn(4, 3, 224, 224) output = model(img) print(f"视线预测: {output['gaze']}") print(f"纯净化特征形状: {output['purified_feat'].shape}")
|