RashiAgarwal commited on
Commit
25fffe1
·
1 Parent(s): c24a19e

Upload 2 files

Browse files
Files changed (2) hide show
  1. utils.py +637 -0
  2. yolov3.py +127 -0
utils.py ADDED
@@ -0,0 +1,637 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import config
2
+ import matplotlib.pyplot as plt
3
+ import matplotlib.patches as patches
4
+ import numpy as np
5
+ import os
6
+ import random
7
+ import torch
8
+
9
+ from collections import Counter
10
+ from torch.utils.data import DataLoader
11
+ from tqdm import tqdm
12
+
13
+
14
+ def iou_width_height(boxes1, boxes2):
15
+ """
16
+ Parameters:
17
+ boxes1 (tensor): width and height of the first bounding boxes
18
+ boxes2 (tensor): width and height of the second bounding boxes
19
+ Returns:
20
+ tensor: Intersection over union of the corresponding boxes
21
+ """
22
+ intersection = torch.min(boxes1[..., 0], boxes2[..., 0]) * torch.min(
23
+ boxes1[..., 1], boxes2[..., 1]
24
+ )
25
+ union = (
26
+ boxes1[..., 0] * boxes1[..., 1] + boxes2[..., 0] * boxes2[..., 1] - intersection
27
+ )
28
+ return intersection / union
29
+
30
+
31
+ def intersection_over_union(boxes_preds, boxes_labels, box_format="midpoint"):
32
+ """
33
+ Video explanation of this function:
34
+ https://youtu.be/XXYG5ZWtjj0
35
+
36
+ This function calculates intersection over union (iou) given pred boxes
37
+ and target boxes.
38
+
39
+ Parameters:
40
+ boxes_preds (tensor): Predictions of Bounding Boxes (BATCH_SIZE, 4)
41
+ boxes_labels (tensor): Correct labels of Bounding Boxes (BATCH_SIZE, 4)
42
+ box_format (str): midpoint/corners, if boxes (x,y,w,h) or (x1,y1,x2,y2)
43
+
44
+ Returns:
45
+ tensor: Intersection over union for all examples
46
+ """
47
+
48
+ if box_format == "midpoint":
49
+ box1_x1 = boxes_preds[..., 0:1] - boxes_preds[..., 2:3] / 2
50
+ box1_y1 = boxes_preds[..., 1:2] - boxes_preds[..., 3:4] / 2
51
+ box1_x2 = boxes_preds[..., 0:1] + boxes_preds[..., 2:3] / 2
52
+ box1_y2 = boxes_preds[..., 1:2] + boxes_preds[..., 3:4] / 2
53
+ box2_x1 = boxes_labels[..., 0:1] - boxes_labels[..., 2:3] / 2
54
+ box2_y1 = boxes_labels[..., 1:2] - boxes_labels[..., 3:4] / 2
55
+ box2_x2 = boxes_labels[..., 0:1] + boxes_labels[..., 2:3] / 2
56
+ box2_y2 = boxes_labels[..., 1:2] + boxes_labels[..., 3:4] / 2
57
+
58
+ if box_format == "corners":
59
+ box1_x1 = boxes_preds[..., 0:1]
60
+ box1_y1 = boxes_preds[..., 1:2]
61
+ box1_x2 = boxes_preds[..., 2:3]
62
+ box1_y2 = boxes_preds[..., 3:4]
63
+ box2_x1 = boxes_labels[..., 0:1]
64
+ box2_y1 = boxes_labels[..., 1:2]
65
+ box2_x2 = boxes_labels[..., 2:3]
66
+ box2_y2 = boxes_labels[..., 3:4]
67
+
68
+ x1 = torch.max(box1_x1, box2_x1)
69
+ y1 = torch.max(box1_y1, box2_y1)
70
+ x2 = torch.min(box1_x2, box2_x2)
71
+ y2 = torch.min(box1_y2, box2_y2)
72
+
73
+ intersection = (x2 - x1).clamp(0) * (y2 - y1).clamp(0)
74
+ box1_area = abs((box1_x2 - box1_x1) * (box1_y2 - box1_y1))
75
+ box2_area = abs((box2_x2 - box2_x1) * (box2_y2 - box2_y1))
76
+
77
+ return intersection / (box1_area + box2_area - intersection + 1e-6)
78
+
79
+
80
+ def non_max_suppression(bboxes, iou_threshold, threshold, box_format="corners"):
81
+ """
82
+ Video explanation of this function:
83
+ https://youtu.be/YDkjWEN8jNA
84
+
85
+ Does Non Max Suppression given bboxes
86
+
87
+ Parameters:
88
+ bboxes (list): list of lists containing all bboxes with each bboxes
89
+ specified as [class_pred, prob_score, x1, y1, x2, y2]
90
+ iou_threshold (float): threshold where predicted bboxes is correct
91
+ threshold (float): threshold to remove predicted bboxes (independent of IoU)
92
+ box_format (str): "midpoint" or "corners" used to specify bboxes
93
+
94
+ Returns:
95
+ list: bboxes after performing NMS given a specific IoU threshold
96
+ """
97
+
98
+ assert type(bboxes) == list
99
+
100
+ bboxes = [box for box in bboxes if box[1] > threshold]
101
+ bboxes = sorted(bboxes, key=lambda x: x[1], reverse=True)
102
+ bboxes_after_nms = []
103
+
104
+ while bboxes:
105
+ chosen_box = bboxes.pop(0)
106
+
107
+ bboxes = [
108
+ box
109
+ for box in bboxes
110
+ if box[0] != chosen_box[0]
111
+ or intersection_over_union(
112
+ torch.tensor(chosen_box[2:]),
113
+ torch.tensor(box[2:]),
114
+ box_format=box_format,
115
+ )
116
+ < iou_threshold
117
+ ]
118
+
119
+ bboxes_after_nms.append(chosen_box)
120
+
121
+ return bboxes_after_nms
122
+
123
+
124
+ def mean_average_precision(
125
+ pred_boxes, true_boxes, iou_threshold=0.5, box_format="midpoint", num_classes=20
126
+ ):
127
+ """
128
+ Video explanation of this function:
129
+ https://youtu.be/FppOzcDvaDI
130
+
131
+ This function calculates mean average precision (mAP)
132
+
133
+ Parameters:
134
+ pred_boxes (list): list of lists containing all bboxes with each bboxes
135
+ specified as [train_idx, class_prediction, prob_score, x1, y1, x2, y2]
136
+ true_boxes (list): Similar as pred_boxes except all the correct ones
137
+ iou_threshold (float): threshold where predicted bboxes is correct
138
+ box_format (str): "midpoint" or "corners" used to specify bboxes
139
+ num_classes (int): number of classes
140
+
141
+ Returns:
142
+ float: mAP value across all classes given a specific IoU threshold
143
+ """
144
+
145
+ # list storing all AP for respective classes
146
+ average_precisions = []
147
+
148
+ # used for numerical stability later on
149
+ epsilon = 1e-6
150
+
151
+ for c in range(num_classes):
152
+ detections = []
153
+ ground_truths = []
154
+
155
+ # Go through all predictions and targets,
156
+ # and only add the ones that belong to the
157
+ # current class c
158
+ for detection in pred_boxes:
159
+ if detection[1] == c:
160
+ detections.append(detection)
161
+
162
+ for true_box in true_boxes:
163
+ if true_box[1] == c:
164
+ ground_truths.append(true_box)
165
+
166
+ # find the amount of bboxes for each training example
167
+ # Counter here finds how many ground truth bboxes we get
168
+ # for each training example, so let's say img 0 has 3,
169
+ # img 1 has 5 then we will obtain a dictionary with:
170
+ # amount_bboxes = {0:3, 1:5}
171
+ amount_bboxes = Counter([gt[0] for gt in ground_truths])
172
+
173
+ # We then go through each key, val in this dictionary
174
+ # and convert to the following (w.r.t same example):
175
+ # ammount_bboxes = {0:torch.tensor[0,0,0], 1:torch.tensor[0,0,0,0,0]}
176
+ for key, val in amount_bboxes.items():
177
+ amount_bboxes[key] = torch.zeros(val)
178
+
179
+ # sort by box probabilities which is index 2
180
+ detections.sort(key=lambda x: x[2], reverse=True)
181
+ TP = torch.zeros((len(detections)))
182
+ FP = torch.zeros((len(detections)))
183
+ total_true_bboxes = len(ground_truths)
184
+
185
+ # If none exists for this class then we can safely skip
186
+ if total_true_bboxes == 0:
187
+ continue
188
+
189
+ for detection_idx, detection in enumerate(detections):
190
+ # Only take out the ground_truths that have the same
191
+ # training idx as detection
192
+ ground_truth_img = [
193
+ bbox for bbox in ground_truths if bbox[0] == detection[0]
194
+ ]
195
+
196
+ num_gts = len(ground_truth_img)
197
+ best_iou = 0
198
+
199
+ for idx, gt in enumerate(ground_truth_img):
200
+ iou = intersection_over_union(
201
+ torch.tensor(detection[3:]),
202
+ torch.tensor(gt[3:]),
203
+ box_format=box_format,
204
+ )
205
+
206
+ if iou > best_iou:
207
+ best_iou = iou
208
+ best_gt_idx = idx
209
+
210
+ if best_iou > iou_threshold:
211
+ # only detect ground truth detection once
212
+ if amount_bboxes[detection[0]][best_gt_idx] == 0:
213
+ # true positive and add this bounding box to seen
214
+ TP[detection_idx] = 1
215
+ amount_bboxes[detection[0]][best_gt_idx] = 1
216
+ else:
217
+ FP[detection_idx] = 1
218
+
219
+ # if IOU is lower then the detection is a false positive
220
+ else:
221
+ FP[detection_idx] = 1
222
+
223
+ TP_cumsum = torch.cumsum(TP, dim=0)
224
+ FP_cumsum = torch.cumsum(FP, dim=0)
225
+ recalls = TP_cumsum / (total_true_bboxes + epsilon)
226
+ precisions = TP_cumsum / (TP_cumsum + FP_cumsum + epsilon)
227
+ precisions = torch.cat((torch.tensor([1]), precisions))
228
+ recalls = torch.cat((torch.tensor([0]), recalls))
229
+ # torch.trapz for numerical integration
230
+ average_precisions.append(torch.trapz(precisions, recalls))
231
+
232
+ return sum(average_precisions) / len(average_precisions)
233
+
234
+
235
+ def plot_image(image, boxes):
236
+ """Plots predicted bounding boxes on the image"""
237
+ cmap = plt.get_cmap("tab20b")
238
+ class_labels = config.COCO_LABELS if config.DATASET=='COCO' else config.PASCAL_CLASSES
239
+ colors = [cmap(i) for i in np.linspace(0, 1, len(class_labels))]
240
+ im = np.array(image)
241
+ height, width, _ = im.shape
242
+
243
+ # Create figure and axes
244
+ fig, ax = plt.subplots(1)
245
+ # Display the image
246
+ ax.imshow(im)
247
+
248
+ # box[0] is x midpoint, box[2] is width
249
+ # box[1] is y midpoint, box[3] is height
250
+
251
+ # Create a Rectangle patch
252
+ for box in boxes:
253
+ assert len(box) == 6, "box should contain class pred, confidence, x, y, width, height"
254
+ class_pred = box[0]
255
+ box = box[2:]
256
+ upper_left_x = box[0] - box[2] / 2
257
+ upper_left_y = box[1] - box[3] / 2
258
+ rect = patches.Rectangle(
259
+ (upper_left_x * width, upper_left_y * height),
260
+ box[2] * width,
261
+ box[3] * height,
262
+ linewidth=2,
263
+ edgecolor=colors[int(class_pred)],
264
+ facecolor="none",
265
+ )
266
+ # Add the patch to the Axes
267
+ ax.add_patch(rect)
268
+ plt.text(
269
+ upper_left_x * width,
270
+ upper_left_y * height,
271
+ s=class_labels[int(class_pred)],
272
+ color="white",
273
+ verticalalignment="top",
274
+ bbox={"color": colors[int(class_pred)], "pad": 0},
275
+ )
276
+
277
+ plt.show()
278
+
279
+
280
+ def get_evaluation_bboxes(
281
+ loader,
282
+ model,
283
+ iou_threshold,
284
+ anchors,
285
+ threshold,
286
+ box_format="midpoint",
287
+ device="cuda",
288
+ ):
289
+ # make sure model is in eval before get bboxes
290
+ model.eval()
291
+ train_idx = 0
292
+ all_pred_boxes = []
293
+ all_true_boxes = []
294
+ for batch_idx, (x, labels) in enumerate(tqdm(loader)):
295
+ x = x.to(device)
296
+
297
+ with torch.no_grad():
298
+ predictions = model(x)
299
+
300
+ batch_size = x.shape[0]
301
+ bboxes = [[] for _ in range(batch_size)]
302
+ for i in range(3):
303
+ S = predictions[i].shape[2]
304
+ anchor = torch.tensor([*anchors[i]]).to(device) * S
305
+ boxes_scale_i = cells_to_bboxes(
306
+ predictions[i], anchor, S=S, is_preds=True
307
+ )
308
+ for idx, (box) in enumerate(boxes_scale_i):
309
+ bboxes[idx] += box
310
+
311
+ # we just want one bbox for each label, not one for each scale
312
+ true_bboxes = cells_to_bboxes(
313
+ labels[2], anchor, S=S, is_preds=False
314
+ )
315
+
316
+ for idx in range(batch_size):
317
+ nms_boxes = non_max_suppression(
318
+ bboxes[idx],
319
+ iou_threshold=iou_threshold,
320
+ threshold=threshold,
321
+ box_format=box_format,
322
+ )
323
+
324
+ for nms_box in nms_boxes:
325
+ all_pred_boxes.append([train_idx] + nms_box)
326
+
327
+ for box in true_bboxes[idx]:
328
+ if box[1] > threshold:
329
+ all_true_boxes.append([train_idx] + box)
330
+
331
+ train_idx += 1
332
+
333
+ model.train()
334
+ return all_pred_boxes, all_true_boxes
335
+
336
+ def get_evaluation_bboxes1(
337
+ batch,
338
+ model,
339
+ iou_threshold,
340
+ anchors,
341
+ threshold,
342
+ box_format="midpoint",
343
+ device="cuda",
344
+ ):
345
+ # make sure model is in eval before get bboxes
346
+
347
+ train_idx = 0
348
+ all_pred_boxes = []
349
+ all_true_boxes = []
350
+ x, labels = batch
351
+ x = x.to(device)
352
+
353
+ with torch.no_grad():
354
+ predictions = model(x)
355
+
356
+ batch_size = x.shape[0]
357
+ bboxes = [[] for _ in range(batch_size)]
358
+ for i in range(3):
359
+ S = predictions[i].shape[2]
360
+ anchor = torch.tensor([*anchors[i]]).to(device) * S
361
+ boxes_scale_i = cells_to_bboxes(
362
+ predictions[i], anchor, S=S, is_preds=True
363
+ )
364
+ for idx, (box) in enumerate(boxes_scale_i):
365
+ bboxes[idx] += box
366
+
367
+ # we just want one bbox for each label, not one for each scale
368
+ true_bboxes = cells_to_bboxes(
369
+ labels[2], anchor, S=S, is_preds=False
370
+ )
371
+
372
+ for idx in range(batch_size):
373
+ nms_boxes = non_max_suppression(
374
+ bboxes[idx],
375
+ iou_threshold=iou_threshold,
376
+ threshold=threshold,
377
+ box_format=box_format,
378
+ )
379
+
380
+ for nms_box in nms_boxes:
381
+ all_pred_boxes.append([train_idx] + nms_box)
382
+
383
+ for box in true_bboxes[idx]:
384
+ if box[1] > threshold:
385
+ all_true_boxes.append([train_idx] + box)
386
+
387
+ train_idx += 1
388
+
389
+
390
+ return all_pred_boxes, all_true_boxes
391
+
392
+ def cells_to_bboxes(predictions, anchors, S, is_preds=True):
393
+ """
394
+ Scales the predictions coming from the model to
395
+ be relative to the entire image such that they for example later
396
+ can be plotted or.
397
+ INPUT:
398
+ predictions: tensor of size (N, 3, S, S, num_classes+5)
399
+ anchors: the anchors used for the predictions
400
+ S: the number of cells the image is divided in on the width (and height)
401
+ is_preds: whether the input is predictions or the true bounding boxes
402
+ OUTPUT:
403
+ converted_bboxes: the converted boxes of sizes (N, num_anchors, S, S, 1+5) with class index,
404
+ object score, bounding box coordinates
405
+ """
406
+ BATCH_SIZE = predictions.shape[0]
407
+ num_anchors = len(anchors)
408
+ box_predictions = predictions[..., 1:5]
409
+ if is_preds:
410
+ anchors = anchors.reshape(1, len(anchors), 1, 1, 2)
411
+ box_predictions[..., 0:2] = torch.sigmoid(box_predictions[..., 0:2])
412
+ box_predictions[..., 2:] = torch.exp(box_predictions[..., 2:]) * anchors
413
+ scores = torch.sigmoid(predictions[..., 0:1])
414
+ best_class = torch.argmax(predictions[..., 5:], dim=-1).unsqueeze(-1)
415
+ else:
416
+ scores = predictions[..., 0:1]
417
+ best_class = predictions[..., 5:6]
418
+
419
+ cell_indices = (
420
+ torch.arange(S)
421
+ .repeat(predictions.shape[0], 3, S, 1)
422
+ .unsqueeze(-1)
423
+ .to(predictions.device)
424
+ )
425
+ x = 1 / S * (box_predictions[..., 0:1] + cell_indices)
426
+ y = 1 / S * (box_predictions[..., 1:2] + cell_indices.permute(0, 1, 3, 2, 4))
427
+ w_h = 1 / S * box_predictions[..., 2:4]
428
+ converted_bboxes = torch.cat((best_class, scores, x, y, w_h), dim=-1).reshape(BATCH_SIZE, num_anchors * S * S, 6)
429
+ return converted_bboxes.tolist()
430
+
431
+ def check_class_accuracy(model, loader, threshold):
432
+ model.eval()
433
+ tot_class_preds, correct_class = 0, 0
434
+ tot_noobj, correct_noobj = 0, 0
435
+ tot_obj, correct_obj = 0, 0
436
+
437
+ for idx, (x, y) in enumerate(tqdm(loader)):
438
+ x = x.to(config.DEVICE)
439
+ with torch.no_grad():
440
+ out = model(x)
441
+
442
+ for i in range(3):
443
+ y[i] = y[i].to(config.DEVICE)
444
+ obj = y[i][..., 0] == 1 # in paper this is Iobj_i
445
+ noobj = y[i][..., 0] == 0 # in paper this is Iobj_i
446
+
447
+ correct_class += torch.sum(
448
+ torch.argmax(out[i][..., 5:][obj], dim=-1) == y[i][..., 5][obj]
449
+ )
450
+ tot_class_preds += torch.sum(obj)
451
+
452
+ obj_preds = torch.sigmoid(out[i][..., 0]) > threshold
453
+ correct_obj += torch.sum(obj_preds[obj] == y[i][..., 0][obj])
454
+ tot_obj += torch.sum(obj)
455
+ correct_noobj += torch.sum(obj_preds[noobj] == y[i][..., 0][noobj])
456
+ tot_noobj += torch.sum(noobj)
457
+
458
+ print(f"Class accuracy is: {(correct_class/(tot_class_preds+1e-16))*100:2f}%")
459
+ print(f"No obj accuracy is: {(correct_noobj/(tot_noobj+1e-16))*100:2f}%")
460
+ print(f"Obj accuracy is: {(correct_obj/(tot_obj+1e-16))*100:2f}%")
461
+ model.train()
462
+
463
+
464
+ def get_mean_std(loader):
465
+ # var[X] = E[X**2] - E[X]**2
466
+ channels_sum, channels_sqrd_sum, num_batches = 0, 0, 0
467
+
468
+ for data, _ in tqdm(loader):
469
+ channels_sum += torch.mean(data, dim=[0, 2, 3])
470
+ channels_sqrd_sum += torch.mean(data ** 2, dim=[0, 2, 3])
471
+ num_batches += 1
472
+
473
+ mean = channels_sum / num_batches
474
+ std = (channels_sqrd_sum / num_batches - mean ** 2) ** 0.5
475
+
476
+ return mean, std
477
+
478
+
479
+ def save_checkpoint(model, optimizer, filename="my_checkpoint.pth.tar"):
480
+ print("=> Saving checkpoint")
481
+ checkpoint = {
482
+ "state_dict": model.state_dict(),
483
+ "optimizer": optimizer.state_dict(),
484
+ }
485
+ torch.save(checkpoint, filename)
486
+
487
+
488
+ def load_checkpoint(checkpoint_file, model, optimizer, lr):
489
+ print("=> Loading checkpoint")
490
+ checkpoint = torch.load(checkpoint_file, map_location=config.DEVICE)
491
+ model.load_state_dict(checkpoint["state_dict"])
492
+ optimizer.load_state_dict(checkpoint["optimizer"])
493
+
494
+ # If we don't do this then it will just have learning rate of old checkpoint
495
+ # and it will lead to many hours of debugging \:
496
+ for param_group in optimizer.param_groups:
497
+ param_group["lr"] = lr
498
+
499
+
500
+ def get_loaders(train_csv_path, test_csv_path):
501
+ from dataset import YOLODataset
502
+
503
+ IMAGE_SIZE = config.IMAGE_SIZE
504
+ train_dataset = YOLODataset(
505
+ train_csv_path,
506
+ transform=config.train_transforms,
507
+ S=[IMAGE_SIZE // 32, IMAGE_SIZE // 16, IMAGE_SIZE // 8],
508
+ img_dir=config.IMG_DIR,
509
+ label_dir=config.LABEL_DIR,
510
+ anchors=config.ANCHORS,
511
+ )
512
+ test_dataset = YOLODataset(
513
+ test_csv_path,
514
+ transform=config.test_transforms,
515
+ S=[IMAGE_SIZE // 32, IMAGE_SIZE // 16, IMAGE_SIZE // 8],
516
+ img_dir=config.IMG_DIR,
517
+ label_dir=config.LABEL_DIR,
518
+ anchors=config.ANCHORS,
519
+ )
520
+ train_loader = DataLoader(
521
+ dataset=train_dataset,
522
+ batch_size=config.BATCH_SIZE,
523
+ num_workers=config.NUM_WORKERS,
524
+ pin_memory=config.PIN_MEMORY,
525
+ shuffle=True,
526
+ drop_last=False,
527
+ )
528
+ test_loader = DataLoader(
529
+ dataset=test_dataset,
530
+ batch_size=config.BATCH_SIZE,
531
+ num_workers=config.NUM_WORKERS,
532
+ pin_memory=config.PIN_MEMORY,
533
+ shuffle=False,
534
+ drop_last=False,
535
+ )
536
+
537
+ train_eval_dataset = YOLODataset(
538
+ train_csv_path,
539
+ transform=config.test_transforms,
540
+ S=[IMAGE_SIZE // 32, IMAGE_SIZE // 16, IMAGE_SIZE // 8],
541
+ img_dir=config.IMG_DIR,
542
+ label_dir=config.LABEL_DIR,
543
+ anchors=config.ANCHORS,
544
+ )
545
+ train_eval_loader = DataLoader(
546
+ dataset=train_eval_dataset,
547
+ batch_size=config.BATCH_SIZE,
548
+ num_workers=config.NUM_WORKERS,
549
+ pin_memory=config.PIN_MEMORY,
550
+ shuffle=False,
551
+ drop_last=False,
552
+ )
553
+
554
+ return train_loader, test_loader, train_eval_loader
555
+
556
+ def plot_couple_examples(model, loader, thresh, iou_thresh, anchors):
557
+ model.eval()
558
+ x, y = next(iter(loader))
559
+ x = x.to("cuda")
560
+ with torch.no_grad():
561
+ out = model(x)
562
+ bboxes = [[] for _ in range(x.shape[0])]
563
+ for i in range(3):
564
+ batch_size, A, S, _, _ = out[i].shape
565
+ anchor = anchors[i]
566
+ boxes_scale_i = cells_to_bboxes(
567
+ out[i], anchor, S=S, is_preds=True
568
+ )
569
+ for idx, (box) in enumerate(boxes_scale_i):
570
+ bboxes[idx] += box
571
+
572
+ model.train()
573
+
574
+ for i in range(batch_size//4):
575
+ nms_boxes = non_max_suppression(
576
+ bboxes[i], iou_threshold=iou_thresh, threshold=thresh, box_format="midpoint",
577
+ )
578
+ plot_image(x[i].permute(1,2,0).detach().cpu(), nms_boxes)
579
+
580
+
581
+
582
+ def seed_everything(seed=42):
583
+ os.environ['PYTHONHASHSEED'] = str(seed)
584
+ random.seed(seed)
585
+ np.random.seed(seed)
586
+ torch.manual_seed(seed)
587
+ torch.cuda.manual_seed(seed)
588
+ torch.cuda.manual_seed_all(seed)
589
+ torch.backends.cudnn.deterministic = True
590
+ torch.backends.cudnn.benchmark = False
591
+
592
+
593
+ def clip_coords(boxes, img_shape):
594
+ # Clip bounding xyxy bounding boxes to image shape (height, width)
595
+ boxes[:, 0].clamp_(0, img_shape[1]) # x1
596
+ boxes[:, 1].clamp_(0, img_shape[0]) # y1
597
+ boxes[:, 2].clamp_(0, img_shape[1]) # x2
598
+ boxes[:, 3].clamp_(0, img_shape[0]) # y2
599
+
600
+ def xywhn2xyxy(x, w=640, h=640, padw=0, padh=0):
601
+ # Convert nx4 boxes from [x, y, w, h] normalized to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right
602
+ y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
603
+ y[..., 0] = w * (x[..., 0] - x[..., 2] / 2) + padw # top left x
604
+ y[..., 1] = h * (x[..., 1] - x[..., 3] / 2) + padh # top left y
605
+ y[..., 2] = w * (x[..., 0] + x[..., 2] / 2) + padw # bottom right x
606
+ y[..., 3] = h * (x[..., 1] + x[..., 3] / 2) + padh # bottom right y
607
+ return y
608
+
609
+
610
+ def xyn2xy(x, w=640, h=640, padw=0, padh=0):
611
+ # Convert normalized segments into pixel segments, shape (n,2)
612
+ y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
613
+ y[..., 0] = w * x[..., 0] + padw # top left x
614
+ y[..., 1] = h * x[..., 1] + padh # top left y
615
+ return y
616
+
617
+ def xyxy2xywhn(x, w=640, h=640, clip=False, eps=0.0):
618
+ # Convert nx4 boxes from [x1, y1, x2, y2] to [x, y, w, h] normalized where xy1=top-left, xy2=bottom-right
619
+ if clip:
620
+ clip_boxes(x, (h - eps, w - eps)) # warning: inplace clip
621
+ y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
622
+ y[..., 0] = ((x[..., 0] + x[..., 2]) / 2) / w # x center
623
+ y[..., 1] = ((x[..., 1] + x[..., 3]) / 2) / h # y center
624
+ y[..., 2] = (x[..., 2] - x[..., 0]) / w # width
625
+ y[..., 3] = (x[..., 3] - x[..., 1]) / h # height
626
+ return y
627
+
628
+ def clip_boxes(boxes, shape):
629
+ # Clip boxes (xyxy) to image shape (height, width)
630
+ if isinstance(boxes, torch.Tensor): # faster individually
631
+ boxes[..., 0].clamp_(0, shape[1]) # x1
632
+ boxes[..., 1].clamp_(0, shape[0]) # y1
633
+ boxes[..., 2].clamp_(0, shape[1]) # x2
634
+ boxes[..., 3].clamp_(0, shape[0]) # y2
635
+ else: # np.array (faster grouped)
636
+ boxes[..., [0, 2]] = boxes[..., [0, 2]].clip(0, shape[1]) # x1, x2
637
+ boxes[..., [1, 3]] = boxes[..., [1, 3]].clip(0, shape[0]) # y1, y2
yolov3.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from pytorch_lightning import LightningModule
3
+ from model import YOLOv3
4
+ from dataset import YOLODataset
5
+ from loss import YoloLoss
6
+ from torch import optim
7
+ from torch.utils.data import DataLoader
8
+ import config
9
+
10
+ class YOLOV3_PL(LightningModule):
11
+ def __init__(self, in_channels=3, num_classes=config.NUM_CLASSES, batch_size=config.BATCH_SIZE,
12
+ learning_rate=config.LEARNING_RATE , num_epochs=config.NUM_EPOCHS):
13
+ super(YOLOV3_PL, self).__init__()
14
+ self.model = YOLOv3(in_channels, num_classes)
15
+ self.criterion = YoloLoss()
16
+ self.batch_size = batch_size
17
+ self.learning_rate = learning_rate
18
+ self.num_epochs = num_epochs
19
+ self.scaled_anchors = config.SCALED_ANCHORS
20
+
21
+ def train_dataloader(self):
22
+ self.train_data = YOLODataset(
23
+ config.DATASET + '/train.csv',
24
+ transform=config.train_transforms,
25
+ img_dir=config.IMG_DIR,
26
+ label_dir=config.LABEL_DIR,
27
+ anchors=config.ANCHORS
28
+ )
29
+
30
+ train_dataloader = DataLoader(
31
+ dataset=self.train_data,
32
+ batch_size=self.batch_size,
33
+ num_workers=config.NUM_WORKERS,
34
+ pin_memory=config.PIN_MEMORY,
35
+ shuffle=True
36
+ )
37
+
38
+ return train_dataloader
39
+
40
+ def val_dataloader(self):
41
+
42
+ self.valid_data = YOLODataset(
43
+ config.DATASET + '/test.csv',
44
+ transform=config.test_transforms,
45
+ img_dir=config.IMG_DIR,
46
+ label_dir=config.LABEL_DIR,
47
+ anchors=config.ANCHORS
48
+ )
49
+
50
+ return DataLoader(
51
+ dataset=self.valid_data,
52
+ batch_size=self.batch_size,
53
+ num_workers=config.NUM_WORKERS,
54
+ pin_memory=config.PIN_MEMORY,
55
+ shuffle=False
56
+ )
57
+
58
+ def test_dataloader(self):
59
+ return self.val_dataloader()
60
+
61
+ def forward(self, x):
62
+ return self.model(x)
63
+
64
+ def training_step(self, batch, batch_idx):
65
+ x, y = batch
66
+ out = self.forward(x)
67
+ loss = self.criterion(out, y, self.scaled_anchors)
68
+ self.log(f"train_loss", loss, on_epoch=True, prog_bar=True, logger=True)
69
+
70
+ return loss
71
+
72
+ def validation_step(self, batch, batch_idx):
73
+ x, y = batch
74
+ out = self.forward(x)
75
+ loss = self.criterion(out, y, self.scaled_anchors)
76
+ self.log(f"val_loss", loss, on_epoch=True, prog_bar=True, logger=True)
77
+ return loss
78
+
79
+ def test_step(self, batch, batch_idx, dataloader_idx=0):
80
+ if isinstance(batch, (tuple, list)):
81
+ x, _ = batch
82
+ else:
83
+ x = batch
84
+ return self.forward(x)
85
+
86
+ def configure_optimizers(self):
87
+ optimizer = optim.Adam(self.parameters(), lr=self.learning_rate/100, weight_decay=config.WEIGHT_DECAY)
88
+ scheduler = optim.lr_scheduler.OneCycleLR(
89
+ optimizer,
90
+ max_lr=self.learning_rate,
91
+ steps_per_epoch=len(self.train_dataloader()),
92
+ epochs=self.num_epochs,
93
+ pct_start=0.2,
94
+ div_factor=10,
95
+ three_phase=False,
96
+ final_div_factor=10,
97
+ anneal_strategy='linear'
98
+ )
99
+ return {
100
+ 'optimizer': optimizer,
101
+ 'lr_scheduler': {
102
+ "scheduler": scheduler,
103
+ "interval": "step",
104
+ }
105
+ }
106
+
107
+
108
+
109
+
110
+
111
+ def main():
112
+ num_classes = 20
113
+ IMAGE_SIZE = 416
114
+ INPUT_SIZE = IMAGE_SIZE
115
+ model = YOLOV3_PL(num_classes=num_classes)
116
+ from torchinfo import summary
117
+ print(summary(model, input_size=(2, 3, INPUT_SIZE, INPUT_SIZE)))
118
+ inp = torch.randn((2, 3, INPUT_SIZE, INPUT_SIZE))
119
+ out = model(inp)
120
+ assert out[0].shape == (2, 3, IMAGE_SIZE//32, IMAGE_SIZE//32, num_classes + 5)
121
+ assert out[1].shape == (2, 3, IMAGE_SIZE//16, IMAGE_SIZE//16, num_classes + 5)
122
+ assert out[2].shape == (2, 3, IMAGE_SIZE//8, IMAGE_SIZE//8, num_classes + 5)
123
+ print("Success!")
124
+
125
+
126
+ if __name__ == "__main__":
127
+ main()