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
| """ Self-Attention Routing (SAR) 实现 参考:GazeCapsNet论文
核心思想: - 替代迭代路由(计算量大) - 使用注意力机制动态分配资源 - 轻量化+精度保持 """
import torch import torch.nn as nn import torch.nn.functional as F
class SelfAttentionRouting(nn.Module): """ 自注意力路由机制 原理: 1. 计算低层胶囊到高层胶囊的注意力权重 2. 基于权重聚合低层胶囊输出 3. 非线性"squash"激活 优势: - 无迭代(vs 传统Routing) - 计算量大幅降低 - 自动聚焦关键面部区域 """ def __init__( self, in_channels: int, out_channels: int, num_routes: int, attention_dim: int = 64 ): """ Args: in_channels: 输入胶囊通道数 out_channels: 输出胶囊通道数 num_routes: 路由数量 attention_dim: 注意力维度 """ super().__init__() self.attention = nn.Sequential( nn.Linear(in_channels, attention_dim), nn.ReLU(), nn.Linear(attention_dim, out_channels), nn.Softmax(dim=-1) ) self.route_weights = nn.Parameter( torch.randn(num_routes, in_channels, out_channels) ) def forward(self, x: torch.Tensor) -> torch.Tensor: """ 前向传播 Args: x: 低层胶囊输出, shape=(B, N, in_channels) N = num_routes Returns: v_j: 高层胶囊输出, shape=(B, out_channels) SAR流程: 1. 计算注意力权重 c_ij 2. 加权聚合 s_j = Σ c_ij * u_i 3. squash激活 v_j = ||s_j||² / (1+||s_j||²) * s_j / ||s_j|| """ B, N, D_in = x.shape c_ij = self.attention(x) s_j = torch.einsum('bnd,nkd->bkd', x, self.route_weights) s_j = torch.einsum('bnd,bnd->bd', s_j, c_ij) norm_s = torch.norm(s_j, dim=-1, keepdim=True) squash_factor = norm_s ** 2 / (1 + norm_s ** 2) v_j = squash_factor * s_j / (norm_s + 1e-8) return v_j
class GazeCapsNet(nn.Module): """ GazeCapsNet完整模型 架构: 1. MobileNet v2 + ResNet-18 双分支特征提取 2. 特征融合 3. 初级胶囊层 4. SAR路由到高层胶囊 5. 3D视线向量回归 """ def __init__( self, gaze_dim: int = 3, num_primary_caps: int = 32, primary_caps_dim: int = 8, num_classes_caps: int = 16 ): super().__init__() self.mobilenet = nn.Sequential( nn.Conv2d(3, 32, 3, stride=2, padding=1), nn.BatchNorm2d(32), nn.ReLU(), nn.Conv2d(32, 64, 3, stride=1, padding=1), nn.BatchNorm2d(64), nn.ReLU(), nn.Conv2d(64, 128, 3, stride=2, padding=1), nn.BatchNorm2d(128), nn.ReLU(), nn.Conv2d(128, 256, 3, stride=2, padding=1), nn.BatchNorm2d(256), nn.ReLU(), nn.AdaptiveAvgPool2d(1) ) self.resnet_lite = nn.Sequential( nn.Conv2d(3, 64, 7, stride=2, padding=3), nn.BatchNorm2d(64), nn.ReLU(), nn.MaxPool2d(3, stride=2, padding=1), nn.Conv2d(64, 128, 3, stride=2, padding=1), nn.BatchNorm2d(128), nn.ReLU(), nn.AdaptiveAvgPool2d(1) ) self.fusion = nn.Sequential( nn.Linear(256 + 128, 512), nn.ReLU(), nn.Dropout(0.3) ) self.primary_caps = nn.Sequential( nn.Linear(512, num_primary_caps * primary_caps_dim), nn.ReLU() ) self.sar = SelfAttentionRouting( in_channels=primary_caps_dim, out_channels=num_classes_caps, num_routes=num_primary_caps ) self.gaze_head = nn.Sequential( nn.Linear(num_classes_caps, 64), nn.ReLU(), nn.Linear(64, gaze_dim) ) def forward(self, x: torch.Tensor) -> torch.Tensor: """ 前向传播 Args: x: 输入图像, shape=(B, C, H, W) Returns: gaze_vector: 3D视线向量, shape=(B, 3) θx: 水平角度(左负右正) θy: 垂直角度(上负下正) θz: 深度方向(前正后负) """ B = x.shape[0] feat1 = self.mobilenet(x).view(B, -1) feat2 = self.resnet_lite(x).view(B, -1) fused = self.fusion(torch.cat([feat1, feat2], dim=-1)) primary = self.primary_caps(fused) primary = primary.view(B, -1, 8) high_caps = self.sar(primary) gaze = self.gaze_head(high_caps) return gaze
if __name__ == "__main__": model = GazeCapsNet() total_params = sum(p.numel() for p in model.parameters()) print(f"模型参数: {total_params / 1e6:.2f}M") x = torch.randn(4, 3, 112, 112) import time start = time.time() gaze = model(x) elapsed = (time.time() - start) * 1000 print(f"推理延迟: {elapsed:.2f}ms") print(f"视线向量:") for i in range(4): print(f" 样本{i+1}: θx={gaze[i,0]:.1f}°, θy={gaze[i,1]:.1f}°, θz={gaze[i,2]:.1f}°")
|