1. Home
  2. Explore
  3. Computer Science
  4. Training YOLO in Colab

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Training YOLO in Colab

Training a Custom YOLO Object Detection Model

A step-by-step guide to gathering a dataset, labeling images, training a YOLO model in Google Colab, and running the trained model locally on a PC. The example used is a candy detection model that identifies different popular candy brands.


Dataset Creation

The first step is to create a labeled dataset of images containing the objects to be detected.

Dataset Size and Diversity

  • A good starting point for a proof-of-concept model is 100 to 200 images.

  • Training images should show the objects in a variety of backgrounds, perspectives, and lighting conditions that match the real-world application.

  • The best way to build a dataset is to manually take pictures of the objects in different settings. For the candy model, photos were taken with a phone and webcam around the house.

  • Alternative sources for pre-labeled images include:

    • Roboflow Universe

    • Kaggle

    • Google Open Images V7

Organizing the Images

  • Collect all images into a single folder on the computer. For example:

    • Create a folder named YOLO in Documents.

    • Inside it, create another folder named candy-images.

    • Move all photos into the candy-images folder.


Labeling with Label Studio

Label Studio is a free, open-source tool used to draw bounding boxes and assign class labels to images. It runs locally on the computer and is accessed through a web browser.

Installing Label Studio via Anaconda

  1. Install Anaconda – Download from anaconda.com/download (skip registration) and run the installer with default options.

  2. Open Anaconda Prompt – Search for "Anaconda Prompt" in the Start menu.

  3. Create a new Python environment:

     conda create --name yolo-env1 python=3.12
  4. Activate the environment:

     conda activate yolo-env1
  5. Install Label Studio:

     pip install label-studio
  6. Start Label Studio:

     label-studio start

    The server starts locally, and a browser window opens to the Label Studio interface.

Setting Up a Label Studio Project

  • Create an account – Use a fake email and password (e.g., fake@fake.com/fakepassword). All data remains on the local machine.

  • Create a new project – Click "Create Project" and give it a name (e.g., "candy images").

  • Import images – Under the "Data Import" tab, drag and drop images from the local folder. Import no more than 100 images at a time to avoid upload errors. For over 1000 images, link a local storage folder or cloud account.

  • Set up labeling configuration – Under "Labeling Setup", choose Object Detection. Delete default labels (airplane, car) and add custom class names (e.g., AirHeads, Nerds, Skittles). Click "Add", then "Save".

