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 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
| """ Swin Transformer疲劳检测模型 论文Section 2.3描述的Swin架构
核心优势:层次化窗口注意力,降低计算复杂度
参考:Scientific Reports 2025, s41598-025-02111-x """
import torch import torch.nn as nn import torch.nn.functional as F from typing import Tuple, Optional import numpy as np
class WindowAttention(nn.Module): """ 窗口注意力机制(论文Section 2.3.1) Swin Transformer的核心创新:局部窗口内的自注意力 Args: dim: 输入维度 window_size: 窗口大小(论文使用7x7) num_heads: 头数量 """ def __init__( self, dim: int = 96, window_size: int = 7, num_heads: int = 3 ): super().__init__() self.dim = dim self.window_size = window_size self.num_heads = num_heads self.head_dim = dim // num_heads self.q_proj = nn.Linear(dim, dim) self.k_proj = nn.Linear(dim, dim) self.v_proj = nn.Linear(dim, dim) self.out_proj = nn.Linear(dim, dim) self.relative_position_bias_table = nn.Parameter( torch.zeros((2 * window_size - 1) ** 2, num_heads) ) nn.init.trunc_normal_(self.relative_position_bias_table, std=0.02) def forward(self, x: torch.Tensor) -> torch.Tensor: """ 前向传播 Args: x: 窗口内输入, shape=(B*num_windows, window_size*window_size, C) Returns: output: 窗口注意力输出 """ Bnw, N, C = x.shape q = self.q_proj(x).view(Bnw, N, self.num_heads, self.head_dim).transpose(1, 2) k = self.k_proj(x).view(Bnw, N, self.num_heads, self.head_dim).transpose(1, 2) v = self.v_proj(x).view(Bnw, N, self.num_heads, self.head_dim).transpose(1, 2) scores = torch.matmul(q, k.transpose(-2, -1)) / np.sqrt(self.head_dim) scores = scores + self.relative_position_bias_table[:N].unsqueeze(0).unsqueeze(0) attn_weights = F.softmax(scores, dim=-1) output = torch.matmul(attn_weights, v) output = output.transpose(1, 2).contiguous().view(Bnw, N, C) output = self.out_proj(output) return output
def window_partition(x: torch.Tensor, window_size: int) -> torch.Tensor: """ 将图像分割为窗口(论文Section 2.3.2) Args: x: 输入特征图, shape=(B, H, W, C) window_size: 窗口大小 Returns: windows: 窗口特征, shape=(B*num_windows, window_size, window_size, C) """ B, H, W, C = x.shape x = x.view(B, H // window_size, window_size, W // window_size, window_size, C) windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C) return windows
def window_reverse(windows: torch.Tensor, window_size: int, H: int, W: int) -> torch.Tensor: """ 将窗口合并为图像(论文Section 2.3.3) Args: windows: 窗口特征 window_size: 窗口大小 H, W: 原始图像大小 Returns: x: 合并后的特征图 """ B = int(windows.shape[0] / (H * W / window_size / window_size)) x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1) x = x.permute(0, 1, 4, 2, 5, 3).contiguous().view(B, H, W, -1) return x
class SwinTransformerBlock(nn.Module): """ Swin Transformer块(论文Section 2.3) 包含窗口注意力 + shifted窗口注意力 Args: dim: 输入维度 input_resolution: 输入分辨率 num_heads: 头数量 window_size: 窗口大小 shift_size: shifted窗口偏移 mlp_ratio: MLP扩展比例 dropout: dropout率 """ def __init__( self, dim: int = 96, input_resolution: Tuple[int, int] = (56, 56), num_heads: int = 3, window_size: int = 7, shift_size: int = 0, mlp_ratio: int = 4, dropout: float = 0.1 ): super().__init__() self.dim = dim self.input_resolution = input_resolution self.num_heads = num_heads self.window_size = window_size self.shift_size = shift_size self.norm1 = nn.LayerNorm(dim) self.attn = WindowAttention(dim, window_size, num_heads) self.drop = nn.Dropout(dropout) self.norm2 = nn.LayerNorm(dim) mlp_dim = dim * mlp_ratio self.mlp = nn.Sequential( nn.Linear(dim, mlp_dim), nn.GELU(), nn.Dropout(dropout), nn.Linear(mlp_dim, dim), nn.Dropout(dropout) ) def forward(self, x: torch.Tensor) -> torch.Tensor: """ 前向传播 Args: x: 输入特征, shape=(B, L, C) where L=H*W Returns: output: Swin块输出 """ H, W = self.input_resolution B, L, C = x.shape shortcut = x x = x.view(B, H, W, C) if self.shift_size > 0: shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2)) else: shifted_x = x x_windows = window_partition(shifted_x, self.window_size) x_windows = x_windows.view(-1, self.window_size * self.window_size, C) attn_windows = self.attn(x_windows) attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C) shifted_x = window_reverse(attn_windows, self.window_size, H, W) if self.shift_size > 0: x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2)) else: x = shifted_x x = x.view(B, H * W, C) x = shortcut + self.drop(self.norm1(x)) x = x + self.mlp(self.norm2(x)) return x
class SwinTransformer(nn.Module): """ Swin Transformer疲劳检测模型(论文Section 2.3) 论文配置: - 图像大小:224x224 - 窗口大小:7x7 - 层数:4阶段,每阶段2块 - 嵌入维度:96 -> 192 -> 384 -> 768 - 头数量:3 -> 6 -> 12 -> 24 - 参数量:约28M Args: img_size: 输入图像大小 in_channels: 输入通道数 num_classes: 分类数 embed_dim: 初始嵌入维度 depths: 每阶段层数 num_heads: 每阶段头数量 window_size: 窗口大小 mlp_ratio: MLP扩展比例 dropout: dropout率 """ def __init__( self, img_size: int = 224, in_channels: int = 3, num_classes: int = 2, embed_dim: int = 96, depths: Tuple[int, int, int, int] = (2, 2, 6, 2), num_heads: Tuple[int, int, int, int] = (3, 6, 12, 24), window_size: int = 7, mlp_ratio: int = 4, dropout: float = 0.1 ): super().__init__() self.num_classes = num_classes self.num_layers = len(depths) self.embed_dim = embed_dim self.patch_embed = nn.Sequential( nn.Conv2d(in_channels, embed_dim, kernel_size=4, stride=4), nn.LayerNorm([embed_dim]) ) self.patches_resolution = (img_size // 4, img_size // 4) self.absolute_pos_embed = nn.Parameter( torch.zeros(1, self.patches_resolution[0] * self.patches_resolution[1], embed_dim) ) self.pos_drop = nn.Dropout(dropout) self.stages = nn.ModuleList() for i_layer in range(self.num_layers): dim = embed_dim * (2 ** i_layer) input_resolution = ( self.patches_resolution[0] // (2 ** i_layer), self.patches_resolution[1] // (2 ** i_layer) ) stage = nn.ModuleList([ SwinTransformerBlock( dim=dim, input_resolution=input_resolution, num_heads=num_heads[i_layer], window_size=window_size, shift_size=0 if (i % 2 == 0) else window_size // 2, mlp_ratio=mlp_ratio, dropout=dropout ) for i in range(depths[i_layer]) ]) self.stages.append(stage) if i_layer < self.num_layers - 1: downsample = nn.Sequential( nn.Linear(dim, 2 * dim), nn.LayerNorm(2 * dim) ) self.stages.append(downsample) self.norm = nn.LayerNorm(embed_dim * (2 ** (self.num_layers - 1))) self.head = nn.Linear(embed_dim * (2 ** (self.num_layers - 1)), num_classes) nn.init.trunc_normal_(self.absolute_pos_embed, std=0.02) def forward(self, x: torch.Tensor) -> torch.Tensor: """ 前向传播 Args: x: 输入图像, shape=(B, C, H, W) Returns: logits: 分类输出 """ B = x.shape[0] x = self.patch_embed(x) x = x.flatten(2).transpose(1, 2) x = x + self.absolute_pos_embed x = self.pos_drop(x) for stage in self.stages: if isinstance(stage, nn.ModuleList): for block in stage: x = block(x) else: x = stage(x) x = self.norm(x) x = x.mean(dim=1) logits = self.head(x) return logits def get_num_parameters(self) -> int: """获取参数数量""" return sum(p.numel() for p in self.parameters())
if __name__ == "__main__": model = SwinTransformer( img_size=224, in_channels=3, num_classes=2, embed_dim=96, depths=(2, 2, 6, 2), num_heads=(3, 6, 12, 24), window_size=7, mlp_ratio=4, dropout=0.1 ) x = torch.randn(4, 3, 224, 224) logits = model(x) probs = torch.softmax(logits, dim=-1) print("=" * 70) print("Swin Transformer疲劳检测模型(论文配置)") print("=" * 70) print(f"图像大小: 224x224") print(f"窗口大小: 7x7") print(f"层数配置: [2, 2, 6, 2]") print(f"嵌入维度: 96 -> 192 -> 384 -> 768") print(f"头数量: [3, 6, 12, 24]") print(f"参数量: {model.get_num_parameters() / 1e6:.2f}M") print(f"输出shape: {logits.shape}") print("\n论文Table 3性能对比:") print(f"Swin Transformer: ~98%+ (论文未给出具体数值)") print(f"ViT: 99.15%") print(f"VGG19: 98.7%") classes = ['Open-Eyes', 'Close-Eyes'] for i in range(4): pred = classes[torch.argmax(probs[i]).item()] print(f"样本{i+1}: {pred} ({probs[i].max():.2%})")
|