mkthoma commited on
Commit
be6ec35
·
1 Parent(s): 698d751

code library push

Browse files
custom_library/callbacks.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import lightning.pytorch as pl
2
+ from . import config
3
+ from .utils import (check_class_accuracy,get_evaluation_bboxes,mean_average_precision,plot_couple_examples)
4
+ from lightning.pytorch.callbacks import Callback
5
+
6
+
7
+ class plot_examples_callback(Callback):
8
+ def __init__(self, epoch_interval: int = 5) -> None:
9
+ super().__init__()
10
+ self.epoch_interval = epoch_interval
11
+
12
+ def on_train_epoch_end(self, trainer: pl.Trainer, pl_module: pl.LightningModule) -> None:
13
+ if (trainer.current_epoch + 1) % self.epoch_interval == 0:
14
+ plot_couple_examples(
15
+ model=pl_module,
16
+ loader=pl_module.train_dataloader(),
17
+ thresh=0.6,
18
+ iou_thresh=0.5,
19
+ anchors=pl_module.scaled_anchors,
20
+ )
21
+
22
+
23
+ class class_accuracy_callback(pl.Callback):
24
+ def __init__(self, train_epoch_interval: int = 1, test_epoch_interval: int = 10) -> None:
25
+ super().__init__()
26
+ self.train_epoch_interval = train_epoch_interval
27
+ self.test_epoch_interval = test_epoch_interval
28
+
29
+ def on_train_epoch_end(self, trainer: pl.Trainer, pl_module: pl.LightningModule) -> None:
30
+ if (trainer.current_epoch + 1) % self.train_epoch_interval == 0:
31
+ class_acc, no_obj_acc, obj_acc = check_class_accuracy(model=pl_module, loader=pl_module.train_dataloader(), threshold=config.CONF_THRESHOLD)
32
+ class_acc = round(class_acc.item(),2)
33
+ no_obj_acc = round(no_obj_acc.item(),2)
34
+ obj_acc = round(obj_acc.item(),2)
35
+
36
+ pl_module.log_dict(
37
+ {
38
+ "train_class_acc": class_acc,
39
+ "train_no_obj_acc": no_obj_acc,
40
+ "train_obj_acc": obj_acc,
41
+ },
42
+ logger=True,
43
+ )
44
+ print(f"Epoch: {trainer.current_epoch + 1}")
45
+ print("Train Metrics")
46
+ print(f"Loss: {trainer.callback_metrics['train_loss_epoch']}")
47
+ print(f"Class Accuracy: {class_acc:2f}%")
48
+ print(f"No Object Accuracy: {no_obj_acc:2f}%")
49
+ print(f"Object Accuracy: {obj_acc:2f}%")
50
+
51
+ if (trainer.current_epoch + 1) % self.test_epoch_interval == 0:
52
+ class_acc, no_obj_acc, obj_acc = check_class_accuracy(model=pl_module, loader=pl_module.test_dataloader(), threshold=config.CONF_THRESHOLD)
53
+ class_acc = round(class_acc.item(),2)
54
+ no_obj_acc = round(no_obj_acc.item(),2)
55
+ obj_acc = round(obj_acc.item(),2)
56
+
57
+ pl_module.log_dict(
58
+ {
59
+ "test_class_acc": class_acc,
60
+ "test_no_obj_acc": no_obj_acc,
61
+ "test_obj_acc": obj_acc,
62
+ },
63
+ logger=True,
64
+ )
65
+
66
+ print("Test Metrics")
67
+ print(f"Class Accuracy: {class_acc:2f}%")
68
+ print(f"No Object Accuracy: {no_obj_acc:2f}%")
69
+ print(f"Object Accuracy: {obj_acc:2f}%")
70
+
71
+ class map_callback(pl.Callback):
72
+ def __init__(self, epoch_interval: int = 10) -> None:
73
+ super().__init__()
74
+ self.epoch_interval = epoch_interval
75
+
76
+ def on_train_epoch_end(self, trainer: pl.Trainer, pl_module: pl.LightningModule) -> None:
77
+ if (trainer.current_epoch + 1) % self.epoch_interval == 0:
78
+ pred_boxes, true_boxes = get_evaluation_bboxes(loader=pl_module.test_dataloader(), model=pl_module, iou_threshold=config.NMS_IOU_THRESH, anchors=config.ANCHORS, threshold=config.CONF_THRESHOLD, device=config.DEVICE,)
79
+
80
+ map_val = mean_average_precision(pred_boxes=pred_boxes, true_boxes=true_boxes, iou_threshold=config.MAP_IOU_THRESH, box_format="midpoint", num_classes=config.NUM_CLASSES)
81
+ print("MAP: ", map_val.item())
82
+ pl_module.log("MAP",map_val.item(),logger=True)
83
+ pl_module.train()
custom_library/config.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import albumentations as A
2
+ import cv2
3
+ import torch
4
+ import os
5
+ from albumentations.pytorch import ToTensorV2
6
+ # from utils import seed_everything
7
+
8
+ DATASET = 'PASCAL_VOC'
9
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
10
+ # seed_everything() # If you want deterministic behavior
11
+ NUM_WORKERS = os.cpu_count()-1
12
+ BATCH_SIZE = 16
13
+ IMAGE_SIZE = 416
14
+ NUM_CLASSES = 20
15
+ LEARNING_RATE = 1e-5
16
+ WEIGHT_DECAY = 1e-4
17
+ NUM_EPOCHS = 100
18
+ CONF_THRESHOLD = 0.05
19
+ MAP_IOU_THRESH = 0.5
20
+ NMS_IOU_THRESH = 0.45
21
+ S = [IMAGE_SIZE // 32, IMAGE_SIZE // 16, IMAGE_SIZE // 8]
22
+ PIN_MEMORY = True
23
+ LOAD_MODEL = False
24
+ SAVE_MODEL = True
25
+ CHECKPOINT_FILE = "checkpoint.pth.tar"
26
+ IMG_DIR = DATASET + "/images/"
27
+ LABEL_DIR = DATASET + "/labels/"
28
+ CHECKPOINT_PATH = "checkpoints/"
29
+
30
+ ANCHORS = [
31
+ [(0.28, 0.22), (0.38, 0.48), (0.9, 0.78)],
32
+ [(0.07, 0.15), (0.15, 0.11), (0.14, 0.29)],
33
+ [(0.02, 0.03), (0.04, 0.07), (0.08, 0.06)],
34
+ ] # Note these have been rescaled to be between [0, 1]
35
+
36
+ means = [0.485, 0.456, 0.406]
37
+
38
+ scale = 1.1
39
+ train_transforms = A.Compose(
40
+ [
41
+ A.LongestMaxSize(max_size=int(IMAGE_SIZE * scale)),
42
+ A.PadIfNeeded(
43
+ min_height=int(IMAGE_SIZE * scale),
44
+ min_width=int(IMAGE_SIZE * scale),
45
+ border_mode=cv2.BORDER_CONSTANT,
46
+ ),
47
+ A.Rotate(limit = 10, interpolation=1, border_mode=4),
48
+ A.RandomCrop(width=IMAGE_SIZE, height=IMAGE_SIZE),
49
+ A.ColorJitter(brightness=0.6, contrast=0.6, saturation=0.6, hue=0.6, p=0.4),
50
+ A.OneOf(
51
+ [
52
+ A.ShiftScaleRotate(
53
+ rotate_limit=20, p=0.5, border_mode=cv2.BORDER_CONSTANT
54
+ ),
55
+ # A.Affine(shear=15, p=0.5, mode="constant"),
56
+ ],
57
+ p=1.0,
58
+ ),
59
+ A.HorizontalFlip(p=0.5),
60
+ A.Blur(p=0.1),
61
+ A.CLAHE(p=0.1),
62
+ A.Posterize(p=0.1),
63
+ A.ToGray(p=0.1),
64
+ A.ChannelShuffle(p=0.05),
65
+ A.Normalize(mean=[0, 0, 0], std=[1, 1, 1], max_pixel_value=255,),
66
+ ToTensorV2(),
67
+ ],
68
+ bbox_params=A.BboxParams(format="yolo", min_visibility=0.4, label_fields=[],),
69
+ )
70
+ test_transforms = A.Compose(
71
+ [
72
+ A.LongestMaxSize(max_size=IMAGE_SIZE),
73
+ A.PadIfNeeded(
74
+ min_height=IMAGE_SIZE, min_width=IMAGE_SIZE, border_mode=cv2.BORDER_CONSTANT
75
+ ),
76
+ A.Normalize(mean=[0, 0, 0], std=[1, 1, 1], max_pixel_value=255,),
77
+ ToTensorV2(),
78
+ ],
79
+ bbox_params=A.BboxParams(format="yolo", min_visibility=0.4, label_fields=[]),
80
+ )
81
+
82
+ PASCAL_CLASSES = [
83
+ "aeroplane",
84
+ "bicycle",
85
+ "bird",
86
+ "boat",
87
+ "bottle",
88
+ "bus",
89
+ "car",
90
+ "cat",
91
+ "chair",
92
+ "cow",
93
+ "diningtable",
94
+ "dog",
95
+ "horse",
96
+ "motorbike",
97
+ "person",
98
+ "pottedplant",
99
+ "sheep",
100
+ "sofa",
101
+ "train",
102
+ "tvmonitor"
103
+ ]
custom_library/dataset.py ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Creates a Pytorch dataset to load the Pascal VOC & MS COCO datasets
3
+ """
4
+
5
+ from . import config
6
+ import numpy as np
7
+ import os
8
+ import pandas as pd
9
+ import torch
10
+ from .utils import xywhn2xyxy, xyxy2xywhn
11
+ import random
12
+
13
+ from PIL import Image, ImageFile
14
+ from torch.utils.data import Dataset, DataLoader
15
+ from .utils import (
16
+ cells_to_bboxes,
17
+ iou_width_height as iou,
18
+ non_max_suppression as nms,
19
+ plot_image
20
+ )
21
+
22
+ ImageFile.LOAD_TRUNCATED_IMAGES = True
23
+
24
+ class YOLOTrainDataset(Dataset):
25
+ def __init__(
26
+ self,
27
+ csv_file,
28
+ img_dir,
29
+ label_dir,
30
+ anchors,
31
+ image_size=config.IMAGE_SIZE,
32
+ S=[13, 26, 52],
33
+ C=20,
34
+ transform=None,
35
+ ):
36
+ self.annotations = pd.read_csv(csv_file)
37
+ self.img_dir = img_dir
38
+ self.label_dir = label_dir
39
+ self.image_size = image_size
40
+ self.mosaic_border = [image_size // 2, image_size // 2]
41
+ self.transform = transform
42
+ self.S = S
43
+ self.anchors = torch.tensor(anchors[0] + anchors[1] + anchors[2]) # for all 3 scales
44
+ self.num_anchors = self.anchors.shape[0]
45
+ self.num_anchors_per_scale = self.num_anchors // 3
46
+ self.C = C
47
+ self.ignore_iou_thresh = 0.5
48
+ self.counter = 0
49
+
50
+ def __len__(self):
51
+ return len(self.annotations)
52
+
53
+ def load_mosaic(self, index):
54
+ # YOLOv5 4-mosaic loader. Loads 1 image + 3 random images into a 4-image mosaic
55
+ labels4 = []
56
+ s = self.image_size
57
+ yc, xc = (int(random.uniform(x, 2 * s - x)) for x in self.mosaic_border) # mosaic center x, y
58
+ indices = [index] + random.choices(range(len(self)), k=3) # 3 additional image indices
59
+ random.shuffle(indices)
60
+ for i, index in enumerate(indices):
61
+ # Load image
62
+ label_path = os.path.join(self.label_dir, self.annotations.iloc[index, 1])
63
+ bboxes = np.roll(np.loadtxt(fname=label_path, delimiter=" ", ndmin=2), 4, axis=1).tolist()
64
+ img_path = os.path.join(self.img_dir, self.annotations.iloc[index, 0])
65
+ img = np.array(Image.open(img_path).convert("RGB"))
66
+
67
+
68
+ h, w = img.shape[0], img.shape[1]
69
+ labels = np.array(bboxes)
70
+
71
+ # place img in img4
72
+ if i == 0: # top left
73
+ img4 = np.full((s * 2, s * 2, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles
74
+ x1a, y1a, x2a, y2a = max(xc - w, 0), max(yc - h, 0), xc, yc # xmin, ymin, xmax, ymax (large image)
75
+ x1b, y1b, x2b, y2b = w - (x2a - x1a), h - (y2a - y1a), w, h # xmin, ymin, xmax, ymax (small image)
76
+ elif i == 1: # top right
77
+ x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, s * 2), yc
78
+ x1b, y1b, x2b, y2b = 0, h - (y2a - y1a), min(w, x2a - x1a), h
79
+ elif i == 2: # bottom left
80
+ x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(s * 2, yc + h)
81
+ x1b, y1b, x2b, y2b = w - (x2a - x1a), 0, w, min(y2a - y1a, h)
82
+ elif i == 3: # bottom right
83
+ x1a, y1a, x2a, y2a = xc, yc, min(xc + w, s * 2), min(s * 2, yc + h)
84
+ x1b, y1b, x2b, y2b = 0, 0, min(w, x2a - x1a), min(y2a - y1a, h)
85
+
86
+ img4[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b] # img4[ymin:ymax, xmin:xmax]
87
+ padw = x1a - x1b
88
+ padh = y1a - y1b
89
+
90
+ # Labels
91
+ if labels.size:
92
+ labels[:, :-1] = xywhn2xyxy(labels[:, :-1], w, h, padw, padh) # normalized xywh to pixel xyxy format
93
+ labels4.append(labels)
94
+
95
+ # Concat/clip labels
96
+ labels4 = np.concatenate(labels4, 0)
97
+ for x in (labels4[:, :-1],):
98
+ np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective()
99
+ # img4, labels4 = replicate(img4, labels4) # replicate
100
+ labels4[:, :-1] = xyxy2xywhn(labels4[:, :-1], 2 * s, 2 * s)
101
+ labels4[:, :-1] = np.clip(labels4[:, :-1], 0, 1)
102
+ labels4 = labels4[labels4[:, 2] > 0]
103
+ labels4 = labels4[labels4[:, 3] > 0]
104
+ return img4, labels4
105
+
106
+ def __getitem__(self, index):
107
+
108
+ # 75% probability to apply mosaic
109
+ self.counter = (self.counter + 1) % 4
110
+ if self.counter != 0:
111
+ image, bboxes = self.load_mosaic(index)
112
+ # Else, load normally without mosaic
113
+ else:
114
+ # Load image and bbox
115
+ label_path = os.path.join(self.label_dir, self.annotations.iloc[index, 1])
116
+ bboxes = np.roll(np.loadtxt(fname=label_path, delimiter=" ", ndmin=2), 4, axis=1).tolist()
117
+ img_path = os.path.join(self.img_dir, self.annotations.iloc[index, 0])
118
+ image = np.array(Image.open(img_path).convert("RGB"))
119
+
120
+ if self.transform:
121
+ augmentations = self.transform(image=image, bboxes=bboxes)
122
+ image = augmentations["image"]
123
+ bboxes = augmentations["bboxes"]
124
+
125
+ # Below assumes 3 scale predictions (as paper) and same num of anchors per scale
126
+ targets = [torch.zeros((self.num_anchors // 3, S, S, 6)) for S in self.S]
127
+ for box in bboxes:
128
+ iou_anchors = iou(torch.tensor(box[2:4]), self.anchors)
129
+ anchor_indices = iou_anchors.argsort(descending=True, dim=0)
130
+ x, y, width, height, class_label = box
131
+ has_anchor = [False] * 3 # each scale should have one anchor
132
+ for anchor_idx in anchor_indices:
133
+ scale_idx = anchor_idx // self.num_anchors_per_scale
134
+ anchor_on_scale = anchor_idx % self.num_anchors_per_scale
135
+ S = self.S[scale_idx]
136
+ i, j = int(S * y), int(S * x) # which cell
137
+ anchor_taken = targets[scale_idx][anchor_on_scale, i, j, 0]
138
+ if not anchor_taken and not has_anchor[scale_idx]:
139
+ targets[scale_idx][anchor_on_scale, i, j, 0] = 1
140
+ x_cell, y_cell = S * x - j, S * y - i # both between [0,1]
141
+ width_cell, height_cell = (
142
+ width * S,
143
+ height * S,
144
+ ) # can be greater than 1 since it's relative to cell
145
+ box_coordinates = torch.tensor(
146
+ [x_cell, y_cell, width_cell, height_cell]
147
+ )
148
+ targets[scale_idx][anchor_on_scale, i, j, 1:5] = box_coordinates
149
+ targets[scale_idx][anchor_on_scale, i, j, 5] = int(class_label)
150
+ has_anchor[scale_idx] = True
151
+
152
+ elif not anchor_taken and iou_anchors[anchor_idx] > self.ignore_iou_thresh:
153
+ targets[scale_idx][anchor_on_scale, i, j, 0] = -1 # ignore prediction
154
+
155
+ return image, tuple(targets)
156
+
157
+ class YOLOTestDataset(Dataset):
158
+ def __init__(
159
+ self,
160
+ csv_file,
161
+ img_dir,
162
+ label_dir,
163
+ anchors,
164
+ image_size=config.IMAGE_SIZE,
165
+ S=[13, 26, 52],
166
+ C=20,
167
+ transform=None,
168
+ ):
169
+ self.annotations = pd.read_csv(csv_file)
170
+ self.img_dir = img_dir
171
+ self.label_dir = label_dir
172
+ self.image_size = image_size
173
+ self.transform = transform
174
+ self.S = S
175
+ self.anchors = torch.tensor(anchors[0] + anchors[1] + anchors[2]) # for all 3 scales
176
+ self.num_anchors = self.anchors.shape[0]
177
+ self.num_anchors_per_scale = self.num_anchors // 3
178
+ self.C = C
179
+ self.ignore_iou_thresh = 0.5
180
+
181
+ def __len__(self):
182
+ return len(self.annotations)
183
+
184
+ def __getitem__(self, index):
185
+ label_path = os.path.join(self.label_dir, self.annotations.iloc[index, 1])
186
+ bboxes = np.roll(np.loadtxt(fname=label_path, delimiter=" ", ndmin=2), 4, axis=1).tolist()
187
+ img_path = os.path.join(self.img_dir, self.annotations.iloc[index, 0])
188
+ image = np.array(Image.open(img_path).convert("RGB"))
189
+
190
+ if self.transform:
191
+ augmentations = self.transform(image=image, bboxes=bboxes)
192
+ image = augmentations["image"]
193
+ bboxes = augmentations["bboxes"]
194
+
195
+ # Below assumes 3 scale predictions (as paper) and same num of anchors per scale
196
+ targets = [torch.zeros((self.num_anchors // 3, S, S, 6)) for S in self.S]
197
+ for box in bboxes:
198
+ iou_anchors = iou(torch.tensor(box[2:4]), self.anchors)
199
+ anchor_indices = iou_anchors.argsort(descending=True, dim=0)
200
+ x, y, width, height, class_label = box
201
+ has_anchor = [False] * 3 # each scale should have one anchor
202
+ for anchor_idx in anchor_indices:
203
+ scale_idx = anchor_idx // self.num_anchors_per_scale
204
+ anchor_on_scale = anchor_idx % self.num_anchors_per_scale
205
+ S = self.S[scale_idx]
206
+ i, j = int(S * y), int(S * x) # which cell
207
+ anchor_taken = targets[scale_idx][anchor_on_scale, i, j, 0]
208
+ if not anchor_taken and not has_anchor[scale_idx]:
209
+ targets[scale_idx][anchor_on_scale, i, j, 0] = 1
210
+ x_cell, y_cell = S * x - j, S * y - i # both between [0,1]
211
+ width_cell, height_cell = (
212
+ width * S,
213
+ height * S,
214
+ ) # can be greater than 1 since it's relative to cell
215
+ box_coordinates = torch.tensor(
216
+ [x_cell, y_cell, width_cell, height_cell]
217
+ )
218
+ targets[scale_idx][anchor_on_scale, i, j, 1:5] = box_coordinates
219
+ targets[scale_idx][anchor_on_scale, i, j, 5] = int(class_label)
220
+ has_anchor[scale_idx] = True
221
+
222
+ elif not anchor_taken and iou_anchors[anchor_idx] > self.ignore_iou_thresh:
223
+ targets[scale_idx][anchor_on_scale, i, j, 0] = -1 # ignore prediction
224
+
225
+ return image, tuple(targets)
226
+
custom_library/lightning_model.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.optim as optim
3
+ import lightning.pytorch as pl
4
+ from tqdm import tqdm
5
+ from .model import YOLOv3
6
+ from .loss import YoloLoss
7
+ from .utils import get_loaders, load_checkpoint, check_class_accuracy, intersection_over_union
8
+ from . import config
9
+ from torch.optim.lr_scheduler import OneCycleLR
10
+
11
+
12
+ class YOLOv3Lightning(pl.LightningModule):
13
+ def __init__(self, config, lr_value=0):
14
+ super().__init__()
15
+ self.automatic_optimization =True
16
+ self.config = config
17
+ self.model = YOLOv3(num_classes=self.config.NUM_CLASSES)
18
+ self.loss_fn = YoloLoss()
19
+
20
+ if lr_value == 0:
21
+ self.learning_rate = self.config.LEARNING_RATE
22
+ else:
23
+ self.learning_rate = lr_value
24
+
25
+ def forward(self, x):
26
+ return self.model(x)
27
+
28
+ def configure_optimizers(self):
29
+ optimizer = optim.Adam(self.model.parameters(), lr=self.config.LEARNING_RATE, weight_decay=self.config.WEIGHT_DECAY)
30
+ EPOCHS = self.config.NUM_EPOCHS * 2 // 5
31
+ scheduler = OneCycleLR(optimizer, max_lr=1E-3, steps_per_epoch=len(self.train_dataloader()), epochs=EPOCHS, pct_start=5/EPOCHS, div_factor=100, three_phase=False, final_div_factor=100, anneal_strategy='linear')
32
+ return [optimizer], [{"scheduler": scheduler, "interval": "step", "frequency": 1}]
33
+
34
+ def train_dataloader(self):
35
+ train_loader, _, _ = get_loaders(
36
+ train_csv_path=self.config.DATASET + "/train.csv",
37
+ test_csv_path=self.config.DATASET + "/test.csv",
38
+ )
39
+ return train_loader
40
+
41
+ def training_step(self, batch, batch_idx):
42
+ x, y = batch
43
+ y0, y1, y2 = (y[0].to(self.device),y[1].to(self.device),y[2].to(self.device))
44
+ out = self(x)
45
+
46
+ loss = (self.loss_fn(out[0], y0, self.scaled_anchors[0])
47
+ + self.loss_fn(out[1], y1, self.scaled_anchors[1])
48
+ + self.loss_fn(out[2], y2, self.scaled_anchors[2]))
49
+
50
+ self.log('train_loss', loss, prog_bar=True, logger=True, on_step=True, on_epoch=True)
51
+ return loss
52
+
53
+ def val_dataloader(self):
54
+ _, _, val_loader = get_loaders(
55
+ train_csv_path=self.config.DATASET + "/train.csv",
56
+ test_csv_path=self.config.DATASET + "/test.csv",
57
+ )
58
+
59
+ return val_loader
60
+
61
+ def validation_step(self, batch, batch_idx):
62
+ x, y = batch
63
+ y0, y1, y2 = (
64
+ y[0].to(self.device),
65
+ y[1].to(self.device),
66
+ y[2].to(self.device),
67
+ )
68
+ out = self(x)
69
+ loss = (
70
+ self.loss_fn(out[0], y0, self.scaled_anchors[0])
71
+ + self.loss_fn(out[1], y1, self.scaled_anchors[1])
72
+ + self.loss_fn(out[2], y2, self.scaled_anchors[2])
73
+ )
74
+
75
+ self.log('val_loss', loss, prog_bar=True, logger=True, on_step=True, on_epoch=True)
76
+
77
+
78
+ def test_dataloader(self):
79
+ _, test_loader, _ = get_loaders(
80
+ train_csv_path=self.config.DATASET + "/train.csv",
81
+ test_csv_path=self.config.DATASET + "/test.csv",
82
+ )
83
+ return test_loader
84
+
85
+ def test_step(self, batch, batch_idx):
86
+ x, y = batch
87
+ y0, y1, y2 = (
88
+ y[0].to(self.device),
89
+ y[1].to(self.device),
90
+ y[2].to(self.device),
91
+ )
92
+ out = self(x)
93
+ loss = (
94
+ self.loss_fn(out[0], y0, self.scaled_anchors[0])
95
+ + self.loss_fn(out[1], y1, self.scaled_anchors[1])
96
+ + self.loss_fn(out[2], y2, self.scaled_anchors[2])
97
+ )
98
+ self.log('test_loss', loss, prog_bar=True, logger=True, on_step=True, on_epoch=True)
99
+
100
+ def on_train_start(self):
101
+ if self.config.LOAD_MODEL:
102
+ load_checkpoint(self.config.CHECKPOINT_FILE, self.model, self.optimizers(), self.config.LEARNING_RATE)
103
+ self.scaled_anchors = (
104
+ torch.tensor(self.config.ANCHORS)
105
+ * torch.tensor(self.config.S).unsqueeze(1).unsqueeze(1).repeat(1, 3, 2)
106
+ ).to(self.device)
107
+
108
+
custom_library/loss.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Implementation of Yolo Loss Function similar to the one in Yolov3 paper,
3
+ the difference from what I can tell is I use CrossEntropy for the classes
4
+ instead of BinaryCrossEntropy.
5
+ """
6
+ import random
7
+ import torch
8
+ import torch.nn as nn
9
+ import lightning.pytorch as pl
10
+ from .utils import intersection_over_union
11
+
12
+
13
+ class YoloLoss(pl.LightningModule):
14
+ def __init__(self):
15
+ super().__init__()
16
+ self.mse = nn.MSELoss()
17
+ self.bce = nn.BCEWithLogitsLoss()
18
+ self.entropy = nn.CrossEntropyLoss()
19
+ self.sigmoid = nn.Sigmoid()
20
+
21
+ # Constants signifying how much to pay for each respective part of the loss
22
+ self.lambda_class = 1
23
+ self.lambda_noobj = 10
24
+ self.lambda_obj = 1
25
+ self.lambda_box = 10
26
+
27
+ def forward(self, predictions, target, anchors):
28
+ # Check where obj and noobj (we ignore if target == -1)
29
+ obj = target[..., 0] == 1 # in paper this is Iobj_i
30
+ noobj = target[..., 0] == 0 # in paper this is Inoobj_i
31
+
32
+ # ======================= #
33
+ # FOR NO OBJECT LOSS #
34
+ # ======================= #
35
+
36
+ no_object_loss = self.bce(
37
+ (predictions[..., 0:1][noobj]), (target[..., 0:1][noobj]),
38
+ )
39
+
40
+ # ==================== #
41
+ # FOR OBJECT LOSS #
42
+ # ==================== #
43
+
44
+ anchors = anchors.reshape(1, 3, 1, 1, 2)
45
+ box_preds = torch.cat([self.sigmoid(predictions[..., 1:3]), torch.exp(predictions[..., 3:5]) * anchors], dim=-1)
46
+ ious = intersection_over_union(box_preds[obj], target[..., 1:5][obj]).detach()
47
+ object_loss = self.mse(self.sigmoid(predictions[..., 0:1][obj]), ious * target[..., 0:1][obj])
48
+
49
+ # ======================== #
50
+ # FOR BOX COORDINATES #
51
+ # ======================== #
52
+
53
+ predictions[..., 1:3] = self.sigmoid(predictions[..., 1:3]) # x,y coordinates
54
+ target[..., 3:5] = torch.log(
55
+ (1e-16 + target[..., 3:5] / anchors)
56
+ ) # width, height coordinates
57
+ box_loss = self.mse(predictions[..., 1:5][obj], target[..., 1:5][obj])
58
+
59
+ # ================== #
60
+ # FOR CLASS LOSS #
61
+ # ================== #
62
+
63
+ class_loss = self.entropy(
64
+ (predictions[..., 5:][obj]), (target[..., 5][obj].long()),
65
+ )
66
+
67
+ #print("__________________________________")
68
+ #print(self.lambda_box * box_loss)
69
+ #print(self.lambda_obj * object_loss)
70
+ #print(self.lambda_noobj * no_object_loss)
71
+ #print(self.lambda_class * class_loss)
72
+ #print("\n")
73
+
74
+ return (
75
+ self.lambda_box * box_loss
76
+ + self.lambda_obj * object_loss
77
+ + self.lambda_noobj * no_object_loss
78
+ + self.lambda_class * class_loss
79
+ )
custom_library/model.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Implementation of YOLOv3 architecture
3
+ """
4
+
5
+ import torch
6
+ import torch.nn as nn
7
+ from . import config
8
+
9
+ """
10
+ Information about architecture config:
11
+ Tuple is structured by (filters, kernel_size, stride)
12
+ Every conv is a same convolution.
13
+ List is structured by "B" indicating a residual block followed by the number of repeats
14
+ "S" is for scale prediction block and computing the yolo loss
15
+ "U" is for upsampling the feature map and concatenating with a previous layer
16
+ """
17
+ config = [
18
+ (32, 3, 1),
19
+ (64, 3, 2),
20
+ ["B", 1],
21
+ (128, 3, 2),
22
+ ["B", 2],
23
+ (256, 3, 2),
24
+ ["B", 8],
25
+ (512, 3, 2),
26
+ ["B", 8],
27
+ (1024, 3, 2),
28
+ ["B", 4], # To this point is Darknet-53
29
+ (512, 1, 1),
30
+ (1024, 3, 1),
31
+ "S",
32
+ (256, 1, 1),
33
+ "U",
34
+ (256, 1, 1),
35
+ (512, 3, 1),
36
+ "S",
37
+ (128, 1, 1),
38
+ "U",
39
+ (128, 1, 1),
40
+ (256, 3, 1),
41
+ "S",
42
+ ]
43
+
44
+
45
+ class CNNBlock(nn.Module):
46
+ def __init__(self, in_channels, out_channels, bn_act=True, **kwargs):
47
+ super().__init__()
48
+ self.conv = nn.Conv2d(in_channels, out_channels, bias=not bn_act, **kwargs)
49
+ self.bn = nn.BatchNorm2d(out_channels)
50
+ self.leaky = nn.LeakyReLU(0.1)
51
+ self.use_bn_act = bn_act
52
+
53
+ def forward(self, x):
54
+ if self.use_bn_act:
55
+ return self.leaky(self.bn(self.conv(x)))
56
+ else:
57
+ return self.conv(x)
58
+
59
+
60
+ class ResidualBlock(nn.Module):
61
+ def __init__(self, channels, use_residual=True, num_repeats=1):
62
+ super().__init__()
63
+ self.layers = nn.ModuleList()
64
+ for repeat in range(num_repeats):
65
+ self.layers += [
66
+ nn.Sequential(
67
+ CNNBlock(channels, channels // 2, kernel_size=1),
68
+ CNNBlock(channels // 2, channels, kernel_size=3, padding=1),
69
+ )
70
+ ]
71
+
72
+ self.use_residual = use_residual
73
+ self.num_repeats = num_repeats
74
+
75
+ def forward(self, x):
76
+ for layer in self.layers:
77
+ if self.use_residual:
78
+ x = x + layer(x)
79
+ else:
80
+ x = layer(x)
81
+
82
+ return x
83
+
84
+
85
+ class ScalePrediction(nn.Module):
86
+ def __init__(self, in_channels, num_classes):
87
+ super().__init__()
88
+ self.pred = nn.Sequential(
89
+ CNNBlock(in_channels, 2 * in_channels, kernel_size=3, padding=1),
90
+ CNNBlock(
91
+ 2 * in_channels, (num_classes + 5) * 3, bn_act=False, kernel_size=1
92
+ ),
93
+ )
94
+ self.num_classes = num_classes
95
+
96
+ def forward(self, x):
97
+ return (
98
+ self.pred(x)
99
+ .reshape(x.shape[0], 3, self.num_classes + 5, x.shape[2], x.shape[3])
100
+ .permute(0, 1, 3, 4, 2)
101
+ )
102
+
103
+
104
+ class YOLOv3(nn.Module):
105
+ def __init__(self, in_channels=3, num_classes=80):
106
+ super().__init__()
107
+ self.num_classes = num_classes
108
+ self.in_channels = in_channels
109
+ self.layers = self._create_conv_layers()
110
+
111
+ def forward(self, x):
112
+ outputs = [] # for each scale
113
+ route_connections = []
114
+ for layer in self.layers:
115
+ if isinstance(layer, ScalePrediction):
116
+ outputs.append(layer(x))
117
+ continue
118
+
119
+ x = layer(x)
120
+
121
+ if isinstance(layer, ResidualBlock) and layer.num_repeats == 8:
122
+ route_connections.append(x)
123
+
124
+ elif isinstance(layer, nn.Upsample):
125
+ x = torch.cat([x, route_connections[-1]], dim=1)
126
+ route_connections.pop()
127
+
128
+ return outputs
129
+
130
+ def _create_conv_layers(self):
131
+ layers = nn.ModuleList()
132
+ in_channels = self.in_channels
133
+
134
+ for module in config:
135
+ if isinstance(module, tuple):
136
+ out_channels, kernel_size, stride = module
137
+ layers.append(
138
+ CNNBlock(
139
+ in_channels,
140
+ out_channels,
141
+ kernel_size=kernel_size,
142
+ stride=stride,
143
+ padding=1 if kernel_size == 3 else 0,
144
+ )
145
+ )
146
+ in_channels = out_channels
147
+
148
+ elif isinstance(module, list):
149
+ num_repeats = module[1]
150
+ layers.append(ResidualBlock(in_channels, num_repeats=num_repeats,))
151
+
152
+ elif isinstance(module, str):
153
+ if module == "S":
154
+ layers += [
155
+ ResidualBlock(in_channels, use_residual=False, num_repeats=1),
156
+ CNNBlock(in_channels, in_channels // 2, kernel_size=1),
157
+ ScalePrediction(in_channels // 2, num_classes=self.num_classes),
158
+ ]
159
+ in_channels = in_channels // 2
160
+
161
+ elif module == "U":
162
+ layers.append(nn.Upsample(scale_factor=2),)
163
+ in_channels = in_channels * 3
164
+
165
+ return layers
166
+
167
+
168
+ if __name__ == "__main__":
169
+ num_classes = 20
170
+ IMAGE_SIZE = config.IMAGE_SIZE
171
+ model = YOLOv3(num_classes=num_classes)
172
+ x = torch.randn((2, 3, IMAGE_SIZE, IMAGE_SIZE))
173
+ out = model(x)
174
+ assert model(x)[0].shape == (2, 3, IMAGE_SIZE//32, IMAGE_SIZE//32, num_classes + 5)
175
+ assert model(x)[1].shape == (2, 3, IMAGE_SIZE//16, IMAGE_SIZE//16, num_classes + 5)
176
+ assert model(x)[2].shape == (2, 3, IMAGE_SIZE//8, IMAGE_SIZE//8, num_classes + 5)
177
+ print("Success!")
custom_library/utils.py ADDED
@@ -0,0 +1,586 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from . 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.notebook import tqdm
12
+
13
+
14
+
15
+ def iou_width_height(boxes1, boxes2):
16
+ """
17
+ Parameters:
18
+ boxes1 (tensor): width and height of the first bounding boxes
19
+ boxes2 (tensor): width and height of the second bounding boxes
20
+ Returns:
21
+ tensor: Intersection over union of the corresponding boxes
22
+ """
23
+ intersection = torch.min(boxes1[..., 0], boxes2[..., 0]) * torch.min(
24
+ boxes1[..., 1], boxes2[..., 1]
25
+ )
26
+ union = (
27
+ boxes1[..., 0] * boxes1[..., 1] + boxes2[..., 0] * boxes2[..., 1] - intersection
28
+ )
29
+ return intersection / union
30
+
31
+
32
+ def intersection_over_union(boxes_preds, boxes_labels, box_format="midpoint"):
33
+ """
34
+ Video explanation of this function:
35
+ https://youtu.be/XXYG5ZWtjj0
36
+
37
+ This function calculates intersection over union (iou) given pred boxes
38
+ and target boxes.
39
+
40
+ Parameters:
41
+ boxes_preds (tensor): Predictions of Bounding Boxes (BATCH_SIZE, 4)
42
+ boxes_labels (tensor): Correct labels of Bounding Boxes (BATCH_SIZE, 4)
43
+ box_format (str): midpoint/corners, if boxes (x,y,w,h) or (x1,y1,x2,y2)
44
+
45
+ Returns:
46
+ tensor: Intersection over union for all examples
47
+ """
48
+
49
+ if box_format == "midpoint":
50
+ box1_x1 = boxes_preds[..., 0:1] - boxes_preds[..., 2:3] / 2
51
+ box1_y1 = boxes_preds[..., 1:2] - boxes_preds[..., 3:4] / 2
52
+ box1_x2 = boxes_preds[..., 0:1] + boxes_preds[..., 2:3] / 2
53
+ box1_y2 = boxes_preds[..., 1:2] + boxes_preds[..., 3:4] / 2
54
+ box2_x1 = boxes_labels[..., 0:1] - boxes_labels[..., 2:3] / 2
55
+ box2_y1 = boxes_labels[..., 1:2] - boxes_labels[..., 3:4] / 2
56
+ box2_x2 = boxes_labels[..., 0:1] + boxes_labels[..., 2:3] / 2
57
+ box2_y2 = boxes_labels[..., 1:2] + boxes_labels[..., 3:4] / 2
58
+
59
+ if box_format == "corners":
60
+ box1_x1 = boxes_preds[..., 0:1]
61
+ box1_y1 = boxes_preds[..., 1:2]
62
+ box1_x2 = boxes_preds[..., 2:3]
63
+ box1_y2 = boxes_preds[..., 3:4]
64
+ box2_x1 = boxes_labels[..., 0:1]
65
+ box2_y1 = boxes_labels[..., 1:2]
66
+ box2_x2 = boxes_labels[..., 2:3]
67
+ box2_y2 = boxes_labels[..., 3:4]
68
+
69
+ x1 = torch.max(box1_x1, box2_x1)
70
+ y1 = torch.max(box1_y1, box2_y1)
71
+ x2 = torch.min(box1_x2, box2_x2)
72
+ y2 = torch.min(box1_y2, box2_y2)
73
+
74
+ intersection = (x2 - x1).clamp(0) * (y2 - y1).clamp(0)
75
+ box1_area = abs((box1_x2 - box1_x1) * (box1_y2 - box1_y1))
76
+ box2_area = abs((box2_x2 - box2_x1) * (box2_y2 - box2_y1))
77
+
78
+ return intersection / (box1_area + box2_area - intersection + 1e-6)
79
+
80
+
81
+ def non_max_suppression(bboxes, iou_threshold, threshold, box_format="corners"):
82
+ """
83
+ Video explanation of this function:
84
+ https://youtu.be/YDkjWEN8jNA
85
+
86
+ Does Non Max Suppression given bboxes
87
+
88
+ Parameters:
89
+ bboxes (list): list of lists containing all bboxes with each bboxes
90
+ specified as [class_pred, prob_score, x1, y1, x2, y2]
91
+ iou_threshold (float): threshold where predicted bboxes is correct
92
+ threshold (float): threshold to remove predicted bboxes (independent of IoU)
93
+ box_format (str): "midpoint" or "corners" used to specify bboxes
94
+
95
+ Returns:
96
+ list: bboxes after performing NMS given a specific IoU threshold
97
+ """
98
+
99
+ assert type(bboxes) == list
100
+
101
+ bboxes = [box for box in bboxes if box[1] > threshold]
102
+ bboxes = sorted(bboxes, key=lambda x: x[1], reverse=True)
103
+ bboxes_after_nms = []
104
+
105
+ while bboxes:
106
+ chosen_box = bboxes.pop(0)
107
+
108
+ bboxes = [
109
+ box
110
+ for box in bboxes
111
+ if box[0] != chosen_box[0]
112
+ or intersection_over_union(
113
+ torch.tensor(chosen_box[2:]),
114
+ torch.tensor(box[2:]),
115
+ box_format=box_format,
116
+ )
117
+ < iou_threshold
118
+ ]
119
+
120
+ bboxes_after_nms.append(chosen_box)
121
+
122
+ return bboxes_after_nms
123
+
124
+
125
+ def mean_average_precision(
126
+ pred_boxes, true_boxes, iou_threshold=0.5, box_format="midpoint", num_classes=20
127
+ ):
128
+ """
129
+ Video explanation of this function:
130
+ https://youtu.be/FppOzcDvaDI
131
+
132
+ This function calculates mean average precision (mAP)
133
+
134
+ Parameters:
135
+ pred_boxes (list): list of lists containing all bboxes with each bboxes
136
+ specified as [train_idx, class_prediction, prob_score, x1, y1, x2, y2]
137
+ true_boxes (list): Similar as pred_boxes except all the correct ones
138
+ iou_threshold (float): threshold where predicted bboxes is correct
139
+ box_format (str): "midpoint" or "corners" used to specify bboxes
140
+ num_classes (int): number of classes
141
+
142
+ Returns:
143
+ float: mAP value across all classes given a specific IoU threshold
144
+ """
145
+
146
+ # list storing all AP for respective classes
147
+ average_precisions = []
148
+
149
+ # used for numerical stability later on
150
+ epsilon = 1e-6
151
+
152
+ for c in range(num_classes):
153
+ detections = []
154
+ ground_truths = []
155
+
156
+ # Go through all predictions and targets,
157
+ # and only add the ones that belong to the
158
+ # current class c
159
+ for detection in pred_boxes:
160
+ if detection[1] == c:
161
+ detections.append(detection)
162
+
163
+ for true_box in true_boxes:
164
+ if true_box[1] == c:
165
+ ground_truths.append(true_box)
166
+
167
+ # find the amount of bboxes for each training example
168
+ # Counter here finds how many ground truth bboxes we get
169
+ # for each training example, so let's say img 0 has 3,
170
+ # img 1 has 5 then we will obtain a dictionary with:
171
+ # amount_bboxes = {0:3, 1:5}
172
+ amount_bboxes = Counter([gt[0] for gt in ground_truths])
173
+
174
+ # We then go through each key, val in this dictionary
175
+ # and convert to the following (w.r.t same example):
176
+ # ammount_bboxes = {0:torch.tensor[0,0,0], 1:torch.tensor[0,0,0,0,0]}
177
+ for key, val in amount_bboxes.items():
178
+ amount_bboxes[key] = torch.zeros(val)
179
+
180
+ # sort by box probabilities which is index 2
181
+ detections.sort(key=lambda x: x[2], reverse=True)
182
+ TP = torch.zeros((len(detections)))
183
+ FP = torch.zeros((len(detections)))
184
+ total_true_bboxes = len(ground_truths)
185
+
186
+ # If none exists for this class then we can safely skip
187
+ if total_true_bboxes == 0:
188
+ continue
189
+
190
+ for detection_idx, detection in enumerate(detections):
191
+ # Only take out the ground_truths that have the same
192
+ # training idx as detection
193
+ ground_truth_img = [
194
+ bbox for bbox in ground_truths if bbox[0] == detection[0]
195
+ ]
196
+
197
+ num_gts = len(ground_truth_img)
198
+ best_iou = 0
199
+
200
+ for idx, gt in enumerate(ground_truth_img):
201
+ iou = intersection_over_union(
202
+ torch.tensor(detection[3:]),
203
+ torch.tensor(gt[3:]),
204
+ box_format=box_format,
205
+ )
206
+
207
+ if iou > best_iou:
208
+ best_iou = iou
209
+ best_gt_idx = idx
210
+
211
+ if best_iou > iou_threshold:
212
+ # only detect ground truth detection once
213
+ if amount_bboxes[detection[0]][best_gt_idx] == 0:
214
+ # true positive and add this bounding box to seen
215
+ TP[detection_idx] = 1
216
+ amount_bboxes[detection[0]][best_gt_idx] = 1
217
+ else:
218
+ FP[detection_idx] = 1
219
+
220
+ # if IOU is lower then the detection is a false positive
221
+ else:
222
+ FP[detection_idx] = 1
223
+
224
+ TP_cumsum = torch.cumsum(TP, dim=0)
225
+ FP_cumsum = torch.cumsum(FP, dim=0)
226
+ recalls = TP_cumsum / (total_true_bboxes + epsilon)
227
+ precisions = TP_cumsum / (TP_cumsum + FP_cumsum + epsilon)
228
+ precisions = torch.cat((torch.tensor([1]), precisions))
229
+ recalls = torch.cat((torch.tensor([0]), recalls))
230
+ # torch.trapz for numerical integration
231
+ average_precisions.append(torch.trapz(precisions, recalls))
232
+
233
+ return sum(average_precisions) / len(average_precisions)
234
+
235
+
236
+ def plot_image(image, boxes):
237
+ """Plots predicted bounding boxes on the image"""
238
+ cmap = plt.get_cmap("tab20b")
239
+ class_labels = config.COCO_LABELS if config.DATASET=='COCO' else config.PASCAL_CLASSES
240
+ colors = [cmap(i) for i in np.linspace(0, 1, len(class_labels))]
241
+ im = np.array(image)
242
+ height, width, _ = im.shape
243
+
244
+ # Create figure and axes
245
+ fig, ax = plt.subplots(1)
246
+ # Display the image
247
+ ax.imshow(im)
248
+
249
+ # box[0] is x midpoint, box[2] is width
250
+ # box[1] is y midpoint, box[3] is height
251
+
252
+ # Create a Rectangle patch
253
+ for box in boxes:
254
+ assert len(box) == 6, "box should contain class pred, confidence, x, y, width, height"
255
+ class_pred = box[0]
256
+ box = box[2:]
257
+ upper_left_x = box[0] - box[2] / 2
258
+ upper_left_y = box[1] - box[3] / 2
259
+ rect = patches.Rectangle(
260
+ (upper_left_x * width, upper_left_y * height),
261
+ box[2] * width,
262
+ box[3] * height,
263
+ linewidth=2,
264
+ edgecolor=colors[int(class_pred)],
265
+ facecolor="none",
266
+ )
267
+ # Add the patch to the Axes
268
+ ax.add_patch(rect)
269
+ plt.text(
270
+ upper_left_x * width,
271
+ upper_left_y * height,
272
+ s=class_labels[int(class_pred)],
273
+ color="white",
274
+ verticalalignment="top",
275
+ bbox={"color": colors[int(class_pred)], "pad": 0},
276
+ )
277
+
278
+ plt.show()
279
+
280
+
281
+ def get_evaluation_bboxes(
282
+ loader,
283
+ model,
284
+ iou_threshold,
285
+ anchors,
286
+ threshold,
287
+ box_format="midpoint",
288
+ device="cuda",
289
+ ):
290
+ # make sure model is in eval before get bboxes
291
+ model.eval()
292
+ train_idx = 0
293
+ all_pred_boxes = []
294
+ all_true_boxes = []
295
+ for batch_idx, (x, labels) in enumerate(tqdm(loader)):
296
+ x = x.to(device)
297
+
298
+ with torch.no_grad():
299
+ predictions = model(x)
300
+
301
+ batch_size = x.shape[0]
302
+ bboxes = [[] for _ in range(batch_size)]
303
+ for i in range(3):
304
+ S = predictions[i].shape[2]
305
+ anchor = torch.tensor([*anchors[i]]).to(device) * S
306
+ boxes_scale_i = cells_to_bboxes(
307
+ predictions[i], anchor, S=S, is_preds=True
308
+ )
309
+ for idx, (box) in enumerate(boxes_scale_i):
310
+ bboxes[idx] += box
311
+
312
+ # we just want one bbox for each label, not one for each scale
313
+ true_bboxes = cells_to_bboxes(
314
+ labels[2], anchor, S=S, is_preds=False
315
+ )
316
+
317
+ for idx in range(batch_size):
318
+ nms_boxes = non_max_suppression(
319
+ bboxes[idx],
320
+ iou_threshold=iou_threshold,
321
+ threshold=threshold,
322
+ box_format=box_format,
323
+ )
324
+
325
+ for nms_box in nms_boxes:
326
+ all_pred_boxes.append([train_idx] + nms_box)
327
+
328
+ for box in true_bboxes[idx]:
329
+ if box[1] > threshold:
330
+ all_true_boxes.append([train_idx] + box)
331
+
332
+ train_idx += 1
333
+
334
+ model.train()
335
+ return all_pred_boxes, all_true_boxes
336
+
337
+
338
+ def cells_to_bboxes(predictions, anchors, S, is_preds=True):
339
+ """
340
+ Scales the predictions coming from the model to
341
+ be relative to the entire image such that they for example later
342
+ can be plotted or.
343
+ INPUT:
344
+ predictions: tensor of size (N, 3, S, S, num_classes+5)
345
+ anchors: the anchors used for the predictions
346
+ S: the number of cells the image is divided in on the width (and height)
347
+ is_preds: whether the input is predictions or the true bounding boxes
348
+ OUTPUT:
349
+ converted_bboxes: the converted boxes of sizes (N, num_anchors, S, S, 1+5) with class index,
350
+ object score, bounding box coordinates
351
+ """
352
+ BATCH_SIZE = predictions.shape[0]
353
+ num_anchors = len(anchors)
354
+ box_predictions = predictions[..., 1:5]
355
+ if is_preds:
356
+ anchors = anchors.reshape(1, len(anchors), 1, 1, 2)
357
+ box_predictions[..., 0:2] = torch.sigmoid(box_predictions[..., 0:2])
358
+ box_predictions[..., 2:] = torch.exp(box_predictions[..., 2:]) * anchors
359
+ scores = torch.sigmoid(predictions[..., 0:1])
360
+ best_class = torch.argmax(predictions[..., 5:], dim=-1).unsqueeze(-1)
361
+ else:
362
+ scores = predictions[..., 0:1]
363
+ best_class = predictions[..., 5:6]
364
+
365
+ cell_indices = (
366
+ torch.arange(S)
367
+ .repeat(predictions.shape[0], 3, S, 1)
368
+ .unsqueeze(-1)
369
+ .to(predictions.device)
370
+ )
371
+ x = 1 / S * (box_predictions[..., 0:1] + cell_indices)
372
+ y = 1 / S * (box_predictions[..., 1:2] + cell_indices.permute(0, 1, 3, 2, 4))
373
+ w_h = 1 / S * box_predictions[..., 2:4]
374
+ converted_bboxes = torch.cat((best_class, scores, x, y, w_h), dim=-1).reshape(BATCH_SIZE, num_anchors * S * S, 6)
375
+ return converted_bboxes.tolist()
376
+
377
+ def check_class_accuracy(model, loader, threshold):
378
+ # model.eval()
379
+ tot_class_preds, correct_class = 0, 0
380
+ tot_noobj, correct_noobj = 0, 0
381
+ tot_obj, correct_obj = 0, 0
382
+
383
+ for idx, (x, y) in enumerate(tqdm(loader)):
384
+ x = x.to(config.DEVICE)
385
+ with torch.no_grad():
386
+ out = model(x)
387
+
388
+ for i in range(3):
389
+ y[i] = y[i].to(config.DEVICE)
390
+ obj = y[i][..., 0] == 1 # in paper this is Iobj_i
391
+ noobj = y[i][..., 0] == 0 # in paper this is Iobj_i
392
+
393
+ correct_class += torch.sum(
394
+ torch.argmax(out[i][..., 5:][obj], dim=-1) == y[i][..., 5][obj]
395
+ )
396
+ tot_class_preds += torch.sum(obj)
397
+
398
+ obj_preds = torch.sigmoid(out[i][..., 0]) > threshold
399
+ correct_obj += torch.sum(obj_preds[obj] == y[i][..., 0][obj])
400
+ tot_obj += torch.sum(obj)
401
+ correct_noobj += torch.sum(obj_preds[noobj] == y[i][..., 0][noobj])
402
+ tot_noobj += torch.sum(noobj)
403
+
404
+ # print(f"Class accuracy is: {(correct_class/(tot_class_preds+1e-16))*100:2f}%")
405
+ # print(f"No obj accuracy is: {(correct_noobj/(tot_noobj+1e-16))*100:2f}%")
406
+ # print(f"Obj accuracy is: {(correct_obj/(tot_obj+1e-16))*100:2f}%")
407
+ # model.train()
408
+ class_acc = (correct_class / (tot_class_preds + 1e-16)) * 100
409
+ no_obj_acc = (correct_noobj / (tot_noobj + 1e-16)) * 100
410
+ obj_acc = (correct_obj / (tot_obj + 1e-16)) * 100
411
+ return class_acc, no_obj_acc, obj_acc
412
+
413
+ def get_mean_std(loader):
414
+ # var[X] = E[X**2] - E[X]**2
415
+ channels_sum, channels_sqrd_sum, num_batches = 0, 0, 0
416
+
417
+ for data, _ in tqdm(loader):
418
+ channels_sum += torch.mean(data, dim=[0, 2, 3])
419
+ channels_sqrd_sum += torch.mean(data ** 2, dim=[0, 2, 3])
420
+ num_batches += 1
421
+
422
+ mean = channels_sum / num_batches
423
+ std = (channels_sqrd_sum / num_batches - mean ** 2) ** 0.5
424
+
425
+ return mean, std
426
+
427
+
428
+ def save_checkpoint(model, optimizer, filename="my_checkpoint.pth.tar"):
429
+ print("=> Saving checkpoint")
430
+ checkpoint = {
431
+ "state_dict": model.state_dict(),
432
+ "optimizer": optimizer.state_dict(),
433
+ }
434
+ torch.save(checkpoint, filename)
435
+
436
+
437
+ def load_checkpoint(checkpoint_file, model, optimizer, lr):
438
+ print("=> Loading checkpoint")
439
+ checkpoint = torch.load(checkpoint_file, map_location=config.DEVICE)
440
+ model.load_state_dict(checkpoint["state_dict"])
441
+ optimizer.load_state_dict(checkpoint["optimizer"])
442
+
443
+ # If we don't do this then it will just have learning rate of old checkpoint
444
+ # and it will lead to many hours of debugging \:
445
+ for param_group in optimizer.param_groups:
446
+ param_group["lr"] = lr
447
+
448
+
449
+ def get_loaders(train_csv_path, test_csv_path):
450
+ from .dataset import YOLOTrainDataset, YOLOTestDataset
451
+
452
+ IMAGE_SIZE = config.IMAGE_SIZE
453
+ train_dataset = YOLOTrainDataset(
454
+ train_csv_path,
455
+ transform=config.train_transforms,
456
+ S=[IMAGE_SIZE // 32, IMAGE_SIZE // 16, IMAGE_SIZE // 8],
457
+ img_dir=config.IMG_DIR,
458
+ label_dir=config.LABEL_DIR,
459
+ anchors=config.ANCHORS,
460
+ )
461
+ test_dataset = YOLOTestDataset(
462
+ test_csv_path,
463
+ transform=config.test_transforms,
464
+ S=[IMAGE_SIZE // 32, IMAGE_SIZE // 16, IMAGE_SIZE // 8],
465
+ img_dir=config.IMG_DIR,
466
+ label_dir=config.LABEL_DIR,
467
+ anchors=config.ANCHORS,
468
+ )
469
+ train_loader = DataLoader(
470
+ dataset=train_dataset,
471
+ batch_size=config.BATCH_SIZE,
472
+ num_workers=config.NUM_WORKERS,
473
+ pin_memory=config.PIN_MEMORY,
474
+ shuffle=True,
475
+ drop_last=False,
476
+ )
477
+ test_loader = DataLoader(
478
+ dataset=test_dataset,
479
+ batch_size=config.BATCH_SIZE,
480
+ num_workers=config.NUM_WORKERS,
481
+ pin_memory=config.PIN_MEMORY,
482
+ shuffle=False,
483
+ drop_last=False,
484
+ )
485
+
486
+ train_eval_dataset = YOLOTestDataset(
487
+ train_csv_path,
488
+ transform=config.test_transforms,
489
+ S=[IMAGE_SIZE // 32, IMAGE_SIZE // 16, IMAGE_SIZE // 8],
490
+ img_dir=config.IMG_DIR,
491
+ label_dir=config.LABEL_DIR,
492
+ anchors=config.ANCHORS,
493
+ )
494
+ train_eval_loader = DataLoader(
495
+ dataset=train_eval_dataset,
496
+ batch_size=config.BATCH_SIZE,
497
+ num_workers=config.NUM_WORKERS,
498
+ pin_memory=config.PIN_MEMORY,
499
+ shuffle=False,
500
+ drop_last=False,
501
+ )
502
+
503
+ return train_loader, test_loader, train_eval_loader
504
+
505
+ def plot_couple_examples(model, loader, thresh, iou_thresh, anchors):
506
+ model.eval()
507
+ x, y = next(iter(loader))
508
+ x = x.to("cuda")
509
+ with torch.no_grad():
510
+ out = model(x)
511
+ bboxes = [[] for _ in range(x.shape[0])]
512
+ for i in range(3):
513
+ batch_size, A, S, _, _ = out[i].shape
514
+ anchor = anchors[i]
515
+ boxes_scale_i = cells_to_bboxes(
516
+ out[i], anchor, S=S, is_preds=True
517
+ )
518
+ for idx, (box) in enumerate(boxes_scale_i):
519
+ bboxes[idx] += box
520
+
521
+ model.train()
522
+
523
+ for i in range(batch_size//4):
524
+ nms_boxes = non_max_suppression(
525
+ bboxes[i], iou_threshold=iou_thresh, threshold=thresh, box_format="midpoint",
526
+ )
527
+ plot_image(x[i].permute(1,2,0).detach().cpu(), nms_boxes)
528
+
529
+
530
+
531
+ # def seed_everything(seed=42):
532
+ # os.environ['PYTHONHASHSEED'] = str(seed)
533
+ # random.seed(seed)
534
+ # np.random.seed(seed)
535
+ # torch.manual_seed(seed)
536
+ # torch.cuda.manual_seed(seed)
537
+ # torch.cuda.manual_seed_all(seed)
538
+ # torch.backends.cudnn.deterministic = True
539
+ # torch.backends.cudnn.benchmark = False
540
+
541
+
542
+ def clip_coords(boxes, img_shape):
543
+ # Clip bounding xyxy bounding boxes to image shape (height, width)
544
+ boxes[:, 0].clamp_(0, img_shape[1]) # x1
545
+ boxes[:, 1].clamp_(0, img_shape[0]) # y1
546
+ boxes[:, 2].clamp_(0, img_shape[1]) # x2
547
+ boxes[:, 3].clamp_(0, img_shape[0]) # y2
548
+
549
+ def xywhn2xyxy(x, w=640, h=640, padw=0, padh=0):
550
+ # Convert nx4 boxes from [x, y, w, h] normalized to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right
551
+ y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
552
+ y[..., 0] = w * (x[..., 0] - x[..., 2] / 2) + padw # top left x
553
+ y[..., 1] = h * (x[..., 1] - x[..., 3] / 2) + padh # top left y
554
+ y[..., 2] = w * (x[..., 0] + x[..., 2] / 2) + padw # bottom right x
555
+ y[..., 3] = h * (x[..., 1] + x[..., 3] / 2) + padh # bottom right y
556
+ return y
557
+
558
+
559
+ def xyn2xy(x, w=640, h=640, padw=0, padh=0):
560
+ # Convert normalized segments into pixel segments, shape (n,2)
561
+ y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
562
+ y[..., 0] = w * x[..., 0] + padw # top left x
563
+ y[..., 1] = h * x[..., 1] + padh # top left y
564
+ return y
565
+
566
+ def xyxy2xywhn(x, w=640, h=640, clip=False, eps=0.0):
567
+ # Convert nx4 boxes from [x1, y1, x2, y2] to [x, y, w, h] normalized where xy1=top-left, xy2=bottom-right
568
+ if clip:
569
+ clip_boxes(x, (h - eps, w - eps)) # warning: inplace clip
570
+ y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
571
+ y[..., 0] = ((x[..., 0] + x[..., 2]) / 2) / w # x center
572
+ y[..., 1] = ((x[..., 1] + x[..., 3]) / 2) / h # y center
573
+ y[..., 2] = (x[..., 2] - x[..., 0]) / w # width
574
+ y[..., 3] = (x[..., 3] - x[..., 1]) / h # height
575
+ return y
576
+
577
+ def clip_boxes(boxes, shape):
578
+ # Clip boxes (xyxy) to image shape (height, width)
579
+ if isinstance(boxes, torch.Tensor): # faster individually
580
+ boxes[..., 0].clamp_(0, shape[1]) # x1
581
+ boxes[..., 1].clamp_(0, shape[0]) # y1
582
+ boxes[..., 2].clamp_(0, shape[1]) # x2
583
+ boxes[..., 3].clamp_(0, shape[0]) # y2
584
+ else: # np.array (faster grouped)
585
+ boxes[..., [0, 2]] = boxes[..., [0, 2]].clip(0, shape[1]) # x1, x2
586
+ boxes[..., [1, 3]] = boxes[..., [1, 3]].clip(0, shape[0]) # y1, y2