build.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #!/usr/bin/env python3
  2. # -*- coding:utf-8 -*-
  3. import torch
  4. import torch.nn as nn
  5. from .loss import build_criterion
  6. from .yolov1 import YOLOv1
  7. # build object detector
  8. def build_yolov1(args, cfg, device, num_classes=80, trainable=False):
  9. print('==============================')
  10. print('Build {} ...'.format(args.model.upper()))
  11. print('==============================')
  12. print('Model Configuration: \n', cfg)
  13. # -------------- Build YOLO --------------
  14. model = YOLOv1(
  15. cfg = cfg,
  16. device = device,
  17. img_size = args.img_size,
  18. num_classes = num_classes,
  19. conf_thresh = args.conf_thresh,
  20. nms_thresh = args.nms_thresh,
  21. trainable = trainable
  22. )
  23. # -------------- Initialize YOLO --------------
  24. # Init bias
  25. init_prob = 0.01
  26. bias_value = -torch.log(torch.tensor((1. - init_prob) / init_prob))
  27. # obj pred
  28. b = model.obj_pred.bias.view(1, -1)
  29. b.data.fill_(bias_value.item())
  30. model.obj_pred.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
  31. # cls pred
  32. b = model.cls_pred.bias.view(1, -1)
  33. b.data.fill_(bias_value.item())
  34. model.cls_pred.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
  35. # reg pred
  36. b = model.reg_pred.bias.view(-1, )
  37. b.data.fill_(1.0)
  38. model.reg_pred.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
  39. w = model.reg_pred.weight
  40. w.data.fill_(0.)
  41. model.reg_pred.weight = torch.nn.Parameter(w, requires_grad=True)
  42. # -------------- Build criterion --------------
  43. criterion = None
  44. if trainable:
  45. # build criterion for training
  46. criterion = build_criterion(cfg, device, num_classes)
  47. return model, criterion