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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import albumentations as A
|
| 2 |
+
import cv2
|
| 3 |
+
import torch
|
| 4 |
+
import os
|
| 5 |
+
|
| 6 |
+
from albumentations.pytorch import ToTensorV2
|
| 7 |
+
# from utils import seed_everything
|
| 8 |
+
|
| 9 |
+
DATASET = 'PASCAL_VOC'
|
| 10 |
+
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 11 |
+
# seed_everything() # If you want deterministic behavior
|
| 12 |
+
|
| 13 |
+
IN_CHANNELS = 3
|
| 14 |
+
NUM_WORKERS = os.cpu_count() - 2
|
| 15 |
+
BATCH_SIZE = 32
|
| 16 |
+
IMAGE_SIZE = 416
|
| 17 |
+
NUM_CLASSES = 20
|
| 18 |
+
LEARNING_RATE = 1e-5
|
| 19 |
+
MAX_LEARNING_RATE = 5e-4
|
| 20 |
+
WEIGHT_DECAY = 1e-4
|
| 21 |
+
NUM_EPOCHS = 100
|
| 22 |
+
CONF_THRESHOLD = 0.05
|
| 23 |
+
MAP_IOU_THRESH = 0.5
|
| 24 |
+
NMS_IOU_THRESH = 0.45
|
| 25 |
+
S = [IMAGE_SIZE // 32, IMAGE_SIZE // 16, IMAGE_SIZE // 8]
|
| 26 |
+
PIN_MEMORY = True
|
| 27 |
+
LOAD_MODEL = False
|
| 28 |
+
SAVE_MODEL = True
|
| 29 |
+
CHECKPOINT_FILE = "checkpoint.pth.tar"
|
| 30 |
+
IMG_DIR = DATASET + "/images/"
|
| 31 |
+
LABEL_DIR = DATASET + "/labels/"
|
| 32 |
+
MOSAIC_PROB_TRAIN = 0.75
|
| 33 |
+
MOSAIC_PROB_TEST = 0.
|
| 34 |
+
|
| 35 |
+
ANCHORS = [
|
| 36 |
+
[(0.28, 0.22), (0.38, 0.48), (0.9, 0.78)],
|
| 37 |
+
[(0.07, 0.15), (0.15, 0.11), (0.14, 0.29)],
|
| 38 |
+
[(0.02, 0.03), (0.04, 0.07), (0.08, 0.06)],
|
| 39 |
+
] # Note these have been rescaled to be between [0, 1]
|
| 40 |
+
|
| 41 |
+
means = [0.485, 0.456, 0.406]
|
| 42 |
+
|
| 43 |
+
scale = 1.1
|
| 44 |
+
train_transforms = A.Compose(
|
| 45 |
+
[
|
| 46 |
+
A.LongestMaxSize(max_size=int(IMAGE_SIZE * scale)),
|
| 47 |
+
A.PadIfNeeded(
|
| 48 |
+
min_height=int(IMAGE_SIZE * scale),
|
| 49 |
+
min_width=int(IMAGE_SIZE * scale),
|
| 50 |
+
border_mode=cv2.BORDER_CONSTANT,
|
| 51 |
+
),
|
| 52 |
+
A.Rotate(limit = 10, interpolation=1, border_mode=4),
|
| 53 |
+
A.RandomCrop(width=IMAGE_SIZE, height=IMAGE_SIZE),
|
| 54 |
+
A.ColorJitter(brightness=0.6, contrast=0.6, saturation=0.6, hue=0.6, p=0.4),
|
| 55 |
+
A.OneOf(
|
| 56 |
+
[
|
| 57 |
+
A.ShiftScaleRotate(
|
| 58 |
+
rotate_limit=20, p=0.5, border_mode=cv2.BORDER_CONSTANT
|
| 59 |
+
),
|
| 60 |
+
# A.Affine(shear=15, p=0.5, mode="constant"),
|
| 61 |
+
],
|
| 62 |
+
p=1.0,
|
| 63 |
+
),
|
| 64 |
+
A.HorizontalFlip(p=0.5),
|
| 65 |
+
A.Blur(p=0.1),
|
| 66 |
+
A.CLAHE(p=0.1),
|
| 67 |
+
A.Posterize(p=0.1),
|
| 68 |
+
A.ToGray(p=0.1),
|
| 69 |
+
A.ChannelShuffle(p=0.05),
|
| 70 |
+
A.Normalize(mean=[0, 0, 0], std=[1, 1, 1], max_pixel_value=255,),
|
| 71 |
+
ToTensorV2(),
|
| 72 |
+
],
|
| 73 |
+
bbox_params=A.BboxParams(format="yolo", min_visibility=0.4, label_fields=[],),
|
| 74 |
+
)
|
| 75 |
+
test_transforms = A.Compose(
|
| 76 |
+
[
|
| 77 |
+
A.LongestMaxSize(max_size=IMAGE_SIZE),
|
| 78 |
+
A.PadIfNeeded(
|
| 79 |
+
min_height=IMAGE_SIZE, min_width=IMAGE_SIZE, border_mode=cv2.BORDER_CONSTANT
|
| 80 |
+
),
|
| 81 |
+
A.Normalize(mean=[0, 0, 0], std=[1, 1, 1], max_pixel_value=255,),
|
| 82 |
+
ToTensorV2(),
|
| 83 |
+
],
|
| 84 |
+
bbox_params=A.BboxParams(format="yolo", min_visibility=0.4, label_fields=[]),
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
infer_transforms = A.Compose(
|
| 88 |
+
[
|
| 89 |
+
A.LongestMaxSize(max_size=IMAGE_SIZE),
|
| 90 |
+
A.PadIfNeeded(
|
| 91 |
+
min_height=IMAGE_SIZE, min_width=IMAGE_SIZE, border_mode=cv2.BORDER_CONSTANT
|
| 92 |
+
),
|
| 93 |
+
A.Normalize(mean=[0, 0, 0], std=[1, 1, 1], max_pixel_value=255,),
|
| 94 |
+
ToTensorV2(),
|
| 95 |
+
])
|
| 96 |
+
|
| 97 |
+
infer_transforms_visualization = A.Compose(
|
| 98 |
+
[
|
| 99 |
+
A.LongestMaxSize(max_size=IMAGE_SIZE),
|
| 100 |
+
A.PadIfNeeded(
|
| 101 |
+
min_height=IMAGE_SIZE, min_width=IMAGE_SIZE, border_mode=cv2.BORDER_CONSTANT
|
| 102 |
+
),
|
| 103 |
+
ToTensorV2(),
|
| 104 |
+
])
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
SCALED_ANCHORS = (
|
| 108 |
+
torch.tensor(ANCHORS) * torch.tensor(S).unsqueeze(1).unsqueeze(1).repeat(1, 3, 2)
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
PASCAL_CLASSES = [
|
| 113 |
+
"aeroplane",
|
| 114 |
+
"bicycle",
|
| 115 |
+
"bird",
|
| 116 |
+
"boat",
|
| 117 |
+
"bottle",
|
| 118 |
+
"bus",
|
| 119 |
+
"car",
|
| 120 |
+
"cat",
|
| 121 |
+
"chair",
|
| 122 |
+
"cow",
|
| 123 |
+
"diningtable",
|
| 124 |
+
"dog",
|
| 125 |
+
"horse",
|
| 126 |
+
"motorbike",
|
| 127 |
+
"person",
|
| 128 |
+
"pottedplant",
|
| 129 |
+
"sheep",
|
| 130 |
+
"sofa",
|
| 131 |
+
"train",
|
| 132 |
+
"tvmonitor"
|
| 133 |
+
]
|
| 134 |
+
|
| 135 |
+
COCO_LABELS = ['person',
|
| 136 |
+
'bicycle',
|
| 137 |
+
'car',
|
| 138 |
+
'motorcycle',
|
| 139 |
+
'airplane',
|
| 140 |
+
'bus',
|
| 141 |
+
'train',
|
| 142 |
+
'truck',
|
| 143 |
+
'boat',
|
| 144 |
+
'traffic light',
|
| 145 |
+
'fire hydrant',
|
| 146 |
+
'stop sign',
|
| 147 |
+
'parking meter',
|
| 148 |
+
'bench',
|
| 149 |
+
'bird',
|
| 150 |
+
'cat',
|
| 151 |
+
'dog',
|
| 152 |
+
'horse',
|
| 153 |
+
'sheep',
|
| 154 |
+
'cow',
|
| 155 |
+
'elephant',
|
| 156 |
+
'bear',
|
| 157 |
+
'zebra',
|
| 158 |
+
'giraffe',
|
| 159 |
+
'backpack',
|
| 160 |
+
'umbrella',
|
| 161 |
+
'handbag',
|
| 162 |
+
'tie',
|
| 163 |
+
'suitcase',
|
| 164 |
+
'frisbee',
|
| 165 |
+
'skis',
|
| 166 |
+
'snowboard',
|
| 167 |
+
'sports ball',
|
| 168 |
+
'kite',
|
| 169 |
+
'baseball bat',
|
| 170 |
+
'baseball glove',
|
| 171 |
+
'skateboard',
|
| 172 |
+
'surfboard',
|
| 173 |
+
'tennis racket',
|
| 174 |
+
'bottle',
|
| 175 |
+
'wine glass',
|
| 176 |
+
'cup',
|
| 177 |
+
'fork',
|
| 178 |
+
'knife',
|
| 179 |
+
'spoon',
|
| 180 |
+
'bowl',
|
| 181 |
+
'banana',
|
| 182 |
+
'apple',
|
| 183 |
+
'sandwich',
|
| 184 |
+
'orange',
|
| 185 |
+
'broccoli',
|
| 186 |
+
'carrot',
|
| 187 |
+
'hot dog',
|
| 188 |
+
'pizza',
|
| 189 |
+
'donut',
|
| 190 |
+
'cake',
|
| 191 |
+
'chair',
|
| 192 |
+
'couch',
|
| 193 |
+
'potted plant',
|
| 194 |
+
'bed',
|
| 195 |
+
'dining table',
|
| 196 |
+
'toilet',
|
| 197 |
+
'tv',
|
| 198 |
+
'laptop',
|
| 199 |
+
'mouse',
|
| 200 |
+
'remote',
|
| 201 |
+
'keyboard',
|
| 202 |
+
'cell phone',
|
| 203 |
+
'microwave',
|
| 204 |
+
'oven',
|
| 205 |
+
'toaster',
|
| 206 |
+
'sink',
|
| 207 |
+
'refrigerator',
|
| 208 |
+
'book',
|
| 209 |
+
'clock',
|
| 210 |
+
'vase',
|
| 211 |
+
'scissors',
|
| 212 |
+
'teddy bear',
|
| 213 |
+
'hair drier',
|
| 214 |
+
'toothbrush'
|
| 215 |
+
]
|
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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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Implementation of YOLOv3 architecture
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import torch.nn as nn
|
| 7 |
+
|
| 8 |
+
"""
|
| 9 |
+
Information about architecture config:
|
| 10 |
+
Tuple is structured by (filters, kernel_size, stride)
|
| 11 |
+
Every conv is a same convolution.
|
| 12 |
+
List is structured by "B" indicating a residual block followed by the number of repeats
|
| 13 |
+
"S" is for scale prediction block and computing the yolo loss
|
| 14 |
+
"U" is for upsampling the feature map and concatenating with a previous layer
|
| 15 |
+
"""
|
| 16 |
+
config = [
|
| 17 |
+
(32, 3, 1),
|
| 18 |
+
(64, 3, 2),
|
| 19 |
+
["B", 1],
|
| 20 |
+
(128, 3, 2),
|
| 21 |
+
["B", 2],
|
| 22 |
+
(256, 3, 2),
|
| 23 |
+
["B", 8],
|
| 24 |
+
(512, 3, 2),
|
| 25 |
+
["B", 8],
|
| 26 |
+
(1024, 3, 2),
|
| 27 |
+
["B", 4], # To this point is Darknet-53
|
| 28 |
+
(512, 1, 1),
|
| 29 |
+
(1024, 3, 1),
|
| 30 |
+
"S",
|
| 31 |
+
(256, 1, 1),
|
| 32 |
+
"U",
|
| 33 |
+
(256, 1, 1),
|
| 34 |
+
(512, 3, 1),
|
| 35 |
+
"S",
|
| 36 |
+
(128, 1, 1),
|
| 37 |
+
"U",
|
| 38 |
+
(128, 1, 1),
|
| 39 |
+
(256, 3, 1),
|
| 40 |
+
"S",
|
| 41 |
+
]
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class CNNBlock(nn.Module):
|
| 45 |
+
def __init__(self, in_channels, out_channels, bn_act=True, **kwargs):
|
| 46 |
+
super().__init__()
|
| 47 |
+
self.conv = nn.Conv2d(in_channels, out_channels, bias=not bn_act, **kwargs)
|
| 48 |
+
self.bn = nn.BatchNorm2d(out_channels)
|
| 49 |
+
self.leaky = nn.LeakyReLU(0.1)
|
| 50 |
+
self.use_bn_act = bn_act
|
| 51 |
+
|
| 52 |
+
def forward(self, x):
|
| 53 |
+
if self.use_bn_act:
|
| 54 |
+
return self.leaky(self.bn(self.conv(x)))
|
| 55 |
+
else:
|
| 56 |
+
return self.conv(x)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class ResidualBlock(nn.Module):
|
| 60 |
+
def __init__(self, channels, use_residual=True, num_repeats=1):
|
| 61 |
+
super().__init__()
|
| 62 |
+
self.layers = nn.ModuleList()
|
| 63 |
+
for repeat in range(num_repeats):
|
| 64 |
+
self.layers += [
|
| 65 |
+
nn.Sequential(
|
| 66 |
+
CNNBlock(channels, channels // 2, kernel_size=1),
|
| 67 |
+
CNNBlock(channels // 2, channels, kernel_size=3, padding=1),
|
| 68 |
+
)
|
| 69 |
+
]
|
| 70 |
+
|
| 71 |
+
self.use_residual = use_residual
|
| 72 |
+
self.num_repeats = num_repeats
|
| 73 |
+
|
| 74 |
+
def forward(self, x):
|
| 75 |
+
for layer in self.layers:
|
| 76 |
+
if self.use_residual:
|
| 77 |
+
x = x + layer(x)
|
| 78 |
+
else:
|
| 79 |
+
x = layer(x)
|
| 80 |
+
|
| 81 |
+
return x
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
class ScalePrediction(nn.Module):
|
| 85 |
+
def __init__(self, in_channels, num_classes):
|
| 86 |
+
super().__init__()
|
| 87 |
+
self.pred = nn.Sequential(
|
| 88 |
+
CNNBlock(in_channels, 2 * in_channels, kernel_size=3, padding=1),
|
| 89 |
+
CNNBlock(
|
| 90 |
+
2 * in_channels, (num_classes + 5) * 3, bn_act=False, kernel_size=1
|
| 91 |
+
),
|
| 92 |
+
)
|
| 93 |
+
self.num_classes = num_classes
|
| 94 |
+
|
| 95 |
+
def forward(self, x):
|
| 96 |
+
return (
|
| 97 |
+
self.pred(x)
|
| 98 |
+
.reshape(x.shape[0], 3, self.num_classes + 5, x.shape[2], x.shape[3])
|
| 99 |
+
.permute(0, 1, 3, 4, 2)
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
class YOLOv3(nn.Module):
|
| 104 |
+
def __init__(self, in_channels=3, num_classes=80):
|
| 105 |
+
super().__init__()
|
| 106 |
+
self.num_classes = num_classes
|
| 107 |
+
self.in_channels = in_channels
|
| 108 |
+
self.layers = self._create_conv_layers()
|
| 109 |
+
|
| 110 |
+
def forward(self, x):
|
| 111 |
+
outputs = [] # for each scale
|
| 112 |
+
route_connections = []
|
| 113 |
+
for layer in self.layers:
|
| 114 |
+
if isinstance(layer, ScalePrediction):
|
| 115 |
+
outputs.append(layer(x))
|
| 116 |
+
continue
|
| 117 |
+
|
| 118 |
+
x = layer(x)
|
| 119 |
+
|
| 120 |
+
if isinstance(layer, ResidualBlock) and layer.num_repeats == 8:
|
| 121 |
+
route_connections.append(x)
|
| 122 |
+
|
| 123 |
+
elif isinstance(layer, nn.Upsample):
|
| 124 |
+
x = torch.cat([x, route_connections[-1]], dim=1)
|
| 125 |
+
route_connections.pop()
|
| 126 |
+
|
| 127 |
+
return outputs
|
| 128 |
+
|
| 129 |
+
def _create_conv_layers(self):
|
| 130 |
+
layers = nn.ModuleList()
|
| 131 |
+
in_channels = self.in_channels
|
| 132 |
+
|
| 133 |
+
for module in config:
|
| 134 |
+
if isinstance(module, tuple):
|
| 135 |
+
out_channels, kernel_size, stride = module
|
| 136 |
+
layers.append(
|
| 137 |
+
CNNBlock(
|
| 138 |
+
in_channels,
|
| 139 |
+
out_channels,
|
| 140 |
+
kernel_size=kernel_size,
|
| 141 |
+
stride=stride,
|
| 142 |
+
padding=1 if kernel_size == 3 else 0,
|
| 143 |
+
)
|
| 144 |
+
)
|
| 145 |
+
in_channels = out_channels
|
| 146 |
+
|
| 147 |
+
elif isinstance(module, list):
|
| 148 |
+
num_repeats = module[1]
|
| 149 |
+
layers.append(ResidualBlock(in_channels, num_repeats=num_repeats,))
|
| 150 |
+
|
| 151 |
+
elif isinstance(module, str):
|
| 152 |
+
if module == "S":
|
| 153 |
+
layers += [
|
| 154 |
+
ResidualBlock(in_channels, use_residual=False, num_repeats=1),
|
| 155 |
+
CNNBlock(in_channels, in_channels // 2, kernel_size=1),
|
| 156 |
+
ScalePrediction(in_channels // 2, num_classes=self.num_classes),
|
| 157 |
+
]
|
| 158 |
+
in_channels = in_channels // 2
|
| 159 |
+
|
| 160 |
+
elif module == "U":
|
| 161 |
+
layers.append(nn.Upsample(scale_factor=2),)
|
| 162 |
+
in_channels = in_channels * 3
|
| 163 |
+
|
| 164 |
+
return layers
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
if __name__ == "__main__":
|
| 168 |
+
num_classes = 20
|
| 169 |
+
IMAGE_SIZE = 416
|
| 170 |
+
model = YOLOv3(num_classes=num_classes)
|
| 171 |
+
x = torch.randn((2, 3, IMAGE_SIZE, IMAGE_SIZE))
|
| 172 |
+
out = model(x)
|
| 173 |
+
assert model(x)[0].shape == (2, 3, IMAGE_SIZE//32, IMAGE_SIZE//32, num_classes + 5)
|
| 174 |
+
assert model(x)[1].shape == (2, 3, IMAGE_SIZE//16, IMAGE_SIZE//16, num_classes + 5)
|
| 175 |
+
assert model(x)[2].shape == (2, 3, IMAGE_SIZE//8, IMAGE_SIZE//8, num_classes + 5)
|
| 176 |
+
print("Success!")
|
utils.py
ADDED
|
@@ -0,0 +1,586 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
plt.axis('off')
|
| 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 |
+
|
| 337 |
+
def cells_to_bboxes(predictions, anchors, S, is_preds=True):
|
| 338 |
+
"""
|
| 339 |
+
Scales the predictions coming from the model to
|
| 340 |
+
be relative to the entire image such that they for example later
|
| 341 |
+
can be plotted or.
|
| 342 |
+
INPUT:
|
| 343 |
+
predictions: tensor of size (N, 3, S, S, num_classes+5)
|
| 344 |
+
anchors: the anchors used for the predictions
|
| 345 |
+
S: the number of cells the image is divided in on the width (and height)
|
| 346 |
+
is_preds: whether the input is predictions or the true bounding boxes
|
| 347 |
+
OUTPUT:
|
| 348 |
+
converted_bboxes: the converted boxes of sizes (N, num_anchors, S, S, 1+5) with class index,
|
| 349 |
+
object score, bounding box coordinates
|
| 350 |
+
"""
|
| 351 |
+
BATCH_SIZE = predictions.shape[0]
|
| 352 |
+
num_anchors = len(anchors)
|
| 353 |
+
box_predictions = predictions[..., 1:5]
|
| 354 |
+
if is_preds:
|
| 355 |
+
anchors = anchors.reshape(1, len(anchors), 1, 1, 2)
|
| 356 |
+
box_predictions[..., 0:2] = torch.sigmoid(box_predictions[..., 0:2])
|
| 357 |
+
box_predictions[..., 2:] = torch.exp(box_predictions[..., 2:]) * anchors
|
| 358 |
+
scores = torch.sigmoid(predictions[..., 0:1])
|
| 359 |
+
best_class = torch.argmax(predictions[..., 5:], dim=-1).unsqueeze(-1)
|
| 360 |
+
else:
|
| 361 |
+
scores = predictions[..., 0:1]
|
| 362 |
+
best_class = predictions[..., 5:6]
|
| 363 |
+
|
| 364 |
+
cell_indices = (
|
| 365 |
+
torch.arange(S)
|
| 366 |
+
.repeat(predictions.shape[0], 3, S, 1)
|
| 367 |
+
.unsqueeze(-1)
|
| 368 |
+
.to(predictions.device)
|
| 369 |
+
)
|
| 370 |
+
x = 1 / S * (box_predictions[..., 0:1] + cell_indices)
|
| 371 |
+
y = 1 / S * (box_predictions[..., 1:2] + cell_indices.permute(0, 1, 3, 2, 4))
|
| 372 |
+
w_h = 1 / S * box_predictions[..., 2:4]
|
| 373 |
+
converted_bboxes = torch.cat((best_class, scores, x, y, w_h), dim=-1).reshape(BATCH_SIZE, num_anchors * S * S, 6)
|
| 374 |
+
return converted_bboxes.tolist()
|
| 375 |
+
|
| 376 |
+
def check_class_accuracy(model, loader, threshold):
|
| 377 |
+
model.eval()
|
| 378 |
+
tot_class_preds, correct_class = 0, 0
|
| 379 |
+
tot_noobj, correct_noobj = 0, 0
|
| 380 |
+
tot_obj, correct_obj = 0, 0
|
| 381 |
+
|
| 382 |
+
for idx, (x, y) in enumerate(tqdm(loader)):
|
| 383 |
+
x = x.to(config.DEVICE)
|
| 384 |
+
with torch.no_grad():
|
| 385 |
+
out = model(x)
|
| 386 |
+
|
| 387 |
+
for i in range(3):
|
| 388 |
+
y[i] = y[i].to(config.DEVICE)
|
| 389 |
+
obj = y[i][..., 0] == 1 # in paper this is Iobj_i
|
| 390 |
+
noobj = y[i][..., 0] == 0 # in paper this is Iobj_i
|
| 391 |
+
|
| 392 |
+
correct_class += torch.sum(
|
| 393 |
+
torch.argmax(out[i][..., 5:][obj], dim=-1) == y[i][..., 5][obj]
|
| 394 |
+
)
|
| 395 |
+
tot_class_preds += torch.sum(obj)
|
| 396 |
+
|
| 397 |
+
obj_preds = torch.sigmoid(out[i][..., 0]) > threshold
|
| 398 |
+
correct_obj += torch.sum(obj_preds[obj] == y[i][..., 0][obj])
|
| 399 |
+
tot_obj += torch.sum(obj)
|
| 400 |
+
correct_noobj += torch.sum(obj_preds[noobj] == y[i][..., 0][noobj])
|
| 401 |
+
tot_noobj += torch.sum(noobj)
|
| 402 |
+
|
| 403 |
+
# print(f"Class accuracy is: {(correct_class/(tot_class_preds+1e-16))*100:2f}%")
|
| 404 |
+
# print(f"No obj accuracy is: {(correct_noobj/(tot_noobj+1e-16))*100:2f}%")
|
| 405 |
+
# print(f"Obj accuracy is: {(correct_obj/(tot_obj+1e-16))*100:2f}%")
|
| 406 |
+
model.train()
|
| 407 |
+
class_acc = (correct_class / (tot_class_preds + 1e-16)) * 100
|
| 408 |
+
no_obj_acc = (correct_noobj / (tot_noobj + 1e-16)) * 100
|
| 409 |
+
obj_acc = (correct_obj / (tot_obj + 1e-16)) * 100
|
| 410 |
+
return class_acc, no_obj_acc, obj_acc
|
| 411 |
+
|
| 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//8):
|
| 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
|