Implementing YOLOv8 for Object Detection with PyTorch
For object detection tasks in PyTorch using YOLOv8, the Ultralytics library provides a streamlined approach. Begin by ensuring the environment supports GPU acceleration if available.
import torch
from ultralytics import YOLO
import os
os.environ['KMP_DUPLICATE_LIB_OK'] = 'True'
def setup_model():
device_type = 'cuda' if torch.cuda.is_available() else 'cpu'
print(f"Using device: {device_type}")
model = YOLO('yolov8n.pt').to(device_type)
return model, device_type
def train_model(model, config_path, device_type):
model.train(data=config_path, epochs=100, device=device_type, workers=0, batch=2)
model.val(device=device_type)
if __name__ == '__main__':
yolo_model, device = setup_model()
train_model(yolo_model, 'dataset_config.yaml', device)
Model weights (yolov8n.pt) should be downloaded from the official Ultralytics documentation and placed in the working directory. Additionally, install the ultralytics package via pip.
Dataset configuration is managed through a YAML file that defines paths to training, valdiation, and test sets:
train: /path/to/training/data
val: /path/to/validation/data
test: /path/to/test/data
nc: 3
classes: [rice, animal, other]
The dataset must follow standard YOLO formatting where each image has a corresponding annotation file with matching filenames. Tools like makesense.ai can assist in creating labeled datsaets.
After training, best performing model is saved as best.pt within the generated runs/detect/train/weights/ directory. To perform inference:
import matplotlib.pyplot as plt
from ultralytics import YOLO
inference_model = YOLO('runs/detect/train/weights/best.pt')
sample_image = 'test_images/sample.jpg'
predictions = inference_model(sample_image)
if isinstance(predictions, list):
for prediction in predictions:
prediction.show()
else:
predictions.show()
plt.imshow(predictions[0].orig_img)
plt.axis('off')
plt.show()
This workflow enables rapid deployment of custom object detection models using YOLOv8 architecture.