The Labeling Workflow

  • Open the first image in the project.

  • Create a bounding box by clicking a class name at the bottom, then clicking and dragging a box around the object.

  • Adjust the box as needed.

  • Use hotkeys – class hotkeys (e.g., 1 for AirHeads, 8 for peanut M&M's) allow faster labeling.

  • After labeling all objects in an image, click Submit.

  • Continue to the next image. Zoom in for tighter bounding boxes.

  • Label all images. This step is time-consuming; breaks are recommended.

Exporting Labeled Data

  • Click the project name at the top, then Export.

  • Select the YOLO export format and click Export.

  • A .zip file is downloaded containing:

    • images/ folder with all images

    • labels/ folder with corresponding .txt files (YOLO format)

    • classes.txt – lists all class names

  • Rename the file to data.zip and move it to the YOLO folder.


Training in Google Colab

Google Colab provides a free GPU (Tesla T4) for training deep learning models.

Setting Up the Colab Notebook

  1. Open the provided Colab notebook (link in original source).

  2. Runtime → Change runtime type – Select T4 GPU. Click "Save".

  3. Click Connect.

  4. Run the !nvidia-smi cell to verify a GPU is available.

Uploading and Preparing the Dataset

  • Click the folder icon in the left sidebar.

  • Drag and drop data.zip into the file browser. Uploading to Google Drive is faster (instructions provided in the notebook).

  • If using a dataset from another source (e.g., Roboflow), ensure it has the required structure:

    data/
    ├── images/ (all images)
    ├── labels/ (YOLO .txt files)
    └── classes.txt (one class per line)
  • Unzip the dataset by running the appropriate code block.

Splitting Data into Train and Validation Sets

  • The notebook contains a Python script that:

    • Creates the folder structure data/train/ and data/val/ (with images and labels subfolders).

    • Randomly moves 90% of the images to the train folder and 10% to the validation folder.

  • Run the code block to execute the script.

Installing Ultralytics

Run the cell with:

pip install ultralytics

This installs the ultralytics Python library used to train YOLO models.

Creating the Training Configuration File (data.yaml)

The data.yaml file tells the trainer where the train/validation data is and what classes exist. The notebook automatically generates it by running a code block. Verify the contents:

train: data/train/images
val: data/val/images
nc: <number_of_classes>
names: ['class1', 'class2', ...]

Choosing Training Parameters

  • Model architecture – Options include YOLO11 (latest), YOLOv8, and YOLOv5. Model sizes range from nano (fastest, least accurate) to extra large (slowest, most accurate).

    • YOLO11s (small) is recommended as a starting point for most projects.

    • Choose a model small enough to meet speed requirements but accurate enough for the task.

  • Number of epochs:

    • Less than 200 images: start with 60 epochs.

    • More than 200 images: start with 40 epochs.

  • Resolution – Default is 640×640. For faster inference or low-resolution images, try 480×480.

Running Training

  • The notebook trains a YOLO11s model for 60 epochs at 640×640 resolution. Parameters can be changed in the code cell.

  • Click play to start. Training:

    • Parses images and labels.

    • Runs through epochs, each time validating on the validation set.

    • Reports mAP (mean Average Precision), precision, and recall after each epoch. mAP generally increases over time.

  • Training duration: 5 minutes to a few hours depending on dataset size and epochs. Colab free instances disconnect after about 5 hours; Colab Pro extends time.

Training Outputs

  • Best model weights saved at runs/detect/train/weights/best.pt.

  • results.png – Shows plots of loss, precision, recall, and mAP per epoch. mAP should increase and then plateau.

Testing the Trained Model

  • Run the code block to perform inference on all validation images.

  • Run the next block to display results for the first 10 images. The model draws bounding boxes with class labels.

  • If accuracy is poor:

    • Check the dataset for label errors.

    • Increase the number of epochs.

    • Switch to a larger model (e.g., YOLO11m or YOLO11l).


Running the Model Locally

Downloading the Trained Model from Colab

  • Run the provided code block to:

    • Rename best.pt to my_model.pt.

    • Move it to a folder named my_model.

    • Zip the folder (my_model.zip).

    • Also zip training results for reference.

  • Download my_model.zip from the Colab file browser.

Setting Up the Local Environment

  • Move the downloaded .zip to the YOLO folder on the PC and extract it.

  • Open Anaconda Prompt (stop Label Studio with CTRL+C if still running).

  • Activate the environment: conda activate yolo-env1

  • Navigate to the my_model folder:

    cd path/to/my_model
  • Install Ultralytics (if not already installed):

    pip install ultralytics
  • Optional: Enable GPU acceleration – If an NVIDIA GPU is available, install the GPU-enabled PyTorch:

    • Go to pytorch.org/get-started-locally.

    • Select OS and latest CUDA version.

    • Copy the installation command and append --upgrade to upgrade the existing PyTorch installation.

    • Run the command. This installs CUDA and cuDNN drivers (takes longer).

Running Inference with a Custom Script

  • A Python script yolo_detect.py is provided to load the model, run inference, and display results.

  • Download the script:

    curl -o yolo_detect.py https://www.ejtech.io/yolo_detect.py
  • Run the script with a model and source:

    python yolo_detect.py --model my_model.pt --source <source> [--resolution WxH]
  • Source options:

    • usb0 for a USB camera (or 0 for default camera). Resolution can be set with --resolution 1280x720.

    • Path to a video file (e.g., test1.mov).

    • Path to an image file or folder of images.

  • The script opens a window showing detection results in real time. Press Q to quit.

Extending the Application

The provided script serves as a foundation. Example extensions:

  • Object counting – Count detections per class.

  • Calorie calculator – For the candy model, sum calories/sugar based on detected candy counts (example source code linked in original description).

  • Additional examples are available in the Train-YOLO-Models GitHub repository.


Key Takeaways

  • Dataset quality matters more than dataset size – capture diverse backgrounds, lighting, and perspectives.

  • Label Studio offers a free, local labeling environment with hotkeys for efficiency.

  • Google Colab provides free GPU training, but sessions expire after ~5 hours; upgrade for longer runs.

  • Model selection is a trade-off between speed and accuracy; YOLO11s is a strong default.

  • Training monitors mAP, precision, and recall – mAP should increase and plateau.

  • Running locally requires installing Ultralytics and optionally GPU-enabled PyTorch.

  • The custom Python script can be adapted for real-time video, image files, or USB cameras.

  • Always verify label accuracy and consider retraining with more epochs or a larger model if performance is insufficient.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent