roboone_auto_dataset / modules /yolov8_train.sh
nyxrobotics's picture
Add yolo trained data
d0c155d
#!/bin/bash
SCRIPT_DIR=$(cd $(dirname $0); pwd)
# Parameters
YOLO_DATASET_DIR=$SCRIPT_DIR/../export_yolo/YOLODataset
MODEL="yolov8n.pt" # YOLOv8 model type
EPOCHS=1000
SAVE_PERIOD=50
OUTPUT_DIR=$SCRIPT_DIR/../export_yolo/train_output
USE_GPU_TUNING=true
RESUME_TRAINING=false
mkdir -p $OUTPUT_DIR/runs/tune
# Install ImageMagick if not already installed
if ! command -v identify &> /dev/null
then
echo "ImageMagick not found. Installing..."
sudo apt install -y imagemagick
fi
# Automatically detect image size from the training images
IMG_SIZE=$(identify -format "%wx%h\n" $YOLO_DATASET_DIR/images/train/*.png | head -n 1 | cut -d 'x' -f 1)
# If USE_GPU_TUNING is true, adjust parameters based on GPU memory
if [ "$USE_GPU_TUNING" = true ]; then
# Get the GPU memory in MB
GPU_MEMORY=$(nvidia-smi --query-gpu=memory.total --format=csv,noheader,nounits | head -n 1)
# Set the batch size and learning rate based on GPU memory
if [ "$GPU_MEMORY" -ge 24576 ]; then
BATCH_SIZE=8 # For 24GB+ GPUs
BATCH_SIZE_PER_IMAGE=512
elif [ "$GPU_MEMORY" -ge 12288 ]; then
BATCH_SIZE=4 # For 12GB+ GPUs
BATCH_SIZE_PER_IMAGE=256
else
BATCH_SIZE=2 # For smaller GPUs
BATCH_SIZE_PER_IMAGE=128
fi
# Adjust learning rate based on batch size
BASE_LR=$(echo "0.00025 * $BATCH_SIZE / 2" | bc -l)
echo "GPU memory: $GPU_MEMORY MB"
echo "Batch size: $BATCH_SIZE, Batch size per image: $BATCH_SIZE_PER_IMAGE"
echo "Base learning rate: $BASE_LR"
fi
cd $OUTPUT_DIR
# Run training with the YOLO model
python3 - <<END
from ultralytics import YOLO
import os
import ray
ray.init(ignore_reinit_error=True)
# Hyperparameters and settings
data_path = "$YOLO_DATASET_DIR/dataset.yaml"
model_path = "$MODEL"
img_size = $IMG_SIZE
batch_size = $BATCH_SIZE
epochs = $EPOCHS
save_period = $SAVE_PERIOD
output_dir = "$OUTPUT_DIR"
resume_training = $([ "$RESUME_TRAINING" = true ] && echo True || echo False) # Convert bash boolean to Python boolean
# Load the model
model = YOLO(model_path)
# Automatically tune hyper-parameters with Ray Tune
print("Starting hyperparameter tuning...")
tune_results = model.tune(
data=data_path,
batch=batch_size,
imgsz=img_size,
augment=True,
multi_scale=True,
rect=True,
scale=0.8
)
print("Tuning completed. Starting final training...")
# Start final training after tuning
results = model.train(
data=data_path,
epochs=epochs,
save_period=save_period,
patience=0,
batch=batch_size,
imgsz=img_size,
project=output_dir,
name="final_train_results",
resume=resume_training,
augment=True,
multi_scale=True,
rect=True,
scale=0.8
)
print("YOLO training completed.")
END