├── .DS_Store
├── .idea
├── YOLOv5_with_BiFPN.iml
├── misc.xml
├── modules.xml
├── vcs.xml
└── workspace.xml
├── README.md
├── data
├── coco128.yaml
├── hyp.finetune.yaml
├── hyp.scratch.yaml
└── scripts
│ └── get_coco.sh
├── detect.py
├── hubconf.py
├── models
├── __init__.py
├── __pycache__
│ ├── __init__.cpython-37.pyc
│ ├── common.cpython-37.pyc
│ └── experimental.cpython-37.pyc
├── common.py
├── experimental.py
├── export.py
├── hub
│ ├── anchors.yaml
│ ├── yolov3-spp.yaml
│ ├── yolov3-tiny.yaml
│ ├── yolov3.yaml
│ ├── yolov5-fpn.yaml
│ ├── yolov5-p2.yaml
│ ├── yolov5-p6.yaml
│ ├── yolov5-p7.yaml
│ ├── yolov5-panet.yaml
│ ├── yolov5l6.yaml
│ ├── yolov5m6.yaml
│ ├── yolov5s-transformer.yaml
│ ├── yolov5s6.yaml
│ └── yolov5x6.yaml
├── yolo.py
└── yolov5x.yaml
├── requirements.txt
├── test.py
├── train.py
├── utils
├── __init__.py
├── __pycache__
│ ├── __init__.cpython-37.pyc
│ ├── autoanchor.cpython-37.pyc
│ ├── datasets.cpython-37.pyc
│ ├── general.cpython-37.pyc
│ ├── google_utils.cpython-37.pyc
│ ├── metrics.cpython-37.pyc
│ ├── plots.cpython-37.pyc
│ └── torch_utils.cpython-37.pyc
├── activations.py
├── autoanchor.py
├── aws
│ ├── __init__.py
│ ├── mime.sh
│ ├── resume.py
│ └── userdata.sh
├── datasets.py
├── flask_rest_api
│ ├── README.md
│ ├── example_request.py
│ └── restapi.py
├── general.py
├── google_app_engine
│ ├── Dockerfile
│ ├── additional_requirements.txt
│ └── app.yaml
├── google_utils.py
├── loss.py
├── metrics.py
├── plots.py
├── torch_utils.py
└── wandb_logging
│ ├── __init__.py
│ ├── log_dataset.py
│ └── wandb_utils.py
└── weights
└── download_weights.sh
/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/XingZeng307/YOLOv5_with_BiFPN/59322217045be24b60f50c4d8a90b98e4d8dd6cf/.DS_Store
--------------------------------------------------------------------------------
/.idea/YOLOv5_with_BiFPN.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/workspace.xml:
--------------------------------------------------------------------------------
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 | color_list
50 | concat
51 |
52 |
53 |
54 |
55 |
56 |
57 |
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 | 1619988871602
170 |
171 |
172 | 1619988871602
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 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # YOLOv5_with_BiFPN
2 |
3 | YOLOv5 implementation is completely from the original repository (https://github.com/ultralytics/yolov5).
4 | This repo is mainly for replacing PANet with BiFPN in YOLOv5, which you can check in models/yolov5x.yaml. I didn't use the exact same BiFPN in the paper, while I try to be consistent with yolov5, so still three scale predictions.
5 |
6 | # Training
7 |
8 | python train.py --img 640 --batch 8 --epochs 200 --data CUB.yaml --weights '' --cfg yolov5x.yaml
9 |
10 | I didn't use pre-trained weights since the architecture changes a bit. And as for the performance, I will check more dataset and update it.
11 |
12 |
13 | # Reference
14 |
15 | https://github.com/ultralytics/yolov5
16 |
17 | https://github.com/zylo117/Yet-Another-EfficientDet-Pytorch/tree/15403b5371a64defb2a7c74e162c6e880a7f462c
18 |
19 | Mingxing Tan, Ruoming Pang, and Quoc V Le. EfficientDet: Scalable and efficient object detection. In Proceedings
20 | of the IEEE Conference on Computer Vision and Pattern
21 | Recognition (CVPR), 2020.
22 |
--------------------------------------------------------------------------------
/data/coco128.yaml:
--------------------------------------------------------------------------------
1 | # COCO 2017 dataset http://cocodataset.org - first 128 training images
2 | # Train command: python train.py --data coco128.yaml
3 | # Default dataset location is next to YOLOv5:
4 | # /parent_folder
5 | # /coco128
6 | # /yolov5
7 |
8 |
9 | # download command/URL (optional)
10 | download: https://github.com/ultralytics/yolov5/releases/download/v1.0/coco128.zip
11 |
12 | # train and val data as 1) directory: path/images/, 2) file: path/images.txt, or 3) list: [path1/images/, path2/images/]
13 | train: ../coco128/images/train2017/ # 128 images
14 | val: ../coco128/images/train2017/ # 128 images
15 |
16 | # number of classes
17 | nc: 80
18 |
19 | # class names
20 | names: [ 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light',
21 | 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',
22 | 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee',
23 | 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard',
24 | 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',
25 | 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch',
26 | 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone',
27 | 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear',
28 | 'hair drier', 'toothbrush' ]
29 |
--------------------------------------------------------------------------------
/data/hyp.finetune.yaml:
--------------------------------------------------------------------------------
1 | # Hyperparameters for VOC finetuning
2 | # python train.py --batch 64 --weights yolov5m.pt --data voc.yaml --img 512 --epochs 50
3 | # See tutorials for hyperparameter evolution https://github.com/ultralytics/yolov5#tutorials
4 |
5 |
6 | # Hyperparameter Evolution Results
7 | # Generations: 306
8 | # P R mAP.5 mAP.5:.95 box obj cls
9 | # Metrics: 0.6 0.936 0.896 0.684 0.0115 0.00805 0.00146
10 |
11 | lr0: 0.0032
12 | lrf: 0.12
13 | momentum: 0.843
14 | weight_decay: 0.00036
15 | warmup_epochs: 2.0
16 | warmup_momentum: 0.5
17 | warmup_bias_lr: 0.05
18 | box: 0.0296
19 | cls: 0.243
20 | cls_pw: 0.631
21 | obj: 0.301
22 | obj_pw: 0.911
23 | iou_t: 0.2
24 | anchor_t: 2.91
25 | # anchors: 3.63
26 | fl_gamma: 0.0
27 | hsv_h: 0.0138
28 | hsv_s: 0.664
29 | hsv_v: 0.464
30 | degrees: 0.373
31 | translate: 0.245
32 | scale: 0.898
33 | shear: 0.602
34 | perspective: 0.0
35 | flipud: 0.00856
36 | fliplr: 0.5
37 | mosaic: 1.0
38 | mixup: 0.243
39 |
--------------------------------------------------------------------------------
/data/hyp.scratch.yaml:
--------------------------------------------------------------------------------
1 | # Hyperparameters for COCO training from scratch
2 | # python train.py --batch 40 --cfg yolov5m.yaml --weights '' --data coco.yaml --img 640 --epochs 300
3 | # See tutorials for hyperparameter evolution https://github.com/ultralytics/yolov5#tutorials
4 |
5 |
6 | lr0: 0.01 # initial learning rate (SGD=1E-2, Adam=1E-3)
7 | lrf: 0.2 # final OneCycleLR learning rate (lr0 * lrf)
8 | momentum: 0.937 # SGD momentum/Adam beta1
9 | weight_decay: 0.0005 # optimizer weight decay 5e-4
10 | warmup_epochs: 3.0 # warmup epochs (fractions ok)
11 | warmup_momentum: 0.8 # warmup initial momentum
12 | warmup_bias_lr: 0.1 # warmup initial bias lr
13 | box: 0.05 # box loss gain
14 | cls: 0.5 # cls loss gain
15 | cls_pw: 1.0 # cls BCELoss positive_weight
16 | obj: 1.0 # obj loss gain (scale with pixels)
17 | obj_pw: 1.0 # obj BCELoss positive_weight
18 | iou_t: 0.20 # IoU training threshold
19 | anchor_t: 4.0 # anchor-multiple threshold
20 | # anchors: 3 # anchors per output layer (0 to ignore)
21 | fl_gamma: 0.0 # focal loss gamma (efficientDet default gamma=1.5)
22 | hsv_h: 0.015 # image HSV-Hue augmentation (fraction)
23 | hsv_s: 0.7 # image HSV-Saturation augmentation (fraction)
24 | hsv_v: 0.4 # image HSV-Value augmentation (fraction)
25 | degrees: 0.0 # image rotation (+/- deg)
26 | translate: 0.1 # image translation (+/- fraction)
27 | scale: 0.5 # image scale (+/- gain)
28 | shear: 0.0 # image shear (+/- deg)
29 | perspective: 0.0 # image perspective (+/- fraction), range 0-0.001
30 | flipud: 0.0 # image flip up-down (probability)
31 | fliplr: 0.5 # image flip left-right (probability)
32 | mosaic: 1.0 # image mosaic (probability)
33 | mixup: 0.0 # image mixup (probability)
34 |
--------------------------------------------------------------------------------
/data/scripts/get_coco.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | # COCO 2017 dataset http://cocodataset.org
3 | # Download command: bash data/scripts/get_coco.sh
4 | # Train command: python train.py --data coco.yaml
5 | # Default dataset location is next to YOLOv5:
6 | # /parent_folder
7 | # /coco
8 | # /yolov5
9 |
10 | # Download/unzip labels
11 | d='../' # unzip directory
12 | url=https://github.com/ultralytics/yolov5/releases/download/v1.0/
13 | f='coco2017labels.zip' # or 'coco2017labels-segments.zip', 68 MB
14 | echo 'Downloading' $url$f ' ...'
15 | curl -L $url$f -o $f && unzip -q $f -d $d && rm $f & # download, unzip, remove in background
16 |
17 | # Download/unzip images
18 | d='../coco/images' # unzip directory
19 | url=http://images.cocodataset.org/zips/
20 | f1='train2017.zip' # 19G, 118k images
21 | f2='val2017.zip' # 1G, 5k images
22 | f3='test2017.zip' # 7G, 41k images (optional)
23 | for f in $f1 $f2; do
24 | echo 'Downloading' $url$f '...'
25 | curl -L $url$f -o $f && unzip -q $f -d $d && rm $f & # download, unzip, remove in background
26 | done
27 | wait # finish background tasks
28 |
--------------------------------------------------------------------------------
/detect.py:
--------------------------------------------------------------------------------
1 | import argparse
2 | import time
3 | from pathlib import Path
4 |
5 | import cv2
6 | import torch
7 | import torch.backends.cudnn as cudnn
8 | from numpy import random
9 |
10 | from models.experimental import attempt_load
11 | from utils.datasets import LoadStreams, LoadImages
12 | from utils.general import check_img_size, check_requirements, check_imshow, non_max_suppression, apply_classifier, \
13 | scale_coords, xyxy2xywh, strip_optimizer, set_logging, increment_path, save_one_box
14 | from utils.plots import plot_one_box
15 | from utils.torch_utils import select_device, load_classifier, time_synchronized
16 |
17 |
18 | def detect(opt):
19 | source, weights, view_img, save_txt, imgsz = opt.source, opt.weights, opt.view_img, opt.save_txt, opt.img_size
20 | save_img = not opt.nosave and not source.endswith('.txt') # save inference images
21 | webcam = source.isnumeric() or source.endswith('.txt') or source.lower().startswith(
22 | ('rtsp://', 'rtmp://', 'http://', 'https://'))
23 |
24 | # Directories
25 | save_dir = increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok) # increment run
26 | (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
27 |
28 | # Initialize
29 | set_logging()
30 | device = select_device(opt.device)
31 | half = device.type != 'cpu' # half precision only supported on CUDA
32 |
33 | # Load model
34 | model = attempt_load(weights, map_location=device) # load FP32 model
35 | stride = int(model.stride.max()) # model stride
36 | imgsz = check_img_size(imgsz, s=stride) # check img_size
37 | if half:
38 | model.half() # to FP16
39 |
40 | # Second-stage classifier
41 | classify = False
42 | if classify:
43 | modelc = load_classifier(name='resnet101', n=2) # initialize
44 | modelc.load_state_dict(torch.load('weights/resnet101.pt', map_location=device)['model']).to(device).eval()
45 |
46 | # Set Dataloader
47 | vid_path, vid_writer = None, None
48 | if webcam:
49 | view_img = check_imshow()
50 | cudnn.benchmark = True # set True to speed up constant image size inference
51 | dataset = LoadStreams(source, img_size=imgsz, stride=stride)
52 | else:
53 | dataset = LoadImages(source, img_size=imgsz, stride=stride)
54 |
55 | # Get names and colors
56 | names = model.module.names if hasattr(model, 'module') else model.names
57 | colors = [[random.randint(0, 255) for _ in range(3)] for _ in names]
58 |
59 | # Run inference
60 | if device.type != 'cpu':
61 | model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) # run once
62 | t0 = time.time()
63 | for path, img, im0s, vid_cap in dataset:
64 | img = torch.from_numpy(img).to(device)
65 | img = img.half() if half else img.float() # uint8 to fp16/32
66 | img /= 255.0 # 0 - 255 to 0.0 - 1.0
67 | if img.ndimension() == 3:
68 | img = img.unsqueeze(0)
69 |
70 | # Inference
71 | t1 = time_synchronized()
72 | pred = model(img, augment=opt.augment)[0]
73 |
74 | # Apply NMS
75 | pred = non_max_suppression(pred, opt.conf_thres, opt.iou_thres, classes=opt.classes, agnostic=opt.agnostic_nms)
76 | t2 = time_synchronized()
77 |
78 | # Apply Classifier
79 | if classify:
80 | pred = apply_classifier(pred, modelc, img, im0s)
81 |
82 | # Process detections
83 | for i, det in enumerate(pred): # detections per image
84 | if webcam: # batch_size >= 1
85 | p, s, im0, frame = path[i], '%g: ' % i, im0s[i].copy(), dataset.count
86 | else:
87 | p, s, im0, frame = path, '', im0s.copy(), getattr(dataset, 'frame', 0)
88 |
89 | p = Path(p) # to Path
90 | save_path = str(save_dir / p.name) # img.jpg
91 | txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # img.txt
92 | s += '%gx%g ' % img.shape[2:] # print string
93 | gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
94 | if len(det):
95 | # Rescale boxes from img_size to im0 size
96 | det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
97 |
98 | # Print results
99 | for c in det[:, -1].unique():
100 | n = (det[:, -1] == c).sum() # detections per class
101 | s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string
102 |
103 | # Write results
104 | for *xyxy, conf, cls in reversed(det):
105 | if save_txt: # Write to file
106 | xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
107 | line = (cls, *xywh, conf) if opt.save_conf else (cls, *xywh) # label format
108 | with open(txt_path + '.txt', 'a') as f:
109 | f.write(('%g ' * len(line)).rstrip() % line + '\n')
110 |
111 | if save_img or opt.save_crop or view_img: # Add bbox to image
112 | c = int(cls) # integer class
113 | label = None if opt.hide_labels else (names[c] if opt.hide_conf else f'{names[c]} {conf:.2f}')
114 |
115 | plot_one_box(xyxy, im0, label=label, color=colors[c], line_thickness=opt.line_thickness)
116 | if opt.save_crop:
117 | save_one_box(xyxy, im0s, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True)
118 |
119 | # Print time (inference + NMS)
120 | print(f'{s}Done. ({t2 - t1:.3f}s)')
121 |
122 | # Stream results
123 | if view_img:
124 | cv2.imshow(str(p), im0)
125 | cv2.waitKey(1) # 1 millisecond
126 |
127 | # Save results (image with detections)
128 | if save_img:
129 | if dataset.mode == 'image':
130 | cv2.imwrite(save_path, im0)
131 | else: # 'video' or 'stream'
132 | if vid_path != save_path: # new video
133 | vid_path = save_path
134 | if isinstance(vid_writer, cv2.VideoWriter):
135 | vid_writer.release() # release previous video writer
136 | if vid_cap: # video
137 | fps = vid_cap.get(cv2.CAP_PROP_FPS)
138 | w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
139 | h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
140 | else: # stream
141 | fps, w, h = 30, im0.shape[1], im0.shape[0]
142 | save_path += '.mp4'
143 | vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
144 | vid_writer.write(im0)
145 |
146 | if save_txt or save_img:
147 | s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
148 | print(f"Results saved to {save_dir}{s}")
149 |
150 | print(f'Done. ({time.time() - t0:.3f}s)')
151 |
152 |
153 | if __name__ == '__main__':
154 | parser = argparse.ArgumentParser()
155 | parser.add_argument('--weights', nargs='+', type=str, default='yolov5s.pt', help='model.pt path(s)')
156 | parser.add_argument('--source', type=str, default='data/images', help='source') # file/folder, 0 for webcam
157 | parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)')
158 | parser.add_argument('--conf-thres', type=float, default=0.25, help='object confidence threshold')
159 | parser.add_argument('--iou-thres', type=float, default=0.45, help='IOU threshold for NMS')
160 | parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
161 | parser.add_argument('--view-img', action='store_true', help='display results')
162 | parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
163 | parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
164 | parser.add_argument('--save-crop', action='store_true', help='save cropped prediction boxes')
165 | parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
166 | parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --class 0, or --class 0 2 3')
167 | parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
168 | parser.add_argument('--augment', action='store_true', help='augmented inference')
169 | parser.add_argument('--update', action='store_true', help='update all models')
170 | parser.add_argument('--project', default='runs/detect', help='save results to project/name')
171 | parser.add_argument('--name', default='exp', help='save results to project/name')
172 | parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
173 | parser.add_argument('--line-thickness', default=3, type=int, help='bounding box thickness (pixels)')
174 | parser.add_argument('--hide-labels', default=False, action='store_true', help='hide labels')
175 | parser.add_argument('--hide-conf', default=True, action='store_true', help='hide confidences')
176 | opt = parser.parse_args()
177 | print(opt)
178 | check_requirements(exclude=('pycocotools', 'thop'))
179 |
180 | with torch.no_grad():
181 | if opt.update: # update all models (to fix SourceChangeWarning)
182 | for opt.weights in ['yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt']:
183 | detect(opt=opt)
184 | strip_optimizer(opt.weights)
185 | else:
186 | detect(opt=opt)
187 |
--------------------------------------------------------------------------------
/hubconf.py:
--------------------------------------------------------------------------------
1 | """YOLOv5 PyTorch Hub models https://pytorch.org/hub/ultralytics_yolov5/
2 |
3 | Usage:
4 | import torch
5 | model = torch.hub.load('ultralytics/yolov5', 'yolov5s')
6 | """
7 |
8 | from pathlib import Path
9 |
10 | import torch
11 |
12 | from models.yolo import Model
13 | from utils.general import check_requirements, set_logging
14 | from utils.google_utils import attempt_download
15 | from utils.torch_utils import select_device
16 |
17 | dependencies = ['torch', 'yaml']
18 | check_requirements(Path(__file__).parent / 'requirements.txt', exclude=('pycocotools', 'thop'))
19 | set_logging()
20 |
21 |
22 | def create(name, pretrained, channels, classes, autoshape):
23 | """Creates a specified YOLOv5 model
24 |
25 | Arguments:
26 | name (str): name of model, i.e. 'yolov5s'
27 | pretrained (bool): load pretrained weights into the model
28 | channels (int): number of input channels
29 | classes (int): number of model classes
30 |
31 | Returns:
32 | pytorch model
33 | """
34 | try:
35 | cfg = list((Path(__file__).parent / 'models').rglob(f'{name}.yaml'))[0] # model.yaml path
36 | model = Model(cfg, channels, classes)
37 | if pretrained:
38 | fname = f'{name}.pt' # checkpoint filename
39 | attempt_download(fname) # download if not found locally
40 | ckpt = torch.load(fname, map_location=torch.device('cpu')) # load
41 | msd = model.state_dict() # model state_dict
42 | csd = ckpt['model'].float().state_dict() # checkpoint state_dict as FP32
43 | csd = {k: v for k, v in csd.items() if msd[k].shape == v.shape} # filter
44 | model.load_state_dict(csd, strict=False) # load
45 | if len(ckpt['model'].names) == classes:
46 | model.names = ckpt['model'].names # set class names attribute
47 | if autoshape:
48 | model = model.autoshape() # for file/URI/PIL/cv2/np inputs and NMS
49 | device = select_device('0' if torch.cuda.is_available() else 'cpu') # default to GPU if available
50 | return model.to(device)
51 |
52 | except Exception as e:
53 | help_url = 'https://github.com/ultralytics/yolov5/issues/36'
54 | s = 'Cache maybe be out of date, try force_reload=True. See %s for help.' % help_url
55 | raise Exception(s) from e
56 |
57 |
58 | def custom(path_or_model='path/to/model.pt', autoshape=True):
59 | """YOLOv5-custom model https://github.com/ultralytics/yolov5
60 |
61 | Arguments (3 options):
62 | path_or_model (str): 'path/to/model.pt'
63 | path_or_model (dict): torch.load('path/to/model.pt')
64 | path_or_model (nn.Module): torch.load('path/to/model.pt')['model']
65 |
66 | Returns:
67 | pytorch model
68 | """
69 | model = torch.load(path_or_model) if isinstance(path_or_model, str) else path_or_model # load checkpoint
70 | if isinstance(model, dict):
71 | model = model['ema' if model.get('ema') else 'model'] # load model
72 |
73 | hub_model = Model(model.yaml).to(next(model.parameters()).device) # create
74 | hub_model.load_state_dict(model.float().state_dict()) # load state_dict
75 | hub_model.names = model.names # class names
76 | if autoshape:
77 | hub_model = hub_model.autoshape() # for file/URI/PIL/cv2/np inputs and NMS
78 | device = select_device('0' if torch.cuda.is_available() else 'cpu') # default to GPU if available
79 | return hub_model.to(device)
80 |
81 |
82 | def yolov5s(pretrained=True, channels=3, classes=80, autoshape=True):
83 | # YOLOv5-small model https://github.com/ultralytics/yolov5
84 | return create('yolov5s', pretrained, channels, classes, autoshape)
85 |
86 |
87 | def yolov5m(pretrained=True, channels=3, classes=80, autoshape=True):
88 | # YOLOv5-medium model https://github.com/ultralytics/yolov5
89 | return create('yolov5m', pretrained, channels, classes, autoshape)
90 |
91 |
92 | def yolov5l(pretrained=True, channels=3, classes=80, autoshape=True):
93 | # YOLOv5-large model https://github.com/ultralytics/yolov5
94 | return create('yolov5l', pretrained, channels, classes, autoshape)
95 |
96 |
97 | def yolov5x(pretrained=True, channels=3, classes=80, autoshape=True):
98 | # YOLOv5-xlarge model https://github.com/ultralytics/yolov5
99 | return create('yolov5x', pretrained, channels, classes, autoshape)
100 |
101 |
102 | def yolov5s6(pretrained=True, channels=3, classes=80, autoshape=True):
103 | # YOLOv5-small model https://github.com/ultralytics/yolov5
104 | return create('yolov5s6', pretrained, channels, classes, autoshape)
105 |
106 |
107 | def yolov5m6(pretrained=True, channels=3, classes=80, autoshape=True):
108 | # YOLOv5-medium model https://github.com/ultralytics/yolov5
109 | return create('yolov5m6', pretrained, channels, classes, autoshape)
110 |
111 |
112 | def yolov5l6(pretrained=True, channels=3, classes=80, autoshape=True):
113 | # YOLOv5-large model https://github.com/ultralytics/yolov5
114 | return create('yolov5l6', pretrained, channels, classes, autoshape)
115 |
116 |
117 | def yolov5x6(pretrained=True, channels=3, classes=80, autoshape=True):
118 | # YOLOv5-xlarge model https://github.com/ultralytics/yolov5
119 | return create('yolov5x6', pretrained, channels, classes, autoshape)
120 |
121 |
122 | if __name__ == '__main__':
123 | model = create(name='yolov5s', pretrained=True, channels=3, classes=80, autoshape=True) # pretrained example
124 | # model = custom(path_or_model='path/to/model.pt') # custom example
125 |
126 | # Verify inference
127 | import cv2
128 | import numpy as np
129 | from PIL import Image
130 |
131 | imgs = ['data/images/zidane.jpg', # filename
132 | 'https://github.com/ultralytics/yolov5/releases/download/v1.0/zidane.jpg', # URI
133 | cv2.imread('data/images/bus.jpg')[:, :, ::-1], # OpenCV
134 | Image.open('data/images/bus.jpg'), # PIL
135 | np.zeros((320, 640, 3))] # numpy
136 |
137 | results = model(imgs) # batched inference
138 | results.print()
139 | results.save()
140 |
--------------------------------------------------------------------------------
/models/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/XingZeng307/YOLOv5_with_BiFPN/59322217045be24b60f50c4d8a90b98e4d8dd6cf/models/__init__.py
--------------------------------------------------------------------------------
/models/__pycache__/__init__.cpython-37.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/XingZeng307/YOLOv5_with_BiFPN/59322217045be24b60f50c4d8a90b98e4d8dd6cf/models/__pycache__/__init__.cpython-37.pyc
--------------------------------------------------------------------------------
/models/__pycache__/common.cpython-37.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/XingZeng307/YOLOv5_with_BiFPN/59322217045be24b60f50c4d8a90b98e4d8dd6cf/models/__pycache__/common.cpython-37.pyc
--------------------------------------------------------------------------------
/models/__pycache__/experimental.cpython-37.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/XingZeng307/YOLOv5_with_BiFPN/59322217045be24b60f50c4d8a90b98e4d8dd6cf/models/__pycache__/experimental.cpython-37.pyc
--------------------------------------------------------------------------------
/models/experimental.py:
--------------------------------------------------------------------------------
1 | # YOLOv5 experimental modules
2 |
3 | import numpy as np
4 | import torch
5 | import torch.nn as nn
6 |
7 | from models.common import Conv, DWConv
8 | from utils.google_utils import attempt_download
9 |
10 |
11 | class CrossConv(nn.Module):
12 | # Cross Convolution Downsample
13 | def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False):
14 | # ch_in, ch_out, kernel, stride, groups, expansion, shortcut
15 | super(CrossConv, self).__init__()
16 | c_ = int(c2 * e) # hidden channels
17 | self.cv1 = Conv(c1, c_, (1, k), (1, s))
18 | self.cv2 = Conv(c_, c2, (k, 1), (s, 1), g=g)
19 | self.add = shortcut and c1 == c2
20 |
21 | def forward(self, x):
22 | return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
23 |
24 |
25 | class Sum(nn.Module):
26 | # Weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070
27 | def __init__(self, n, weight=False): # n: number of inputs
28 | super(Sum, self).__init__()
29 | self.weight = weight # apply weights boolean
30 | self.iter = range(n - 1) # iter object
31 | if weight:
32 | self.w = nn.Parameter(-torch.arange(1., n) / 2, requires_grad=True) # layer weights
33 |
34 | def forward(self, x):
35 | y = x[0] # no weight
36 | if self.weight:
37 | w = torch.sigmoid(self.w) * 2
38 | for i in self.iter:
39 | y = y + x[i + 1] * w[i]
40 | else:
41 | for i in self.iter:
42 | y = y + x[i + 1]
43 | return y
44 |
45 |
46 | class GhostConv(nn.Module):
47 | # Ghost Convolution https://github.com/huawei-noah/ghostnet
48 | def __init__(self, c1, c2, k=1, s=1, g=1, act=True): # ch_in, ch_out, kernel, stride, groups
49 | super(GhostConv, self).__init__()
50 | c_ = c2 // 2 # hidden channels
51 | self.cv1 = Conv(c1, c_, k, s, None, g, act)
52 | self.cv2 = Conv(c_, c_, 5, 1, None, c_, act)
53 |
54 | def forward(self, x):
55 | y = self.cv1(x)
56 | return torch.cat([y, self.cv2(y)], 1)
57 |
58 |
59 | class GhostBottleneck(nn.Module):
60 | # Ghost Bottleneck https://github.com/huawei-noah/ghostnet
61 | def __init__(self, c1, c2, k=3, s=1): # ch_in, ch_out, kernel, stride
62 | super(GhostBottleneck, self).__init__()
63 | c_ = c2 // 2
64 | self.conv = nn.Sequential(GhostConv(c1, c_, 1, 1), # pw
65 | DWConv(c_, c_, k, s, act=False) if s == 2 else nn.Identity(), # dw
66 | GhostConv(c_, c2, 1, 1, act=False)) # pw-linear
67 | self.shortcut = nn.Sequential(DWConv(c1, c1, k, s, act=False),
68 | Conv(c1, c2, 1, 1, act=False)) if s == 2 else nn.Identity()
69 |
70 | def forward(self, x):
71 | return self.conv(x) + self.shortcut(x)
72 |
73 |
74 | class MixConv2d(nn.Module):
75 | # Mixed Depthwise Conv https://arxiv.org/abs/1907.09595
76 | def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True):
77 | super(MixConv2d, self).__init__()
78 | groups = len(k)
79 | if equal_ch: # equal c_ per group
80 | i = torch.linspace(0, groups - 1E-6, c2).floor() # c2 indices
81 | c_ = [(i == g).sum() for g in range(groups)] # intermediate channels
82 | else: # equal weight.numel() per group
83 | b = [c2] + [0] * groups
84 | a = np.eye(groups + 1, groups, k=-1)
85 | a -= np.roll(a, 1, axis=1)
86 | a *= np.array(k) ** 2
87 | a[0] = 1
88 | c_ = np.linalg.lstsq(a, b, rcond=None)[0].round() # solve for equal weight indices, ax = b
89 |
90 | self.m = nn.ModuleList([nn.Conv2d(c1, int(c_[g]), k[g], s, k[g] // 2, bias=False) for g in range(groups)])
91 | self.bn = nn.BatchNorm2d(c2)
92 | self.act = nn.LeakyReLU(0.1, inplace=True)
93 |
94 | def forward(self, x):
95 | return x + self.act(self.bn(torch.cat([m(x) for m in self.m], 1)))
96 |
97 |
98 | class Ensemble(nn.ModuleList):
99 | # Ensemble of models
100 | def __init__(self):
101 | super(Ensemble, self).__init__()
102 |
103 | def forward(self, x, augment=False):
104 | y = []
105 | for module in self:
106 | y.append(module(x, augment)[0])
107 | # y = torch.stack(y).max(0)[0] # max ensemble
108 | # y = torch.stack(y).mean(0) # mean ensemble
109 | y = torch.cat(y, 1) # nms ensemble
110 | return y, None # inference, train output
111 |
112 |
113 | def attempt_load(weights, map_location=None):
114 | # Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a
115 | model = Ensemble()
116 | for w in weights if isinstance(weights, list) else [weights]:
117 | attempt_download(w)
118 | ckpt = torch.load(w, map_location=map_location) # load
119 | model.append(ckpt['ema' if ckpt.get('ema') else 'model'].float().fuse().eval()) # FP32 model
120 |
121 | # Compatibility updates
122 | for m in model.modules():
123 | if type(m) in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU]:
124 | m.inplace = True # pytorch 1.7.0 compatibility
125 | elif type(m) is Conv:
126 | m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatibility
127 |
128 | if len(model) == 1:
129 | return model[-1] # return model
130 | else:
131 | print('Ensemble created with %s\n' % weights)
132 | for k in ['names', 'stride']:
133 | setattr(model, k, getattr(model[-1], k))
134 | return model # return ensemble
135 |
--------------------------------------------------------------------------------
/models/export.py:
--------------------------------------------------------------------------------
1 | """Exports a YOLOv5 *.pt model to ONNX and TorchScript formats
2 |
3 | Usage:
4 | $ export PYTHONPATH="$PWD" && python models/export.py --weights yolov5s.pt --img 640 --batch 1
5 | """
6 |
7 | import argparse
8 | import sys
9 | import time
10 |
11 | sys.path.append('./') # to run '$ python *.py' files in subdirectories
12 |
13 | import torch
14 | import torch.nn as nn
15 | from torch.utils.mobile_optimizer import optimize_for_mobile
16 |
17 | import models
18 | from models.experimental import attempt_load
19 | from utils.activations import Hardswish, SiLU
20 | from utils.general import colorstr, check_img_size, check_requirements, file_size, set_logging
21 | from utils.torch_utils import select_device
22 |
23 | if __name__ == '__main__':
24 | parser = argparse.ArgumentParser()
25 | parser.add_argument('--weights', type=str, default='./yolov5s.pt', help='weights path')
26 | parser.add_argument('--img-size', nargs='+', type=int, default=[640, 640], help='image size') # height, width
27 | parser.add_argument('--batch-size', type=int, default=1, help='batch size')
28 | parser.add_argument('--grid', action='store_true', help='export Detect() layer grid')
29 | parser.add_argument('--device', default='cpu', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
30 | parser.add_argument('--dynamic', action='store_true', help='dynamic ONNX axes') # ONNX-only
31 | parser.add_argument('--simplify', action='store_true', help='simplify ONNX model') # ONNX-only
32 | opt = parser.parse_args()
33 | opt.img_size *= 2 if len(opt.img_size) == 1 else 1 # expand
34 | print(opt)
35 | set_logging()
36 | t = time.time()
37 |
38 | # Load PyTorch model
39 | device = select_device(opt.device)
40 | model = attempt_load(opt.weights, map_location=device) # load FP32 model
41 | labels = model.names
42 |
43 | # Checks
44 | gs = int(max(model.stride)) # grid size (max stride)
45 | opt.img_size = [check_img_size(x, gs) for x in opt.img_size] # verify img_size are gs-multiples
46 |
47 | # Input
48 | img = torch.zeros(opt.batch_size, 3, *opt.img_size).to(device) # image size(1,3,320,192) iDetection
49 |
50 | # Update model
51 | for k, m in model.named_modules():
52 | m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatibility
53 | if isinstance(m, models.common.Conv): # assign export-friendly activations
54 | if isinstance(m.act, nn.Hardswish):
55 | m.act = Hardswish()
56 | elif isinstance(m.act, nn.SiLU):
57 | m.act = SiLU()
58 | # elif isinstance(m, models.yolo.Detect):
59 | # m.forward = m.forward_export # assign forward (optional)
60 | model.model[-1].export = not opt.grid # set Detect() layer grid export
61 | for _ in range(2):
62 | y = model(img) # dry runs
63 | print(f"\n{colorstr('PyTorch:')} starting from {opt.weights} ({file_size(opt.weights):.1f} MB)")
64 |
65 | # TorchScript export -----------------------------------------------------------------------------------------------
66 | prefix = colorstr('TorchScript:')
67 | try:
68 | print(f'\n{prefix} starting export with torch {torch.__version__}...')
69 | f = opt.weights.replace('.pt', '.torchscript.pt') # filename
70 | ts = torch.jit.trace(model, img, strict=False)
71 | ts = optimize_for_mobile(ts) # https://pytorch.org/tutorials/recipes/script_optimized.html
72 | ts.save(f)
73 | print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
74 | except Exception as e:
75 | print(f'{prefix} export failure: {e}')
76 |
77 | # ONNX export ------------------------------------------------------------------------------------------------------
78 | prefix = colorstr('ONNX:')
79 | try:
80 | import onnx
81 |
82 | print(f'{prefix} starting export with onnx {onnx.__version__}...')
83 | f = opt.weights.replace('.pt', '.onnx') # filename
84 | torch.onnx.export(model, img, f, verbose=False, opset_version=12, input_names=['images'],
85 | dynamic_axes={'images': {0: 'batch', 2: 'height', 3: 'width'}, # size(1,3,640,640)
86 | 'output': {0: 'batch', 2: 'y', 3: 'x'}} if opt.dynamic else None)
87 |
88 | # Checks
89 | model_onnx = onnx.load(f) # load onnx model
90 | onnx.checker.check_model(model_onnx) # check onnx model
91 | # print(onnx.helper.printable_graph(model_onnx.graph)) # print
92 |
93 | # Simplify
94 | if opt.simplify:
95 | try:
96 | check_requirements(['onnx-simplifier'])
97 | import onnxsim
98 |
99 | print(f'{prefix} simplifying with onnx-simplifier {onnxsim.__version__}...')
100 | model_onnx, check = onnxsim.simplify(model_onnx,
101 | dynamic_input_shape=opt.dynamic,
102 | input_shapes={'images': list(img.shape)} if opt.dynamic else None)
103 | assert check, 'assert check failed'
104 | onnx.save(model_onnx, f)
105 | except Exception as e:
106 | print(f'{prefix} simplifier failure: {e}')
107 | print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
108 | except Exception as e:
109 | print(f'{prefix} export failure: {e}')
110 |
111 | # CoreML export ----------------------------------------------------------------------------------------------------
112 | prefix = colorstr('CoreML:')
113 | try:
114 | import coremltools as ct
115 |
116 | print(f'{prefix} starting export with coremltools {ct.__version__}...')
117 | # convert model from torchscript and apply pixel scaling as per detect.py
118 | model = ct.convert(ts, inputs=[ct.ImageType(name='image', shape=img.shape, scale=1 / 255.0, bias=[0, 0, 0])])
119 | f = opt.weights.replace('.pt', '.mlmodel') # filename
120 | model.save(f)
121 | print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
122 | except Exception as e:
123 | print(f'{prefix} export failure: {e}')
124 |
125 | # Finish
126 | print(f'\nExport complete ({time.time() - t:.2f}s). Visualize with https://github.com/lutzroeder/netron.')
127 |
--------------------------------------------------------------------------------
/models/hub/anchors.yaml:
--------------------------------------------------------------------------------
1 | # Default YOLOv5 anchors for COCO data
2 |
3 |
4 | # P5 -------------------------------------------------------------------------------------------------------------------
5 | # P5-640:
6 | anchors_p5_640:
7 | - [ 10,13, 16,30, 33,23 ] # P3/8
8 | - [ 30,61, 62,45, 59,119 ] # P4/16
9 | - [ 116,90, 156,198, 373,326 ] # P5/32
10 |
11 |
12 | # P6 -------------------------------------------------------------------------------------------------------------------
13 | # P6-640: thr=0.25: 0.9964 BPR, 5.54 anchors past thr, n=12, img_size=640, metric_all=0.281/0.716-mean/best, past_thr=0.469-mean: 9,11, 21,19, 17,41, 43,32, 39,70, 86,64, 65,131, 134,130, 120,265, 282,180, 247,354, 512,387
14 | anchors_p6_640:
15 | - [ 9,11, 21,19, 17,41 ] # P3/8
16 | - [ 43,32, 39,70, 86,64 ] # P4/16
17 | - [ 65,131, 134,130, 120,265 ] # P5/32
18 | - [ 282,180, 247,354, 512,387 ] # P6/64
19 |
20 | # P6-1280: thr=0.25: 0.9950 BPR, 5.55 anchors past thr, n=12, img_size=1280, metric_all=0.281/0.714-mean/best, past_thr=0.468-mean: 19,27, 44,40, 38,94, 96,68, 86,152, 180,137, 140,301, 303,264, 238,542, 436,615, 739,380, 925,792
21 | anchors_p6_1280:
22 | - [ 19,27, 44,40, 38,94 ] # P3/8
23 | - [ 96,68, 86,152, 180,137 ] # P4/16
24 | - [ 140,301, 303,264, 238,542 ] # P5/32
25 | - [ 436,615, 739,380, 925,792 ] # P6/64
26 |
27 | # P6-1920: thr=0.25: 0.9950 BPR, 5.55 anchors past thr, n=12, img_size=1920, metric_all=0.281/0.714-mean/best, past_thr=0.468-mean: 28,41, 67,59, 57,141, 144,103, 129,227, 270,205, 209,452, 455,396, 358,812, 653,922, 1109,570, 1387,1187
28 | anchors_p6_1920:
29 | - [ 28,41, 67,59, 57,141 ] # P3/8
30 | - [ 144,103, 129,227, 270,205 ] # P4/16
31 | - [ 209,452, 455,396, 358,812 ] # P5/32
32 | - [ 653,922, 1109,570, 1387,1187 ] # P6/64
33 |
34 |
35 | # P7 -------------------------------------------------------------------------------------------------------------------
36 | # P7-640: thr=0.25: 0.9962 BPR, 6.76 anchors past thr, n=15, img_size=640, metric_all=0.275/0.733-mean/best, past_thr=0.466-mean: 11,11, 13,30, 29,20, 30,46, 61,38, 39,92, 78,80, 146,66, 79,163, 149,150, 321,143, 157,303, 257,402, 359,290, 524,372
37 | anchors_p7_640:
38 | - [ 11,11, 13,30, 29,20 ] # P3/8
39 | - [ 30,46, 61,38, 39,92 ] # P4/16
40 | - [ 78,80, 146,66, 79,163 ] # P5/32
41 | - [ 149,150, 321,143, 157,303 ] # P6/64
42 | - [ 257,402, 359,290, 524,372 ] # P7/128
43 |
44 | # P7-1280: thr=0.25: 0.9968 BPR, 6.71 anchors past thr, n=15, img_size=1280, metric_all=0.273/0.732-mean/best, past_thr=0.463-mean: 19,22, 54,36, 32,77, 70,83, 138,71, 75,173, 165,159, 148,334, 375,151, 334,317, 251,626, 499,474, 750,326, 534,814, 1079,818
45 | anchors_p7_1280:
46 | - [ 19,22, 54,36, 32,77 ] # P3/8
47 | - [ 70,83, 138,71, 75,173 ] # P4/16
48 | - [ 165,159, 148,334, 375,151 ] # P5/32
49 | - [ 334,317, 251,626, 499,474 ] # P6/64
50 | - [ 750,326, 534,814, 1079,818 ] # P7/128
51 |
52 | # P7-1920: thr=0.25: 0.9968 BPR, 6.71 anchors past thr, n=15, img_size=1920, metric_all=0.273/0.732-mean/best, past_thr=0.463-mean: 29,34, 81,55, 47,115, 105,124, 207,107, 113,259, 247,238, 222,500, 563,227, 501,476, 376,939, 749,711, 1126,489, 801,1222, 1618,1227
53 | anchors_p7_1920:
54 | - [ 29,34, 81,55, 47,115 ] # P3/8
55 | - [ 105,124, 207,107, 113,259 ] # P4/16
56 | - [ 247,238, 222,500, 563,227 ] # P5/32
57 | - [ 501,476, 376,939, 749,711 ] # P6/64
58 | - [ 1126,489, 801,1222, 1618,1227 ] # P7/128
59 |
--------------------------------------------------------------------------------
/models/hub/yolov3-spp.yaml:
--------------------------------------------------------------------------------
1 | # parameters
2 | nc: 80 # number of classes
3 | depth_multiple: 1.0 # model depth multiple
4 | width_multiple: 1.0 # layer channel multiple
5 |
6 | # anchors
7 | anchors:
8 | - [10,13, 16,30, 33,23] # P3/8
9 | - [30,61, 62,45, 59,119] # P4/16
10 | - [116,90, 156,198, 373,326] # P5/32
11 |
12 | # darknet53 backbone
13 | backbone:
14 | # [from, number, module, args]
15 | [[-1, 1, Conv, [32, 3, 1]], # 0
16 | [-1, 1, Conv, [64, 3, 2]], # 1-P1/2
17 | [-1, 1, Bottleneck, [64]],
18 | [-1, 1, Conv, [128, 3, 2]], # 3-P2/4
19 | [-1, 2, Bottleneck, [128]],
20 | [-1, 1, Conv, [256, 3, 2]], # 5-P3/8
21 | [-1, 8, Bottleneck, [256]],
22 | [-1, 1, Conv, [512, 3, 2]], # 7-P4/16
23 | [-1, 8, Bottleneck, [512]],
24 | [-1, 1, Conv, [1024, 3, 2]], # 9-P5/32
25 | [-1, 4, Bottleneck, [1024]], # 10
26 | ]
27 |
28 | # YOLOv3-SPP head
29 | head:
30 | [[-1, 1, Bottleneck, [1024, False]],
31 | [-1, 1, SPP, [512, [5, 9, 13]]],
32 | [-1, 1, Conv, [1024, 3, 1]],
33 | [-1, 1, Conv, [512, 1, 1]],
34 | [-1, 1, Conv, [1024, 3, 1]], # 15 (P5/32-large)
35 |
36 | [-2, 1, Conv, [256, 1, 1]],
37 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
38 | [[-1, 8], 1, Concat, [1]], # cat backbone P4
39 | [-1, 1, Bottleneck, [512, False]],
40 | [-1, 1, Bottleneck, [512, False]],
41 | [-1, 1, Conv, [256, 1, 1]],
42 | [-1, 1, Conv, [512, 3, 1]], # 22 (P4/16-medium)
43 |
44 | [-2, 1, Conv, [128, 1, 1]],
45 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
46 | [[-1, 6], 1, Concat, [1]], # cat backbone P3
47 | [-1, 1, Bottleneck, [256, False]],
48 | [-1, 2, Bottleneck, [256, False]], # 27 (P3/8-small)
49 |
50 | [[27, 22, 15], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
51 | ]
52 |
--------------------------------------------------------------------------------
/models/hub/yolov3-tiny.yaml:
--------------------------------------------------------------------------------
1 | # parameters
2 | nc: 80 # number of classes
3 | depth_multiple: 1.0 # model depth multiple
4 | width_multiple: 1.0 # layer channel multiple
5 |
6 | # anchors
7 | anchors:
8 | - [10,14, 23,27, 37,58] # P4/16
9 | - [81,82, 135,169, 344,319] # P5/32
10 |
11 | # YOLOv3-tiny backbone
12 | backbone:
13 | # [from, number, module, args]
14 | [[-1, 1, Conv, [16, 3, 1]], # 0
15 | [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 1-P1/2
16 | [-1, 1, Conv, [32, 3, 1]],
17 | [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 3-P2/4
18 | [-1, 1, Conv, [64, 3, 1]],
19 | [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 5-P3/8
20 | [-1, 1, Conv, [128, 3, 1]],
21 | [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 7-P4/16
22 | [-1, 1, Conv, [256, 3, 1]],
23 | [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 9-P5/32
24 | [-1, 1, Conv, [512, 3, 1]],
25 | [-1, 1, nn.ZeroPad2d, [[0, 1, 0, 1]]], # 11
26 | [-1, 1, nn.MaxPool2d, [2, 1, 0]], # 12
27 | ]
28 |
29 | # YOLOv3-tiny head
30 | head:
31 | [[-1, 1, Conv, [1024, 3, 1]],
32 | [-1, 1, Conv, [256, 1, 1]],
33 | [-1, 1, Conv, [512, 3, 1]], # 15 (P5/32-large)
34 |
35 | [-2, 1, Conv, [128, 1, 1]],
36 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
37 | [[-1, 8], 1, Concat, [1]], # cat backbone P4
38 | [-1, 1, Conv, [256, 3, 1]], # 19 (P4/16-medium)
39 |
40 | [[19, 15], 1, Detect, [nc, anchors]], # Detect(P4, P5)
41 | ]
42 |
--------------------------------------------------------------------------------
/models/hub/yolov3.yaml:
--------------------------------------------------------------------------------
1 | # parameters
2 | nc: 80 # number of classes
3 | depth_multiple: 1.0 # model depth multiple
4 | width_multiple: 1.0 # layer channel multiple
5 |
6 | # anchors
7 | anchors:
8 | - [10,13, 16,30, 33,23] # P3/8
9 | - [30,61, 62,45, 59,119] # P4/16
10 | - [116,90, 156,198, 373,326] # P5/32
11 |
12 | # darknet53 backbone
13 | backbone:
14 | # [from, number, module, args]
15 | [[-1, 1, Conv, [32, 3, 1]], # 0
16 | [-1, 1, Conv, [64, 3, 2]], # 1-P1/2
17 | [-1, 1, Bottleneck, [64]],
18 | [-1, 1, Conv, [128, 3, 2]], # 3-P2/4
19 | [-1, 2, Bottleneck, [128]],
20 | [-1, 1, Conv, [256, 3, 2]], # 5-P3/8
21 | [-1, 8, Bottleneck, [256]],
22 | [-1, 1, Conv, [512, 3, 2]], # 7-P4/16
23 | [-1, 8, Bottleneck, [512]],
24 | [-1, 1, Conv, [1024, 3, 2]], # 9-P5/32
25 | [-1, 4, Bottleneck, [1024]], # 10
26 | ]
27 |
28 | # YOLOv3 head
29 | head:
30 | [[-1, 1, Bottleneck, [1024, False]],
31 | [-1, 1, Conv, [512, [1, 1]]],
32 | [-1, 1, Conv, [1024, 3, 1]],
33 | [-1, 1, Conv, [512, 1, 1]],
34 | [-1, 1, Conv, [1024, 3, 1]], # 15 (P5/32-large)
35 |
36 | [-2, 1, Conv, [256, 1, 1]],
37 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
38 | [[-1, 8], 1, Concat, [1]], # cat backbone P4
39 | [-1, 1, Bottleneck, [512, False]],
40 | [-1, 1, Bottleneck, [512, False]],
41 | [-1, 1, Conv, [256, 1, 1]],
42 | [-1, 1, Conv, [512, 3, 1]], # 22 (P4/16-medium)
43 |
44 | [-2, 1, Conv, [128, 1, 1]],
45 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
46 | [[-1, 6], 1, Concat, [1]], # cat backbone P3
47 | [-1, 1, Bottleneck, [256, False]],
48 | [-1, 2, Bottleneck, [256, False]], # 27 (P3/8-small)
49 |
50 | [[27, 22, 15], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
51 | ]
52 |
--------------------------------------------------------------------------------
/models/hub/yolov5-fpn.yaml:
--------------------------------------------------------------------------------
1 | # parameters
2 | nc: 80 # number of classes
3 | depth_multiple: 1.0 # model depth multiple
4 | width_multiple: 1.0 # layer channel multiple
5 |
6 | # anchors
7 | anchors:
8 | - [10,13, 16,30, 33,23] # P3/8
9 | - [30,61, 62,45, 59,119] # P4/16
10 | - [116,90, 156,198, 373,326] # P5/32
11 |
12 | # YOLOv5 backbone
13 | backbone:
14 | # [from, number, module, args]
15 | [[-1, 1, Focus, [64, 3]], # 0-P1/2
16 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
17 | [-1, 3, Bottleneck, [128]],
18 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
19 | [-1, 9, BottleneckCSP, [256]],
20 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
21 | [-1, 9, BottleneckCSP, [512]],
22 | [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
23 | [-1, 1, SPP, [1024, [5, 9, 13]]],
24 | [-1, 6, BottleneckCSP, [1024]], # 9
25 | ]
26 |
27 | # YOLOv5 FPN head
28 | head:
29 | [[-1, 3, BottleneckCSP, [1024, False]], # 10 (P5/32-large)
30 |
31 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
32 | [[-1, 6], 1, Concat, [1]], # cat backbone P4
33 | [-1, 1, Conv, [512, 1, 1]],
34 | [-1, 3, BottleneckCSP, [512, False]], # 14 (P4/16-medium)
35 |
36 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
37 | [[-1, 4], 1, Concat, [1]], # cat backbone P3
38 | [-1, 1, Conv, [256, 1, 1]],
39 | [-1, 3, BottleneckCSP, [256, False]], # 18 (P3/8-small)
40 |
41 | [[18, 14, 10], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
42 | ]
43 |
--------------------------------------------------------------------------------
/models/hub/yolov5-p2.yaml:
--------------------------------------------------------------------------------
1 | # parameters
2 | nc: 80 # number of classes
3 | depth_multiple: 1.0 # model depth multiple
4 | width_multiple: 1.0 # layer channel multiple
5 |
6 | # anchors
7 | anchors: 3
8 |
9 | # YOLOv5 backbone
10 | backbone:
11 | # [from, number, module, args]
12 | [ [ -1, 1, Focus, [ 64, 3 ] ], # 0-P1/2
13 | [ -1, 1, Conv, [ 128, 3, 2 ] ], # 1-P2/4
14 | [ -1, 3, C3, [ 128 ] ],
15 | [ -1, 1, Conv, [ 256, 3, 2 ] ], # 3-P3/8
16 | [ -1, 9, C3, [ 256 ] ],
17 | [ -1, 1, Conv, [ 512, 3, 2 ] ], # 5-P4/16
18 | [ -1, 9, C3, [ 512 ] ],
19 | [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 7-P5/32
20 | [ -1, 1, SPP, [ 1024, [ 5, 9, 13 ] ] ],
21 | [ -1, 3, C3, [ 1024, False ] ], # 9
22 | ]
23 |
24 | # YOLOv5 head
25 | head:
26 | [ [ -1, 1, Conv, [ 512, 1, 1 ] ],
27 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
28 | [ [ -1, 6 ], 1, Concat, [ 1 ] ], # cat backbone P4
29 | [ -1, 3, C3, [ 512, False ] ], # 13
30 |
31 | [ -1, 1, Conv, [ 256, 1, 1 ] ],
32 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
33 | [ [ -1, 4 ], 1, Concat, [ 1 ] ], # cat backbone P3
34 | [ -1, 3, C3, [ 256, False ] ], # 17 (P3/8-small)
35 |
36 | [ -1, 1, Conv, [ 128, 1, 1 ] ],
37 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
38 | [ [ -1, 2 ], 1, Concat, [ 1 ] ], # cat backbone P2
39 | [ -1, 1, C3, [ 128, False ] ], # 21 (P2/4-xsmall)
40 |
41 | [ -1, 1, Conv, [ 128, 3, 2 ] ],
42 | [ [ -1, 18 ], 1, Concat, [ 1 ] ], # cat head P3
43 | [ -1, 3, C3, [ 256, False ] ], # 24 (P3/8-small)
44 |
45 | [ -1, 1, Conv, [ 256, 3, 2 ] ],
46 | [ [ -1, 14 ], 1, Concat, [ 1 ] ], # cat head P4
47 | [ -1, 3, C3, [ 512, False ] ], # 27 (P4/16-medium)
48 |
49 | [ -1, 1, Conv, [ 512, 3, 2 ] ],
50 | [ [ -1, 10 ], 1, Concat, [ 1 ] ], # cat head P5
51 | [ -1, 3, C3, [ 1024, False ] ], # 30 (P5/32-large)
52 |
53 | [ [ 24, 27, 30 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4, P5)
54 | ]
55 |
--------------------------------------------------------------------------------
/models/hub/yolov5-p6.yaml:
--------------------------------------------------------------------------------
1 | # parameters
2 | nc: 80 # number of classes
3 | depth_multiple: 1.0 # model depth multiple
4 | width_multiple: 1.0 # layer channel multiple
5 |
6 | # anchors
7 | anchors: 3
8 |
9 | # YOLOv5 backbone
10 | backbone:
11 | # [from, number, module, args]
12 | [ [ -1, 1, Focus, [ 64, 3 ] ], # 0-P1/2
13 | [ -1, 1, Conv, [ 128, 3, 2 ] ], # 1-P2/4
14 | [ -1, 3, C3, [ 128 ] ],
15 | [ -1, 1, Conv, [ 256, 3, 2 ] ], # 3-P3/8
16 | [ -1, 9, C3, [ 256 ] ],
17 | [ -1, 1, Conv, [ 512, 3, 2 ] ], # 5-P4/16
18 | [ -1, 9, C3, [ 512 ] ],
19 | [ -1, 1, Conv, [ 768, 3, 2 ] ], # 7-P5/32
20 | [ -1, 3, C3, [ 768 ] ],
21 | [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 9-P6/64
22 | [ -1, 1, SPP, [ 1024, [ 3, 5, 7 ] ] ],
23 | [ -1, 3, C3, [ 1024, False ] ], # 11
24 | ]
25 |
26 | # YOLOv5 head
27 | head:
28 | [ [ -1, 1, Conv, [ 768, 1, 1 ] ],
29 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
30 | [ [ -1, 8 ], 1, Concat, [ 1 ] ], # cat backbone P5
31 | [ -1, 3, C3, [ 768, False ] ], # 15
32 |
33 | [ -1, 1, Conv, [ 512, 1, 1 ] ],
34 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
35 | [ [ -1, 6 ], 1, Concat, [ 1 ] ], # cat backbone P4
36 | [ -1, 3, C3, [ 512, False ] ], # 19
37 |
38 | [ -1, 1, Conv, [ 256, 1, 1 ] ],
39 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
40 | [ [ -1, 4 ], 1, Concat, [ 1 ] ], # cat backbone P3
41 | [ -1, 3, C3, [ 256, False ] ], # 23 (P3/8-small)
42 |
43 | [ -1, 1, Conv, [ 256, 3, 2 ] ],
44 | [ [ -1, 20 ], 1, Concat, [ 1 ] ], # cat head P4
45 | [ -1, 3, C3, [ 512, False ] ], # 26 (P4/16-medium)
46 |
47 | [ -1, 1, Conv, [ 512, 3, 2 ] ],
48 | [ [ -1, 16 ], 1, Concat, [ 1 ] ], # cat head P5
49 | [ -1, 3, C3, [ 768, False ] ], # 29 (P5/32-large)
50 |
51 | [ -1, 1, Conv, [ 768, 3, 2 ] ],
52 | [ [ -1, 12 ], 1, Concat, [ 1 ] ], # cat head P6
53 | [ -1, 3, C3, [ 1024, False ] ], # 32 (P5/64-xlarge)
54 |
55 | [ [ 23, 26, 29, 32 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4, P5, P6)
56 | ]
57 |
--------------------------------------------------------------------------------
/models/hub/yolov5-p7.yaml:
--------------------------------------------------------------------------------
1 | # parameters
2 | nc: 80 # number of classes
3 | depth_multiple: 1.0 # model depth multiple
4 | width_multiple: 1.0 # layer channel multiple
5 |
6 | # anchors
7 | anchors: 3
8 |
9 | # YOLOv5 backbone
10 | backbone:
11 | # [from, number, module, args]
12 | [ [ -1, 1, Focus, [ 64, 3 ] ], # 0-P1/2
13 | [ -1, 1, Conv, [ 128, 3, 2 ] ], # 1-P2/4
14 | [ -1, 3, C3, [ 128 ] ],
15 | [ -1, 1, Conv, [ 256, 3, 2 ] ], # 3-P3/8
16 | [ -1, 9, C3, [ 256 ] ],
17 | [ -1, 1, Conv, [ 512, 3, 2 ] ], # 5-P4/16
18 | [ -1, 9, C3, [ 512 ] ],
19 | [ -1, 1, Conv, [ 768, 3, 2 ] ], # 7-P5/32
20 | [ -1, 3, C3, [ 768 ] ],
21 | [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 9-P6/64
22 | [ -1, 3, C3, [ 1024 ] ],
23 | [ -1, 1, Conv, [ 1280, 3, 2 ] ], # 11-P7/128
24 | [ -1, 1, SPP, [ 1280, [ 3, 5 ] ] ],
25 | [ -1, 3, C3, [ 1280, False ] ], # 13
26 | ]
27 |
28 | # YOLOv5 head
29 | head:
30 | [ [ -1, 1, Conv, [ 1024, 1, 1 ] ],
31 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
32 | [ [ -1, 10 ], 1, Concat, [ 1 ] ], # cat backbone P6
33 | [ -1, 3, C3, [ 1024, False ] ], # 17
34 |
35 | [ -1, 1, Conv, [ 768, 1, 1 ] ],
36 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
37 | [ [ -1, 8 ], 1, Concat, [ 1 ] ], # cat backbone P5
38 | [ -1, 3, C3, [ 768, False ] ], # 21
39 |
40 | [ -1, 1, Conv, [ 512, 1, 1 ] ],
41 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
42 | [ [ -1, 6 ], 1, Concat, [ 1 ] ], # cat backbone P4
43 | [ -1, 3, C3, [ 512, False ] ], # 25
44 |
45 | [ -1, 1, Conv, [ 256, 1, 1 ] ],
46 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
47 | [ [ -1, 4 ], 1, Concat, [ 1 ] ], # cat backbone P3
48 | [ -1, 3, C3, [ 256, False ] ], # 29 (P3/8-small)
49 |
50 | [ -1, 1, Conv, [ 256, 3, 2 ] ],
51 | [ [ -1, 26 ], 1, Concat, [ 1 ] ], # cat head P4
52 | [ -1, 3, C3, [ 512, False ] ], # 32 (P4/16-medium)
53 |
54 | [ -1, 1, Conv, [ 512, 3, 2 ] ],
55 | [ [ -1, 22 ], 1, Concat, [ 1 ] ], # cat head P5
56 | [ -1, 3, C3, [ 768, False ] ], # 35 (P5/32-large)
57 |
58 | [ -1, 1, Conv, [ 768, 3, 2 ] ],
59 | [ [ -1, 18 ], 1, Concat, [ 1 ] ], # cat head P6
60 | [ -1, 3, C3, [ 1024, False ] ], # 38 (P6/64-xlarge)
61 |
62 | [ -1, 1, Conv, [ 1024, 3, 2 ] ],
63 | [ [ -1, 14 ], 1, Concat, [ 1 ] ], # cat head P7
64 | [ -1, 3, C3, [ 1280, False ] ], # 41 (P7/128-xxlarge)
65 |
66 | [ [ 29, 32, 35, 38, 41 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4, P5, P6, P7)
67 | ]
68 |
--------------------------------------------------------------------------------
/models/hub/yolov5-panet.yaml:
--------------------------------------------------------------------------------
1 | # parameters
2 | nc: 80 # number of classes
3 | depth_multiple: 1.0 # model depth multiple
4 | width_multiple: 1.0 # layer channel multiple
5 |
6 | # anchors
7 | anchors:
8 | - [10,13, 16,30, 33,23] # P3/8
9 | - [30,61, 62,45, 59,119] # P4/16
10 | - [116,90, 156,198, 373,326] # P5/32
11 |
12 | # YOLOv5 backbone
13 | backbone:
14 | # [from, number, module, args]
15 | [[-1, 1, Focus, [64, 3]], # 0-P1/2
16 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
17 | [-1, 3, BottleneckCSP, [128]],
18 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
19 | [-1, 9, BottleneckCSP, [256]],
20 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
21 | [-1, 9, BottleneckCSP, [512]],
22 | [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
23 | [-1, 1, SPP, [1024, [5, 9, 13]]],
24 | [-1, 3, BottleneckCSP, [1024, False]], # 9
25 | ]
26 |
27 | # YOLOv5 PANet head
28 | head:
29 | [[-1, 1, Conv, [512, 1, 1]],
30 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
31 | [[-1, 6], 1, Concat, [1]], # cat backbone P4
32 | [-1, 3, BottleneckCSP, [512, False]], # 13
33 |
34 | [-1, 1, Conv, [256, 1, 1]],
35 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
36 | [[-1, 4], 1, Concat, [1]], # cat backbone P3
37 | [-1, 3, BottleneckCSP, [256, False]], # 17 (P3/8-small)
38 |
39 | [-1, 1, Conv, [256, 3, 2]],
40 | [[-1, 14], 1, Concat, [1]], # cat head P4
41 | [-1, 3, BottleneckCSP, [512, False]], # 20 (P4/16-medium)
42 |
43 | [-1, 1, Conv, [512, 3, 2]],
44 | [[-1, 10], 1, Concat, [1]], # cat head P5
45 | [-1, 3, BottleneckCSP, [1024, False]], # 23 (P5/32-large)
46 |
47 | [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
48 | ]
49 |
--------------------------------------------------------------------------------
/models/hub/yolov5l6.yaml:
--------------------------------------------------------------------------------
1 | # parameters
2 | nc: 80 # number of classes
3 | depth_multiple: 1.0 # model depth multiple
4 | width_multiple: 1.0 # layer channel multiple
5 |
6 | # anchors
7 | anchors:
8 | - [ 19,27, 44,40, 38,94 ] # P3/8
9 | - [ 96,68, 86,152, 180,137 ] # P4/16
10 | - [ 140,301, 303,264, 238,542 ] # P5/32
11 | - [ 436,615, 739,380, 925,792 ] # P6/64
12 |
13 | # YOLOv5 backbone
14 | backbone:
15 | # [from, number, module, args]
16 | [ [ -1, 1, Focus, [ 64, 3 ] ], # 0-P1/2
17 | [ -1, 1, Conv, [ 128, 3, 2 ] ], # 1-P2/4
18 | [ -1, 3, C3, [ 128 ] ],
19 | [ -1, 1, Conv, [ 256, 3, 2 ] ], # 3-P3/8
20 | [ -1, 9, C3, [ 256 ] ],
21 | [ -1, 1, Conv, [ 512, 3, 2 ] ], # 5-P4/16
22 | [ -1, 9, C3, [ 512 ] ],
23 | [ -1, 1, Conv, [ 768, 3, 2 ] ], # 7-P5/32
24 | [ -1, 3, C3, [ 768 ] ],
25 | [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 9-P6/64
26 | [ -1, 1, SPP, [ 1024, [ 3, 5, 7 ] ] ],
27 | [ -1, 3, C3, [ 1024, False ] ], # 11
28 | ]
29 |
30 | # YOLOv5 head
31 | head:
32 | [ [ -1, 1, Conv, [ 768, 1, 1 ] ],
33 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
34 | [ [ -1, 8 ], 1, Concat, [ 1 ] ], # cat backbone P5
35 | [ -1, 3, C3, [ 768, False ] ], # 15
36 |
37 | [ -1, 1, Conv, [ 512, 1, 1 ] ],
38 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
39 | [ [ -1, 6 ], 1, Concat, [ 1 ] ], # cat backbone P4
40 | [ -1, 3, C3, [ 512, False ] ], # 19
41 |
42 | [ -1, 1, Conv, [ 256, 1, 1 ] ],
43 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
44 | [ [ -1, 4 ], 1, Concat, [ 1 ] ], # cat backbone P3
45 | [ -1, 3, C3, [ 256, False ] ], # 23 (P3/8-small)
46 |
47 | [ -1, 1, Conv, [ 256, 3, 2 ] ],
48 | [ [ -1, 20 ], 1, Concat, [ 1 ] ], # cat head P4
49 | [ -1, 3, C3, [ 512, False ] ], # 26 (P4/16-medium)
50 |
51 | [ -1, 1, Conv, [ 512, 3, 2 ] ],
52 | [ [ -1, 16 ], 1, Concat, [ 1 ] ], # cat head P5
53 | [ -1, 3, C3, [ 768, False ] ], # 29 (P5/32-large)
54 |
55 | [ -1, 1, Conv, [ 768, 3, 2 ] ],
56 | [ [ -1, 12 ], 1, Concat, [ 1 ] ], # cat head P6
57 | [ -1, 3, C3, [ 1024, False ] ], # 32 (P6/64-xlarge)
58 |
59 | [ [ 23, 26, 29, 32 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4, P5, P6)
60 | ]
61 |
--------------------------------------------------------------------------------
/models/hub/yolov5m6.yaml:
--------------------------------------------------------------------------------
1 | # parameters
2 | nc: 80 # number of classes
3 | depth_multiple: 0.67 # model depth multiple
4 | width_multiple: 0.75 # layer channel multiple
5 |
6 | # anchors
7 | anchors:
8 | - [ 19,27, 44,40, 38,94 ] # P3/8
9 | - [ 96,68, 86,152, 180,137 ] # P4/16
10 | - [ 140,301, 303,264, 238,542 ] # P5/32
11 | - [ 436,615, 739,380, 925,792 ] # P6/64
12 |
13 | # YOLOv5 backbone
14 | backbone:
15 | # [from, number, module, args]
16 | [ [ -1, 1, Focus, [ 64, 3 ] ], # 0-P1/2
17 | [ -1, 1, Conv, [ 128, 3, 2 ] ], # 1-P2/4
18 | [ -1, 3, C3, [ 128 ] ],
19 | [ -1, 1, Conv, [ 256, 3, 2 ] ], # 3-P3/8
20 | [ -1, 9, C3, [ 256 ] ],
21 | [ -1, 1, Conv, [ 512, 3, 2 ] ], # 5-P4/16
22 | [ -1, 9, C3, [ 512 ] ],
23 | [ -1, 1, Conv, [ 768, 3, 2 ] ], # 7-P5/32
24 | [ -1, 3, C3, [ 768 ] ],
25 | [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 9-P6/64
26 | [ -1, 1, SPP, [ 1024, [ 3, 5, 7 ] ] ],
27 | [ -1, 3, C3, [ 1024, False ] ], # 11
28 | ]
29 |
30 | # YOLOv5 head
31 | head:
32 | [ [ -1, 1, Conv, [ 768, 1, 1 ] ],
33 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
34 | [ [ -1, 8 ], 1, Concat, [ 1 ] ], # cat backbone P5
35 | [ -1, 3, C3, [ 768, False ] ], # 15
36 |
37 | [ -1, 1, Conv, [ 512, 1, 1 ] ],
38 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
39 | [ [ -1, 6 ], 1, Concat, [ 1 ] ], # cat backbone P4
40 | [ -1, 3, C3, [ 512, False ] ], # 19
41 |
42 | [ -1, 1, Conv, [ 256, 1, 1 ] ],
43 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
44 | [ [ -1, 4 ], 1, Concat, [ 1 ] ], # cat backbone P3
45 | [ -1, 3, C3, [ 256, False ] ], # 23 (P3/8-small)
46 |
47 | [ -1, 1, Conv, [ 256, 3, 2 ] ],
48 | [ [ -1, 20 ], 1, Concat, [ 1 ] ], # cat head P4
49 | [ -1, 3, C3, [ 512, False ] ], # 26 (P4/16-medium)
50 |
51 | [ -1, 1, Conv, [ 512, 3, 2 ] ],
52 | [ [ -1, 16 ], 1, Concat, [ 1 ] ], # cat head P5
53 | [ -1, 3, C3, [ 768, False ] ], # 29 (P5/32-large)
54 |
55 | [ -1, 1, Conv, [ 768, 3, 2 ] ],
56 | [ [ -1, 12 ], 1, Concat, [ 1 ] ], # cat head P6
57 | [ -1, 3, C3, [ 1024, False ] ], # 32 (P6/64-xlarge)
58 |
59 | [ [ 23, 26, 29, 32 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4, P5, P6)
60 | ]
61 |
--------------------------------------------------------------------------------
/models/hub/yolov5s-transformer.yaml:
--------------------------------------------------------------------------------
1 | # parameters
2 | nc: 80 # number of classes
3 | depth_multiple: 0.33 # model depth multiple
4 | width_multiple: 0.50 # layer channel multiple
5 |
6 | # anchors
7 | anchors:
8 | - [10,13, 16,30, 33,23] # P3/8
9 | - [30,61, 62,45, 59,119] # P4/16
10 | - [116,90, 156,198, 373,326] # P5/32
11 |
12 | # YOLOv5 backbone
13 | backbone:
14 | # [from, number, module, args]
15 | [[-1, 1, Focus, [64, 3]], # 0-P1/2
16 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
17 | [-1, 3, C3, [128]],
18 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
19 | [-1, 9, C3, [256]],
20 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
21 | [-1, 9, C3, [512]],
22 | [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
23 | [-1, 1, SPP, [1024, [5, 9, 13]]],
24 | [-1, 3, C3TR, [1024, False]], # 9 <-------- C3TR() Transformer module
25 | ]
26 |
27 | # YOLOv5 head
28 | head:
29 | [[-1, 1, Conv, [512, 1, 1]],
30 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
31 | [[-1, 6], 1, Concat, [1]], # cat backbone P4
32 | [-1, 3, C3, [512, False]], # 13
33 |
34 | [-1, 1, Conv, [256, 1, 1]],
35 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
36 | [[-1, 4], 1, Concat, [1]], # cat backbone P3
37 | [-1, 3, C3, [256, False]], # 17 (P3/8-small)
38 |
39 | [-1, 1, Conv, [256, 3, 2]],
40 | [[-1, 14], 1, Concat, [1]], # cat head P4
41 | [-1, 3, C3, [512, False]], # 20 (P4/16-medium)
42 |
43 | [-1, 1, Conv, [512, 3, 2]],
44 | [[-1, 10], 1, Concat, [1]], # cat head P5
45 | [-1, 3, C3, [1024, False]], # 23 (P5/32-large)
46 |
47 | [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
48 | ]
49 |
--------------------------------------------------------------------------------
/models/hub/yolov5s6.yaml:
--------------------------------------------------------------------------------
1 | # parameters
2 | nc: 80 # number of classes
3 | depth_multiple: 0.33 # model depth multiple
4 | width_multiple: 0.50 # layer channel multiple
5 |
6 | # anchors
7 | anchors:
8 | - [ 19,27, 44,40, 38,94 ] # P3/8
9 | - [ 96,68, 86,152, 180,137 ] # P4/16
10 | - [ 140,301, 303,264, 238,542 ] # P5/32
11 | - [ 436,615, 739,380, 925,792 ] # P6/64
12 |
13 | # YOLOv5 backbone
14 | backbone:
15 | # [from, number, module, args]
16 | [ [ -1, 1, Focus, [ 64, 3 ] ], # 0-P1/2
17 | [ -1, 1, Conv, [ 128, 3, 2 ] ], # 1-P2/4
18 | [ -1, 3, C3, [ 128 ] ],
19 | [ -1, 1, Conv, [ 256, 3, 2 ] ], # 3-P3/8
20 | [ -1, 9, C3, [ 256 ] ],
21 | [ -1, 1, Conv, [ 512, 3, 2 ] ], # 5-P4/16
22 | [ -1, 9, C3, [ 512 ] ],
23 | [ -1, 1, Conv, [ 768, 3, 2 ] ], # 7-P5/32
24 | [ -1, 3, C3, [ 768 ] ],
25 | [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 9-P6/64
26 | [ -1, 1, SPP, [ 1024, [ 3, 5, 7 ] ] ],
27 | [ -1, 3, C3, [ 1024, False ] ], # 11
28 | ]
29 |
30 | # YOLOv5 head
31 | head:
32 | [ [ -1, 1, Conv, [ 768, 1, 1 ] ],
33 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
34 | [ [ -1, 8 ], 1, Concat, [ 1 ] ], # cat backbone P5
35 | [ -1, 3, C3, [ 768, False ] ], # 15
36 |
37 | [ -1, 1, Conv, [ 512, 1, 1 ] ],
38 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
39 | [ [ -1, 6 ], 1, Concat, [ 1 ] ], # cat backbone P4
40 | [ -1, 3, C3, [ 512, False ] ], # 19
41 |
42 | [ -1, 1, Conv, [ 256, 1, 1 ] ],
43 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
44 | [ [ -1, 4 ], 1, Concat, [ 1 ] ], # cat backbone P3
45 | [ -1, 3, C3, [ 256, False ] ], # 23 (P3/8-small)
46 |
47 | [ -1, 1, Conv, [ 256, 3, 2 ] ],
48 | [ [ -1, 20 ], 1, Concat, [ 1 ] ], # cat head P4
49 | [ -1, 3, C3, [ 512, False ] ], # 26 (P4/16-medium)
50 |
51 | [ -1, 1, Conv, [ 512, 3, 2 ] ],
52 | [ [ -1, 16 ], 1, Concat, [ 1 ] ], # cat head P5
53 | [ -1, 3, C3, [ 768, False ] ], # 29 (P5/32-large)
54 |
55 | [ -1, 1, Conv, [ 768, 3, 2 ] ],
56 | [ [ -1, 12 ], 1, Concat, [ 1 ] ], # cat head P6
57 | [ -1, 3, C3, [ 1024, False ] ], # 32 (P6/64-xlarge)
58 |
59 | [ [ 23, 26, 29, 32 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4, P5, P6)
60 | ]
61 |
--------------------------------------------------------------------------------
/models/hub/yolov5x6.yaml:
--------------------------------------------------------------------------------
1 | # parameters
2 | nc: 80 # number of classes
3 | depth_multiple: 1.33 # model depth multiple
4 | width_multiple: 1.25 # layer channel multiple
5 |
6 | # anchors
7 | anchors:
8 | - [ 19,27, 44,40, 38,94 ] # P3/8
9 | - [ 96,68, 86,152, 180,137 ] # P4/16
10 | - [ 140,301, 303,264, 238,542 ] # P5/32
11 | - [ 436,615, 739,380, 925,792 ] # P6/64
12 |
13 | # YOLOv5 backbone
14 | backbone:
15 | # [from, number, module, args]
16 | [ [ -1, 1, Focus, [ 64, 3 ] ], # 0-P1/2
17 | [ -1, 1, Conv, [ 128, 3, 2 ] ], # 1-P2/4
18 | [ -1, 3, C3, [ 128 ] ],
19 | [ -1, 1, Conv, [ 256, 3, 2 ] ], # 3-P3/8
20 | [ -1, 9, C3, [ 256 ] ],
21 | [ -1, 1, Conv, [ 512, 3, 2 ] ], # 5-P4/16
22 | [ -1, 9, C3, [ 512 ] ],
23 | [ -1, 1, Conv, [ 768, 3, 2 ] ], # 7-P5/32
24 | [ -1, 3, C3, [ 768 ] ],
25 | [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 9-P6/64
26 | [ -1, 1, SPP, [ 1024, [ 3, 5, 7 ] ] ],
27 | [ -1, 3, C3, [ 1024, False ] ], # 11
28 | ]
29 |
30 | # YOLOv5 head
31 | head:
32 | [ [ -1, 1, Conv, [ 768, 1, 1 ] ],
33 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
34 | [ [ -1, 8 ], 1, Concat, [ 1 ] ], # cat backbone P5
35 | [ -1, 3, C3, [ 768, False ] ], # 15
36 |
37 | [ -1, 1, Conv, [ 512, 1, 1 ] ],
38 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
39 | [ [ -1, 6 ], 1, Concat, [ 1 ] ], # cat backbone P4
40 | [ -1, 3, C3, [ 512, False ] ], # 19
41 |
42 | [ -1, 1, Conv, [ 256, 1, 1 ] ],
43 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
44 | [ [ -1, 4 ], 1, Concat, [ 1 ] ], # cat backbone P3
45 | [ -1, 3, C3, [ 256, False ] ], # 23 (P3/8-small)
46 |
47 | [ -1, 1, Conv, [ 256, 3, 2 ] ],
48 | [ [ -1, 20 ], 1, Concat, [ 1 ] ], # cat head P4
49 | [ -1, 3, C3, [ 512, False ] ], # 26 (P4/16-medium)
50 |
51 | [ -1, 1, Conv, [ 512, 3, 2 ] ],
52 | [ [ -1, 16 ], 1, Concat, [ 1 ] ], # cat head P5
53 | [ -1, 3, C3, [ 768, False ] ], # 29 (P5/32-large)
54 |
55 | [ -1, 1, Conv, [ 768, 3, 2 ] ],
56 | [ [ -1, 12 ], 1, Concat, [ 1 ] ], # cat head P6
57 | [ -1, 3, C3, [ 1024, False ] ], # 32 (P6/64-xlarge)
58 |
59 | [ [ 23, 26, 29, 32 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4, P5, P6)
60 | ]
61 |
--------------------------------------------------------------------------------
/models/yolo.py:
--------------------------------------------------------------------------------
1 | # YOLOv5 YOLO-specific modules
2 |
3 | import argparse
4 | import logging
5 | import sys
6 | from copy import deepcopy
7 |
8 | sys.path.append('./') # to run '$ python *.py' files in subdirectories
9 | logger = logging.getLogger(__name__)
10 |
11 | from models.common import *
12 | from models.experimental import *
13 | from utils.autoanchor import check_anchor_order
14 | from utils.general import make_divisible, check_file, set_logging
15 | from utils.torch_utils import time_synchronized, fuse_conv_and_bn, model_info, scale_img, initialize_weights, \
16 | select_device, copy_attr
17 |
18 | try:
19 | import thop # for FLOPS computation
20 | except ImportError:
21 | thop = None
22 |
23 |
24 | class Detect(nn.Module):
25 | stride = None # strides computed during build
26 | export = False # onnx export
27 |
28 | def __init__(self, nc=80, anchors=(), ch=()): # detection layer
29 | super(Detect, self).__init__()
30 | self.nc = nc # number of classes
31 | self.no = nc + 5 # number of outputs per anchor
32 | self.nl = len(anchors) # number of detection layers
33 | self.na = len(anchors[0]) // 2 # number of anchors
34 | self.grid = [torch.zeros(1)] * self.nl # init grid
35 | a = torch.tensor(anchors).float().view(self.nl, -1, 2)
36 | self.register_buffer('anchors', a) # shape(nl,na,2)
37 | self.register_buffer('anchor_grid', a.clone().view(self.nl, 1, -1, 1, 1, 2)) # shape(nl,1,na,1,1,2)
38 | self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv
39 |
40 | def forward(self, x):
41 | # x = x.copy() # for profiling
42 | z = [] # inference output
43 | self.training |= self.export
44 | for i in range(self.nl):
45 | x[i] = self.m[i](x[i]) # conv
46 | bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85)
47 | x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()
48 |
49 | if not self.training: # inference
50 | if self.grid[i].shape[2:4] != x[i].shape[2:4]:
51 | self.grid[i] = self._make_grid(nx, ny).to(x[i].device)
52 |
53 | y = x[i].sigmoid()
54 | y[..., 0:2] = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i] # xy
55 | y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh
56 | z.append(y.view(bs, -1, self.no))
57 |
58 | return x if self.training else (torch.cat(z, 1), x)
59 |
60 | @staticmethod
61 | def _make_grid(nx=20, ny=20):
62 | yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)])
63 | return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float()
64 |
65 |
66 | class Model(nn.Module):
67 | def __init__(self, cfg='yolov5s.yaml', ch=3, nc=None, anchors=None): # model, input channels, number of classes
68 | super(Model, self).__init__()
69 | if isinstance(cfg, dict):
70 | self.yaml = cfg # model dict
71 | else: # is *.yaml
72 | import yaml # for torch hub
73 | self.yaml_file = Path(cfg).name
74 | with open(cfg) as f:
75 | self.yaml = yaml.safe_load(f) # model dict
76 |
77 | # Define model
78 | ch = self.yaml['ch'] = self.yaml.get('ch', ch) # input channels
79 | if nc and nc != self.yaml['nc']:
80 | logger.info(f"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}")
81 | self.yaml['nc'] = nc # override yaml value
82 | if anchors:
83 | logger.info(f'Overriding model.yaml anchors with anchors={anchors}')
84 | self.yaml['anchors'] = round(anchors) # override yaml value
85 | self.model, self.save = parse_model(deepcopy(self.yaml), ch=[ch]) # model, savelist
86 | self.names = [str(i) for i in range(self.yaml['nc'])] # default names
87 | # print([x.shape for x in self.forward(torch.zeros(1, ch, 64, 64))])
88 |
89 | # Build strides, anchors
90 | m = self.model[-1] # Detect()
91 | if isinstance(m, Detect):
92 | s = 256 # 2x min stride
93 | m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]) # forward
94 | m.anchors /= m.stride.view(-1, 1, 1)
95 | check_anchor_order(m)
96 | self.stride = m.stride
97 | self._initialize_biases() # only run once
98 | # print('Strides: %s' % m.stride.tolist())
99 |
100 | # Init weights, biases
101 | initialize_weights(self)
102 | self.info()
103 | logger.info('')
104 |
105 | def forward(self, x, augment=False, profile=False):
106 | if augment:
107 | img_size = x.shape[-2:] # height, width
108 | s = [1, 0.83, 0.67] # scales
109 | f = [None, 3, None] # flips (2-ud, 3-lr)
110 | y = [] # outputs
111 | for si, fi in zip(s, f):
112 | xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max()))
113 | yi = self.forward_once(xi)[0] # forward
114 | # cv2.imwrite(f'img_{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1]) # save
115 | yi[..., :4] /= si # de-scale
116 | if fi == 2:
117 | yi[..., 1] = img_size[0] - yi[..., 1] # de-flip ud
118 | elif fi == 3:
119 | yi[..., 0] = img_size[1] - yi[..., 0] # de-flip lr
120 | y.append(yi)
121 | return torch.cat(y, 1), None # augmented inference, train
122 | else:
123 | return self.forward_once(x, profile) # single-scale inference, train
124 |
125 | def forward_once(self, x, profile=False):
126 | y, dt = [], [] # outputs
127 | for m in self.model:
128 | if m.f != -1: # if not from previous layer
129 | x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers
130 |
131 | if profile:
132 | o = thop.profile(m, inputs=(x,), verbose=False)[0] / 1E9 * 2 if thop else 0 # FLOPS
133 | t = time_synchronized()
134 | for _ in range(10):
135 | _ = m(x)
136 | dt.append((time_synchronized() - t) * 100)
137 | print('%10.1f%10.0f%10.1fms %-40s' % (o, m.np, dt[-1], m.type))
138 |
139 | x = m(x) # run
140 | y.append(x if m.i in self.save else None) # save output
141 |
142 | if profile:
143 | print('%.1fms total' % sum(dt))
144 | return x
145 |
146 | def _initialize_biases(self, cf=None): # initialize biases into Detect(), cf is class frequency
147 | # https://arxiv.org/abs/1708.02002 section 3.3
148 | # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.
149 | m = self.model[-1] # Detect() module
150 | for mi, s in zip(m.m, m.stride): # from
151 | b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85)
152 | b.data[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image)
153 | b.data[:, 5:] += math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum()) # cls
154 | mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
155 |
156 | def _print_biases(self):
157 | m = self.model[-1] # Detect() module
158 | for mi in m.m: # from
159 | b = mi.bias.detach().view(m.na, -1).T # conv.bias(255) to (3,85)
160 | print(('%6g Conv2d.bias:' + '%10.3g' * 6) % (mi.weight.shape[1], *b[:5].mean(1).tolist(), b[5:].mean()))
161 |
162 | # def _print_weights(self):
163 | # for m in self.model.modules():
164 | # if type(m) is Bottleneck:
165 | # print('%10.3g' % (m.w.detach().sigmoid() * 2)) # shortcut weights
166 |
167 | def fuse(self): # fuse model Conv2d() + BatchNorm2d() layers
168 | print('Fusing layers... ')
169 | for m in self.model.modules():
170 | if type(m) is Conv and hasattr(m, 'bn'):
171 | m.conv = fuse_conv_and_bn(m.conv, m.bn) # update conv
172 | delattr(m, 'bn') # remove batchnorm
173 | m.forward = m.fuseforward # update forward
174 | self.info()
175 | return self
176 |
177 | def nms(self, mode=True): # add or remove NMS module
178 | present = type(self.model[-1]) is NMS # last layer is NMS
179 | if mode and not present:
180 | print('Adding NMS... ')
181 | m = NMS() # module
182 | m.f = -1 # from
183 | m.i = self.model[-1].i + 1 # index
184 | self.model.add_module(name='%s' % m.i, module=m) # add
185 | self.eval()
186 | elif not mode and present:
187 | print('Removing NMS... ')
188 | self.model = self.model[:-1] # remove
189 | return self
190 |
191 | def autoshape(self): # add autoShape module
192 | print('Adding autoShape... ')
193 | m = autoShape(self) # wrap model
194 | copy_attr(m, self, include=('yaml', 'nc', 'hyp', 'names', 'stride'), exclude=()) # copy attributes
195 | return m
196 |
197 | def info(self, verbose=False, img_size=640): # print model information
198 | model_info(self, verbose, img_size)
199 |
200 |
201 | def parse_model(d, ch): # model_dict, input_channels(3)
202 | logger.info('\n%3s%18s%3s%10s %-40s%-30s' % ('', 'from', 'n', 'params', 'module', 'arguments'))
203 | anchors, nc, gd, gw = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple']
204 | na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors
205 | no = na * (nc + 5) # number of outputs = anchors * (classes + 5)
206 |
207 | layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out
208 | for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']): # from, number, module, args
209 | m = eval(m) if isinstance(m, str) else m # eval strings
210 | for j, a in enumerate(args):
211 | try:
212 | args[j] = eval(a) if isinstance(a, str) else a # eval strings
213 | except:
214 | pass
215 |
216 | n = max(round(n * gd), 1) if n > 1 else n # depth gain
217 | if m in [Conv, GhostConv, Bottleneck, GhostBottleneck, SPP, DWConv, MixConv2d, Focus, CrossConv, BottleneckCSP,
218 | C3, C3TR]:
219 | c1, c2 = ch[f], args[0]
220 | if c2 != no: # if not output
221 | c2 = make_divisible(c2 * gw, 8)
222 |
223 | args = [c1, c2, *args[1:]]
224 | if m in [BottleneckCSP, C3, C3TR]:
225 | args.insert(2, n) # number of repeats
226 | n = 1
227 | elif m is nn.BatchNorm2d:
228 | args = [ch[f]]
229 | # elif m is Concat:
230 | # c2 = sum([ch[x] for x in f])
231 | elif m is Concat:
232 | c2 = max([ch[x] for x in f])
233 |
234 | elif m is Detect:
235 | args.append([ch[x] for x in f])
236 | if isinstance(args[1], int): # number of anchors
237 | args[1] = [list(range(args[1] * 2))] * len(f)
238 | elif m is Contract:
239 | c2 = ch[f] * args[0] ** 2
240 | elif m is Expand:
241 | c2 = ch[f] // args[0] ** 2
242 | else:
243 | c2 = ch[f]
244 |
245 | m_ = nn.Sequential(*[m(*args) for _ in range(n)]) if n > 1 else m(*args) # module
246 | t = str(m)[8:-2].replace('__main__.', '') # module type
247 | np = sum([x.numel() for x in m_.parameters()]) # number params
248 | m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params
249 | logger.info('%3s%18s%3s%10.0f %-40s%-30s' % (i, f, n, np, t, args)) # print
250 | save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist
251 | layers.append(m_)
252 | if i == 0:
253 | ch = []
254 | ch.append(c2)
255 | return nn.Sequential(*layers), sorted(save)
256 |
257 |
258 | if __name__ == '__main__':
259 | parser = argparse.ArgumentParser()
260 | parser.add_argument('--cfg', type=str, default='yolov5x.yaml', help='model.yaml')
261 | parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
262 | opt = parser.parse_args()
263 | opt.cfg = check_file(opt.cfg) # check file
264 | set_logging()
265 | device = select_device(opt.device)
266 |
267 | # Create model
268 | model = Model(opt.cfg).to(device)
269 | print(model)
270 |
271 | # Profile
272 | # img = torch.rand(8 if torch.cuda.is_available() else 1, 3, 320, 320).to(device)
273 | # y = model(img, profile=True)
274 |
275 | # Tensorboard (not working https://github.com/ultralytics/yolov5/issues/2898)
276 | # from torch.utils.tensorboard import SummaryWriter
277 | # tb_writer = SummaryWriter('.')
278 | # print("Run 'tensorboard --logdir=models' to view tensorboard at http://localhost:6006/")
279 | # tb_writer.add_graph(torch.jit.trace(model, img, strict=False), []) # add model graph
280 | # tb_writer.add_image('test', img[0], dataformats='CWH') # add model to tensorboard
281 |
--------------------------------------------------------------------------------
/models/yolov5x.yaml:
--------------------------------------------------------------------------------
1 | # parameters
2 | nc: 80 # number of classes
3 | depth_multiple: 1.33 # model depth multiple
4 | width_multiple: 1.25 # layer channel multiple
5 |
6 |
7 | # anchors
8 | anchors:
9 | - [10,13, 16,30, 33,23] # P3/8
10 | - [30,61, 62,45, 59,119] # P4/16
11 | - [116,90, 156,198, 373,326] # P5/32
12 |
13 | # YOLOv5 backbone
14 | backbone:
15 | # [from, number, module, args]
16 | [[-1, 1, Focus, [64, 3]], # 0-P1/2 320 3,80
17 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 160 80,160
18 | [-1, 3, C3, [128]], # 160, 160
19 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 80 # 160, 320
20 | [-1, 9, C3, [256]], # 320, 320
21 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 40 # 320, 640
22 | [-1, 9, C3, [512]], # 640, 640
23 | [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 20 # 640, 1280
24 | [-1, 1, SPP, [1024, [5, 9, 13]]], # 1280, 1280
25 | [-1, 3, C3, [1024, False]], # 9 1280, 1280
26 | ]
27 |
28 | # YOLOv5 head
29 | head:
30 | [[-1, 1, Conv, [512, 1, 1]], # 10 1280, 640
31 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], # 11 40 上采样
32 | [[-1, 6], 1, Concat, [640, 640]], # 12 cat backbone P4 # cat 40,40
33 | [-1, 3, C3, [512, False]], # 13 # 640, 640
34 |
35 | [-1, 1, Conv, [256, 1, 1]], # 640, 320
36 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], # 80 640, 320 上采样
37 | [[-1, 4], 1, Concat, [320, 320]], # cat backbone P3 # cat 80,80
38 | [-1, 4, C3, [256, False]], # 17 (P3/8-small) # 320, 320
39 |
40 | # [-1, 1, Conv, [256, 1, 1]], # 320, 320
41 | [-1, 1, Conv, [512, 3, 2]], # 320, 640 # 下 40
42 | [[-1, 6, 13], 1, Concat, [640, 640]], # cat head P4 # cat 40,40
43 | [-1, 3, C3, [512, False]], # 21 (P4/16-medium) # 640, 640 #20
44 |
45 | # [-1, 1, Conv, [512, 1, 1]], # 640, 640
46 | [-1, 1, Conv, [1024, 3, 2]], # 640, 1280 # 下 20 #21
47 | [[-1, 9], 1, Concat, [1280, 1280]], # cat head P5 cat 20,20 #22
48 | [-1, 3, C3, [1024, False]], # 25 (P5/32-large) # 1280, 1280 #23
49 |
50 | # [[17, 21, 25], 1, Detect, [nc, anchors]] # Detect(P3, P4, P5)
51 | [[17, 20, 23], 1, Detect, [nc, anchors]] # Detect(P3, P4, P5)
52 | ]
53 |
54 | # layer 2
55 | # [-1, 1, Conv, [512, 1, 1]], # 1280, 640
56 | # [-1, 1, nn.Upsample, [None, 2, 'nearest']], # 40 上采样
57 | # [[-1, 21], 1, Concat, [640, 640]], # cat backbone P4 # cat 40,40
58 | # [-1, 3, C3, [512, False]], # 29 # 640, 640
59 | #
60 | # [-1, 1, Conv, [256, 1, 1]], # 640, 320
61 | # [-1, 1, nn.Upsample, [None, 2, 'nearest']], # 80 640, 320 上采样
62 | # [[-1, 17], 1, Concat, [320, 320]], # cat backbone P3 # cat 80,80
63 | # [-1, 3, C3, [256, False]], # 33 (P3/8-small) # 320, 320
64 | #
65 | # [-1, 1, Conv, [256, 1, 1]], # 320, 320
66 | # [-1, 1, Conv, [512, 3, 2]], # 320, 640 # 下 40
67 | # [[-1, 21, 29], 1, Concat, [640, 640]], # cat head P4 # cat 40,40
68 | # [-1, 3, C3, [512, False]], # 37 (P4/16-medium) # 640, 640
69 | #
70 | # [-1, 1, Conv, [512, 1, 1]], # 640, 640
71 | # [-1, 1, Conv, [1024, 3, 2]], # 640, 1280 # 下 20
72 | # [[-1, 25], 1, Concat, [1280, 1280]], # cat head P5 cat 20,20
73 | # [-1, 3, C3, [1024, False]], # 41 (P5/32-large) # 640, 1280
74 | #
75 | # [[33, 37, 41], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
76 | #]
77 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | # pip install -r requirements.txt
2 |
3 | # base ----------------------------------------
4 | matplotlib>=3.2.2
5 | numpy>=1.18.5
6 | opencv-python>=4.1.2
7 | Pillow
8 | PyYAML>=5.3.1
9 | scipy>=1.4.1
10 | torch>=1.7.0
11 | torchvision>=0.8.1
12 | tqdm>=4.41.0
13 |
14 | # logging -------------------------------------
15 | tensorboard>=2.4.1
16 | # wandb
17 |
18 | # plotting ------------------------------------
19 | seaborn>=0.11.0
20 | pandas
21 |
22 | # export --------------------------------------
23 | # coremltools>=4.1
24 | # onnx>=1.8.1
25 | # scikit-learn==0.19.2 # for coreml quantization
26 |
27 | # extras --------------------------------------
28 | thop # FLOPS computation
29 | pycocotools>=2.0 # COCO mAP
30 |
--------------------------------------------------------------------------------
/test.py:
--------------------------------------------------------------------------------
1 | import argparse
2 | import json
3 | import os
4 | from pathlib import Path
5 | from threading import Thread
6 |
7 | import numpy as np
8 | import torch
9 | import yaml
10 | from tqdm import tqdm
11 |
12 | from models.experimental import attempt_load
13 | from utils.datasets import create_dataloader
14 | from utils.general import coco80_to_coco91_class, check_dataset, check_file, check_img_size, check_requirements, \
15 | box_iou, non_max_suppression, scale_coords, xyxy2xywh, xywh2xyxy, set_logging, increment_path, colorstr
16 | from utils.metrics import ap_per_class, ConfusionMatrix
17 | from utils.plots import plot_images, output_to_target, plot_study_txt
18 | from utils.torch_utils import select_device, time_synchronized
19 |
20 |
21 | def test(data,
22 | weights=None,
23 | batch_size=32,
24 | imgsz=640,
25 | conf_thres=0.001,
26 | iou_thres=0.6, # for NMS
27 | save_json=False,
28 | single_cls=False,
29 | augment=False,
30 | verbose=False,
31 | model=None,
32 | dataloader=None,
33 | save_dir=Path(''), # for saving images
34 | save_txt=False, # for auto-labelling
35 | save_hybrid=False, # for hybrid auto-labelling
36 | save_conf=False, # save auto-label confidences
37 | plots=True,
38 | wandb_logger=None,
39 | compute_loss=None,
40 | half_precision=True,
41 | is_coco=False,
42 | opt=None):
43 | # Initialize/load model and set device
44 | training = model is not None
45 | if training: # called by train.py
46 | device = next(model.parameters()).device # get model device
47 |
48 | else: # called directly
49 | set_logging()
50 | device = select_device(opt.device, batch_size=batch_size)
51 |
52 | # Directories
53 | save_dir = increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok) # increment run
54 | (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
55 |
56 | # Load model
57 | model = attempt_load(weights, map_location=device) # load FP32 model
58 | gs = max(int(model.stride.max()), 32) # grid size (max stride)
59 | imgsz = check_img_size(imgsz, s=gs) # check img_size
60 |
61 | # Multi-GPU disabled, incompatible with .half() https://github.com/ultralytics/yolov5/issues/99
62 | # if device.type != 'cpu' and torch.cuda.device_count() > 1:
63 | # model = nn.DataParallel(model)
64 |
65 | # Half
66 | half = device.type != 'cpu' and half_precision # half precision only supported on CUDA
67 | if half:
68 | model.half()
69 |
70 | # Configure
71 | model.eval()
72 | if isinstance(data, str):
73 | is_coco = data.endswith('coco.yaml')
74 | with open(data) as f:
75 | data = yaml.safe_load(f)
76 | check_dataset(data) # check
77 | nc = 1 if single_cls else int(data['nc']) # number of classes
78 | iouv = torch.linspace(0.5, 0.95, 10).to(device) # iou vector for mAP@0.5:0.95
79 | niou = iouv.numel()
80 |
81 | # Logging
82 | log_imgs = 0
83 | if wandb_logger and wandb_logger.wandb:
84 | log_imgs = min(wandb_logger.log_imgs, 100)
85 | # Dataloader
86 | if not training:
87 | if device.type != 'cpu':
88 | model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) # run once
89 | task = opt.task if opt.task in ('train', 'val', 'test') else 'val' # path to train/val/test images
90 | dataloader = create_dataloader(data[task], imgsz, batch_size, gs, opt, pad=0.5, rect=True,
91 | prefix=colorstr(f'{task}: '))[0]
92 |
93 | seen = 0
94 | confusion_matrix = ConfusionMatrix(nc=nc)
95 | names = {k: v for k, v in enumerate(model.names if hasattr(model, 'names') else model.module.names)}
96 | coco91class = coco80_to_coco91_class()
97 | s = ('%20s' + '%12s' * 6) % ('Class', 'Images', 'Labels', 'P', 'R', 'mAP@.5', 'mAP@.5:.95')
98 | p, r, f1, mp, mr, map50, map, t0, t1 = 0., 0., 0., 0., 0., 0., 0., 0., 0.
99 | loss = torch.zeros(3, device=device)
100 | jdict, stats, ap, ap_class, wandb_images = [], [], [], [], []
101 | for batch_i, (img, targets, paths, shapes) in enumerate(tqdm(dataloader, desc=s)):
102 | img = img.to(device, non_blocking=True)
103 | img = img.half() if half else img.float() # uint8 to fp16/32
104 | img /= 255.0 # 0 - 255 to 0.0 - 1.0
105 | targets = targets.to(device)
106 | nb, _, height, width = img.shape # batch size, channels, height, width
107 |
108 | with torch.no_grad():
109 | # Run model
110 | t = time_synchronized()
111 | out, train_out = model(img, augment=augment) # inference and training outputs
112 | t0 += time_synchronized() - t
113 |
114 | # Compute loss
115 | if compute_loss:
116 | loss += compute_loss([x.float() for x in train_out], targets)[1][:3] # box, obj, cls
117 |
118 | # Run NMS
119 | targets[:, 2:] *= torch.Tensor([width, height, width, height]).to(device) # to pixels
120 | lb = [targets[targets[:, 0] == i, 1:] for i in range(nb)] if save_hybrid else [] # for autolabelling
121 | t = time_synchronized()
122 | out = non_max_suppression(out, conf_thres=conf_thres, iou_thres=iou_thres, labels=lb, multi_label=True)
123 | t1 += time_synchronized() - t
124 |
125 | # Statistics per image
126 | for si, pred in enumerate(out):
127 | labels = targets[targets[:, 0] == si, 1:]
128 | nl = len(labels)
129 | tcls = labels[:, 0].tolist() if nl else [] # target class
130 | path = Path(paths[si])
131 | seen += 1
132 |
133 | if len(pred) == 0:
134 | if nl:
135 | stats.append((torch.zeros(0, niou, dtype=torch.bool), torch.Tensor(), torch.Tensor(), tcls))
136 | continue
137 |
138 | # Predictions
139 | predn = pred.clone()
140 | scale_coords(img[si].shape[1:], predn[:, :4], shapes[si][0], shapes[si][1]) # native-space pred
141 |
142 | # Append to text file
143 | if save_txt:
144 | gn = torch.tensor(shapes[si][0])[[1, 0, 1, 0]] # normalization gain whwh
145 | for *xyxy, conf, cls in predn.tolist():
146 | xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
147 | line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format
148 | with open(save_dir / 'labels' / (path.stem + '.txt'), 'a') as f:
149 | f.write(('%g ' * len(line)).rstrip() % line + '\n')
150 |
151 | # W&B logging - Media Panel Plots
152 | if len(wandb_images) < log_imgs and wandb_logger.current_epoch > 0: # Check for test operation
153 | if wandb_logger.current_epoch % wandb_logger.bbox_interval == 0:
154 | box_data = [{"position": {"minX": xyxy[0], "minY": xyxy[1], "maxX": xyxy[2], "maxY": xyxy[3]},
155 | "class_id": int(cls),
156 | "box_caption": "%s %.3f" % (names[cls], conf),
157 | "scores": {"class_score": conf},
158 | "domain": "pixel"} for *xyxy, conf, cls in pred.tolist()]
159 | boxes = {"predictions": {"box_data": box_data, "class_labels": names}} # inference-space
160 | wandb_images.append(wandb_logger.wandb.Image(img[si], boxes=boxes, caption=path.name))
161 | wandb_logger.log_training_progress(predn, path, names) if wandb_logger and wandb_logger.wandb_run else None
162 |
163 | # Append to pycocotools JSON dictionary
164 | if save_json:
165 | # [{"image_id": 42, "category_id": 18, "bbox": [258.15, 41.29, 348.26, 243.78], "score": 0.236}, ...
166 | image_id = int(path.stem) if path.stem.isnumeric() else path.stem
167 | box = xyxy2xywh(predn[:, :4]) # xywh
168 | box[:, :2] -= box[:, 2:] / 2 # xy center to top-left corner
169 | for p, b in zip(pred.tolist(), box.tolist()):
170 | jdict.append({'image_id': image_id,
171 | 'category_id': coco91class[int(p[5])] if is_coco else int(p[5]),
172 | 'bbox': [round(x, 3) for x in b],
173 | 'score': round(p[4], 5)})
174 |
175 | # Assign all predictions as incorrect
176 | correct = torch.zeros(pred.shape[0], niou, dtype=torch.bool, device=device)
177 | if nl:
178 | detected = [] # target indices
179 | tcls_tensor = labels[:, 0]
180 |
181 | # target boxes
182 | tbox = xywh2xyxy(labels[:, 1:5])
183 | scale_coords(img[si].shape[1:], tbox, shapes[si][0], shapes[si][1]) # native-space labels
184 | if plots:
185 | confusion_matrix.process_batch(predn, torch.cat((labels[:, 0:1], tbox), 1))
186 |
187 | # Per target class
188 | for cls in torch.unique(tcls_tensor):
189 | ti = (cls == tcls_tensor).nonzero(as_tuple=False).view(-1) # prediction indices
190 | pi = (cls == pred[:, 5]).nonzero(as_tuple=False).view(-1) # target indices
191 |
192 | # Search for detections
193 | if pi.shape[0]:
194 | # Prediction to target ious
195 | ious, i = box_iou(predn[pi, :4], tbox[ti]).max(1) # best ious, indices
196 |
197 | # Append detections
198 | detected_set = set()
199 | for j in (ious > iouv[0]).nonzero(as_tuple=False):
200 | d = ti[i[j]] # detected target
201 | if d.item() not in detected_set:
202 | detected_set.add(d.item())
203 | detected.append(d)
204 | correct[pi[j]] = ious[j] > iouv # iou_thres is 1xn
205 | if len(detected) == nl: # all targets already located in image
206 | break
207 |
208 | # Append statistics (correct, conf, pcls, tcls)
209 | stats.append((correct.cpu(), pred[:, 4].cpu(), pred[:, 5].cpu(), tcls))
210 |
211 | # Plot images
212 | if plots and batch_i < 3:
213 | f = save_dir / f'test_batch{batch_i}_labels.jpg' # labels
214 | Thread(target=plot_images, args=(img, targets, paths, f, names), daemon=True).start()
215 | f = save_dir / f'test_batch{batch_i}_pred.jpg' # predictions
216 | Thread(target=plot_images, args=(img, output_to_target(out), paths, f, names), daemon=True).start()
217 |
218 | # Compute statistics
219 | stats = [np.concatenate(x, 0) for x in zip(*stats)] # to numpy
220 | if len(stats) and stats[0].any():
221 | p, r, ap, f1, ap_class = ap_per_class(*stats, plot=plots, save_dir=save_dir, names=names)
222 | ap50, ap = ap[:, 0], ap.mean(1) # AP@0.5, AP@0.5:0.95
223 | mp, mr, map50, map = p.mean(), r.mean(), ap50.mean(), ap.mean()
224 | nt = np.bincount(stats[3].astype(np.int64), minlength=nc) # number of targets per class
225 | else:
226 | nt = torch.zeros(1)
227 |
228 | # Print results
229 | pf = '%20s' + '%12i' * 2 + '%12.3g' * 4 # print format
230 | print(pf % ('all', seen, nt.sum(), mp, mr, map50, map))
231 |
232 | # Print results per class
233 | if (verbose or (nc < 50 and not training)) and nc > 1 and len(stats):
234 | for i, c in enumerate(ap_class):
235 | print(pf % (names[c], seen, nt[c], p[i], r[i], ap50[i], ap[i]))
236 |
237 | # Print speeds
238 | t = tuple(x / seen * 1E3 for x in (t0, t1, t0 + t1)) + (imgsz, imgsz, batch_size) # tuple
239 | if not training:
240 | print('Speed: %.1f/%.1f/%.1f ms inference/NMS/total per %gx%g image at batch-size %g' % t)
241 |
242 | # Plots
243 | if plots:
244 | confusion_matrix.plot(save_dir=save_dir, names=list(names.values()))
245 | if wandb_logger and wandb_logger.wandb:
246 | val_batches = [wandb_logger.wandb.Image(str(f), caption=f.name) for f in sorted(save_dir.glob('test*.jpg'))]
247 | wandb_logger.log({"Validation": val_batches})
248 | if wandb_images:
249 | wandb_logger.log({"Bounding Box Debugger/Images": wandb_images})
250 |
251 | # Save JSON
252 | if save_json and len(jdict):
253 | w = Path(weights[0] if isinstance(weights, list) else weights).stem if weights is not None else '' # weights
254 | anno_json = '../coco/annotations/instances_val2017.json' # annotations json
255 | pred_json = str(save_dir / f"{w}_predictions.json") # predictions json
256 | print('\nEvaluating pycocotools mAP... saving %s...' % pred_json)
257 | with open(pred_json, 'w') as f:
258 | json.dump(jdict, f)
259 |
260 | try: # https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocoEvalDemo.ipynb
261 | from pycocotools.coco import COCO
262 | from pycocotools.cocoeval import COCOeval
263 |
264 | anno = COCO(anno_json) # init annotations api
265 | pred = anno.loadRes(pred_json) # init predictions api
266 | eval = COCOeval(anno, pred, 'bbox')
267 | if is_coco:
268 | eval.params.imgIds = [int(Path(x).stem) for x in dataloader.dataset.img_files] # image IDs to evaluate
269 | eval.evaluate()
270 | eval.accumulate()
271 | eval.summarize()
272 | map, map50 = eval.stats[:2] # update results (mAP@0.5:0.95, mAP@0.5)
273 | except Exception as e:
274 | print(f'pycocotools unable to run: {e}')
275 |
276 | # Return results
277 | model.float() # for training
278 | if not training:
279 | s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
280 | print(f"Results saved to {save_dir}{s}")
281 | maps = np.zeros(nc) + map
282 | for i, c in enumerate(ap_class):
283 | maps[c] = ap[i]
284 | return (mp, mr, map50, map, *(loss.cpu() / len(dataloader)).tolist()), maps, t
285 |
286 |
287 | if __name__ == '__main__':
288 | parser = argparse.ArgumentParser(prog='test.py')
289 | parser.add_argument('--weights', nargs='+', type=str, default='yolov5s.pt', help='model.pt path(s)')
290 | parser.add_argument('--data', type=str, default='data/coco128.yaml', help='*.data path')
291 | parser.add_argument('--batch-size', type=int, default=32, help='size of each image batch')
292 | parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)')
293 | parser.add_argument('--conf-thres', type=float, default=0.001, help='object confidence threshold')
294 | parser.add_argument('--iou-thres', type=float, default=0.6, help='IOU threshold for NMS')
295 | parser.add_argument('--task', default='val', help='train, val, test, speed or study')
296 | parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
297 | parser.add_argument('--single-cls', action='store_true', help='treat as single-class dataset')
298 | parser.add_argument('--augment', action='store_true', help='augmented inference')
299 | parser.add_argument('--verbose', action='store_true', help='report mAP by class')
300 | parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
301 | parser.add_argument('--save-hybrid', action='store_true', help='save label+prediction hybrid results to *.txt')
302 | parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
303 | parser.add_argument('--save-json', action='store_true', help='save a cocoapi-compatible JSON results file')
304 | parser.add_argument('--project', default='runs/test', help='save to project/name')
305 | parser.add_argument('--name', default='exp', help='save to project/name')
306 | parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
307 | opt = parser.parse_args()
308 | opt.save_json |= opt.data.endswith('coco.yaml')
309 | opt.data = check_file(opt.data) # check file
310 | print(opt)
311 | check_requirements()
312 |
313 | if opt.task in ('train', 'val', 'test'): # run normally
314 | test(opt.data,
315 | opt.weights,
316 | opt.batch_size,
317 | opt.img_size,
318 | opt.conf_thres,
319 | opt.iou_thres,
320 | opt.save_json,
321 | opt.single_cls,
322 | opt.augment,
323 | opt.verbose,
324 | save_txt=opt.save_txt | opt.save_hybrid,
325 | save_hybrid=opt.save_hybrid,
326 | save_conf=opt.save_conf,
327 | opt=opt
328 | )
329 |
330 | elif opt.task == 'speed': # speed benchmarks
331 | for w in opt.weights:
332 | test(opt.data, w, opt.batch_size, opt.img_size, 0.25, 0.45, save_json=False, plots=False, opt=opt)
333 |
334 | elif opt.task == 'study': # run over a range of settings and save/plot
335 | # python test.py --task study --data coco.yaml --iou 0.7 --weights yolov5s.pt yolov5m.pt yolov5l.pt yolov5x.pt
336 | x = list(range(256, 1536 + 128, 128)) # x axis (image sizes)
337 | for w in opt.weights:
338 | f = f'study_{Path(opt.data).stem}_{Path(w).stem}.txt' # filename to save to
339 | y = [] # y axis
340 | for i in x: # img-size
341 | print(f'\nRunning {f} point {i}...')
342 | r, _, t = test(opt.data, w, opt.batch_size, i, opt.conf_thres, opt.iou_thres, opt.save_json,
343 | plots=False, opt=opt)
344 | y.append(r + t) # results and times
345 | np.savetxt(f, y, fmt='%10.4g') # save
346 | os.system('zip -r study.zip study_*.txt')
347 | plot_study_txt(x=x) # plot
348 |
--------------------------------------------------------------------------------
/utils/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/XingZeng307/YOLOv5_with_BiFPN/59322217045be24b60f50c4d8a90b98e4d8dd6cf/utils/__init__.py
--------------------------------------------------------------------------------
/utils/__pycache__/__init__.cpython-37.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/XingZeng307/YOLOv5_with_BiFPN/59322217045be24b60f50c4d8a90b98e4d8dd6cf/utils/__pycache__/__init__.cpython-37.pyc
--------------------------------------------------------------------------------
/utils/__pycache__/autoanchor.cpython-37.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/XingZeng307/YOLOv5_with_BiFPN/59322217045be24b60f50c4d8a90b98e4d8dd6cf/utils/__pycache__/autoanchor.cpython-37.pyc
--------------------------------------------------------------------------------
/utils/__pycache__/datasets.cpython-37.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/XingZeng307/YOLOv5_with_BiFPN/59322217045be24b60f50c4d8a90b98e4d8dd6cf/utils/__pycache__/datasets.cpython-37.pyc
--------------------------------------------------------------------------------
/utils/__pycache__/general.cpython-37.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/XingZeng307/YOLOv5_with_BiFPN/59322217045be24b60f50c4d8a90b98e4d8dd6cf/utils/__pycache__/general.cpython-37.pyc
--------------------------------------------------------------------------------
/utils/__pycache__/google_utils.cpython-37.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/XingZeng307/YOLOv5_with_BiFPN/59322217045be24b60f50c4d8a90b98e4d8dd6cf/utils/__pycache__/google_utils.cpython-37.pyc
--------------------------------------------------------------------------------
/utils/__pycache__/metrics.cpython-37.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/XingZeng307/YOLOv5_with_BiFPN/59322217045be24b60f50c4d8a90b98e4d8dd6cf/utils/__pycache__/metrics.cpython-37.pyc
--------------------------------------------------------------------------------
/utils/__pycache__/plots.cpython-37.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/XingZeng307/YOLOv5_with_BiFPN/59322217045be24b60f50c4d8a90b98e4d8dd6cf/utils/__pycache__/plots.cpython-37.pyc
--------------------------------------------------------------------------------
/utils/__pycache__/torch_utils.cpython-37.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/XingZeng307/YOLOv5_with_BiFPN/59322217045be24b60f50c4d8a90b98e4d8dd6cf/utils/__pycache__/torch_utils.cpython-37.pyc
--------------------------------------------------------------------------------
/utils/activations.py:
--------------------------------------------------------------------------------
1 | # Activation functions
2 |
3 | import torch
4 | import torch.nn as nn
5 | import torch.nn.functional as F
6 |
7 |
8 | # SiLU https://arxiv.org/pdf/1606.08415.pdf ----------------------------------------------------------------------------
9 | class SiLU(nn.Module): # export-friendly version of nn.SiLU()
10 | @staticmethod
11 | def forward(x):
12 | return x * torch.sigmoid(x)
13 |
14 |
15 | class Hardswish(nn.Module): # export-friendly version of nn.Hardswish()
16 | @staticmethod
17 | def forward(x):
18 | # return x * F.hardsigmoid(x) # for torchscript and CoreML
19 | return x * F.hardtanh(x + 3, 0., 6.) / 6. # for torchscript, CoreML and ONNX
20 |
21 |
22 | # Mish https://github.com/digantamisra98/Mish --------------------------------------------------------------------------
23 | class Mish(nn.Module):
24 | @staticmethod
25 | def forward(x):
26 | return x * F.softplus(x).tanh()
27 |
28 |
29 | class MemoryEfficientMish(nn.Module):
30 | class F(torch.autograd.Function):
31 | @staticmethod
32 | def forward(ctx, x):
33 | ctx.save_for_backward(x)
34 | return x.mul(torch.tanh(F.softplus(x))) # x * tanh(ln(1 + exp(x)))
35 |
36 | @staticmethod
37 | def backward(ctx, grad_output):
38 | x = ctx.saved_tensors[0]
39 | sx = torch.sigmoid(x)
40 | fx = F.softplus(x).tanh()
41 | return grad_output * (fx + x * sx * (1 - fx * fx))
42 |
43 | def forward(self, x):
44 | return self.F.apply(x)
45 |
46 |
47 | # FReLU https://arxiv.org/abs/2007.11824 -------------------------------------------------------------------------------
48 | class FReLU(nn.Module):
49 | def __init__(self, c1, k=3): # ch_in, kernel
50 | super().__init__()
51 | self.conv = nn.Conv2d(c1, c1, k, 1, 1, groups=c1, bias=False)
52 | self.bn = nn.BatchNorm2d(c1)
53 |
54 | def forward(self, x):
55 | return torch.max(x, self.bn(self.conv(x)))
56 |
57 |
58 | # ACON https://arxiv.org/pdf/2009.04759.pdf ----------------------------------------------------------------------------
59 | class AconC(nn.Module):
60 | r""" ACON activation (activate or not).
61 | AconC: (p1*x-p2*x) * sigmoid(beta*(p1*x-p2*x)) + p2*x, beta is a learnable parameter
62 | according to "Activate or Not: Learning Customized Activation" .
63 | """
64 |
65 | def __init__(self, c1):
66 | super().__init__()
67 | self.p1 = nn.Parameter(torch.randn(1, c1, 1, 1))
68 | self.p2 = nn.Parameter(torch.randn(1, c1, 1, 1))
69 | self.beta = nn.Parameter(torch.ones(1, c1, 1, 1))
70 |
71 | def forward(self, x):
72 | dpx = (self.p1 - self.p2) * x
73 | return dpx * torch.sigmoid(self.beta * dpx) + self.p2 * x
74 |
75 |
76 | class MetaAconC(nn.Module):
77 | r""" ACON activation (activate or not).
78 | MetaAconC: (p1*x-p2*x) * sigmoid(beta*(p1*x-p2*x)) + p2*x, beta is generated by a small network
79 | according to "Activate or Not: Learning Customized Activation" .
80 | """
81 |
82 | def __init__(self, c1, k=1, s=1, r=16): # ch_in, kernel, stride, r
83 | super().__init__()
84 | c2 = max(r, c1 // r)
85 | self.p1 = nn.Parameter(torch.randn(1, c1, 1, 1))
86 | self.p2 = nn.Parameter(torch.randn(1, c1, 1, 1))
87 | self.fc1 = nn.Conv2d(c1, c2, k, s, bias=False)
88 | self.bn1 = nn.BatchNorm2d(c2)
89 | self.fc2 = nn.Conv2d(c2, c1, k, s, bias=False)
90 | self.bn2 = nn.BatchNorm2d(c1)
91 |
92 | def forward(self, x):
93 | y = x.mean(dim=2, keepdims=True).mean(dim=3, keepdims=True)
94 | beta = torch.sigmoid(self.bn2(self.fc2(self.bn1(self.fc1(y)))))
95 | dpx = (self.p1 - self.p2) * x
96 | return dpx * torch.sigmoid(beta * dpx) + self.p2 * x
97 |
--------------------------------------------------------------------------------
/utils/autoanchor.py:
--------------------------------------------------------------------------------
1 | # Auto-anchor utils
2 |
3 | import numpy as np
4 | import torch
5 | import yaml
6 | from scipy.cluster.vq import kmeans
7 | from tqdm import tqdm
8 |
9 | from utils.general import colorstr
10 |
11 |
12 | def check_anchor_order(m):
13 | # Check anchor order against stride order for YOLOv5 Detect() module m, and correct if necessary
14 | a = m.anchor_grid.prod(-1).view(-1) # anchor area
15 | da = a[-1] - a[0] # delta a
16 | ds = m.stride[-1] - m.stride[0] # delta s
17 | if da.sign() != ds.sign(): # same order
18 | print('Reversing anchor order')
19 | m.anchors[:] = m.anchors.flip(0)
20 | m.anchor_grid[:] = m.anchor_grid.flip(0)
21 |
22 |
23 | def check_anchors(dataset, model, thr=4.0, imgsz=640):
24 | # Check anchor fit to data, recompute if necessary
25 | prefix = colorstr('autoanchor: ')
26 | print(f'\n{prefix}Analyzing anchors... ', end='')
27 | m = model.module.model[-1] if hasattr(model, 'module') else model.model[-1] # Detect()
28 | shapes = imgsz * dataset.shapes / dataset.shapes.max(1, keepdims=True)
29 | scale = np.random.uniform(0.9, 1.1, size=(shapes.shape[0], 1)) # augment scale
30 | wh = torch.tensor(np.concatenate([l[:, 3:5] * s for s, l in zip(shapes * scale, dataset.labels)])).float() # wh
31 |
32 | def metric(k): # compute metric
33 | r = wh[:, None] / k[None]
34 | x = torch.min(r, 1. / r).min(2)[0] # ratio metric
35 | best = x.max(1)[0] # best_x
36 | aat = (x > 1. / thr).float().sum(1).mean() # anchors above threshold
37 | bpr = (best > 1. / thr).float().mean() # best possible recall
38 | return bpr, aat
39 |
40 | anchors = m.anchor_grid.clone().cpu().view(-1, 2) # current anchors
41 | bpr, aat = metric(anchors)
42 | print(f'anchors/target = {aat:.2f}, Best Possible Recall (BPR) = {bpr:.4f}', end='')
43 | if bpr < 0.98: # threshold to recompute
44 | print('. Attempting to improve anchors, please wait...')
45 | na = m.anchor_grid.numel() // 2 # number of anchors
46 | try:
47 | anchors = kmean_anchors(dataset, n=na, img_size=imgsz, thr=thr, gen=1000, verbose=False)
48 | except Exception as e:
49 | print(f'{prefix}ERROR: {e}')
50 | new_bpr = metric(anchors)[0]
51 | if new_bpr > bpr: # replace anchors
52 | anchors = torch.tensor(anchors, device=m.anchors.device).type_as(m.anchors)
53 | m.anchor_grid[:] = anchors.clone().view_as(m.anchor_grid) # for inference
54 | m.anchors[:] = anchors.clone().view_as(m.anchors) / m.stride.to(m.anchors.device).view(-1, 1, 1) # loss
55 | check_anchor_order(m)
56 | print(f'{prefix}New anchors saved to model. Update model *.yaml to use these anchors in the future.')
57 | else:
58 | print(f'{prefix}Original anchors better than new anchors. Proceeding with original anchors.')
59 | print('') # newline
60 |
61 |
62 | def kmean_anchors(path='./data/coco128.yaml', n=9, img_size=640, thr=4.0, gen=1000, verbose=True):
63 | """ Creates kmeans-evolved anchors from training dataset
64 |
65 | Arguments:
66 | path: path to dataset *.yaml, or a loaded dataset
67 | n: number of anchors
68 | img_size: image size used for training
69 | thr: anchor-label wh ratio threshold hyperparameter hyp['anchor_t'] used for training, default=4.0
70 | gen: generations to evolve anchors using genetic algorithm
71 | verbose: print all results
72 |
73 | Return:
74 | k: kmeans evolved anchors
75 |
76 | Usage:
77 | from utils.autoanchor import *; _ = kmean_anchors()
78 | """
79 | thr = 1. / thr
80 | prefix = colorstr('autoanchor: ')
81 |
82 | def metric(k, wh): # compute metrics
83 | r = wh[:, None] / k[None]
84 | x = torch.min(r, 1. / r).min(2)[0] # ratio metric
85 | # x = wh_iou(wh, torch.tensor(k)) # iou metric
86 | return x, x.max(1)[0] # x, best_x
87 |
88 | def anchor_fitness(k): # mutation fitness
89 | _, best = metric(torch.tensor(k, dtype=torch.float32), wh)
90 | return (best * (best > thr).float()).mean() # fitness
91 |
92 | def print_results(k):
93 | k = k[np.argsort(k.prod(1))] # sort small to large
94 | x, best = metric(k, wh0)
95 | bpr, aat = (best > thr).float().mean(), (x > thr).float().mean() * n # best possible recall, anch > thr
96 | print(f'{prefix}thr={thr:.2f}: {bpr:.4f} best possible recall, {aat:.2f} anchors past thr')
97 | print(f'{prefix}n={n}, img_size={img_size}, metric_all={x.mean():.3f}/{best.mean():.3f}-mean/best, '
98 | f'past_thr={x[x > thr].mean():.3f}-mean: ', end='')
99 | for i, x in enumerate(k):
100 | print('%i,%i' % (round(x[0]), round(x[1])), end=', ' if i < len(k) - 1 else '\n') # use in *.cfg
101 | return k
102 |
103 | if isinstance(path, str): # *.yaml file
104 | with open(path) as f:
105 | data_dict = yaml.safe_load(f) # model dict
106 | from utils.datasets import LoadImagesAndLabels
107 | dataset = LoadImagesAndLabels(data_dict['train'], augment=True, rect=True)
108 | else:
109 | dataset = path # dataset
110 |
111 | # Get label wh
112 | shapes = img_size * dataset.shapes / dataset.shapes.max(1, keepdims=True)
113 | wh0 = np.concatenate([l[:, 3:5] * s for s, l in zip(shapes, dataset.labels)]) # wh
114 |
115 | # Filter
116 | i = (wh0 < 3.0).any(1).sum()
117 | if i:
118 | print(f'{prefix}WARNING: Extremely small objects found. {i} of {len(wh0)} labels are < 3 pixels in size.')
119 | wh = wh0[(wh0 >= 2.0).any(1)] # filter > 2 pixels
120 | # wh = wh * (np.random.rand(wh.shape[0], 1) * 0.9 + 0.1) # multiply by random scale 0-1
121 |
122 | # Kmeans calculation
123 | print(f'{prefix}Running kmeans for {n} anchors on {len(wh)} points...')
124 | s = wh.std(0) # sigmas for whitening
125 | k, dist = kmeans(wh / s, n, iter=30) # points, mean distance
126 | assert len(k) == n, print(f'{prefix}ERROR: scipy.cluster.vq.kmeans requested {n} points but returned only {len(k)}')
127 | k *= s
128 | wh = torch.tensor(wh, dtype=torch.float32) # filtered
129 | wh0 = torch.tensor(wh0, dtype=torch.float32) # unfiltered
130 | k = print_results(k)
131 |
132 | # Plot
133 | # k, d = [None] * 20, [None] * 20
134 | # for i in tqdm(range(1, 21)):
135 | # k[i-1], d[i-1] = kmeans(wh / s, i) # points, mean distance
136 | # fig, ax = plt.subplots(1, 2, figsize=(14, 7), tight_layout=True)
137 | # ax = ax.ravel()
138 | # ax[0].plot(np.arange(1, 21), np.array(d) ** 2, marker='.')
139 | # fig, ax = plt.subplots(1, 2, figsize=(14, 7)) # plot wh
140 | # ax[0].hist(wh[wh[:, 0]<100, 0],400)
141 | # ax[1].hist(wh[wh[:, 1]<100, 1],400)
142 | # fig.savefig('wh.png', dpi=200)
143 |
144 | # Evolve
145 | npr = np.random
146 | f, sh, mp, s = anchor_fitness(k), k.shape, 0.9, 0.1 # fitness, generations, mutation prob, sigma
147 | pbar = tqdm(range(gen), desc=f'{prefix}Evolving anchors with Genetic Algorithm:') # progress bar
148 | for _ in pbar:
149 | v = np.ones(sh)
150 | while (v == 1).all(): # mutate until a change occurs (prevent duplicates)
151 | v = ((npr.random(sh) < mp) * npr.random() * npr.randn(*sh) * s + 1).clip(0.3, 3.0)
152 | kg = (k.copy() * v).clip(min=2.0)
153 | fg = anchor_fitness(kg)
154 | if fg > f:
155 | f, k = fg, kg.copy()
156 | pbar.desc = f'{prefix}Evolving anchors with Genetic Algorithm: fitness = {f:.4f}'
157 | if verbose:
158 | print_results(k)
159 |
160 | return print_results(k)
161 |
--------------------------------------------------------------------------------
/utils/aws/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/XingZeng307/YOLOv5_with_BiFPN/59322217045be24b60f50c4d8a90b98e4d8dd6cf/utils/aws/__init__.py
--------------------------------------------------------------------------------
/utils/aws/mime.sh:
--------------------------------------------------------------------------------
1 | # AWS EC2 instance startup 'MIME' script https://aws.amazon.com/premiumsupport/knowledge-center/execute-user-data-ec2/
2 | # This script will run on every instance restart, not only on first start
3 | # --- DO NOT COPY ABOVE COMMENTS WHEN PASTING INTO USERDATA ---
4 |
5 | Content-Type: multipart/mixed; boundary="//"
6 | MIME-Version: 1.0
7 |
8 | --//
9 | Content-Type: text/cloud-config; charset="us-ascii"
10 | MIME-Version: 1.0
11 | Content-Transfer-Encoding: 7bit
12 | Content-Disposition: attachment; filename="cloud-config.txt"
13 |
14 | #cloud-config
15 | cloud_final_modules:
16 | - [scripts-user, always]
17 |
18 | --//
19 | Content-Type: text/x-shellscript; charset="us-ascii"
20 | MIME-Version: 1.0
21 | Content-Transfer-Encoding: 7bit
22 | Content-Disposition: attachment; filename="userdata.txt"
23 |
24 | #!/bin/bash
25 | # --- paste contents of userdata.sh here ---
26 | --//
27 |
--------------------------------------------------------------------------------
/utils/aws/resume.py:
--------------------------------------------------------------------------------
1 | # Resume all interrupted trainings in yolov5/ dir including DDP trainings
2 | # Usage: $ python utils/aws/resume.py
3 |
4 | import os
5 | import sys
6 | from pathlib import Path
7 |
8 | import torch
9 | import yaml
10 |
11 | sys.path.append('./') # to run '$ python *.py' files in subdirectories
12 |
13 | port = 0 # --master_port
14 | path = Path('').resolve()
15 | for last in path.rglob('*/**/last.pt'):
16 | ckpt = torch.load(last)
17 | if ckpt['optimizer'] is None:
18 | continue
19 |
20 | # Load opt.yaml
21 | with open(last.parent.parent / 'opt.yaml') as f:
22 | opt = yaml.safe_load(f)
23 |
24 | # Get device count
25 | d = opt['device'].split(',') # devices
26 | nd = len(d) # number of devices
27 | ddp = nd > 1 or (nd == 0 and torch.cuda.device_count() > 1) # distributed data parallel
28 |
29 | if ddp: # multi-GPU
30 | port += 1
31 | cmd = f'python -m torch.distributed.launch --nproc_per_node {nd} --master_port {port} train.py --resume {last}'
32 | else: # single-GPU
33 | cmd = f'python train.py --resume {last}'
34 |
35 | cmd += ' > /dev/null 2>&1 &' # redirect output to dev/null and run in daemon thread
36 | print(cmd)
37 | os.system(cmd)
38 |
--------------------------------------------------------------------------------
/utils/aws/userdata.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | # AWS EC2 instance startup script https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html
3 | # This script will run only once on first instance start (for a re-start script see mime.sh)
4 | # /home/ubuntu (ubuntu) or /home/ec2-user (amazon-linux) is working dir
5 | # Use >300 GB SSD
6 |
7 | cd home/ubuntu
8 | if [ ! -d yolov5 ]; then
9 | echo "Running first-time script." # install dependencies, download COCO, pull Docker
10 | git clone https://github.com/ultralytics/yolov5 && sudo chmod -R 777 yolov5
11 | cd yolov5
12 | bash data/scripts/get_coco.sh && echo "Data done." &
13 | sudo docker pull ultralytics/yolov5:latest && echo "Docker done." &
14 | python -m pip install --upgrade pip && pip install -r requirements.txt && python detect.py && echo "Requirements done." &
15 | wait && echo "All tasks done." # finish background tasks
16 | else
17 | echo "Running re-start script." # resume interrupted runs
18 | i=0
19 | list=$(sudo docker ps -qa) # container list i.e. $'one\ntwo\nthree\nfour'
20 | while IFS= read -r id; do
21 | ((i++))
22 | echo "restarting container $i: $id"
23 | sudo docker start $id
24 | # sudo docker exec -it $id python train.py --resume # single-GPU
25 | sudo docker exec -d $id python utils/aws/resume.py # multi-scenario
26 | done <<<"$list"
27 | fi
28 |
--------------------------------------------------------------------------------
/utils/flask_rest_api/README.md:
--------------------------------------------------------------------------------
1 | # Flask REST API
2 | [REST](https://en.wikipedia.org/wiki/Representational_state_transfer) [API](https://en.wikipedia.org/wiki/API)s are commonly used to expose Machine Learning (ML) models to other services. This folder contains an example REST API created using Flask to expose the `yolov5s` model from [PyTorch Hub](https://pytorch.org/hub/ultralytics_yolov5/).
3 |
4 | ## Requirements
5 |
6 | [Flask](https://palletsprojects.com/p/flask/) is required. Install with:
7 | ```shell
8 | $ pip install Flask
9 | ```
10 |
11 | ## Run
12 |
13 | After Flask installation run:
14 |
15 | ```shell
16 | $ python3 restapi.py --port 5000
17 | ```
18 |
19 | Then use [curl](https://curl.se/) to perform a request:
20 |
21 | ```shell
22 | $ curl -X POST -F image=@zidane.jpg 'http://localhost:5000/v1/object-detection/yolov5s'`
23 | ```
24 |
25 | The model inference results are returned:
26 |
27 | ```shell
28 | [{'class': 0,
29 | 'confidence': 0.8197850585,
30 | 'name': 'person',
31 | 'xmax': 1159.1403808594,
32 | 'xmin': 750.912902832,
33 | 'ymax': 711.2583007812,
34 | 'ymin': 44.0350036621},
35 | {'class': 0,
36 | 'confidence': 0.5667674541,
37 | 'name': 'person',
38 | 'xmax': 1065.5523681641,
39 | 'xmin': 116.0448303223,
40 | 'ymax': 713.8904418945,
41 | 'ymin': 198.4603881836},
42 | {'class': 27,
43 | 'confidence': 0.5661227107,
44 | 'name': 'tie',
45 | 'xmax': 516.7975463867,
46 | 'xmin': 416.6880187988,
47 | 'ymax': 717.0524902344,
48 | 'ymin': 429.2020568848}]
49 | ```
50 |
51 | An example python script to perform inference using [requests](https://docs.python-requests.org/en/master/) is given in `example_request.py`
52 |
--------------------------------------------------------------------------------
/utils/flask_rest_api/example_request.py:
--------------------------------------------------------------------------------
1 | """Perform test request"""
2 | import pprint
3 |
4 | import requests
5 |
6 | DETECTION_URL = "http://localhost:5000/v1/object-detection/yolov5s"
7 | TEST_IMAGE = "zidane.jpg"
8 |
9 | image_data = open(TEST_IMAGE, "rb").read()
10 |
11 | response = requests.post(DETECTION_URL, files={"image": image_data}).json()
12 |
13 | pprint.pprint(response)
14 |
--------------------------------------------------------------------------------
/utils/flask_rest_api/restapi.py:
--------------------------------------------------------------------------------
1 | """
2 | Run a rest API exposing the yolov5s object detection model
3 | """
4 | import argparse
5 | import io
6 |
7 | import torch
8 | from PIL import Image
9 | from flask import Flask, request
10 |
11 | app = Flask(__name__)
12 |
13 | DETECTION_URL = "/v1/object-detection/yolov5s"
14 |
15 |
16 | @app.route(DETECTION_URL, methods=["POST"])
17 | def predict():
18 | if not request.method == "POST":
19 | return
20 |
21 | if request.files.get("image"):
22 | image_file = request.files["image"]
23 | image_bytes = image_file.read()
24 |
25 | img = Image.open(io.BytesIO(image_bytes))
26 |
27 | results = model(img, size=640)
28 | data = results.pandas().xyxy[0].to_json(orient="records")
29 | return data
30 |
31 |
32 | if __name__ == "__main__":
33 | parser = argparse.ArgumentParser(description="Flask api exposing yolov5 model")
34 | parser.add_argument("--port", default=5000, type=int, help="port number")
35 | args = parser.parse_args()
36 |
37 | model = torch.hub.load("ultralytics/yolov5", "yolov5s", force_reload=True).autoshape() # force_reload to recache
38 | app.run(host="0.0.0.0", port=args.port) # debug=True causes Restarting with stat
39 |
--------------------------------------------------------------------------------
/utils/google_app_engine/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM gcr.io/google-appengine/python
2 |
3 | # Create a virtualenv for dependencies. This isolates these packages from
4 | # system-level packages.
5 | # Use -p python3 or -p python3.7 to select python version. Default is version 2.
6 | RUN virtualenv /env -p python3
7 |
8 | # Setting these environment variables are the same as running
9 | # source /env/bin/activate.
10 | ENV VIRTUAL_ENV /env
11 | ENV PATH /env/bin:$PATH
12 |
13 | RUN apt-get update && apt-get install -y python-opencv
14 |
15 | # Copy the application's requirements.txt and run pip to install all
16 | # dependencies into the virtualenv.
17 | ADD requirements.txt /app/requirements.txt
18 | RUN pip install -r /app/requirements.txt
19 |
20 | # Add the application source code.
21 | ADD . /app
22 |
23 | # Run a WSGI server to serve the application. gunicorn must be declared as
24 | # a dependency in requirements.txt.
25 | CMD gunicorn -b :$PORT main:app
26 |
--------------------------------------------------------------------------------
/utils/google_app_engine/additional_requirements.txt:
--------------------------------------------------------------------------------
1 | # add these requirements in your app on top of the existing ones
2 | pip==18.1
3 | Flask==1.0.2
4 | gunicorn==19.9.0
5 |
--------------------------------------------------------------------------------
/utils/google_app_engine/app.yaml:
--------------------------------------------------------------------------------
1 | runtime: custom
2 | env: flex
3 |
4 | service: yolov5app
5 |
6 | liveness_check:
7 | initial_delay_sec: 600
8 |
9 | manual_scaling:
10 | instances: 1
11 | resources:
12 | cpu: 1
13 | memory_gb: 4
14 | disk_size_gb: 20
--------------------------------------------------------------------------------
/utils/google_utils.py:
--------------------------------------------------------------------------------
1 | # Google utils: https://cloud.google.com/storage/docs/reference/libraries
2 |
3 | import os
4 | import platform
5 | import subprocess
6 | import time
7 | from pathlib import Path
8 |
9 | import requests
10 | import torch
11 |
12 |
13 | def gsutil_getsize(url=''):
14 | # gs://bucket/file size https://cloud.google.com/storage/docs/gsutil/commands/du
15 | s = subprocess.check_output(f'gsutil du {url}', shell=True).decode('utf-8')
16 | return eval(s.split(' ')[0]) if len(s) else 0 # bytes
17 |
18 |
19 | def attempt_download(file, repo='ultralytics/yolov5'):
20 | # Attempt file download if does not exist
21 | file = Path(str(file).strip().replace("'", ''))
22 |
23 | if not file.exists():
24 | try:
25 | response = requests.get(f'https://api.github.com/repos/{repo}/releases/latest').json() # github api
26 | assets = [x['name'] for x in response['assets']] # release assets, i.e. ['yolov5s.pt', 'yolov5m.pt', ...]
27 | tag = response['tag_name'] # i.e. 'v1.0'
28 | except: # fallback plan
29 | assets = ['yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt',
30 | 'yolov5s6.pt', 'yolov5m6.pt', 'yolov5l6.pt', 'yolov5x6.pt']
31 | try:
32 | tag = subprocess.check_output('git tag', shell=True, stderr=subprocess.STDOUT).decode().split()[-1]
33 | except:
34 | tag = 'v5.0' # current release
35 |
36 | name = file.name
37 | if name in assets:
38 | msg = f'{file} missing, try downloading from https://github.com/{repo}/releases/'
39 | redundant = False # second download option
40 | try: # GitHub
41 | url = f'https://github.com/{repo}/releases/download/{tag}/{name}'
42 | print(f'Downloading {url} to {file}...')
43 | torch.hub.download_url_to_file(url, file)
44 | assert file.exists() and file.stat().st_size > 1E6 # check
45 | except Exception as e: # GCP
46 | print(f'Download error: {e}')
47 | assert redundant, 'No secondary mirror'
48 | url = f'https://storage.googleapis.com/{repo}/ckpt/{name}'
49 | print(f'Downloading {url} to {file}...')
50 | os.system(f'curl -L {url} -o {file}') # torch.hub.download_url_to_file(url, weights)
51 | finally:
52 | if not file.exists() or file.stat().st_size < 1E6: # check
53 | file.unlink(missing_ok=True) # remove partial downloads
54 | print(f'ERROR: Download failure: {msg}')
55 | print('')
56 | return
57 |
58 |
59 | def gdrive_download(id='16TiPfZj7htmTyhntwcZyEEAejOUxuT6m', file='tmp.zip'):
60 | # Downloads a file from Google Drive. from yolov5.utils.google_utils import *; gdrive_download()
61 | t = time.time()
62 | file = Path(file)
63 | cookie = Path('cookie') # gdrive cookie
64 | print(f'Downloading https://drive.google.com/uc?export=download&id={id} as {file}... ', end='')
65 | file.unlink(missing_ok=True) # remove existing file
66 | cookie.unlink(missing_ok=True) # remove existing cookie
67 |
68 | # Attempt file download
69 | out = "NUL" if platform.system() == "Windows" else "/dev/null"
70 | os.system(f'curl -c ./cookie -s -L "drive.google.com/uc?export=download&id={id}" > {out}')
71 | if os.path.exists('cookie'): # large file
72 | s = f'curl -Lb ./cookie "drive.google.com/uc?export=download&confirm={get_token()}&id={id}" -o {file}'
73 | else: # small file
74 | s = f'curl -s -L -o {file} "drive.google.com/uc?export=download&id={id}"'
75 | r = os.system(s) # execute, capture return
76 | cookie.unlink(missing_ok=True) # remove existing cookie
77 |
78 | # Error check
79 | if r != 0:
80 | file.unlink(missing_ok=True) # remove partial
81 | print('Download error ') # raise Exception('Download error')
82 | return r
83 |
84 | # Unzip if archive
85 | if file.suffix == '.zip':
86 | print('unzipping... ', end='')
87 | os.system(f'unzip -q {file}') # unzip
88 | file.unlink() # remove zip to free space
89 |
90 | print(f'Done ({time.time() - t:.1f}s)')
91 | return r
92 |
93 |
94 | def get_token(cookie="./cookie"):
95 | with open(cookie) as f:
96 | for line in f:
97 | if "download" in line:
98 | return line.split()[-1]
99 | return ""
100 |
101 | # def upload_blob(bucket_name, source_file_name, destination_blob_name):
102 | # # Uploads a file to a bucket
103 | # # https://cloud.google.com/storage/docs/uploading-objects#storage-upload-object-python
104 | #
105 | # storage_client = storage.Client()
106 | # bucket = storage_client.get_bucket(bucket_name)
107 | # blob = bucket.blob(destination_blob_name)
108 | #
109 | # blob.upload_from_filename(source_file_name)
110 | #
111 | # print('File {} uploaded to {}.'.format(
112 | # source_file_name,
113 | # destination_blob_name))
114 | #
115 | #
116 | # def download_blob(bucket_name, source_blob_name, destination_file_name):
117 | # # Uploads a blob from a bucket
118 | # storage_client = storage.Client()
119 | # bucket = storage_client.get_bucket(bucket_name)
120 | # blob = bucket.blob(source_blob_name)
121 | #
122 | # blob.download_to_filename(destination_file_name)
123 | #
124 | # print('Blob {} downloaded to {}.'.format(
125 | # source_blob_name,
126 | # destination_file_name))
127 |
--------------------------------------------------------------------------------
/utils/loss.py:
--------------------------------------------------------------------------------
1 | # Loss functions
2 |
3 | import torch
4 | import torch.nn as nn
5 |
6 | from utils.general import bbox_iou
7 | from utils.torch_utils import is_parallel
8 |
9 |
10 | def smooth_BCE(eps=0.1): # https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441
11 | # return positive, negative label smoothing BCE targets
12 | return 1.0 - 0.5 * eps, 0.5 * eps
13 |
14 |
15 | class BCEBlurWithLogitsLoss(nn.Module):
16 | # BCEwithLogitLoss() with reduced missing label effects.
17 | def __init__(self, alpha=0.05):
18 | super(BCEBlurWithLogitsLoss, self).__init__()
19 | self.loss_fcn = nn.BCEWithLogitsLoss(reduction='none') # must be nn.BCEWithLogitsLoss()
20 | self.alpha = alpha
21 |
22 | def forward(self, pred, true):
23 | loss = self.loss_fcn(pred, true)
24 | pred = torch.sigmoid(pred) # prob from logits
25 | dx = pred - true # reduce only missing label effects
26 | # dx = (pred - true).abs() # reduce missing label and false label effects
27 | alpha_factor = 1 - torch.exp((dx - 1) / (self.alpha + 1e-4))
28 | loss *= alpha_factor
29 | return loss.mean()
30 |
31 |
32 | class FocalLoss(nn.Module):
33 | # Wraps focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)
34 | def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
35 | super(FocalLoss, self).__init__()
36 | self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss()
37 | self.gamma = gamma
38 | self.alpha = alpha
39 | self.reduction = loss_fcn.reduction
40 | self.loss_fcn.reduction = 'none' # required to apply FL to each element
41 |
42 | def forward(self, pred, true):
43 | loss = self.loss_fcn(pred, true)
44 | # p_t = torch.exp(-loss)
45 | # loss *= self.alpha * (1.000001 - p_t) ** self.gamma # non-zero power for gradient stability
46 |
47 | # TF implementation https://github.com/tensorflow/addons/blob/v0.7.1/tensorflow_addons/losses/focal_loss.py
48 | pred_prob = torch.sigmoid(pred) # prob from logits
49 | p_t = true * pred_prob + (1 - true) * (1 - pred_prob)
50 | alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha)
51 | modulating_factor = (1.0 - p_t) ** self.gamma
52 | loss *= alpha_factor * modulating_factor
53 |
54 | if self.reduction == 'mean':
55 | return loss.mean()
56 | elif self.reduction == 'sum':
57 | return loss.sum()
58 | else: # 'none'
59 | return loss
60 |
61 |
62 | class QFocalLoss(nn.Module):
63 | # Wraps Quality focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)
64 | def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
65 | super(QFocalLoss, self).__init__()
66 | self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss()
67 | self.gamma = gamma
68 | self.alpha = alpha
69 | self.reduction = loss_fcn.reduction
70 | self.loss_fcn.reduction = 'none' # required to apply FL to each element
71 |
72 | def forward(self, pred, true):
73 | loss = self.loss_fcn(pred, true)
74 |
75 | pred_prob = torch.sigmoid(pred) # prob from logits
76 | alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha)
77 | modulating_factor = torch.abs(true - pred_prob) ** self.gamma
78 | loss *= alpha_factor * modulating_factor
79 |
80 | if self.reduction == 'mean':
81 | return loss.mean()
82 | elif self.reduction == 'sum':
83 | return loss.sum()
84 | else: # 'none'
85 | return loss
86 |
87 |
88 | class ComputeLoss:
89 | # Compute losses
90 | def __init__(self, model, autobalance=False):
91 | super(ComputeLoss, self).__init__()
92 | device = next(model.parameters()).device # get model device
93 | h = model.hyp # hyperparameters
94 |
95 | # Define criteria
96 | BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['cls_pw']], device=device))
97 | BCEobj = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['obj_pw']], device=device))
98 |
99 | # Class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3
100 | self.cp, self.cn = smooth_BCE(eps=h.get('label_smoothing', 0.0)) # positive, negative BCE targets
101 |
102 | # Focal loss
103 | g = h['fl_gamma'] # focal loss gamma
104 | if g > 0:
105 | BCEcls, BCEobj = FocalLoss(BCEcls, g), FocalLoss(BCEobj, g)
106 |
107 | det = model.module.model[-1] if is_parallel(model) else model.model[-1] # Detect() module
108 | self.balance = {3: [4.0, 1.0, 0.4]}.get(det.nl, [4.0, 1.0, 0.25, 0.06, .02]) # P3-P7
109 | self.ssi = list(det.stride).index(16) if autobalance else 0 # stride 16 index
110 | self.BCEcls, self.BCEobj, self.gr, self.hyp, self.autobalance = BCEcls, BCEobj, model.gr, h, autobalance
111 | for k in 'na', 'nc', 'nl', 'anchors':
112 | setattr(self, k, getattr(det, k))
113 |
114 | def __call__(self, p, targets): # predictions, targets, model
115 | device = targets.device
116 | lcls, lbox, lobj = torch.zeros(1, device=device), torch.zeros(1, device=device), torch.zeros(1, device=device)
117 | tcls, tbox, indices, anchors = self.build_targets(p, targets) # targets
118 |
119 | # Losses
120 | for i, pi in enumerate(p): # layer index, layer predictions
121 | b, a, gj, gi = indices[i] # image, anchor, gridy, gridx
122 | tobj = torch.zeros_like(pi[..., 0], device=device) # target obj
123 |
124 | n = b.shape[0] # number of targets
125 | if n:
126 | ps = pi[b, a, gj, gi] # prediction subset corresponding to targets
127 |
128 | # Regression
129 | pxy = ps[:, :2].sigmoid() * 2. - 0.5
130 | pwh = (ps[:, 2:4].sigmoid() * 2) ** 2 * anchors[i]
131 | pbox = torch.cat((pxy, pwh), 1) # predicted box
132 | iou = bbox_iou(pbox.T, tbox[i], x1y1x2y2=False, CIoU=True) # iou(prediction, target)
133 | lbox += (1.0 - iou).mean() # iou loss
134 |
135 | # Objectness
136 | tobj[b, a, gj, gi] = (1.0 - self.gr) + self.gr * iou.detach().clamp(0).type(tobj.dtype) # iou ratio
137 |
138 | # Classification
139 | if self.nc > 1: # cls loss (only if multiple classes)
140 | t = torch.full_like(ps[:, 5:], self.cn, device=device) # targets
141 | t[range(n), tcls[i]] = self.cp
142 | lcls += self.BCEcls(ps[:, 5:], t) # BCE
143 |
144 | # Append targets to text file
145 | # with open('targets.txt', 'a') as file:
146 | # [file.write('%11.5g ' * 4 % tuple(x) + '\n') for x in torch.cat((txy[i], twh[i]), 1)]
147 |
148 | obji = self.BCEobj(pi[..., 4], tobj)
149 | lobj += obji * self.balance[i] # obj loss
150 | if self.autobalance:
151 | self.balance[i] = self.balance[i] * 0.9999 + 0.0001 / obji.detach().item()
152 |
153 | if self.autobalance:
154 | self.balance = [x / self.balance[self.ssi] for x in self.balance]
155 | lbox *= self.hyp['box']
156 | lobj *= self.hyp['obj']
157 | lcls *= self.hyp['cls']
158 | bs = tobj.shape[0] # batch size
159 |
160 | loss = lbox + lobj + lcls
161 | return loss * bs, torch.cat((lbox, lobj, lcls, loss)).detach()
162 |
163 | def build_targets(self, p, targets):
164 | # Build targets for compute_loss(), input targets(image,class,x,y,w,h)
165 | na, nt = self.na, targets.shape[0] # number of anchors, targets
166 | tcls, tbox, indices, anch = [], [], [], []
167 | gain = torch.ones(7, device=targets.device) # normalized to gridspace gain
168 | ai = torch.arange(na, device=targets.device).float().view(na, 1).repeat(1, nt) # same as .repeat_interleave(nt)
169 | targets = torch.cat((targets.repeat(na, 1, 1), ai[:, :, None]), 2) # append anchor indices
170 |
171 | g = 0.5 # bias
172 | off = torch.tensor([[0, 0],
173 | [1, 0], [0, 1], [-1, 0], [0, -1], # j,k,l,m
174 | # [1, 1], [1, -1], [-1, 1], [-1, -1], # jk,jm,lk,lm
175 | ], device=targets.device).float() * g # offsets
176 |
177 | for i in range(self.nl):
178 | anchors = self.anchors[i]
179 | gain[2:6] = torch.tensor(p[i].shape)[[3, 2, 3, 2]] # xyxy gain
180 |
181 | # Match targets to anchors
182 | t = targets * gain
183 | if nt:
184 | # Matches
185 | r = t[:, :, 4:6] / anchors[:, None] # wh ratio
186 | j = torch.max(r, 1. / r).max(2)[0] < self.hyp['anchor_t'] # compare
187 | # j = wh_iou(anchors, t[:, 4:6]) > model.hyp['iou_t'] # iou(3,n)=wh_iou(anchors(3,2), gwh(n,2))
188 | t = t[j] # filter
189 |
190 | # Offsets
191 | gxy = t[:, 2:4] # grid xy
192 | gxi = gain[[2, 3]] - gxy # inverse
193 | j, k = ((gxy % 1. < g) & (gxy > 1.)).T
194 | l, m = ((gxi % 1. < g) & (gxi > 1.)).T
195 | j = torch.stack((torch.ones_like(j), j, k, l, m))
196 | t = t.repeat((5, 1, 1))[j]
197 | offsets = (torch.zeros_like(gxy)[None] + off[:, None])[j]
198 | else:
199 | t = targets[0]
200 | offsets = 0
201 |
202 | # Define
203 | b, c = t[:, :2].long().T # image, class
204 | gxy = t[:, 2:4] # grid xy
205 | gwh = t[:, 4:6] # grid wh
206 | gij = (gxy - offsets).long()
207 | gi, gj = gij.T # grid xy indices
208 |
209 | # Append
210 | a = t[:, 6].long() # anchor indices
211 | indices.append((b, a, gj.clamp_(0, gain[3] - 1), gi.clamp_(0, gain[2] - 1))) # image, anchor, grid indices
212 | tbox.append(torch.cat((gxy - gij, gwh), 1)) # box
213 | anch.append(anchors[a]) # anchors
214 | tcls.append(c) # class
215 |
216 | return tcls, tbox, indices, anch
217 |
--------------------------------------------------------------------------------
/utils/metrics.py:
--------------------------------------------------------------------------------
1 | # Model validation metrics
2 |
3 | from pathlib import Path
4 |
5 | import matplotlib.pyplot as plt
6 | import numpy as np
7 | import torch
8 |
9 | from . import general
10 |
11 |
12 | def fitness(x):
13 | # Model fitness as a weighted combination of metrics
14 | w = [0.0, 0.0, 0.1, 0.9] # weights for [P, R, mAP@0.5, mAP@0.5:0.95]
15 | return (x[:, :4] * w).sum(1)
16 |
17 |
18 | def ap_per_class(tp, conf, pred_cls, target_cls, plot=False, save_dir='.', names=()):
19 | """ Compute the average precision, given the recall and precision curves.
20 | Source: https://github.com/rafaelpadilla/Object-Detection-Metrics.
21 | # Arguments
22 | tp: True positives (nparray, nx1 or nx10).
23 | conf: Objectness value from 0-1 (nparray).
24 | pred_cls: Predicted object classes (nparray).
25 | target_cls: True object classes (nparray).
26 | plot: Plot precision-recall curve at mAP@0.5
27 | save_dir: Plot save directory
28 | # Returns
29 | The average precision as computed in py-faster-rcnn.
30 | """
31 |
32 | # Sort by objectness
33 | i = np.argsort(-conf)
34 | tp, conf, pred_cls = tp[i], conf[i], pred_cls[i]
35 |
36 | # Find unique classes
37 | unique_classes = np.unique(target_cls)
38 | nc = unique_classes.shape[0] # number of classes, number of detections
39 |
40 | # Create Precision-Recall curve and compute AP for each class
41 | px, py = np.linspace(0, 1, 1000), [] # for plotting
42 | ap, p, r = np.zeros((nc, tp.shape[1])), np.zeros((nc, 1000)), np.zeros((nc, 1000))
43 | for ci, c in enumerate(unique_classes):
44 | i = pred_cls == c
45 | n_l = (target_cls == c).sum() # number of labels
46 | n_p = i.sum() # number of predictions
47 |
48 | if n_p == 0 or n_l == 0:
49 | continue
50 | else:
51 | # Accumulate FPs and TPs
52 | fpc = (1 - tp[i]).cumsum(0)
53 | tpc = tp[i].cumsum(0)
54 |
55 | # Recall
56 | recall = tpc / (n_l + 1e-16) # recall curve
57 | r[ci] = np.interp(-px, -conf[i], recall[:, 0], left=0) # negative x, xp because xp decreases
58 |
59 | # Precision
60 | precision = tpc / (tpc + fpc) # precision curve
61 | p[ci] = np.interp(-px, -conf[i], precision[:, 0], left=1) # p at pr_score
62 |
63 | # AP from recall-precision curve
64 | for j in range(tp.shape[1]):
65 | ap[ci, j], mpre, mrec = compute_ap(recall[:, j], precision[:, j])
66 | if plot and j == 0:
67 | py.append(np.interp(px, mrec, mpre)) # precision at mAP@0.5
68 |
69 | # Compute F1 (harmonic mean of precision and recall)
70 | f1 = 2 * p * r / (p + r + 1e-16)
71 | if plot:
72 | plot_pr_curve(px, py, ap, Path(save_dir) / 'PR_curve.png', names)
73 | plot_mc_curve(px, f1, Path(save_dir) / 'F1_curve.png', names, ylabel='F1')
74 | plot_mc_curve(px, p, Path(save_dir) / 'P_curve.png', names, ylabel='Precision')
75 | plot_mc_curve(px, r, Path(save_dir) / 'R_curve.png', names, ylabel='Recall')
76 |
77 | i = f1.mean(0).argmax() # max F1 index
78 | return p[:, i], r[:, i], ap, f1[:, i], unique_classes.astype('int32')
79 |
80 |
81 | def compute_ap(recall, precision):
82 | """ Compute the average precision, given the recall and precision curves
83 | # Arguments
84 | recall: The recall curve (list)
85 | precision: The precision curve (list)
86 | # Returns
87 | Average precision, precision curve, recall curve
88 | """
89 |
90 | # Append sentinel values to beginning and end
91 | mrec = np.concatenate(([0.], recall, [recall[-1] + 0.01]))
92 | mpre = np.concatenate(([1.], precision, [0.]))
93 |
94 | # Compute the precision envelope
95 | mpre = np.flip(np.maximum.accumulate(np.flip(mpre)))
96 |
97 | # Integrate area under curve
98 | method = 'interp' # methods: 'continuous', 'interp'
99 | if method == 'interp':
100 | x = np.linspace(0, 1, 101) # 101-point interp (COCO)
101 | ap = np.trapz(np.interp(x, mrec, mpre), x) # integrate
102 | else: # 'continuous'
103 | i = np.where(mrec[1:] != mrec[:-1])[0] # points where x axis (recall) changes
104 | ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) # area under curve
105 |
106 | return ap, mpre, mrec
107 |
108 |
109 | class ConfusionMatrix:
110 | # Updated version of https://github.com/kaanakan/object_detection_confusion_matrix
111 | def __init__(self, nc, conf=0.25, iou_thres=0.45):
112 | self.matrix = np.zeros((nc + 1, nc + 1))
113 | self.nc = nc # number of classes
114 | self.conf = conf
115 | self.iou_thres = iou_thres
116 |
117 | def process_batch(self, detections, labels):
118 | """
119 | Return intersection-over-union (Jaccard index) of boxes.
120 | Both sets of boxes are expected to be in (x1, y1, x2, y2) format.
121 | Arguments:
122 | detections (Array[N, 6]), x1, y1, x2, y2, conf, class
123 | labels (Array[M, 5]), class, x1, y1, x2, y2
124 | Returns:
125 | None, updates confusion matrix accordingly
126 | """
127 | detections = detections[detections[:, 4] > self.conf]
128 | gt_classes = labels[:, 0].int()
129 | detection_classes = detections[:, 5].int()
130 | iou = general.box_iou(labels[:, 1:], detections[:, :4])
131 |
132 | x = torch.where(iou > self.iou_thres)
133 | if x[0].shape[0]:
134 | matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), 1).cpu().numpy()
135 | if x[0].shape[0] > 1:
136 | matches = matches[matches[:, 2].argsort()[::-1]]
137 | matches = matches[np.unique(matches[:, 1], return_index=True)[1]]
138 | matches = matches[matches[:, 2].argsort()[::-1]]
139 | matches = matches[np.unique(matches[:, 0], return_index=True)[1]]
140 | else:
141 | matches = np.zeros((0, 3))
142 |
143 | n = matches.shape[0] > 0
144 | m0, m1, _ = matches.transpose().astype(np.int16)
145 | for i, gc in enumerate(gt_classes):
146 | j = m0 == i
147 | if n and sum(j) == 1:
148 | self.matrix[detection_classes[m1[j]], gc] += 1 # correct
149 | else:
150 | self.matrix[self.nc, gc] += 1 # background FP
151 |
152 | if n:
153 | for i, dc in enumerate(detection_classes):
154 | if not any(m1 == i):
155 | self.matrix[dc, self.nc] += 1 # background FN
156 |
157 | def matrix(self):
158 | return self.matrix
159 |
160 | def plot(self, save_dir='', names=()):
161 | try:
162 | import seaborn as sn
163 |
164 | array = self.matrix / (self.matrix.sum(0).reshape(1, self.nc + 1) + 1E-6) # normalize
165 | array[array < 0.005] = np.nan # don't annotate (would appear as 0.00)
166 |
167 | fig = plt.figure(figsize=(12, 9), tight_layout=True)
168 | sn.set(font_scale=1.0 if self.nc < 50 else 0.8) # for label size
169 | labels = (0 < len(names) < 99) and len(names) == self.nc # apply names to ticklabels
170 | sn.heatmap(array, annot=self.nc < 30, annot_kws={"size": 8}, cmap='Blues', fmt='.2f', square=True,
171 | xticklabels=names + ['background FP'] if labels else "auto",
172 | yticklabels=names + ['background FN'] if labels else "auto").set_facecolor((1, 1, 1))
173 | fig.axes[0].set_xlabel('True')
174 | fig.axes[0].set_ylabel('Predicted')
175 | fig.savefig(Path(save_dir) / 'confusion_matrix.png', dpi=250)
176 | except Exception as e:
177 | pass
178 |
179 | def print(self):
180 | for i in range(self.nc + 1):
181 | print(' '.join(map(str, self.matrix[i])))
182 |
183 |
184 | # Plots ----------------------------------------------------------------------------------------------------------------
185 |
186 | def plot_pr_curve(px, py, ap, save_dir='pr_curve.png', names=()):
187 | # Precision-recall curve
188 | fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)
189 | py = np.stack(py, axis=1)
190 |
191 | if 0 < len(names) < 21: # display per-class legend if < 21 classes
192 | for i, y in enumerate(py.T):
193 | ax.plot(px, y, linewidth=1, label=f'{names[i]} {ap[i, 0]:.3f}') # plot(recall, precision)
194 | else:
195 | ax.plot(px, py, linewidth=1, color='grey') # plot(recall, precision)
196 |
197 | ax.plot(px, py.mean(1), linewidth=3, color='blue', label='all classes %.3f mAP@0.5' % ap[:, 0].mean())
198 | ax.set_xlabel('Recall')
199 | ax.set_ylabel('Precision')
200 | ax.set_xlim(0, 1)
201 | ax.set_ylim(0, 1)
202 | plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left")
203 | fig.savefig(Path(save_dir), dpi=250)
204 |
205 |
206 | def plot_mc_curve(px, py, save_dir='mc_curve.png', names=(), xlabel='Confidence', ylabel='Metric'):
207 | # Metric-confidence curve
208 | fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)
209 |
210 | if 0 < len(names) < 21: # display per-class legend if < 21 classes
211 | for i, y in enumerate(py):
212 | ax.plot(px, y, linewidth=1, label=f'{names[i]}') # plot(confidence, metric)
213 | else:
214 | ax.plot(px, py.T, linewidth=1, color='grey') # plot(confidence, metric)
215 |
216 | y = py.mean(0)
217 | ax.plot(px, y, linewidth=3, color='blue', label=f'all classes {y.max():.2f} at {px[y.argmax()]:.3f}')
218 | ax.set_xlabel(xlabel)
219 | ax.set_ylabel(ylabel)
220 | ax.set_xlim(0, 1)
221 | ax.set_ylim(0, 1)
222 | plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left")
223 | fig.savefig(Path(save_dir), dpi=250)
224 |
--------------------------------------------------------------------------------
/utils/plots.py:
--------------------------------------------------------------------------------
1 | # Plotting utils
2 |
3 | import glob
4 | import math
5 | import os
6 | import random
7 | from copy import copy
8 | from pathlib import Path
9 |
10 | import cv2
11 | import matplotlib
12 | import matplotlib.pyplot as plt
13 | import numpy as np
14 | import pandas as pd
15 | import seaborn as sns
16 | import torch
17 | import yaml
18 | from PIL import Image, ImageDraw, ImageFont
19 | from scipy.signal import butter, filtfilt
20 |
21 | from utils.general import xywh2xyxy, xyxy2xywh
22 | from utils.metrics import fitness
23 |
24 | # Settings
25 | matplotlib.rc('font', **{'size': 11})
26 | matplotlib.use('Agg') # for writing to files only
27 |
28 |
29 | def color_list():
30 | # Return first 10 plt colors as (r,g,b) https://stackoverflow.com/questions/51350872/python-from-color-name-to-rgb
31 | def hex2rgb(h):
32 | return tuple(int(h[1 + i:1 + i + 2], 16) for i in (0, 2, 4))
33 |
34 | return [hex2rgb(h) for h in matplotlib.colors.TABLEAU_COLORS.values()] # or BASE_ (8), CSS4_ (148), XKCD_ (949)
35 |
36 |
37 | def hist2d(x, y, n=100):
38 | # 2d histogram used in labels.png and evolve.png
39 | xedges, yedges = np.linspace(x.min(), x.max(), n), np.linspace(y.min(), y.max(), n)
40 | hist, xedges, yedges = np.histogram2d(x, y, (xedges, yedges))
41 | xidx = np.clip(np.digitize(x, xedges) - 1, 0, hist.shape[0] - 1)
42 | yidx = np.clip(np.digitize(y, yedges) - 1, 0, hist.shape[1] - 1)
43 | return np.log(hist[xidx, yidx])
44 |
45 |
46 | def butter_lowpass_filtfilt(data, cutoff=1500, fs=50000, order=5):
47 | # https://stackoverflow.com/questions/28536191/how-to-filter-smooth-with-scipy-numpy
48 | def butter_lowpass(cutoff, fs, order):
49 | nyq = 0.5 * fs
50 | normal_cutoff = cutoff / nyq
51 | return butter(order, normal_cutoff, btype='low', analog=False)
52 |
53 | b, a = butter_lowpass(cutoff, fs, order=order)
54 | return filtfilt(b, a, data) # forward-backward filter
55 |
56 |
57 | def plot_one_box(x, im, color=None, label=None, line_thickness=3):
58 | # Plots one bounding box on image 'im' using OpenCV
59 | assert im.data.contiguous, 'Image not contiguous. Apply np.ascontiguousarray(im) to plot_on_box() input image.'
60 | tl = line_thickness or round(0.002 * (im.shape[0] + im.shape[1]) / 2) + 1 # line/font thickness
61 | color = color or [random.randint(0, 255) for _ in range(3)]
62 | c1, c2 = (int(x[0]), int(x[1])), (int(x[2]), int(x[3]))
63 | cv2.rectangle(im, c1, c2, color, thickness=tl, lineType=cv2.LINE_AA)
64 | if label:
65 | tf = max(tl - 1, 1) # font thickness
66 | t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0]
67 | c2 = c1[0] + t_size[0], c1[1] - t_size[1] - 3
68 | cv2.rectangle(im, c1, c2, color, -1, cv2.LINE_AA) # filled
69 | cv2.putText(im, label, (c1[0], c1[1] - 2), 0, tl / 3, [225, 255, 255], thickness=tf, lineType=cv2.LINE_AA)
70 |
71 |
72 | def plot_one_box_PIL(box, im, color=None, label=None, line_thickness=None):
73 | # Plots one bounding box on image 'im' using PIL
74 | im = Image.fromarray(im)
75 | draw = ImageDraw.Draw(im)
76 | line_thickness = line_thickness or max(int(min(im.size) / 200), 2)
77 | draw.rectangle(box, width=line_thickness, outline=tuple(color)) # plot
78 | if label:
79 | fontsize = max(round(max(im.size) / 40), 12)
80 | font = ImageFont.truetype("Arial.ttf", fontsize)
81 | txt_width, txt_height = font.getsize(label)
82 | draw.rectangle([box[0], box[1] - txt_height + 4, box[0] + txt_width, box[1]], fill=tuple(color))
83 | draw.text((box[0], box[1] - txt_height + 1), label, fill=(255, 255, 255), font=font)
84 | return np.asarray(im)
85 |
86 |
87 | def plot_wh_methods(): # from utils.plots import *; plot_wh_methods()
88 | # Compares the two methods for width-height anchor multiplication
89 | # https://github.com/ultralytics/yolov3/issues/168
90 | x = np.arange(-4.0, 4.0, .1)
91 | ya = np.exp(x)
92 | yb = torch.sigmoid(torch.from_numpy(x)).numpy() * 2
93 |
94 | fig = plt.figure(figsize=(6, 3), tight_layout=True)
95 | plt.plot(x, ya, '.-', label='YOLOv3')
96 | plt.plot(x, yb ** 2, '.-', label='YOLOv5 ^2')
97 | plt.plot(x, yb ** 1.6, '.-', label='YOLOv5 ^1.6')
98 | plt.xlim(left=-4, right=4)
99 | plt.ylim(bottom=0, top=6)
100 | plt.xlabel('input')
101 | plt.ylabel('output')
102 | plt.grid()
103 | plt.legend()
104 | fig.savefig('comparison.png', dpi=200)
105 |
106 |
107 | def output_to_target(output):
108 | # Convert model output to target format [batch_id, class_id, x, y, w, h, conf]
109 | targets = []
110 | for i, o in enumerate(output):
111 | for *box, conf, cls in o.cpu().numpy():
112 | targets.append([i, cls, *list(*xyxy2xywh(np.array(box)[None])), conf])
113 | return np.array(targets)
114 |
115 |
116 | def plot_images(images, targets, paths=None, fname='images.jpg', names=None, max_size=640, max_subplots=16):
117 | # Plot image grid with labels
118 |
119 | if isinstance(images, torch.Tensor):
120 | images = images.cpu().float().numpy()
121 | if isinstance(targets, torch.Tensor):
122 | targets = targets.cpu().numpy()
123 |
124 | # un-normalise
125 | if np.max(images[0]) <= 1:
126 | images *= 255
127 |
128 | tl = 3 # line thickness
129 | tf = max(tl - 1, 1) # font thickness
130 | bs, _, h, w = images.shape # batch size, _, height, width
131 | bs = min(bs, max_subplots) # limit plot images
132 | ns = np.ceil(bs ** 0.5) # number of subplots (square)
133 |
134 | # Check if we should resize
135 | scale_factor = max_size / max(h, w)
136 | if scale_factor < 1:
137 | h = math.ceil(scale_factor * h)
138 | w = math.ceil(scale_factor * w)
139 |
140 | colors = color_list() # list of colors
141 | mosaic = np.full((int(ns * h), int(ns * w), 3), 255, dtype=np.uint8) # init
142 | for i, img in enumerate(images):
143 | if i == max_subplots: # if last batch has fewer images than we expect
144 | break
145 |
146 | block_x = int(w * (i // ns))
147 | block_y = int(h * (i % ns))
148 |
149 | img = img.transpose(1, 2, 0)
150 | if scale_factor < 1:
151 | img = cv2.resize(img, (w, h))
152 |
153 | mosaic[block_y:block_y + h, block_x:block_x + w, :] = img
154 | if len(targets) > 0:
155 | image_targets = targets[targets[:, 0] == i]
156 | boxes = xywh2xyxy(image_targets[:, 2:6]).T
157 | classes = image_targets[:, 1].astype('int')
158 | labels = image_targets.shape[1] == 6 # labels if no conf column
159 | conf = None if labels else image_targets[:, 6] # check for confidence presence (label vs pred)
160 |
161 | if boxes.shape[1]:
162 | if boxes.max() <= 1.01: # if normalized with tolerance 0.01
163 | boxes[[0, 2]] *= w # scale to pixels
164 | boxes[[1, 3]] *= h
165 | elif scale_factor < 1: # absolute coords need scale if image scales
166 | boxes *= scale_factor
167 | boxes[[0, 2]] += block_x
168 | boxes[[1, 3]] += block_y
169 | for j, box in enumerate(boxes.T):
170 | cls = int(classes[j])
171 | color = colors[cls % len(colors)]
172 | cls = names[cls] if names else cls
173 | if labels or conf[j] > 0.25: # 0.25 conf thresh
174 | label = '%s' % cls if labels else '%s %.1f' % (cls, conf[j])
175 | plot_one_box(box, mosaic, label=label, color=color, line_thickness=tl)
176 |
177 | # Draw image filename labels
178 | if paths:
179 | label = Path(paths[i]).name[:40] # trim to 40 char
180 | t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0]
181 | cv2.putText(mosaic, label, (block_x + 5, block_y + t_size[1] + 5), 0, tl / 3, [220, 220, 220], thickness=tf,
182 | lineType=cv2.LINE_AA)
183 |
184 | # Image border
185 | cv2.rectangle(mosaic, (block_x, block_y), (block_x + w, block_y + h), (255, 255, 255), thickness=3)
186 |
187 | if fname:
188 | r = min(1280. / max(h, w) / ns, 1.0) # ratio to limit image size
189 | mosaic = cv2.resize(mosaic, (int(ns * w * r), int(ns * h * r)), interpolation=cv2.INTER_AREA)
190 | # cv2.imwrite(fname, cv2.cvtColor(mosaic, cv2.COLOR_BGR2RGB)) # cv2 save
191 | Image.fromarray(mosaic).save(fname) # PIL save
192 | return mosaic
193 |
194 |
195 | def plot_lr_scheduler(optimizer, scheduler, epochs=300, save_dir=''):
196 | # Plot LR simulating training for full epochs
197 | optimizer, scheduler = copy(optimizer), copy(scheduler) # do not modify originals
198 | y = []
199 | for _ in range(epochs):
200 | scheduler.step()
201 | y.append(optimizer.param_groups[0]['lr'])
202 | plt.plot(y, '.-', label='LR')
203 | plt.xlabel('epoch')
204 | plt.ylabel('LR')
205 | plt.grid()
206 | plt.xlim(0, epochs)
207 | plt.ylim(0)
208 | plt.savefig(Path(save_dir) / 'LR.png', dpi=200)
209 | plt.close()
210 |
211 |
212 | def plot_test_txt(): # from utils.plots import *; plot_test()
213 | # Plot test.txt histograms
214 | x = np.loadtxt('test.txt', dtype=np.float32)
215 | box = xyxy2xywh(x[:, :4])
216 | cx, cy = box[:, 0], box[:, 1]
217 |
218 | fig, ax = plt.subplots(1, 1, figsize=(6, 6), tight_layout=True)
219 | ax.hist2d(cx, cy, bins=600, cmax=10, cmin=0)
220 | ax.set_aspect('equal')
221 | plt.savefig('hist2d.png', dpi=300)
222 |
223 | fig, ax = plt.subplots(1, 2, figsize=(12, 6), tight_layout=True)
224 | ax[0].hist(cx, bins=600)
225 | ax[1].hist(cy, bins=600)
226 | plt.savefig('hist1d.png', dpi=200)
227 |
228 |
229 | def plot_targets_txt(): # from utils.plots import *; plot_targets_txt()
230 | # Plot targets.txt histograms
231 | x = np.loadtxt('targets.txt', dtype=np.float32).T
232 | s = ['x targets', 'y targets', 'width targets', 'height targets']
233 | fig, ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)
234 | ax = ax.ravel()
235 | for i in range(4):
236 | ax[i].hist(x[i], bins=100, label='%.3g +/- %.3g' % (x[i].mean(), x[i].std()))
237 | ax[i].legend()
238 | ax[i].set_title(s[i])
239 | plt.savefig('targets.jpg', dpi=200)
240 |
241 |
242 | def plot_study_txt(path='', x=None): # from utils.plots import *; plot_study_txt()
243 | # Plot study.txt generated by test.py
244 | fig, ax = plt.subplots(2, 4, figsize=(10, 6), tight_layout=True)
245 | # ax = ax.ravel()
246 |
247 | fig2, ax2 = plt.subplots(1, 1, figsize=(8, 4), tight_layout=True)
248 | # for f in [Path(path) / f'study_coco_{x}.txt' for x in ['yolov5s6', 'yolov5m6', 'yolov5l6', 'yolov5x6']]:
249 | for f in sorted(Path(path).glob('study*.txt')):
250 | y = np.loadtxt(f, dtype=np.float32, usecols=[0, 1, 2, 3, 7, 8, 9], ndmin=2).T
251 | x = np.arange(y.shape[1]) if x is None else np.array(x)
252 | s = ['P', 'R', 'mAP@.5', 'mAP@.5:.95', 't_inference (ms/img)', 't_NMS (ms/img)', 't_total (ms/img)']
253 | # for i in range(7):
254 | # ax[i].plot(x, y[i], '.-', linewidth=2, markersize=8)
255 | # ax[i].set_title(s[i])
256 |
257 | j = y[3].argmax() + 1
258 | ax2.plot(y[6, 1:j], y[3, 1:j] * 1E2, '.-', linewidth=2, markersize=8,
259 | label=f.stem.replace('study_coco_', '').replace('yolo', 'YOLO'))
260 |
261 | ax2.plot(1E3 / np.array([209, 140, 97, 58, 35, 18]), [34.6, 40.5, 43.0, 47.5, 49.7, 51.5],
262 | 'k.-', linewidth=2, markersize=8, alpha=.25, label='EfficientDet')
263 |
264 | ax2.grid(alpha=0.2)
265 | ax2.set_yticks(np.arange(20, 60, 5))
266 | ax2.set_xlim(0, 57)
267 | ax2.set_ylim(30, 55)
268 | ax2.set_xlabel('GPU Speed (ms/img)')
269 | ax2.set_ylabel('COCO AP val')
270 | ax2.legend(loc='lower right')
271 | plt.savefig(str(Path(path).name) + '.png', dpi=300)
272 |
273 |
274 | def plot_labels(labels, names=(), save_dir=Path(''), loggers=None):
275 | # plot dataset labels
276 | print('Plotting labels... ')
277 | c, b = labels[:, 0], labels[:, 1:].transpose() # classes, boxes
278 | nc = int(c.max() + 1) # number of classes
279 | colors = color_list()
280 | x = pd.DataFrame(b.transpose(), columns=['x', 'y', 'width', 'height'])
281 |
282 | # seaborn correlogram
283 | sns.pairplot(x, corner=True, diag_kind='auto', kind='hist', diag_kws=dict(bins=50), plot_kws=dict(pmax=0.9))
284 | plt.savefig(save_dir / 'labels_correlogram.jpg', dpi=200)
285 | plt.close()
286 |
287 | # matplotlib labels
288 | matplotlib.use('svg') # faster
289 | ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)[1].ravel()
290 | ax[0].hist(c, bins=np.linspace(0, nc, nc + 1) - 0.5, rwidth=0.8)
291 | ax[0].set_ylabel('instances')
292 | if 0 < len(names) < 30:
293 | ax[0].set_xticks(range(len(names)))
294 | ax[0].set_xticklabels(names, rotation=90, fontsize=10)
295 | else:
296 | ax[0].set_xlabel('classes')
297 | sns.histplot(x, x='x', y='y', ax=ax[2], bins=50, pmax=0.9)
298 | sns.histplot(x, x='width', y='height', ax=ax[3], bins=50, pmax=0.9)
299 |
300 | # rectangles
301 | labels[:, 1:3] = 0.5 # center
302 | labels[:, 1:] = xywh2xyxy(labels[:, 1:]) * 2000
303 | img = Image.fromarray(np.ones((2000, 2000, 3), dtype=np.uint8) * 255)
304 | for cls, *box in labels[:1000]:
305 | ImageDraw.Draw(img).rectangle(box, width=1, outline=colors[int(cls) % 10]) # plot
306 | ax[1].imshow(img)
307 | ax[1].axis('off')
308 |
309 | for a in [0, 1, 2, 3]:
310 | for s in ['top', 'right', 'left', 'bottom']:
311 | ax[a].spines[s].set_visible(False)
312 |
313 | plt.savefig(save_dir / 'labels.jpg', dpi=200)
314 | matplotlib.use('Agg')
315 | plt.close()
316 |
317 | # loggers
318 | for k, v in loggers.items() or {}:
319 | if k == 'wandb' and v:
320 | v.log({"Labels": [v.Image(str(x), caption=x.name) for x in save_dir.glob('*labels*.jpg')]}, commit=False)
321 |
322 |
323 | def plot_evolution(yaml_file='data/hyp.finetune.yaml'): # from utils.plots import *; plot_evolution()
324 | # Plot hyperparameter evolution results in evolve.txt
325 | with open(yaml_file) as f:
326 | hyp = yaml.safe_load(f)
327 | x = np.loadtxt('evolve.txt', ndmin=2)
328 | f = fitness(x)
329 | # weights = (f - f.min()) ** 2 # for weighted results
330 | plt.figure(figsize=(10, 12), tight_layout=True)
331 | matplotlib.rc('font', **{'size': 8})
332 | for i, (k, v) in enumerate(hyp.items()):
333 | y = x[:, i + 7]
334 | # mu = (y * weights).sum() / weights.sum() # best weighted result
335 | mu = y[f.argmax()] # best single result
336 | plt.subplot(6, 5, i + 1)
337 | plt.scatter(y, f, c=hist2d(y, f, 20), cmap='viridis', alpha=.8, edgecolors='none')
338 | plt.plot(mu, f.max(), 'k+', markersize=15)
339 | plt.title('%s = %.3g' % (k, mu), fontdict={'size': 9}) # limit to 40 characters
340 | if i % 5 != 0:
341 | plt.yticks([])
342 | print('%15s: %.3g' % (k, mu))
343 | plt.savefig('evolve.png', dpi=200)
344 | print('\nPlot saved as evolve.png')
345 |
346 |
347 | def profile_idetection(start=0, stop=0, labels=(), save_dir=''):
348 | # Plot iDetection '*.txt' per-image logs. from utils.plots import *; profile_idetection()
349 | ax = plt.subplots(2, 4, figsize=(12, 6), tight_layout=True)[1].ravel()
350 | s = ['Images', 'Free Storage (GB)', 'RAM Usage (GB)', 'Battery', 'dt_raw (ms)', 'dt_smooth (ms)', 'real-world FPS']
351 | files = list(Path(save_dir).glob('frames*.txt'))
352 | for fi, f in enumerate(files):
353 | try:
354 | results = np.loadtxt(f, ndmin=2).T[:, 90:-30] # clip first and last rows
355 | n = results.shape[1] # number of rows
356 | x = np.arange(start, min(stop, n) if stop else n)
357 | results = results[:, x]
358 | t = (results[0] - results[0].min()) # set t0=0s
359 | results[0] = x
360 | for i, a in enumerate(ax):
361 | if i < len(results):
362 | label = labels[fi] if len(labels) else f.stem.replace('frames_', '')
363 | a.plot(t, results[i], marker='.', label=label, linewidth=1, markersize=5)
364 | a.set_title(s[i])
365 | a.set_xlabel('time (s)')
366 | # if fi == len(files) - 1:
367 | # a.set_ylim(bottom=0)
368 | for side in ['top', 'right']:
369 | a.spines[side].set_visible(False)
370 | else:
371 | a.remove()
372 | except Exception as e:
373 | print('Warning: Plotting error for %s; %s' % (f, e))
374 |
375 | ax[1].legend()
376 | plt.savefig(Path(save_dir) / 'idetection_profile.png', dpi=200)
377 |
378 |
379 | def plot_results_overlay(start=0, stop=0): # from utils.plots import *; plot_results_overlay()
380 | # Plot training 'results*.txt', overlaying train and val losses
381 | s = ['train', 'train', 'train', 'Precision', 'mAP@0.5', 'val', 'val', 'val', 'Recall', 'mAP@0.5:0.95'] # legends
382 | t = ['Box', 'Objectness', 'Classification', 'P-R', 'mAP-F1'] # titles
383 | for f in sorted(glob.glob('results*.txt') + glob.glob('../../Downloads/results*.txt')):
384 | results = np.loadtxt(f, usecols=[2, 3, 4, 8, 9, 12, 13, 14, 10, 11], ndmin=2).T
385 | n = results.shape[1] # number of rows
386 | x = range(start, min(stop, n) if stop else n)
387 | fig, ax = plt.subplots(1, 5, figsize=(14, 3.5), tight_layout=True)
388 | ax = ax.ravel()
389 | for i in range(5):
390 | for j in [i, i + 5]:
391 | y = results[j, x]
392 | ax[i].plot(x, y, marker='.', label=s[j])
393 | # y_smooth = butter_lowpass_filtfilt(y)
394 | # ax[i].plot(x, np.gradient(y_smooth), marker='.', label=s[j])
395 |
396 | ax[i].set_title(t[i])
397 | ax[i].legend()
398 | ax[i].set_ylabel(f) if i == 0 else None # add filename
399 | fig.savefig(f.replace('.txt', '.png'), dpi=200)
400 |
401 |
402 | def plot_results(start=0, stop=0, bucket='', id=(), labels=(), save_dir=''):
403 | # Plot training 'results*.txt'. from utils.plots import *; plot_results(save_dir='runs/train/exp')
404 | fig, ax = plt.subplots(2, 5, figsize=(12, 6), tight_layout=True)
405 | ax = ax.ravel()
406 | s = ['Box', 'Objectness', 'Classification', 'Precision', 'Recall',
407 | 'val Box', 'val Objectness', 'val Classification', 'mAP@0.5', 'mAP@0.5:0.95']
408 | if bucket:
409 | # files = ['https://storage.googleapis.com/%s/results%g.txt' % (bucket, x) for x in id]
410 | files = ['results%g.txt' % x for x in id]
411 | c = ('gsutil cp ' + '%s ' * len(files) + '.') % tuple('gs://%s/results%g.txt' % (bucket, x) for x in id)
412 | os.system(c)
413 | else:
414 | files = list(Path(save_dir).glob('results*.txt'))
415 | assert len(files), 'No results.txt files found in %s, nothing to plot.' % os.path.abspath(save_dir)
416 | for fi, f in enumerate(files):
417 | try:
418 | results = np.loadtxt(f, usecols=[2, 3, 4, 8, 9, 12, 13, 14, 10, 11], ndmin=2).T
419 | n = results.shape[1] # number of rows
420 | x = range(start, min(stop, n) if stop else n)
421 | for i in range(10):
422 | y = results[i, x]
423 | if i in [0, 1, 2, 5, 6, 7]:
424 | y[y == 0] = np.nan # don't show zero loss values
425 | # y /= y[0] # normalize
426 | label = labels[fi] if len(labels) else f.stem
427 | ax[i].plot(x, y, marker='.', label=label, linewidth=2, markersize=8)
428 | ax[i].set_title(s[i])
429 | # if i in [5, 6, 7]: # share train and val loss y axes
430 | # ax[i].get_shared_y_axes().join(ax[i], ax[i - 5])
431 | except Exception as e:
432 | print('Warning: Plotting error for %s; %s' % (f, e))
433 |
434 | ax[1].legend()
435 | fig.savefig(Path(save_dir) / 'results.png', dpi=200)
436 |
--------------------------------------------------------------------------------
/utils/torch_utils.py:
--------------------------------------------------------------------------------
1 | # YOLOv5 PyTorch utils
2 |
3 | import datetime
4 | import logging
5 | import math
6 | import os
7 | import platform
8 | import subprocess
9 | import time
10 | from contextlib import contextmanager
11 | from copy import deepcopy
12 | from pathlib import Path
13 |
14 | import torch
15 | import torch.backends.cudnn as cudnn
16 | import torch.nn as nn
17 | import torch.nn.functional as F
18 | import torchvision
19 |
20 | try:
21 | import thop # for FLOPS computation
22 | except ImportError:
23 | thop = None
24 | logger = logging.getLogger(__name__)
25 |
26 |
27 | @contextmanager
28 | def torch_distributed_zero_first(local_rank: int):
29 | """
30 | Decorator to make all processes in distributed training wait for each local_master to do something.
31 | """
32 | if local_rank not in [-1, 0]:
33 | torch.distributed.barrier()
34 | yield
35 | if local_rank == 0:
36 | torch.distributed.barrier()
37 |
38 |
39 | def init_torch_seeds(seed=0):
40 | # Speed-reproducibility tradeoff https://pytorch.org/docs/stable/notes/randomness.html
41 | torch.manual_seed(seed)
42 | if seed == 0: # slower, more reproducible
43 | cudnn.benchmark, cudnn.deterministic = False, True
44 | else: # faster, less reproducible
45 | cudnn.benchmark, cudnn.deterministic = True, False
46 |
47 |
48 | def date_modified(path=__file__):
49 | # return human-readable file modification date, i.e. '2021-3-26'
50 | t = datetime.datetime.fromtimestamp(Path(path).stat().st_mtime)
51 | return f'{t.year}-{t.month}-{t.day}'
52 |
53 |
54 | def git_describe(path=Path(__file__).parent): # path must be a directory
55 | # return human-readable git description, i.e. v5.0-5-g3e25f1e https://git-scm.com/docs/git-describe
56 | s = f'git -C {path} describe --tags --long --always'
57 | try:
58 | return subprocess.check_output(s, shell=True, stderr=subprocess.STDOUT).decode()[:-1]
59 | except subprocess.CalledProcessError as e:
60 | return '' # not a git repository
61 |
62 |
63 | def select_device(device='', batch_size=None):
64 | # device = 'cpu' or '0' or '0,1,2,3'
65 | s = f'YOLOv5 🚀 {git_describe() or date_modified()} torch {torch.__version__} ' # string
66 | cpu = device.lower() == 'cpu'
67 | if cpu:
68 | os.environ['CUDA_VISIBLE_DEVICES'] = '-1' # force torch.cuda.is_available() = False
69 | elif device: # non-cpu device requested
70 | os.environ['CUDA_VISIBLE_DEVICES'] = device # set environment variable
71 | assert torch.cuda.is_available(), f'CUDA unavailable, invalid device {device} requested' # check availability
72 |
73 | cuda = not cpu and torch.cuda.is_available()
74 | if cuda:
75 | n = torch.cuda.device_count()
76 | if n > 1 and batch_size: # check that batch_size is compatible with device_count
77 | assert batch_size % n == 0, f'batch-size {batch_size} not multiple of GPU count {n}'
78 | space = ' ' * len(s)
79 | for i, d in enumerate(device.split(',') if device else range(n)):
80 | p = torch.cuda.get_device_properties(i)
81 | s += f"{'' if i == 0 else space}CUDA:{d} ({p.name}, {p.total_memory / 1024 ** 2}MB)\n" # bytes to MB
82 | else:
83 | s += 'CPU\n'
84 |
85 | logger.info(s.encode().decode('ascii', 'ignore') if platform.system() == 'Windows' else s) # emoji-safe
86 | return torch.device('cuda:0' if cuda else 'cpu')
87 |
88 |
89 | def time_synchronized():
90 | # pytorch-accurate time
91 | if torch.cuda.is_available():
92 | torch.cuda.synchronize()
93 | return time.time()
94 |
95 |
96 | def profile(x, ops, n=100, device=None):
97 | # profile a pytorch module or list of modules. Example usage:
98 | # x = torch.randn(16, 3, 640, 640) # input
99 | # m1 = lambda x: x * torch.sigmoid(x)
100 | # m2 = nn.SiLU()
101 | # profile(x, [m1, m2], n=100) # profile speed over 100 iterations
102 |
103 | device = device or torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
104 | x = x.to(device)
105 | x.requires_grad = True
106 | print(torch.__version__, device.type, torch.cuda.get_device_properties(0) if device.type == 'cuda' else '')
107 | print(f"\n{'Params':>12s}{'GFLOPS':>12s}{'forward (ms)':>16s}{'backward (ms)':>16s}{'input':>24s}{'output':>24s}")
108 | for m in ops if isinstance(ops, list) else [ops]:
109 | m = m.to(device) if hasattr(m, 'to') else m # device
110 | m = m.half() if hasattr(m, 'half') and isinstance(x, torch.Tensor) and x.dtype is torch.float16 else m # type
111 | dtf, dtb, t = 0., 0., [0., 0., 0.] # dt forward, backward
112 | try:
113 | flops = thop.profile(m, inputs=(x,), verbose=False)[0] / 1E9 * 2 # GFLOPS
114 | except:
115 | flops = 0
116 |
117 | for _ in range(n):
118 | t[0] = time_synchronized()
119 | y = m(x)
120 | t[1] = time_synchronized()
121 | try:
122 | _ = y.sum().backward()
123 | t[2] = time_synchronized()
124 | except: # no backward method
125 | t[2] = float('nan')
126 | dtf += (t[1] - t[0]) * 1000 / n # ms per op forward
127 | dtb += (t[2] - t[1]) * 1000 / n # ms per op backward
128 |
129 | s_in = tuple(x.shape) if isinstance(x, torch.Tensor) else 'list'
130 | s_out = tuple(y.shape) if isinstance(y, torch.Tensor) else 'list'
131 | p = sum(list(x.numel() for x in m.parameters())) if isinstance(m, nn.Module) else 0 # parameters
132 | print(f'{p:12}{flops:12.4g}{dtf:16.4g}{dtb:16.4g}{str(s_in):>24s}{str(s_out):>24s}')
133 |
134 |
135 | def is_parallel(model):
136 | return type(model) in (nn.parallel.DataParallel, nn.parallel.DistributedDataParallel)
137 |
138 |
139 | def intersect_dicts(da, db, exclude=()):
140 | # Dictionary intersection of matching keys and shapes, omitting 'exclude' keys, using da values
141 | return {k: v for k, v in da.items() if k in db and not any(x in k for x in exclude) and v.shape == db[k].shape}
142 |
143 |
144 | def initialize_weights(model):
145 | for m in model.modules():
146 | t = type(m)
147 | if t is nn.Conv2d:
148 | pass # nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
149 | elif t is nn.BatchNorm2d:
150 | m.eps = 1e-3
151 | m.momentum = 0.03
152 | elif t in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6]:
153 | m.inplace = True
154 |
155 |
156 | def find_modules(model, mclass=nn.Conv2d):
157 | # Finds layer indices matching module class 'mclass'
158 | return [i for i, m in enumerate(model.module_list) if isinstance(m, mclass)]
159 |
160 |
161 | def sparsity(model):
162 | # Return global model sparsity
163 | a, b = 0., 0.
164 | for p in model.parameters():
165 | a += p.numel()
166 | b += (p == 0).sum()
167 | return b / a
168 |
169 |
170 | def prune(model, amount=0.3):
171 | # Prune model to requested global sparsity
172 | import torch.nn.utils.prune as prune
173 | print('Pruning model... ', end='')
174 | for name, m in model.named_modules():
175 | if isinstance(m, nn.Conv2d):
176 | prune.l1_unstructured(m, name='weight', amount=amount) # prune
177 | prune.remove(m, 'weight') # make permanent
178 | print(' %.3g global sparsity' % sparsity(model))
179 |
180 |
181 | def fuse_conv_and_bn(conv, bn):
182 | # Fuse convolution and batchnorm layers https://tehnokv.com/posts/fusing-batchnorm-and-conv/
183 | fusedconv = nn.Conv2d(conv.in_channels,
184 | conv.out_channels,
185 | kernel_size=conv.kernel_size,
186 | stride=conv.stride,
187 | padding=conv.padding,
188 | groups=conv.groups,
189 | bias=True).requires_grad_(False).to(conv.weight.device)
190 |
191 | # prepare filters
192 | w_conv = conv.weight.clone().view(conv.out_channels, -1)
193 | w_bn = torch.diag(bn.weight.div(torch.sqrt(bn.eps + bn.running_var)))
194 | fusedconv.weight.copy_(torch.mm(w_bn, w_conv).view(fusedconv.weight.shape))
195 |
196 | # prepare spatial bias
197 | b_conv = torch.zeros(conv.weight.size(0), device=conv.weight.device) if conv.bias is None else conv.bias
198 | b_bn = bn.bias - bn.weight.mul(bn.running_mean).div(torch.sqrt(bn.running_var + bn.eps))
199 | fusedconv.bias.copy_(torch.mm(w_bn, b_conv.reshape(-1, 1)).reshape(-1) + b_bn)
200 |
201 | return fusedconv
202 |
203 |
204 | def model_info(model, verbose=False, img_size=640):
205 | # Model information. img_size may be int or list, i.e. img_size=640 or img_size=[640, 320]
206 | n_p = sum(x.numel() for x in model.parameters()) # number parameters
207 | n_g = sum(x.numel() for x in model.parameters() if x.requires_grad) # number gradients
208 | if verbose:
209 | print('%5s %40s %9s %12s %20s %10s %10s' % ('layer', 'name', 'gradient', 'parameters', 'shape', 'mu', 'sigma'))
210 | for i, (name, p) in enumerate(model.named_parameters()):
211 | name = name.replace('module_list.', '')
212 | print('%5g %40s %9s %12g %20s %10.3g %10.3g' %
213 | (i, name, p.requires_grad, p.numel(), list(p.shape), p.mean(), p.std()))
214 |
215 | try: # FLOPS
216 | from thop import profile
217 | stride = max(int(model.stride.max()), 32) if hasattr(model, 'stride') else 32
218 | img = torch.zeros((1, model.yaml.get('ch', 3), stride, stride), device=next(model.parameters()).device) # input
219 | flops = profile(deepcopy(model), inputs=(img,), verbose=False)[0] / 1E9 * 2 # stride GFLOPS
220 | img_size = img_size if isinstance(img_size, list) else [img_size, img_size] # expand if int/float
221 | fs = ', %.1f GFLOPS' % (flops * img_size[0] / stride * img_size[1] / stride) # 640x640 GFLOPS
222 | except (ImportError, Exception):
223 | fs = ''
224 |
225 | logger.info(f"Model Summary: {len(list(model.modules()))} layers, {n_p} parameters, {n_g} gradients{fs}")
226 |
227 |
228 | def load_classifier(name='resnet101', n=2):
229 | # Loads a pretrained model reshaped to n-class output
230 | model = torchvision.models.__dict__[name](pretrained=True)
231 |
232 | # ResNet model properties
233 | # input_size = [3, 224, 224]
234 | # input_space = 'RGB'
235 | # input_range = [0, 1]
236 | # mean = [0.485, 0.456, 0.406]
237 | # std = [0.229, 0.224, 0.225]
238 |
239 | # Reshape output to n classes
240 | filters = model.fc.weight.shape[1]
241 | model.fc.bias = nn.Parameter(torch.zeros(n), requires_grad=True)
242 | model.fc.weight = nn.Parameter(torch.zeros(n, filters), requires_grad=True)
243 | model.fc.out_features = n
244 | return model
245 |
246 |
247 | def scale_img(img, ratio=1.0, same_shape=False, gs=32): # img(16,3,256,416)
248 | # scales img(bs,3,y,x) by ratio constrained to gs-multiple
249 | if ratio == 1.0:
250 | return img
251 | else:
252 | h, w = img.shape[2:]
253 | s = (int(h * ratio), int(w * ratio)) # new size
254 | img = F.interpolate(img, size=s, mode='bilinear', align_corners=False) # resize
255 | if not same_shape: # pad/crop img
256 | h, w = [math.ceil(x * ratio / gs) * gs for x in (h, w)]
257 | return F.pad(img, [0, w - s[1], 0, h - s[0]], value=0.447) # value = imagenet mean
258 |
259 |
260 | def copy_attr(a, b, include=(), exclude=()):
261 | # Copy attributes from b to a, options to only include [...] and to exclude [...]
262 | for k, v in b.__dict__.items():
263 | if (len(include) and k not in include) or k.startswith('_') or k in exclude:
264 | continue
265 | else:
266 | setattr(a, k, v)
267 |
268 |
269 | class ModelEMA:
270 | """ Model Exponential Moving Average from https://github.com/rwightman/pytorch-image-models
271 | Keep a moving average of everything in the model state_dict (parameters and buffers).
272 | This is intended to allow functionality like
273 | https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage
274 | A smoothed version of the weights is necessary for some training schemes to perform well.
275 | This class is sensitive where it is initialized in the sequence of model init,
276 | GPU assignment and distributed training wrappers.
277 | """
278 |
279 | def __init__(self, model, decay=0.9999, updates=0):
280 | # Create EMA
281 | self.ema = deepcopy(model.module if is_parallel(model) else model).eval() # FP32 EMA
282 | # if next(model.parameters()).device.type != 'cpu':
283 | # self.ema.half() # FP16 EMA
284 | self.updates = updates # number of EMA updates
285 | self.decay = lambda x: decay * (1 - math.exp(-x / 2000)) # decay exponential ramp (to help early epochs)
286 | for p in self.ema.parameters():
287 | p.requires_grad_(False)
288 |
289 | def update(self, model):
290 | # Update EMA parameters
291 | with torch.no_grad():
292 | self.updates += 1
293 | d = self.decay(self.updates)
294 |
295 | msd = model.module.state_dict() if is_parallel(model) else model.state_dict() # model state_dict
296 | for k, v in self.ema.state_dict().items():
297 | if v.dtype.is_floating_point:
298 | v *= d
299 | v += (1. - d) * msd[k].detach()
300 |
301 | def update_attr(self, model, include=(), exclude=('process_group', 'reducer')):
302 | # Update EMA attributes
303 | copy_attr(self.ema, model, include, exclude)
304 |
--------------------------------------------------------------------------------
/utils/wandb_logging/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/XingZeng307/YOLOv5_with_BiFPN/59322217045be24b60f50c4d8a90b98e4d8dd6cf/utils/wandb_logging/__init__.py
--------------------------------------------------------------------------------
/utils/wandb_logging/log_dataset.py:
--------------------------------------------------------------------------------
1 | import argparse
2 |
3 | import yaml
4 |
5 | from wandb_utils import WandbLogger
6 |
7 | WANDB_ARTIFACT_PREFIX = 'wandb-artifact://'
8 |
9 |
10 | def create_dataset_artifact(opt):
11 | with open(opt.data) as f:
12 | data = yaml.safe_load(f) # data dict
13 | logger = WandbLogger(opt, '', None, data, job_type='Dataset Creation')
14 |
15 |
16 | if __name__ == '__main__':
17 | parser = argparse.ArgumentParser()
18 | parser.add_argument('--data', type=str, default='data/coco128.yaml', help='data.yaml path')
19 | parser.add_argument('--single-cls', action='store_true', help='train as single-class dataset')
20 | parser.add_argument('--project', type=str, default='YOLOv5', help='name of W&B Project')
21 | opt = parser.parse_args()
22 | opt.resume = False # Explicitly disallow resume check for dataset upload job
23 |
24 | create_dataset_artifact(opt)
25 |
--------------------------------------------------------------------------------
/utils/wandb_logging/wandb_utils.py:
--------------------------------------------------------------------------------
1 | import json
2 | import sys
3 | from pathlib import Path
4 |
5 | import torch
6 | import yaml
7 | from tqdm import tqdm
8 |
9 | sys.path.append(str(Path(__file__).parent.parent.parent)) # add utils/ to path
10 | from utils.datasets import LoadImagesAndLabels
11 | from utils.datasets import img2label_paths
12 | from utils.general import colorstr, xywh2xyxy, check_dataset
13 |
14 | try:
15 | import wandb
16 | from wandb import init, finish
17 | except ImportError:
18 | wandb = None
19 |
20 | WANDB_ARTIFACT_PREFIX = 'wandb-artifact://'
21 |
22 |
23 | def remove_prefix(from_string, prefix=WANDB_ARTIFACT_PREFIX):
24 | return from_string[len(prefix):]
25 |
26 |
27 | def check_wandb_config_file(data_config_file):
28 | wandb_config = '_wandb.'.join(data_config_file.rsplit('.', 1)) # updated data.yaml path
29 | if Path(wandb_config).is_file():
30 | return wandb_config
31 | return data_config_file
32 |
33 |
34 | def get_run_info(run_path):
35 | run_path = Path(remove_prefix(run_path, WANDB_ARTIFACT_PREFIX))
36 | run_id = run_path.stem
37 | project = run_path.parent.stem
38 | model_artifact_name = 'run_' + run_id + '_model'
39 | return run_id, project, model_artifact_name
40 |
41 |
42 | def check_wandb_resume(opt):
43 | process_wandb_config_ddp_mode(opt) if opt.global_rank not in [-1, 0] else None
44 | if isinstance(opt.resume, str):
45 | if opt.resume.startswith(WANDB_ARTIFACT_PREFIX):
46 | if opt.global_rank not in [-1, 0]: # For resuming DDP runs
47 | run_id, project, model_artifact_name = get_run_info(opt.resume)
48 | api = wandb.Api()
49 | artifact = api.artifact(project + '/' + model_artifact_name + ':latest')
50 | modeldir = artifact.download()
51 | opt.weights = str(Path(modeldir) / "last.pt")
52 | return True
53 | return None
54 |
55 |
56 | def process_wandb_config_ddp_mode(opt):
57 | with open(opt.data) as f:
58 | data_dict = yaml.safe_load(f) # data dict
59 | train_dir, val_dir = None, None
60 | if isinstance(data_dict['train'], str) and data_dict['train'].startswith(WANDB_ARTIFACT_PREFIX):
61 | api = wandb.Api()
62 | train_artifact = api.artifact(remove_prefix(data_dict['train']) + ':' + opt.artifact_alias)
63 | train_dir = train_artifact.download()
64 | train_path = Path(train_dir) / 'data/images/'
65 | data_dict['train'] = str(train_path)
66 |
67 | if isinstance(data_dict['val'], str) and data_dict['val'].startswith(WANDB_ARTIFACT_PREFIX):
68 | api = wandb.Api()
69 | val_artifact = api.artifact(remove_prefix(data_dict['val']) + ':' + opt.artifact_alias)
70 | val_dir = val_artifact.download()
71 | val_path = Path(val_dir) / 'data/images/'
72 | data_dict['val'] = str(val_path)
73 | if train_dir or val_dir:
74 | ddp_data_path = str(Path(val_dir) / 'wandb_local_data.yaml')
75 | with open(ddp_data_path, 'w') as f:
76 | yaml.safe_dump(data_dict, f)
77 | opt.data = ddp_data_path
78 |
79 |
80 | class WandbLogger():
81 | def __init__(self, opt, name, run_id, data_dict, job_type='Training'):
82 | # Pre-training routine --
83 | self.job_type = job_type
84 | self.wandb, self.wandb_run, self.data_dict = wandb, None if not wandb else wandb.run, data_dict
85 | # It's more elegant to stick to 1 wandb.init call, but useful config data is overwritten in the WandbLogger's wandb.init call
86 | if isinstance(opt.resume, str): # checks resume from artifact
87 | if opt.resume.startswith(WANDB_ARTIFACT_PREFIX):
88 | run_id, project, model_artifact_name = get_run_info(opt.resume)
89 | model_artifact_name = WANDB_ARTIFACT_PREFIX + model_artifact_name
90 | assert wandb, 'install wandb to resume wandb runs'
91 | # Resume wandb-artifact:// runs here| workaround for not overwriting wandb.config
92 | self.wandb_run = wandb.init(id=run_id, project=project, resume='allow')
93 | opt.resume = model_artifact_name
94 | elif self.wandb:
95 | self.wandb_run = wandb.init(config=opt,
96 | resume="allow",
97 | project='YOLOv5' if opt.project == 'runs/train' else Path(opt.project).stem,
98 | name=name,
99 | job_type=job_type,
100 | id=run_id) if not wandb.run else wandb.run
101 | if self.wandb_run:
102 | if self.job_type == 'Training':
103 | if not opt.resume:
104 | wandb_data_dict = self.check_and_upload_dataset(opt) if opt.upload_dataset else data_dict
105 | # Info useful for resuming from artifacts
106 | self.wandb_run.config.opt = vars(opt)
107 | self.wandb_run.config.data_dict = wandb_data_dict
108 | self.data_dict = self.setup_training(opt, data_dict)
109 | if self.job_type == 'Dataset Creation':
110 | self.data_dict = self.check_and_upload_dataset(opt)
111 | else:
112 | prefix = colorstr('wandb: ')
113 | print(f"{prefix}Install Weights & Biases for YOLOv5 logging with 'pip install wandb' (recommended)")
114 |
115 | def check_and_upload_dataset(self, opt):
116 | assert wandb, 'Install wandb to upload dataset'
117 | check_dataset(self.data_dict)
118 | config_path = self.log_dataset_artifact(opt.data,
119 | opt.single_cls,
120 | 'YOLOv5' if opt.project == 'runs/train' else Path(opt.project).stem)
121 | print("Created dataset config file ", config_path)
122 | with open(config_path) as f:
123 | wandb_data_dict = yaml.safe_load(f)
124 | return wandb_data_dict
125 |
126 | def setup_training(self, opt, data_dict):
127 | self.log_dict, self.current_epoch, self.log_imgs = {}, 0, 16 # Logging Constants
128 | self.bbox_interval = opt.bbox_interval
129 | if isinstance(opt.resume, str):
130 | modeldir, _ = self.download_model_artifact(opt)
131 | if modeldir:
132 | self.weights = Path(modeldir) / "last.pt"
133 | config = self.wandb_run.config
134 | opt.weights, opt.save_period, opt.batch_size, opt.bbox_interval, opt.epochs, opt.hyp = str(
135 | self.weights), config.save_period, config.total_batch_size, config.bbox_interval, config.epochs, \
136 | config.opt['hyp']
137 | data_dict = dict(self.wandb_run.config.data_dict) # eliminates the need for config file to resume
138 | if 'val_artifact' not in self.__dict__: # If --upload_dataset is set, use the existing artifact, don't download
139 | self.train_artifact_path, self.train_artifact = self.download_dataset_artifact(data_dict.get('train'),
140 | opt.artifact_alias)
141 | self.val_artifact_path, self.val_artifact = self.download_dataset_artifact(data_dict.get('val'),
142 | opt.artifact_alias)
143 | self.result_artifact, self.result_table, self.val_table, self.weights = None, None, None, None
144 | if self.train_artifact_path is not None:
145 | train_path = Path(self.train_artifact_path) / 'data/images/'
146 | data_dict['train'] = str(train_path)
147 | if self.val_artifact_path is not None:
148 | val_path = Path(self.val_artifact_path) / 'data/images/'
149 | data_dict['val'] = str(val_path)
150 | self.val_table = self.val_artifact.get("val")
151 | self.map_val_table_path()
152 | if self.val_artifact is not None:
153 | self.result_artifact = wandb.Artifact("run_" + wandb.run.id + "_progress", "evaluation")
154 | self.result_table = wandb.Table(["epoch", "id", "prediction", "avg_confidence"])
155 | if opt.bbox_interval == -1:
156 | self.bbox_interval = opt.bbox_interval = (opt.epochs // 10) if opt.epochs > 10 else 1
157 | return data_dict
158 |
159 | def download_dataset_artifact(self, path, alias):
160 | if isinstance(path, str) and path.startswith(WANDB_ARTIFACT_PREFIX):
161 | dataset_artifact = wandb.use_artifact(remove_prefix(path, WANDB_ARTIFACT_PREFIX) + ":" + alias)
162 | assert dataset_artifact is not None, "'Error: W&B dataset artifact doesn\'t exist'"
163 | datadir = dataset_artifact.download()
164 | return datadir, dataset_artifact
165 | return None, None
166 |
167 | def download_model_artifact(self, opt):
168 | if opt.resume.startswith(WANDB_ARTIFACT_PREFIX):
169 | model_artifact = wandb.use_artifact(remove_prefix(opt.resume, WANDB_ARTIFACT_PREFIX) + ":latest")
170 | assert model_artifact is not None, 'Error: W&B model artifact doesn\'t exist'
171 | modeldir = model_artifact.download()
172 | epochs_trained = model_artifact.metadata.get('epochs_trained')
173 | total_epochs = model_artifact.metadata.get('total_epochs')
174 | assert epochs_trained < total_epochs, 'training to %g epochs is finished, nothing to resume.' % (
175 | total_epochs)
176 | return modeldir, model_artifact
177 | return None, None
178 |
179 | def log_model(self, path, opt, epoch, fitness_score, best_model=False):
180 | model_artifact = wandb.Artifact('run_' + wandb.run.id + '_model', type='model', metadata={
181 | 'original_url': str(path),
182 | 'epochs_trained': epoch + 1,
183 | 'save period': opt.save_period,
184 | 'project': opt.project,
185 | 'total_epochs': opt.epochs,
186 | 'fitness_score': fitness_score
187 | })
188 | model_artifact.add_file(str(path / 'last.pt'), name='last.pt')
189 | wandb.log_artifact(model_artifact,
190 | aliases=['latest', 'epoch ' + str(self.current_epoch), 'best' if best_model else ''])
191 | print("Saving model artifact on epoch ", epoch + 1)
192 |
193 | def log_dataset_artifact(self, data_file, single_cls, project, overwrite_config=False):
194 | with open(data_file) as f:
195 | data = yaml.safe_load(f) # data dict
196 | nc, names = (1, ['item']) if single_cls else (int(data['nc']), data['names'])
197 | names = {k: v for k, v in enumerate(names)} # to index dictionary
198 | self.train_artifact = self.create_dataset_table(LoadImagesAndLabels(
199 | data['train']), names, name='train') if data.get('train') else None
200 | self.val_artifact = self.create_dataset_table(LoadImagesAndLabels(
201 | data['val']), names, name='val') if data.get('val') else None
202 | if data.get('train'):
203 | data['train'] = WANDB_ARTIFACT_PREFIX + str(Path(project) / 'train')
204 | if data.get('val'):
205 | data['val'] = WANDB_ARTIFACT_PREFIX + str(Path(project) / 'val')
206 | path = data_file if overwrite_config else '_wandb.'.join(data_file.rsplit('.', 1)) # updated data.yaml path
207 | data.pop('download', None)
208 | with open(path, 'w') as f:
209 | yaml.safe_dump(data, f)
210 |
211 | if self.job_type == 'Training': # builds correct artifact pipeline graph
212 | self.wandb_run.use_artifact(self.val_artifact)
213 | self.wandb_run.use_artifact(self.train_artifact)
214 | self.val_artifact.wait()
215 | self.val_table = self.val_artifact.get('val')
216 | self.map_val_table_path()
217 | else:
218 | self.wandb_run.log_artifact(self.train_artifact)
219 | self.wandb_run.log_artifact(self.val_artifact)
220 | return path
221 |
222 | def map_val_table_path(self):
223 | self.val_table_map = {}
224 | print("Mapping dataset")
225 | for i, data in enumerate(tqdm(self.val_table.data)):
226 | self.val_table_map[data[3]] = data[0]
227 |
228 | def create_dataset_table(self, dataset, class_to_id, name='dataset'):
229 | # TODO: Explore multiprocessing to slpit this loop parallely| This is essential for speeding up the the logging
230 | artifact = wandb.Artifact(name=name, type="dataset")
231 | img_files = tqdm([dataset.path]) if isinstance(dataset.path, str) and Path(dataset.path).is_dir() else None
232 | img_files = tqdm(dataset.img_files) if not img_files else img_files
233 | for img_file in img_files:
234 | if Path(img_file).is_dir():
235 | artifact.add_dir(img_file, name='data/images')
236 | labels_path = 'labels'.join(dataset.path.rsplit('images', 1))
237 | artifact.add_dir(labels_path, name='data/labels')
238 | else:
239 | artifact.add_file(img_file, name='data/images/' + Path(img_file).name)
240 | label_file = Path(img2label_paths([img_file])[0])
241 | artifact.add_file(str(label_file),
242 | name='data/labels/' + label_file.name) if label_file.exists() else None
243 | table = wandb.Table(columns=["id", "train_image", "Classes", "name"])
244 | class_set = wandb.Classes([{'id': id, 'name': name} for id, name in class_to_id.items()])
245 | for si, (img, labels, paths, shapes) in enumerate(tqdm(dataset)):
246 | height, width = shapes[0]
247 | labels[:, 2:] = (xywh2xyxy(labels[:, 2:].view(-1, 4))) * torch.Tensor([width, height, width, height])
248 | box_data, img_classes = [], {}
249 | for cls, *xyxy in labels[:, 1:].tolist():
250 | cls = int(cls)
251 | box_data.append({"position": {"minX": xyxy[0], "minY": xyxy[1], "maxX": xyxy[2], "maxY": xyxy[3]},
252 | "class_id": cls,
253 | "box_caption": "%s" % (class_to_id[cls]),
254 | "scores": {"acc": 1},
255 | "domain": "pixel"})
256 | img_classes[cls] = class_to_id[cls]
257 | boxes = {"ground_truth": {"box_data": box_data, "class_labels": class_to_id}} # inference-space
258 | table.add_data(si, wandb.Image(paths, classes=class_set, boxes=boxes), json.dumps(img_classes),
259 | Path(paths).name)
260 | artifact.add(table, name)
261 | return artifact
262 |
263 | def log_training_progress(self, predn, path, names):
264 | if self.val_table and self.result_table:
265 | class_set = wandb.Classes([{'id': id, 'name': name} for id, name in names.items()])
266 | box_data = []
267 | total_conf = 0
268 | for *xyxy, conf, cls in predn.tolist():
269 | if conf >= 0.25:
270 | box_data.append(
271 | {"position": {"minX": xyxy[0], "minY": xyxy[1], "maxX": xyxy[2], "maxY": xyxy[3]},
272 | "class_id": int(cls),
273 | "box_caption": "%s %.3f" % (names[cls], conf),
274 | "scores": {"class_score": conf},
275 | "domain": "pixel"})
276 | total_conf = total_conf + conf
277 | boxes = {"predictions": {"box_data": box_data, "class_labels": names}} # inference-space
278 | id = self.val_table_map[Path(path).name]
279 | self.result_table.add_data(self.current_epoch,
280 | id,
281 | wandb.Image(self.val_table.data[id][1], boxes=boxes, classes=class_set),
282 | total_conf / max(1, len(box_data))
283 | )
284 |
285 | def log(self, log_dict):
286 | if self.wandb_run:
287 | for key, value in log_dict.items():
288 | self.log_dict[key] = value
289 |
290 | def end_epoch(self, best_result=False):
291 | if self.wandb_run:
292 | wandb.log(self.log_dict)
293 | self.log_dict = {}
294 | if self.result_artifact:
295 | train_results = wandb.JoinedTable(self.val_table, self.result_table, "id")
296 | self.result_artifact.add(train_results, 'result')
297 | wandb.log_artifact(self.result_artifact, aliases=['latest', 'epoch ' + str(self.current_epoch),
298 | ('best' if best_result else '')])
299 | self.result_table = wandb.Table(["epoch", "id", "prediction", "avg_confidence"])
300 | self.result_artifact = wandb.Artifact("run_" + wandb.run.id + "_progress", "evaluation")
301 |
302 | def finish_run(self):
303 | if self.wandb_run:
304 | if self.log_dict:
305 | wandb.log(self.log_dict)
306 | wandb.run.finish()
307 |
--------------------------------------------------------------------------------
/weights/download_weights.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | # Download latest models from https://github.com/ultralytics/yolov5/releases
3 | # Usage:
4 | # $ bash weights/download_weights.sh
5 |
6 | python - <