Datasets:
DOI:
License:
File size: 4,039 Bytes
f21c035 404e2b5 24efc8e 404e2b5 24efc8e 404e2b5 24efc8e 404e2b5 24efc8e 404e2b5 24efc8e 404e2b5 24efc8e 404e2b5 24efc8e 404e2b5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 | # 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()
|