| # Install required package | |
| # pip install ultralytics | |
| from ultralytics import YOLO | |
| # Dataset structure expected: | |
| # βββ dataset/ | |
| # β βββ train/ | |
| # β β βββ images/ | |
| # β β βββ labels/ | |
| # β βββ valid/ | |
| # β β βββ images/ | |
| # β β βββ labels/ | |
| # β βββ test/ | |
| # β βββ images/ | |
| # β βββ labels/ | |
| # data.yaml example: | |
| # path: /path/to/dataset | |
| # train: train/images | |
| # val: valid/images | |
| # test: test/images | |
| # names: | |
| # 0: class1 | |
| # 1: class2 | |
| # ... | |
| def train_yolov8(): | |
| # Load the YOLOv8 Large model | |
| model = YOLO('yolov8l.pt') # pretrained model | |
| # Train the model | |
| results = model.train( | |
| data='data.yaml', | |
| epochs=100, | |
| batch=16, | |
| imgsz=640, | |
| device='0', # 'cpu' or '0' for GPU | |
| name='yolov8l_custom', | |
| optimizer='Adam', | |
| lr0=0.001, | |
| warmup_epochs=3, | |
| augment=True, | |
| patience=50, | |
| pretrained=True | |
| ) | |
| # Validate the model | |
| metrics = model.val() # Validate on validation set | |
| print(f"Validation mAP@0.5: {metrics.box.map}") | |
| # Test the model (optional) | |
| test_model = YOLO('runs/detect/yolov8l_custom/weights/best.pt') | |
| test_metrics = test_model.val(data='data.yaml', split='test') | |
| print(f"Test mAP@0.5: {test_metrics.box.map}") | |
| # Export to ONNX format (optional) | |
| model.export(format='onnx') | |
| if __name__ == '__main__': | |
| train_yolov8() |