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
| """ YOLOv11n疲劳检测模型 针对嵌入式设备优化 """
import torch import torch.nn as nn import torch.nn.functional as F from typing import Tuple, List, Optional import numpy as np
class ConvBlock(nn.Module): """ 标准卷积块:Conv + BN + SiLU """ def __init__( self, in_channels: int, out_channels: int, kernel_size: int = 3, stride: int = 1, padding: Optional[int] = None, groups: int = 1 ): super().__init__() if padding is None: padding = kernel_size // 2 self.conv = nn.Conv2d( in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=padding, groups=groups, bias=False ) self.bn = nn.BatchNorm2d(out_channels) self.act = nn.SiLU(inplace=True) def forward(self, x: torch.Tensor) -> torch.Tensor: return self.act(self.bn(self.conv(x)))
class C3k2(nn.Module): """ C3k2: YOLOv11轻量瓶颈模块 两层CSP瓶颈,优化计算效率 """ def __init__( self, in_channels: int, out_channels: int, num_bottlenecks: int = 2, expansion: float = 0.5, shortcut: bool = True ): super().__init__() hidden_channels = int(out_channels * expansion) self.cv1 = ConvBlock(in_channels, hidden_channels, 1, 1) self.cv2 = ConvBlock(in_channels, hidden_channels, 1, 1) self.bottlenecks = nn.ModuleList([ self._make_bottleneck(hidden_channels, hidden_channels, shortcut) for _ in range(num_bottlenecks) ]) self.cv3 = ConvBlock(hidden_channels * 2, out_channels, 1, 1) def _make_bottleneck( self, in_channels: int, out_channels: int, shortcut: bool ) -> nn.Module: """创建单个瓶颈块""" return nn.Sequential( ConvBlock(in_channels, out_channels, 3, 1), ConvBlock(out_channels, out_channels, 3, 1) ) def forward(self, x: torch.Tensor) -> torch.Tensor: y1 = self.cv1(x) y2 = self.cv2(x) for bottleneck in self.bottlenecks: y1 = bottleneck(y1) y = torch.cat([y1, y2], dim=1) return self.cv3(y)
class SPPF(nn.Module): """ SPPF: 快速空间金字塔池化 在保持计算效率的同时增大感受野 """ def __init__( self, in_channels: int, out_channels: int, kernel_size: int = 5 ): super().__init__() hidden_channels = in_channels // 2 self.cv1 = ConvBlock(in_channels, hidden_channels, 1, 1) self.cv2 = ConvBlock(hidden_channels * 4, out_channels, 1, 1) self.m = nn.MaxPool2d(kernel_size=kernel_size, stride=1, padding=kernel_size // 2) def forward(self, x: torch.Tensor) -> torch.Tensor: x = self.cv1(x) y1 = self.m(x) y2 = self.m(y1) y3 = self.m(y2) return self.cv2(torch.cat([x, y1, y2, y3], dim=1))
class AttentionModule(nn.Module): """ 轻量注意力模块 结合通道注意力和空间注意力 """ def __init__( self, channels: int, reduction: int = 16 ): super().__init__() self.channel_attention = nn.Sequential( nn.AdaptiveAvgPool2d(1), nn.Conv2d(channels, channels // reduction, 1), nn.SiLU(inplace=True), nn.Conv2d(channels // reduction, channels, 1), nn.Sigmoid() ) self.spatial_attention = nn.Sequential( nn.Conv2d(channels, 1, 7, padding=3), nn.Sigmoid() ) def forward(self, x: torch.Tensor) -> torch.Tensor: ca = self.channel_attention(x) x = x * ca sa = self.spatial_attention(x) x = x * sa return x
class DetectHead(nn.Module): """ 检测头 Anchor-free设计 """ def __init__( self, in_channels: List[int], num_classes: int, num_anchors: int = 1 ): super().__init__() self.num_classes = num_classes self.num_anchors = num_anchors self.heads = nn.ModuleList([ nn.Sequential( ConvBlock(c, c, 3, 1), ConvBlock(c, c, 3, 1), nn.Conv2d(c, (num_classes + 5) * num_anchors, 1) ) for c in in_channels ]) def forward( self, features: List[torch.Tensor] ) -> List[torch.Tensor]: """ Args: features: 多尺度特征列表 Returns: detections: 检测结果列表 """ outputs = [] for i, (feat, head) in enumerate(zip(features, self.heads)): out = head(feat) outputs.append(out) return outputs
class YOLOv11nFatigue(nn.Module): """ YOLOv11n疲劳检测模型 专为嵌入式设备优化的轻量级检测网络 """ def __init__( self, num_classes: int = 6, width_mult: float = 0.25, depth_mult: float = 0.34 ): super().__init__() base_channels = int(64 * width_mult) self.backbone = nn.Sequential( ConvBlock(3, base_channels, 3, 2), ConvBlock(base_channels, base_channels * 2, 3, 2), C3k2(base_channels * 2, base_channels * 2), ConvBlock(base_channels * 2, base_channels * 4, 3, 2), C3k2(base_channels * 4, base_channels * 4), ConvBlock(base_channels * 4, base_channels * 8, 3, 2), C3k2(base_channels * 8, base_channels * 8), ConvBlock(base_channels * 8, base_channels * 16, 3, 2), C3k2(base_channels * 16, base_channels * 16), SPPF(base_channels * 16, base_channels * 16) ) self.neck = nn.Sequential( nn.Upsample(scale_factor=2, mode='nearest'), C3k2(base_channels * 16 + base_channels * 8, base_channels * 8), nn.Upsample(scale_factor=2, mode='nearest'), C3k2(base_channels * 8 + base_channels * 4, base_channels * 4), ) self.detect = DetectHead( [base_channels * 4, base_channels * 8, base_channels * 16], num_classes ) def forward( self, x: torch.Tensor ) -> List[torch.Tensor]: """ Args: x: (batch, 3, H, W) Returns: detections: 多尺度检测结果 """ features = [] for i, layer in enumerate(self.backbone): x = layer(x) if i in [4, 6, 9]: features.append(x) outputs = self.detect(features) return outputs
if __name__ == "__main__": model = YOLOv11nFatigue(num_classes=6) x = torch.randn(1, 3, 640, 640) outputs = model(x) print("=== YOLOv11n疲劳检测模型测试 ===") print(f"输入形状: {x.shape}") print(f"输出尺度数: {len(outputs)}") for i, out in enumerate(outputs): print(f" 尺度{i+1}: {out.shape}") print(f"\n参数量: {sum(p.numel() for p in model.parameters()):,}") print(f"模型大小: {sum(p.numel() for p in model.parameters()) * 4 / 1024 / 1024:.2f} MB")
|