build.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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(
  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. deploy = deploy,
  23. nms_class_agnostic=args.nms_class_agnostic
  24. )
  25. # -------------- Initialize YOLO --------------
  26. # Init bias
  27. init_prob = 0.01
  28. bias_value = -torch.log(torch.tensor((1. - init_prob) / init_prob))
  29. # obj pred
  30. b = model.obj_pred.bias.view(1, -1)
  31. b.data.fill_(bias_value.item())
  32. model.obj_pred.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
  33. # cls pred
  34. b = model.cls_pred.bias.view(1, -1)
  35. b.data.fill_(bias_value.item())
  36. model.cls_pred.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
  37. # reg pred
  38. b = model.reg_pred.bias.view(-1, )
  39. b.data.fill_(1.0)
  40. model.reg_pred.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
  41. w = model.reg_pred.weight
  42. w.data.fill_(0.)
  43. model.reg_pred.weight = torch.nn.Parameter(w, requires_grad=True)
  44. # -------------- Build criterion --------------
  45. criterion = None
  46. if trainable:
  47. # build criterion for training
  48. criterion = build_criterion(cfg, device, num_classes)
  49. return model, criterion