0% found this document useful (0 votes)
58 views4 pages

Pip Install Ultralytics

The document outlines a process for training a YOLO model using the Roboflow dataset, including installation of necessary libraries, model training, evaluation, and hyperparameter optimization with Optuna. It details steps for downloading the dataset, training the model with sample and optimized parameters, and comparing performance metrics such as mAP, precision, recall, and accuracy. Finally, it includes visualization of the performance comparison between pre-finetuned and best parameters from the optimization study.

Uploaded by

Ke Vin Ooi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
58 views4 pages

Pip Install Ultralytics

The document outlines a process for training a YOLO model using the Roboflow dataset, including installation of necessary libraries, model training, evaluation, and hyperparameter optimization with Optuna. It details steps for downloading the dataset, training the model with sample and optimized parameters, and comparing performance metrics such as mAP, precision, recall, and accuracy. Finally, it includes visualization of the performance comparison between pre-finetuned and best parameters from the optimization study.

Uploaded by

Ke Vin Ooi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

!

pip install ultralytics

from ultralytics import YOLO

import os

from IPython.display import display, Image

from IPython import display

display.clear_output()

!yolo mode=checks

!pip install roboflow

from roboflow import Roboflow

rf = Roboflow(api_key="rPKTIfP9ER2GOcYShCBs")

project = rf.workspace("roboflow-100").project("cavity-rs0uf")

version = project.version(3)

dataset = version.download("yolov11")

from ultralytics import YOLO

# Load a model

model = YOLO("yolo11n.pt")

# Train the model

train_results = model.train(

data="/content/cavity-3/data.yaml", # path to dataset YAML

epochs=20, # number of training epochs

imgsz=640, # training image size

device="cpu", # device to run on, i.e. device=0 or device=0,1,2,3 or


device=cpu
)

# Evaluate model performance on the validation set

metrics = model.val()

# Perform object detection on an image

results = model("cavity-3/x.jpeg")

results[0].show()

# Export the model to ONNX format

path = model.export(format="onnx") # return path to exported model

from google.colab import drive

drive.mount('/content/drive')

# Section 1: Dataset Analysis import os import yaml !pip install roboflow !


pip install optuna !pip install ultralytics from roboflow import Roboflow rf =
Roboflow(api_key="rPKTIfP9ER2GOcYShCBs") project =
rf.workspace("roboflow-100").project("cavity-rs0uf") version =
project.version(3) dataset = version.download("yolov11") from ultralytics
import YOLO # Section 2: Train with Sample Parameters
pre_finetune_model = YOLO("yolo11n.pt") # Load the pre-trained model #
Train with sample parameters to get the pre-finetuned model
pre_finetune_model.train( data="/content/cavity-3/data.yaml",
epochs=20, # Arbitrary sample training epochs imgsz=640, # Common
size batch=16, # Standard batch size lr0=1e-3, # Typical learning rate
weight_decay=1e-4, # Typical weight decay device="cpu", ) # Validate
the pre finetuned model pre_finetune_metrics =
pre_finetune_model.val(data="/content/cavity-3/data.yaml") # Section 3:
Hyperparameter Optimization with Optuna import optuna def
objective(trial): # Suggest hyperparameters epochs =
trial.suggest_int('epochs', 10, 50) imgsz = trial.suggest_int('imgsz', 320,
640, step=32) batch = trial.suggest_int('batch', 8, 32, step=8) lr0 =
trial.suggest_float('lr0', 1e-5, 1e-2, log=True) weight_decay =
trial.suggest_float('weight_decay', 1e-6, 1e-3, log=True) # Train model
with suggested parameters model = YOLO("yolo11n.pt")
model.train( data="/content/cavity-3/data.yaml", epochs=epochs,
imgsz=imgsz, batch=batch, lr0=lr0, weight_decay=weight_decay,
device="cpu", ) # Evaluate model metrics =
model.val(data="/content/cavity-3/data.yaml") return metrics.box.map50
# Objective is to maximize [email protected] # Run Optuna optimization study =
optuna.create_study(direction="maximize") study.optimize(objective,
n_trials=10) # Print best parameters print("Best Parameters:",
study.best_params) # Section 4: Train with Best Parameters
finetuned_model = YOLO("yolo11n.pt") # Load the pre-trained model #
Train with best parameters from Optuna finetuned_model.train(
data="/content/cavity-3/data.yaml", epochs=study.best_params['epochs'],
imgsz=study.best_params['imgsz'], batch=study.best_params['batch'],
lr0=study.best_params['lr0'],
weight_decay=study.best_params['weight_decay'], device="cpu", ) #
Validate the fine-tuned model finetuned_metrics =
finetuned_model.val(data="/content/cavity-3/data.yaml") # Section 5:
Model Evaluation and Comparison import numpy as np import
matplotlib.pyplot as plt # Metrics for Pre Finetuned Model
pre_finetune_map50 = pre_finetune_metrics.box.map50
pre_finetune_precision = pre_finetune_metrics.box.precision
pre_finetune_recall = pre_finetune_metrics.box.recall pre_finetune_tp =
pre_finetune_metrics.box.tp pre_finetune_fp = pre_finetune_metrics.box.fp
pre_finetune_fn = pre_finetune_metrics.box.fn pre_finetune_accuracy =
pre_finetune_tp / (pre_finetune_tp + pre_finetune_fp + pre_finetune_fn) #
Metrics for Fine-Tuned Model finetuned_map50 =
finetuned_metrics.box.map50 finetuned_precision =
finetuned_metrics.box.precision finetuned_recall =
finetuned_metrics.box.recall finetuned_tp = finetuned_metrics.box.tp
finetuned_fp = finetuned_metrics.box.fp finetuned_fn =
finetuned_metrics.box.fn finetuned_accuracy = finetuned_tp /
(finetuned_tp + finetuned_fp + finetuned_fn) # Plot Performance
Comparison labels = ['Pre Finetuned Params', 'Best Params (Optuna)']
map50_scores = [pre_finetune_map50, finetuned_map50]
precision_scores = [pre_finetune_precision, finetuned_precision]
recall_scores = [pre_finetune_recall, finetuned_recall] accuracy_scores =
[pre_finetune_accuracy, finetuned_accuracy] x = np.arange(len(labels))
width = 0.2 plt.figure(figsize=(14, 7)) plt.bar(x - 1.5*width, map50_scores,
width=width, label='[email protected]', align='center', color='blue') plt.bar(x -
0.5*width, precision_scores, width=width, label='Precision', align='center',
color='orange') plt.bar(x + 0.5*width, recall_scores, width=width,
label='Recall', align='center', color='green') plt.bar(x + 1.5*width,
accuracy_scores, width=width, label='Accuracy', align='center',
color='red') plt.xlabel('Training Configuration') plt.ylabel('Score')
plt.title('Performance Comparison (Pre Finetuned Params vs Best Params)')
plt.xticks(x, labels) plt.ylim(0, 1) plt.legend() plt.grid(axis='y',
linestyle='--', alpha=0.7) plt.show()

You might also like