-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrain.py
More file actions
1703 lines (1351 loc) · 52.6 KB
/
train.py
File metadata and controls
1703 lines (1351 loc) · 52.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Complete YOLOv8 Training, Evaluation and Prediction Script
Author: LenIAC
Date: 2024
Description: End-to-end implementation for YOLOv8 object detection
"""
import os
import yaml
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms
import numpy as np
from PIL import Image
import cv2
import random
from pathlib import Path
from typing import Dict, List, Tuple, Optional, Union
import matplotlib.pyplot as plt
from tqdm import tqdm
import warnings
warnings.filterwarnings('ignore')
from yolov8 import YOLOv8
from loss_fn import ComputeLoss
# Import the provided modules (assuming they're in the same directory)
# Note: We're not copying the model and loss function as requested
# They should be imported from the provided files
# ============================================================================
# DATA LOADING AND PREPROCESSING
# ============================================================================
class YOLODataset(Dataset):
"""
Custom Dataset for YOLO format data.
This class handles loading images and labels in YOLO format,
applies augmentations, and prepares data for training.
"""
def __init__(self,
data_yaml_path: str,
split: str = 'train',
img_size: int = 640,
augment: bool = True):
"""
Initialize YOLO dataset.
Args:
data_yaml_path: Path to data.yaml file
split: 'train' or 'val'
img_size: Input image size (square)
augment: Whether to apply data augmentation
"""
super().__init__()
self.img_size = img_size
self.augment = augment and split == 'train'
data_yaml_path = Path(data_yaml_path)
self.datasets_dir = data_yaml_path.parent
# Load data configuration
with open(data_yaml_path, 'r') as f:
data_config = yaml.safe_load(f)
# Get image paths
if split == 'train':
image_dir = data_config['train']
else:
image_dir = data_config['val']
self.image_dir = self.datasets_dir / image_dir
self.label_dir = self.image_dir.parent / 'labels'
# Get class names
self.class_names = data_config['names']
self.num_classes = data_config['nc']
# Collect all image files
self.image_files = list(self.image_dir.glob('*.jpg')) + \
list(self.image_dir.glob('*.jpeg')) + \
list(self.image_dir.glob('*.png'))
if not self.image_files:
raise ValueError(f"No images found in {self.image_dir}")
print(f"Found {len(self.image_files)} images for {split} split")
# Define augmentations
self.transform = self._get_transforms()
def _get_transforms(self):
"""Get image transformations based on augmentation flag."""
if self.augment:
return transforms.Compose([
transforms.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2, hue=0.1),
transforms.ToTensor(),
transforms.RandomHorizontalFlip(p=0.5),
])
else:
return transforms.Compose([
transforms.ToTensor(),
])
def __len__(self) -> int:
"""Return number of images in dataset."""
return len(self.image_files)
def load_image(self, image_path: Path) -> torch.Tensor:
"""
Load and preprocess image.
Args:
image_path: Path to image file
Returns:
Preprocessed image tensor
"""
# Load image
img = Image.open(image_path).convert('RGB')
# Resize maintaining aspect ratio with padding
img, ratio, pad = self.letterbox(img, self.img_size)
# Apply transformations
img = self.transform(img)
return img, ratio, pad
def load_labels(self, label_path: Path, ratio: Tuple, pad: Tuple) -> torch.Tensor:
"""
Load and preprocess labels.
Args:
label_path: Path to label file
ratio: Resize ratio (width_ratio, height_ratio)
pad: Padding (width_pad, height_pad)
Returns:
Tensor of labels [num_objects, 5] where 5 = [class, x, y, w, h]
"""
if not label_path.exists():
return torch.zeros((0, 5))
labels = []
with open(label_path, 'r') as f:
for line in f:
parts = line.strip().split()
if len(parts) == 5:
class_id = int(parts[0])
x_center = float(parts[1])
y_center = float(parts[2])
width = float(parts[3])
height = float(parts[4])
# Adjust for letterbox
x_center = x_center * ratio[0] + pad[0]
y_center = y_center * ratio[1] + pad[1]
width = width * ratio[0]
height = height * ratio[1]
# Normalize to image size
x_center /= self.img_size
y_center /= self.img_size
width /= self.img_size
height /= self.img_size
labels.append([class_id, x_center, y_center, width, height])
if labels:
return torch.tensor(labels)
else:
return torch.zeros((0, 5))
def letterbox(self, img: Image.Image, new_shape: int = 640) -> Tuple:
"""
Resize image with padding to maintain aspect ratio.
Args:
img: Input PIL Image
new_shape: Target size
Returns:
Resized image, ratio, padding
"""
# Current shape
shape = img.size # (width, height)
# Calculate ratio
r = min(new_shape / shape[0], new_shape / shape[1])
# New dimensions
new_unpad = (int(round(shape[0] * r)), int(round(shape[1] * r)))
# Calculate padding
dw = new_shape - new_unpad[0]
dh = new_shape - new_unpad[1]
dw /= 2
dh /= 2
# Resize
img = img.resize(new_unpad, Image.BILINEAR)
# Create new image with padding
new_img = Image.new('RGB', (new_shape, new_shape), (114, 114, 114))
new_img.paste(img, (int(round(dw)), int(round(dh))))
return new_img, (r, r), (dw/new_shape, dh/new_shape)
def __getitem__(self, idx: int) -> Dict:
"""
Get single data sample.
Args:
idx: Index of sample
Returns:
Dictionary containing image and labels
"""
# Get image path
img_path = self.image_files[idx]
# Load image
image, ratio, pad = self.load_image(img_path)
# Load corresponding labels
label_path = self.label_dir / f"{img_path.stem}.txt"
labels = self.load_labels(label_path, ratio, pad)
return {
'image': image,
'labels': labels,
'image_path': str(img_path)
}
def collate_fn(batch: List[Dict]) -> Dict:
"""
Custom collate function for DataLoader.
Args:
batch: List of samples
Returns:
Batched data
"""
images = []
labels = []
image_paths = []
for sample in batch:
images.append(sample['image'])
labels.append(sample['labels'])
image_paths.append(sample['image_path'])
# Stack images
images = torch.stack(images, dim=0)
return {
'images': images,
'labels': labels,
'image_paths': image_paths
}
# ============================================================================
# TRAINING UTILITIES
# ============================================================================
class ModelEMA:
"""
Exponential Moving Average for model weights.
This helps stabilize training and improve final model performance.
"""
def __init__(self, model: nn.Module, decay: float = 0.9999):
"""
Initialize EMA.
Args:
model: Model to apply EMA to
decay: EMA decay rate
"""
self.model = model
self.decay = decay
self.shadow = {}
self.backup = {}
# Register parameters
for name, param in model.named_parameters():
if param.requires_grad:
self.shadow[name] = param.data.clone()
def update(self):
"""Update EMA parameters."""
for name, param in self.model.named_parameters():
if param.requires_grad:
assert name in self.shadow
new_average = (1.0 - self.decay) * param.data + self.decay * self.shadow[name]
self.shadow[name] = new_average.clone()
def apply_shadow(self):
"""Apply EMA parameters to model."""
for name, param in self.model.named_parameters():
if param.requires_grad:
assert name in self.shadow
self.backup[name] = param.data.clone()
param.data = self.shadow[name]
def restore(self):
"""Restore original parameters."""
for name, param in self.model.named_parameters():
if param.requires_grad:
assert name in self.backup
param.data = self.backup[name]
self.backup = {}
class EarlyStopping:
"""
Early stopping to prevent overfitting.
Stops training when validation loss doesn't improve for a given patience.
"""
def __init__(self, patience: int = 10, min_delta: float = 0.0):
"""
Initialize early stopping.
Args:
patience: Number of epochs to wait for improvement
min_delta: Minimum change to qualify as improvement
"""
self.patience = patience
self.min_delta = min_delta
self.counter = 0
self.best_loss = None
self.early_stop = False
def __call__(self, val_loss: float) -> bool:
"""
Check if training should stop.
Args:
val_loss: Current validation loss
Returns:
True if training should stop
"""
if self.best_loss is None:
self.best_loss = val_loss
return False
if val_loss > self.best_loss - self.min_delta:
self.counter += 1
if self.counter >= self.patience:
self.early_stop = True
else:
self.best_loss = val_loss
self.counter = 0
return self.early_stop
# ============================================================================
# METRICS AND EVALUATION
# ============================================================================
class MetricsCalculator:
"""
Calculate evaluation metrics for object detection.
Computes mAP, precision, recall, and other relevant metrics.
"""
def __init__(self, num_classes: int, iou_threshold: float = 0.5):
"""
Initialize metrics calculator.
Args:
num_classes: Number of object classes
iou_threshold: IoU threshold for considering detection as correct
"""
self.num_classes = num_classes
self.iou_threshold = iou_threshold
self.reset()
def reset(self):
"""Reset all metrics."""
self.true_positives = []
self.false_positives = []
self.confidence_scores = []
self.num_ground_truths = [0] * self.num_classes
def update(self,
predictions: List[torch.Tensor],
ground_truths: List[torch.Tensor]):
"""
Update metrics with new batch.
Args:
predictions: List of prediction tensors [N, 6] where 6 = [x1, y1, x2, y2, conf, class]
ground_truths: List of ground truth tensors [M, 5] where 5 = [class, x, y, w, h]
"""
for preds, gts in zip(predictions, ground_truths):
if len(preds) == 0:
continue
if len(gts) == 0:
# All predictions are false positives
for pred in preds:
self.false_positives.append(pred[4].item())
self.confidence_scores.append(pred[4].item())
continue
# Convert ground truth format
gt_boxes = []
gt_classes = []
for gt in gts:
class_id = int(gt[0])
x_center, y_center, width, height = gt[1:5].tolist()
x1 = x_center - width / 2
y1 = y_center - height / 2
x2 = x_center + width / 2
y2 = y_center + height / 2
gt_boxes.append([x1, y1, x2, y2])
gt_classes.append(class_id)
self.num_ground_truths[class_id] += 1
if not gt_boxes:
continue
gt_boxes = torch.tensor(gt_boxes)
gt_classes = torch.tensor(gt_classes)
# Sort predictions by confidence
sorted_indices = torch.argsort(preds[:, 4], descending=True)
preds = preds[sorted_indices]
# Track which ground truths have been matched
gt_matched = torch.zeros(len(gt_boxes), dtype=torch.bool)
for pred in preds:
pred_box = pred[:4].unsqueeze(0)
pred_class = int(pred[5])
confidence = pred[4].item()
self.confidence_scores.append(confidence)
# Find matching ground truth
if len(gt_boxes) > 0:
# Get IoU with all ground truths of same class
same_class_mask = (gt_classes == pred_class)
if same_class_mask.any():
ious = self.calculate_iou(pred_box, gt_boxes[same_class_mask])
best_iou, best_idx = torch.max(ious, dim=1)
if best_iou.item() >= self.iou_threshold:
# Get original index
original_idx = torch.where(same_class_mask)[0][best_idx.item()]
if not gt_matched[original_idx]:
# True positive
self.true_positives.append(confidence)
gt_matched[original_idx] = True
continue
# False positive
self.false_positives.append(confidence)
def calculate_iou(self, box1: torch.Tensor, box2: torch.Tensor) -> torch.Tensor:
"""
Calculate IoU between boxes.
Args:
box1: Tensor of shape [1, 4]
box2: Tensor of shape [N, 4]
Returns:
IoU values
"""
# Get coordinates
x1 = torch.max(box1[:, 0], box2[:, 0])
y1 = torch.max(box1[:, 1], box2[:, 1])
x2 = torch.min(box1[:, 2], box2[:, 2])
y2 = torch.min(box1[:, 3], box2[:, 3])
# Intersection area
intersection = torch.clamp(x2 - x1, min=0) * torch.clamp(y2 - y1, min=0)
# Union area
area1 = (box1[:, 2] - box1[:, 0]) * (box1[:, 3] - box1[:, 1])
area2 = (box2[:, 2] - box2[:, 0]) * (box2[:, 3] - box2[:, 1])
union = area1 + area2 - intersection
# IoU
iou = intersection / union
return iou
def compute_map(self) -> float:
"""
Compute mean Average Precision.
Returns:
mAP value
"""
if not self.confidence_scores:
return 0.0
# Sort by confidence
sorted_indices = np.argsort(self.confidence_scores)[::-1]
# Convert to numpy arrays
tp = np.array([1 if score in self.true_positives else 0
for score in self.confidence_scores])
fp = np.array([1 if score in self.false_positives else 0
for score in self.confidence_scores])
# Sort by confidence
tp = tp[sorted_indices]
fp = fp[sorted_indices]
# Compute precision-recall curve
tp_cumsum = np.cumsum(tp)
fp_cumsum = np.cumsum(fp)
recalls = tp_cumsum / (sum(self.num_ground_truths) + 1e-16)
precisions = tp_cumsum / (tp_cumsum + fp_cumsum + 1e-16)
# Compute AP using 101-point interpolation
ap = 0.0
for t in np.arange(0, 1.01, 0.01):
mask = recalls >= t
if mask.any():
ap += np.max(precisions[mask])
return ap / 101
# ============================================================================
# TRAINING LOOP
# ============================================================================
class YOLOv8Trainer:
"""
Complete trainer for YOLOv8 model.
Handles training, validation, and model saving.
"""
def __init__(self,
model: nn.Module,
train_loader: DataLoader,
val_loader: DataLoader,
config: Dict):
"""
Initialize trainer.
Args:
model: YOLOv8 model
train_loader: Training data loader
val_loader: Validation data loader
config: Training configuration
"""
self.model = model
self.train_loader = train_loader
self.val_loader = val_loader
self.config = config
# Setup device
self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
self.model.to(self.device)
self.loss_fn = ComputeLoss(self.model, self.config)
# Setup optimizer
self.optimizer = optim.AdamW(
model.parameters(), lr=config['learning_rate'], weight_decay=config['weight_decay']
)
# Setup learning rate scheduler
self.scheduler = optim.lr_scheduler.CosineAnnealingLR(
self.optimizer,
T_max=config['epochs'],
eta_min=config['learning_rate'] * 0.01
)
# Setup EMA
self.ema = ModelEMA(model, decay=config['ema_decay'])
# Setup early stopping
self.early_stopping = EarlyStopping(
patience=config['early_stopping_patience'],
min_delta=config['early_stopping_min_delta']
)
# Setup metrics
self.metrics_calculator = MetricsCalculator(
num_classes=config['num_classes']
)
# Training state
self.current_epoch = 0
self.best_map = 0.0
self.train_losses = []
self.val_losses = []
self.val_maps = []
# Create output directory
self.output_dir = Path(config['output_dir'])
self.output_dir.mkdir(parents=True, exist_ok=True)
# Save configuration
with open(self.output_dir / 'config.yaml', 'w') as f:
yaml.dump(config, f)
def train_epoch(self) -> float:
"""
Train for one epoch.
Returns:
Average training loss
"""
self.model.train()
total_loss = 0.0
num_batches = 0
progress_bar = tqdm(self.train_loader, desc=f"Epoch {self.current_epoch + 1}")
for batch_idx, batch in enumerate(progress_bar):
# Move data to device
images = batch['images'].to(self.device)
labels = batch['labels']
# Prepare targets
targets = self.prepare_targets(labels)
# Forward pass
self.optimizer.zero_grad()
outputs = self.model(images)
# Compute loss
# Note: We assume the loss function is available
# In practice, you would import it from loss_fn.py
progress_bar.write("outputs: " + str(outputs) + " targets: " + str(targets))
loss_box, loss_cls, loss_dfl = self.compute_loss(outputs, targets)
total_loss = loss_box + loss_cls + loss_dfl
# Backward pass
total_loss.backward()
# Gradient clipping
torch.nn.utils.clip_grad_norm_(self.model.parameters(),max_norm=self.config['grad_clip'])
# Optimizer step
self.optimizer.step()
# Update EMA
self.ema.update()
# Update progress bar
progress_bar.set_postfix({
'loss': total_loss.item(),
'box': loss_box.item(),
'cls': loss_cls.item(),
'dfl': loss_dfl.item()
})
total_loss += total_loss.item()
num_batches += 1
return total_loss / num_batches
def validate(self) -> Tuple[float, float]:
"""
Validate model.
Returns:
Tuple of (validation loss, mAP)
"""
self.model.eval()
self.ema.apply_shadow()
total_loss = 0.0
num_batches = 0
all_predictions = []
all_ground_truths = []
with torch.no_grad():
progress_bar = tqdm(self.val_loader, desc="Validation")
for batch_idx, batch in enumerate(progress_bar):
# Move data to device
images = batch['images'].to(self.device)
labels = batch['labels']
# Prepare targets
targets = self.prepare_targets(labels)
# Forward pass
outputs = self.model(images)
# Compute loss
progress_bar.write("outputs: " + str(outputs) + " targets: " + str(targets))
loss_box, loss_cls, loss_dfl = self.compute_loss(outputs, targets)
batch_loss = loss_box + loss_cls + loss_dfl
total_loss += batch_loss.item()
num_batches += 1
# Get predictions for metrics
predictions = self.get_predictions(outputs)
all_predictions.extend(predictions)
all_ground_truths.extend(labels)
progress_bar.set_postfix({
'val_loss': batch_loss.item()
})
# Restore original model
self.ema.restore()
# Calculate mAP
self.metrics_calculator.reset()
self.metrics_calculator.update(all_predictions, all_ground_truths)
mAP = self.metrics_calculator.compute_map()
return total_loss / num_batches, mAP
def prepare_targets(self, labels: List[torch.Tensor]) -> Dict:
"""
Prepare targets for loss computation.
Args:
labels: List of label tensors
Returns:
Dictionary of targets
"""
# This is a simplified version
# In practice, you would implement the full target preparation
# as in the loss_fn.py file
batch_size = len(labels)
max_objects = max(len(l) for l in labels) if labels else 0
if max_objects == 0:
return {
'idx': torch.zeros((0, 1)),
'cls': torch.zeros((0, 1)),
'box': torch.zeros((0, 4))
}
# Initialize tensors
idx_tensor = torch.zeros((batch_size * max_objects, 1))
cls_tensor = torch.zeros((batch_size * max_objects, 1))
box_tensor = torch.zeros((batch_size * max_objects, 4))
idx = 0
for batch_idx, label_batch in enumerate(labels):
for obj_idx in range(len(label_batch)):
label = label_batch[obj_idx]
idx_tensor[idx] = batch_idx
cls_tensor[idx] = label[0]
# Convert from center format to corner format
x_center, y_center, width, height = label[1:5]
x1 = x_center - width / 2
y1 = y_center - height / 2
x2 = x_center + width / 2
y2 = y_center + height / 2
box_tensor[idx] = torch.tensor([x1, y1, x2, y2])
idx += 1
# Trim to actual number of objects
idx_tensor = idx_tensor[:idx]
cls_tensor = cls_tensor[:idx]
box_tensor = box_tensor[:idx]
return {
'idx': idx_tensor,
'cls': cls_tensor,
'box': box_tensor
}
def compute_loss(self, outputs, targets):
"""
Compute loss using the provided loss function.
Args:
outputs: Model outputs
targets: Prepared targets
Returns:
Tuple of (box_loss, cls_loss, dfl_loss)
"""
# Note: In practice, you would import and use the ComputeLoss class
# from loss_fn.py. This is a simplified placeholder.
# For demonstration, we'll use placeholder losses
box_loss, cls_loss, dfl_loss = self.loss_fn(outputs, targets)
# Placeholder implementation
# device = outputs[0].device
# box_loss = torch.tensor(0.5, device=device, requires_grad=True)
# cls_loss = torch.tensor(0.3, device=device, requires_grad=True)
# dfl_loss = torch.tensor(0.2, device=device, requires_grad=True)
return box_loss, cls_loss, dfl_loss
def get_predictions(self, outputs, confidence_threshold: float = 0.25):
"""
Convert model outputs to predictions.
Args:
outputs: Model outputs
confidence_threshold: Minimum confidence score
Returns:
List of predictions per image
"""
predictions = []
# Note: This is a simplified version
# In practice, use the model's head for inference
for output in outputs:
# output shape: [batch_size, num_predictions, 85] for COCO
# where 85 = 4 box coordinates + 1 objectness + 80 classes
batch_predictions = []
for img_idx in range(output.shape[0]):
img_preds = output[img_idx]
# Filter by confidence
if img_preds.shape[1] > 5: # Has class predictions
# Get objectness and class scores
obj_scores = img_preds[:, 4:5]
cls_scores = img_preds[:, 5:]
# Combine scores
scores = obj_scores * cls_scores.max(dim=1, keepdim=True)[0]
# Filter by threshold
mask = scores.squeeze() > confidence_threshold
filtered_preds = img_preds[mask]
if len(filtered_preds) > 0:
# Get boxes and classes
boxes = filtered_preds[:, :4]
confidences = scores[mask]
class_ids = filtered_preds[:, 5:].argmax(dim=1)
# Combine into [x1, y1, x2, y2, conf, class]
batch_preds = torch.cat([boxes, confidences, class_ids.unsqueeze(1).float()], dim=1)
batch_predictions.append(batch_preds)
else:
batch_predictions.append(torch.zeros((0, 6)))
else:
batch_predictions.append(torch.zeros((0, 6)))
predictions.extend(batch_predictions)
return predictions
def save_checkpoint(self, filename: str, is_best: bool = False):
"""
Save model checkpoint.
Args:
filename: Checkpoint filename
is_best: Whether this is the best model
"""
checkpoint = {
'epoch': self.current_epoch,
'model_state_dict': self.model.state_dict(),
'optimizer_state_dict': self.optimizer.state_dict(),
'scheduler_state_dict': self.scheduler.state_dict(),
'best_map': self.best_map,
'train_losses': self.train_losses,
'val_losses': self.val_losses,
'val_maps': self.val_maps,
'config': self.config
}
torch.save(checkpoint, self.output_dir / filename)
if is_best:
torch.save(self.model.state_dict(), self.output_dir / 'best_model.pth')
def load_checkpoint(self, checkpoint_path: str):
"""
Load model checkpoint.
Args:
checkpoint_path: Path to checkpoint file
"""
checkpoint = torch.load(checkpoint_path, map_location=self.device)
self.model.load_state_dict(checkpoint['model_state_dict'])
self.optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
self.scheduler.load_state_dict(checkpoint['scheduler_state_dict'])
self.current_epoch = checkpoint['epoch']
self.best_map = checkpoint['best_map']
self.train_losses = checkpoint['train_losses']
self.val_losses = checkpoint['val_losses']
self.val_maps = checkpoint['val_maps']
print(f"Loaded checkpoint from epoch {self.current_epoch}")
print(f"Best mAP: {self.best_map:.4f}")
def plot_training_history(self):
"""Plot training history."""
fig, axes = plt.subplots(1, 2, figsize=(12, 4))
# Plot losses
axes[0].plot(self.train_losses, label='Training Loss', color='blue')
axes[0].plot(self.val_losses, label='Validation Loss', color='red')
axes[0].set_xlabel('Epoch')
axes[0].set_ylabel('Loss')
axes[0].set_title('Training and Validation Loss')
axes[0].legend()
axes[0].grid(True)
# Plot mAP
axes[1].plot(self.val_maps, label='Validation mAP', color='green')
axes[1].set_xlabel('Epoch')
axes[1].set_ylabel('mAP')
axes[1].set_title('Validation mAP')
axes[1].legend()
axes[1].grid(True)
plt.tight_layout()
plt.savefig(self.output_dir / 'training_history.png', dpi=150)
plt.close()
def train(self):
"""Main training loop."""
print(f"Starting training on {self.device}")
print(f"Number of parameters: {sum(p.numel() for p in self.model.parameters()):,}")
for epoch in range(self.current_epoch, self.config['epochs']):
self.current_epoch = epoch
# Train for one epoch
train_loss = self.train_epoch()
self.train_losses.append(train_loss)
# Validate
val_loss, val_map = self.validate()
self.val_losses.append(val_loss)
self.val_maps.append(val_map)
# Update learning rate
self.scheduler.step()
# Print epoch summary
print(f"\nEpoch {epoch + 1}/{self.config['epochs']}:")
print(f" Train Loss: {train_loss:.4f}")
print(f" Val Loss: {val_loss:.4f}")
print(f" Val mAP: {val_map:.4f}")
print(f" Learning Rate: {self.scheduler.get_last_lr()[0]:.6f}")
# Save checkpoint
self.save_checkpoint(f'checkpoint_epoch_{epoch + 1}.pth')
# Save best model
if val_map > self.best_map:
self.best_map = val_map
self.save_checkpoint('best_checkpoint.pth', is_best=True)
print(f" New best model saved with mAP: {val_map:.4f}")
# Check early stopping
if self.early_stopping(val_loss):
print(f"Early stopping triggered at epoch {epoch + 1}")
break
# Plot training history
if (epoch + 1) % 5 == 0:
self.plot_training_history()
# Final plot
self.plot_training_history()
print(f"\nTraining completed. Best mAP: {self.best_map:.4f}")
# ============================================================================
# PREDICTION AND INFERENCE
# ============================================================================
class YOLOv8Predictor:
"""
Predictor for YOLOv8 model.
Handles loading trained models and making predictions on new images.