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
| import torch import torch.nn as nn import torch.nn.functional as F
class ISAPatching(nn.Module): """ Input-Size-Agnostic Patching 动态调整patch尺寸,使任意纵横比的雷达数据 都能被分解为标准的14×14个patch, 从而复用ImageNet预训练的Positional Embedding Vectors。 论文Section 3.2: ISA-ViT Architecture Args: in_channels: 输入通道数 (1 for magnitude) embed_dim: ViT嵌入维度 (768 for ViT-Base) target_patches: 目标patch网格数 (14×14=196) """ def __init__(self, in_channels: int = 1, embed_dim: int = 768, target_patches: int = 14): super().__init__() self.target_patches = target_patches self.embed_dim = embed_dim self.patch_embed = nn.AdaptiveAvgPool2d( (target_patches, target_patches) ) self.proj = nn.Linear(in_channels, embed_dim) self.pos_embed = nn.Parameter( torch.randn(1, target_patches * target_patches + 1, embed_dim) * 0.02 ) self.cls_token = nn.Parameter(torch.randn(1, 1, embed_dim) * 0.02) def forward(self, x: torch.Tensor) -> torch.Tensor: """ Args: x: 雷达数据, shape=(B, 1, H, W) RT域: (B, 1, 51, 500) FT域: (B, 1, 51, 500) Returns: tokens: shape=(B, 197, embed_dim) # 196 patches + 1 CLS """ B = x.size(0) x = self.patch_embed(x) x = x.flatten(2).transpose(1, 2) x = self.proj(x) cls = self.cls_token.expand(B, -1, -1) x = torch.cat([cls, x], dim=1) x = x + self.pos_embed return x
class ISAViTBlock(nn.Module): """ ViT编码器块(标准Transformer Encoder Layer) 与标准ViT-Base一致,可加载ImageNet预训练权重 """ def __init__(self, embed_dim: int = 768, num_heads: int = 12, mlp_ratio: float = 4.0, dropout: float = 0.1): super().__init__() self.norm1 = nn.LayerNorm(embed_dim) self.attn = nn.MultiheadAttention( embed_dim, num_heads, dropout=dropout, batch_first=True ) self.norm2 = nn.LayerNorm(embed_dim) self.mlp = nn.Sequential( nn.Linear(embed_dim, int(embed_dim * mlp_ratio)), nn.GELU(), nn.Dropout(dropout), nn.Linear(int(embed_dim * mlp_ratio), embed_dim), nn.Dropout(dropout) ) def forward(self, x: torch.Tensor) -> torch.Tensor: attn_out, _ = self.attn(self.norm1(x), self.norm1(x), self.norm1(x)) x = x + attn_out x = x + self.mlp(self.norm2(x)) return x
class ISAViT(nn.Module): """ Input-Size-Agnostic Vision Transformer for IR-UWB 双分支架构: RT域 + FT域 → 晚融合 论文Section 3.3: Multi-Domain Fusion Args: img_size: 输入尺寸 (H, W) in_channels: 输入通道数 embed_dim: ViT嵌入维度 depth: Transformer块数量 num_heads: 注意力头数 num_classes: 活动类别数 """ def __init__(self, img_size=(51, 500), in_channels: int = 1, embed_dim: int = 768, depth: int = 12, num_heads: int = 12, num_classes: int = 7): super().__init__() self.rt_patch = ISAPatching(in_channels, embed_dim) self.rt_blocks = nn.ModuleList([ ISAViTBlock(embed_dim, num_heads) for _ in range(depth) ]) self.ft_patch = ISAPatching(in_channels, embed_dim) self.ft_blocks = nn.ModuleList([ ISAViTBlock(embed_dim, num_heads) for _ in range(depth) ]) self.beta = nn.Parameter(torch.tensor(0.5)) self.norm = nn.LayerNorm(embed_dim) self.head = nn.Linear(embed_dim, num_classes) def forward(self, rt_input: torch.Tensor, ft_input: torch.Tensor) -> torch.Tensor: """ Args: rt_input: Range-Time域数据, shape=(B, 1, 51, 500) ft_input: Frequency-Time域数据, shape=(B, 1, 51, 500) Returns: logits: shape=(B, num_classes) """ rt_tokens = self.rt_patch(rt_input) for block in self.rt_blocks: rt_tokens = block(rt_tokens) rt_feat = rt_tokens[:, 0] ft_tokens = self.ft_patch(ft_input) for block in self.ft_blocks: ft_tokens = block(ft_tokens) ft_feat = ft_tokens[:, 0] beta = torch.sigmoid(self.beta) fused = beta * rt_feat + (1 - beta) * ft_feat fused = self.norm(fused) return self.head(fused)
if __name__ == "__main__": import numpy as np import time from sklearn.metrics import accuracy_score, classification_report NUM_CLASSES = 7 BATCH_SIZE = 16 H, W = 51, 500 ACTIVITIES = ['Relax', 'Drive', 'Nodding', 'Smoking', 'Drinking', 'Panel', 'Smartphone'] model = ISAViT( img_size=(H, W), in_channels=1, embed_dim=768, depth=12, num_heads=12, num_classes=NUM_CLASSES ) total_params = sum(p.numel() for p in model.parameters()) print(f"ISA-ViT参数量: {total_params:,}") print(f"计算量: ~0.3 GFLOPs") np.random.seed(42) def generate_uwb_signal(activity: str, batch=1): """根据活动类型生成模拟UWB信号""" t = np.linspace(0, 2, W) base = np.random.randn(batch, 1, H, W) * 0.1 if activity == 'Drive': base += 0.3 * np.sin(2*np.pi*5*t)[None,None,:] elif activity == 'Smartphone': base += 0.8 * np.sin(2*np.pi*15*t)[None,None,:] elif activity == 'Nodding': base += 1.0 * np.sin(2*np.pi*2*t)[None,None,:] elif activity == 'Smoking': base += 0.5 * np.sin(2*np.pi*8*t)[None,None,:] elif activity == 'Drinking': base += 0.7 * (np.sin(2*np.pi*20*t) > 0.5).astype(float)[None,None,:] return torch.tensor(base, dtype=torch.float32) print("\n--- 生成模拟数据 ---") for act in ACTIVITIES: rt = generate_uwb_signal(act, batch=1) print(f" {act:12s}: shape={rt.shape}, mean={rt.mean():.4f}, std={rt.std():.4f}") print("\n--- 前向传播 ---") model.eval() with torch.no_grad(): rt_batch = torch.cat([generate_uwb_signal(a, batch=2) for a in ACTIVITIES]) ft_batch = torch.cat([generate_uwb_signal(a, batch=2) for a in ACTIVITIES]) labels = torch.arange(7).repeat(2) logits = model(rt_batch, ft_batch) preds = torch.argmax(logits, dim=1) print(f"输入: RT={rt_batch.shape}, FT={ft_batch.shape}") print(f"输出: {logits.shape}") print(f"预测: {[ACTIVITIES[p] for p in preds]}") print("\n--- 训练流程 ---") criterion = nn.CrossEntropyLoss() optimizer = torch.optim.AdamW(model.parameters(), lr=3e-4, weight_decay=0.05) model.train() for epoch in range(3): optimizer.zero_grad() logits = model(rt_batch, ft_batch) loss = criterion(logits, labels) loss.backward() optimizer.step() acc = accuracy_score(labels.numpy(), torch.argmax(logits, dim=1).detach().numpy()) print(f"Epoch {epoch+1}: Loss={loss.item():.4f}, Acc={acc:.2%}") model.eval() with torch.no_grad(): start = time.time() for _ in range(50): _ = model(rt_batch[:1], ft_batch[:1]) elapsed = (time.time() - start) / 50 print(f"\n单样本推理延迟: {elapsed*1000:.1f}ms") print(f"计算量: 0.3 GFLOPs → 适合嵌入式部署")
|