build.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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, deploy=False):
  9. print('==============================')
  10. print('Build {} ...'.format(args.model.upper()))
  11. print('==============================')
  12. print('Model Configuration: \n', cfg)
  13. # -------------- Build YOLO --------------
  14. model = YOLOv1(cfg = cfg,
  15. device = device,
  16. img_size = args.img_size,
  17. num_classes = num_classes,
  18. conf_thresh = args.conf_thresh,
  19. nms_thresh = args.nms_thresh,
  20. trainable = trainable,
  21. deploy = deploy,
  22. nms_class_agnostic = args.nms_class_agnostic
  23. )
  24. # -------------- Initialize YOLO --------------
  25. # Init bias
  26. init_prob = 0.01
  27. bias_value = -torch.log(torch.tensor((1. - init_prob) / init_prob))
  28. # obj pred
  29. b = model.obj_pred.bias.view(1, -1)
  30. b.data.fill_(bias_value.item())
  31. model.obj_pred.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
  32. # cls pred
  33. b = model.cls_pred.bias.view(1, -1)
  34. b.data.fill_(bias_value.item())
  35. model.cls_pred.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
  36. # reg pred
  37. b = model.reg_pred.bias.view(-1, )
  38. b.data.fill_(1.0)
  39. model.reg_pred.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
  40. w = model.reg_pred.weight
  41. w.data.fill_(0.)
  42. model.reg_pred.weight = torch.nn.Parameter(w, requires_grad=True)
  43. # -------------- Build criterion --------------
  44. criterion = None
  45. if trainable:
  46. # build criterion for training
  47. criterion = build_criterion(cfg, device, num_classes)
  48. return model, criterion