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
| import torch import torch.nn as nn import torch.nn.functional as F from collections import OrderedDict
class YOLOv1(nn.Module): """YOLOv1实现""" def __init__(self, num_classes=20, num_boxes=2): super(YOLOv1, self).__init__() self.num_classes = num_classes self.num_boxes = num_boxes self.features = self._make_layers() self.classifier = nn.Sequential( nn.Linear(1024 * 7 * 7, 4096), nn.ReLU(inplace=True), nn.Dropout(0.5), nn.Linear(4096, 7 * 7 * (num_classes + 5 * num_boxes)) ) def _make_layers(self): """构建特征提取网络""" layers = [] cfg = [ (64, 7, 2, 3), 'M', (192, 3, 1, 1), 'M', (128, 1, 1, 0), (256, 3, 1, 1), (256, 1, 1, 0), (512, 3, 1, 1), 'M', ] in_channels = 3 for v in cfg: if v == 'M': layers.append(nn.MaxPool2d(kernel_size=2, stride=2)) else: out_channels, kernel_size, stride, padding = v conv = nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=padding) layers.extend([conv, nn.BatchNorm2d(out_channels), nn.ReLU(inplace=True)]) in_channels = out_channels return nn.Sequential(*layers) def forward(self, x): """前向传播""" x = self.features(x) x = x.view(x.size(0), -1) x = self.classifier(x) batch_size = x.size(0) x = x.view(batch_size, 7, 7, self.num_classes + 5 * self.num_boxes) return x
class YOLOv3(nn.Module): """YOLOv3实现""" def __init__(self, num_classes=80): super(YOLOv3, self).__init__() self.num_classes = num_classes self.num_anchors = 3 self.backbone = Darknet53() self.detection_layers = nn.ModuleList([ self._make_detection_layer(1024, num_classes), self._make_detection_layer(512, num_classes), self._make_detection_layer(256, num_classes), ]) self.upsample = nn.Upsample(scale_factor=2, mode='nearest') self.conv_sets = nn.ModuleList([ self._make_conv_set(512, 1024), self._make_conv_set(256, 512), ]) def _make_detection_layer(self, in_channels, num_classes): """创建检测层""" return nn.Conv2d(in_channels, self.num_anchors * (5 + num_classes), kernel_size=1) def _make_conv_set(self, in_channels, out_channels): """创建卷积组""" return nn.Sequential( nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1), nn.BatchNorm2d(out_channels), nn.ReLU(inplace=True), nn.Conv2d(out_channels, in_channels, kernel_size=1), nn.BatchNorm2d(in_channels), nn.ReLU(inplace=True), ) def forward(self, x): """前向传播""" features = self.backbone(x) outputs = [] x = features[-1] detection_13 = self.detection_layers[0](x) outputs.append(detection_13) x = self.conv_sets[0](x) x = self.upsample(x) x = torch.cat([x, features[-2]], dim=1) detection_26 = self.detection_layers[1](x) outputs.append(detection_26) x = self.conv_sets[1](x) x = self.upsample(x) x = torch.cat([x, features[-3]], dim=1) detection_52 = self.detection_layers[2](x) outputs.append(detection_52) return outputs
class Darknet53(nn.Module): """Darknet-53骨干网络""" def __init__(self): super(Darknet53, self).__init__() self.conv1 = nn.Sequential( nn.Conv2d(3, 32, kernel_size=3, padding=1), nn.BatchNorm2d(32), nn.ReLU(inplace=True) ) self.layer1 = self._make_layer(32, 64, 1) self.layer2 = self._make_layer(64, 128, 2) self.layer3 = self._make_layer(128, 256, 8) self.layer4 = self._make_layer(256, 512, 8) self.layer5 = self._make_layer(512, 1024, 4) def _make_layer(self, in_channels, out_channels, num_blocks): """创建残差层""" layers = [] layers.append(nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=2, padding=1)) layers.append(nn.BatchNorm2d(out_channels)) layers.append(nn.ReLU(inplace=True)) for _ in range(num_blocks): layers.append(ResidualBlock(out_channels)) return nn.Sequential(*layers) def forward(self, x): """前向传播""" x = self.conv1(x) x1 = self.layer1(x) x2 = self.layer2(x1) x3 = self.layer3(x2) x4 = self.layer4(x3) x5 = self.layer5(x4) return [x3, x4, x5]
class ResidualBlock(nn.Module): """残差块""" def __init__(self, channels): super(ResidualBlock, self).__init__() self.conv1 = nn.Conv2d(channels, channels // 2, kernel_size=1) self.bn1 = nn.BatchNorm2d(channels // 2) self.conv2 = nn.Conv2d(channels // 2, channels, kernel_size=3, padding=1) self.bn2 = nn.BatchNorm2d(channels) self.relu = nn.ReLU(inplace=True) def forward(self, x): """前向传播""" residual = x out = self.relu(self.bn1(self.conv1(x))) out = self.bn2(self.conv2(out)) out += residual out = self.relu(out) return out
class YOLOLoss(nn.Module): """YOLO损失函数""" def __init__(self, num_classes=80, lambda_coord=5.0, lambda_noobj=0.5): super(YOLOLoss, self).__init__() self.num_classes = num_classes self.lambda_coord = lambda_coord self.lambda_noobj = lambda_noobj self.mse_loss = nn.MSELoss(reduction='sum') self.bce_loss = nn.BCELoss(reduction='sum') def forward(self, predictions, targets): """计算损失""" batch_size = predictions.size(0) pred_boxes = predictions[..., :4] pred_conf = predictions[..., 4] pred_cls = predictions[..., 5:] target_boxes = targets[..., :4] target_conf = targets[..., 4] target_cls = targets[..., 5:] coord_mask = target_conf > 0 coord_loss = self.lambda_coord * self.mse_loss( pred_boxes[coord_mask], target_boxes[coord_mask] ) conf_loss_obj = self.mse_loss( pred_conf[coord_mask], target_conf[coord_mask] ) conf_loss_noobj = self.lambda_noobj * self.mse_loss( pred_conf[~coord_mask], target_conf[~coord_mask] ) cls_loss = self.mse_loss( pred_cls[coord_mask], target_cls[coord_mask] ) total_loss = coord_loss + conf_loss_obj + conf_loss_noobj + cls_loss return total_loss / batch_size
class YOLOv5(nn.Module): """YOLOv5实现""" def __init__(self, num_classes=80, depth_multiple=1.0, width_multiple=1.0): super(YOLOv5, self).__init__() self.num_classes = num_classes self.backbone = CSPDarknet(depth_multiple, width_multiple) self.neck = PANet() self.head = YOLOHead(num_classes) def forward(self, x): """前向传播""" features = self.backbone(x) enhanced_features = self.neck(features) outputs = self.head(enhanced_features) return outputs
class CSPDarknet(nn.Module): """CSPDarknet骨干网络""" def __init__(self, depth_multiple=1.0, width_multiple=1.0): super(CSPDarknet, self).__init__() self.depth_multiple = depth_multiple self.width_multiple = width_multiple self.layers = self._build_layers() def _build_layers(self): """构建网络层""" layers = nn.ModuleList() configs = [ [-1, 1, 'Conv', [64, 6, 2, 2]], [-1, 1, 'Conv', [128, 3, 2]], [-1, 3, 'C3', [128]], [-1, 1, 'Conv', [256, 3, 2]], [-1, 6, 'C3', [256]], [-1, 1, 'Conv', [512, 3, 2]], [-1, 9, 'C3', [512]], [-1, 1, 'Conv', [1024, 3, 2]], [-1, 3, 'C3', [1024]], [-1, 1, 'SPPF', [1024, 5]], ] for config in configs: layers.append(self._make_layer(config)) return layers def _make_layer(self, config): """根据配置创建层""" from_layer, number, module_name, args = config if module_name == 'Conv': return Conv(*args) elif module_name == 'C3': return C3(*args) elif module_name == 'SPPF': return SPPF(*args) else: raise ValueError(f"Unknown module: {module_name}") def forward(self, x): """前向传播""" outputs = [] for layer in self.layers: x = layer(x) outputs.append(x) return [outputs[4], outputs[6], outputs[9]]
class Conv(nn.Module): """标准卷积层""" def __init__(self, in_channels, out_channels, kernel_size=1, stride=1, padding=None, groups=1, activation=True): super(Conv, self).__init__() if padding is None: padding = kernel_size // 2 self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding, groups=groups, bias=False) self.bn = nn.BatchNorm2d(out_channels) self.act = nn.SiLU() if activation else nn.Identity() def forward(self, x): return self.act(self.bn(self.conv(x)))
class C3(nn.Module): """CSP Bottleneck with 3 convolutions""" def __init__(self, in_channels, out_channels, number=1, shortcut=True, groups=1, expansion=0.5): super(C3, self).__init__() hidden_channels = int(out_channels * expansion) self.cv1 = Conv(in_channels, hidden_channels, 1, 1) self.cv2 = Conv(in_channels, hidden_channels, 1, 1) self.cv3 = Conv(2 * hidden_channels, out_channels, 1) self.m = nn.Sequential(*[Bottleneck(hidden_channels, hidden_channels, shortcut, groups, expansion=1.0) for _ in range(number)]) def forward(self, x): return self.cv3(torch.cat([self.m(self.cv1(x)), self.cv2(x)], dim=1))
class Bottleneck(nn.Module): """标准瓶颈层""" def __init__(self, in_channels, out_channels, shortcut=True, groups=1, expansion=0.5): super(Bottleneck, self).__init__() hidden_channels = int(out_channels * expansion) self.cv1 = Conv(in_channels, hidden_channels, 1, 1) self.cv2 = Conv(hidden_channels, out_channels, 3, 1, groups=groups) self.add = shortcut and in_channels == out_channels def forward(self, x): return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
class SPPF(nn.Module): """Spatial Pyramid Pooling - Fast""" def __init__(self, in_channels, out_channels, kernel_size=5): super(SPPF, self).__init__() hidden_channels = in_channels // 2 self.cv1 = Conv(in_channels, hidden_channels, 1, 1) self.cv2 = Conv(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): 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], 1))
|