Datasets:

Veridis / train.py
lpril's picture
Update train.py
f21c035 verified
# Copyright 2025 Robotics Group of the University of León (ULE)
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
from pathlib import Path
from ultralytics import YOLO
DATASET_NAME = "veridis"
def count_images(directory):
"""Count the number of JPG image files in a directory.
Args:
directory: Path to the directory containing images.
Returns:
Integer count of JPG files found in the directory.
"""
if not os.path.exists(directory):
return 0
count = 0
for file in os.listdir(directory):
if file.lower().endswith(".jpg"):
count += 1
return count
def find_dataset_yaml(current_dir, dataset_name):
"""Find data.yml file in a specific dataset directory.
Args:
current_dir: Current directory to search from.
dataset_name: Specific dataset name to use.
Returns:
Path to the data.yml file or None if not found.
"""
dataset_path = current_dir / dataset_name
yaml_path = dataset_path / "data.yml"
if yaml_path.exists():
print(f"Found dataset: {dataset_name}")
return str(yaml_path), dataset_path
return None, None
def main():
"""Main training function that initializes and trains the YOLO model.
Counts dataset images, prints statistics, and executes model training
with predefined hyperparameters.
"""
current_dir = Path(__file__).parent
os.chdir(current_dir)
print(f"Training dataset: {DATASET_NAME}")
yaml_path, dataset_root = find_dataset_yaml(current_dir, DATASET_NAME)
if yaml_path is None:
print(f"ERROR: Dataset '{DATASET_NAME}' not found or missing data.yml")
print("\nAvailable datasets: veridis, beet_augmented, beet, corn_augmented, corn")
return
train_images = count_images(dataset_root / "train" / "images")
val_images = count_images(dataset_root / "val" / "images")
test_images = count_images(dataset_root / "test" / "images")
print("\n=== Dataset Statistics ===")
print(f"Dataset path: {dataset_root}")
print(f"Config file: {yaml_path}")
print(f"Training images: {train_images}")
print(f"Validation images: {val_images}")
print(f"Test images: {test_images}")
print(f"Total images: {train_images + val_images + test_images}")
print("=========================\n")
print("Initializing YOLO model...")
model = YOLO("yolo11n.pt")
print("Starting training...\n")
results = model.train(
data=yaml_path,
epochs=10,
imgsz=640,
batch=16,
name=f"{dataset_root.name}_detection",
project="runs/train",
verbose=True
)
print("\n=== Training Complete ===")
print(f"Results saved to: {results.save_dir}")
print("\n=== Training Metrics ===")
if hasattr(results, "results_dict"):
metrics = results.results_dict
for key, value in metrics.items():
print(f"{key}: {value}")
metrics = model.val()
print("\n=== Validation Results ===")
print(f"mAP50: {metrics.box.map50:.4f}")
print(f"mAP50-95: {metrics.box.map:.4f}")
print(f"Precision: {metrics.box.mp:.4f}")
print(f"Recall: {metrics.box.mr:.4f}")
if hasattr(metrics.box, "maps"):
print("\nPer-class mAP50-95:")
class_names = metrics.names
for i, map_value in enumerate(metrics.box.maps):
print(f" {class_names[i]}: {map_value:.4f}")
if __name__ == "__main__":
main()