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|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Script simplificado de entrenamiento YOLOv8 clasificación
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
from ultralytics import YOLO
|
| 8 |
+
import os
|
| 9 |
+
|
| 10 |
+
def main():
|
| 11 |
+
print("🚀 ENTRENAMIENTO YOLO CLASIFICACIÓN")
|
| 12 |
+
print("=" * 50)
|
| 13 |
+
|
| 14 |
+
# Verificar CUDA
|
| 15 |
+
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
| 16 |
+
print(f"💻 Dispositivo: {device}")
|
| 17 |
+
print(f"🎯 Objetivo: >90% precisión")
|
| 18 |
+
|
| 19 |
+
# Dataset path
|
| 20 |
+
dataset_path = "/home/leonel/sistema_polinizador/Dataset/Classification_YOLO"
|
| 21 |
+
|
| 22 |
+
if not os.path.exists(dataset_path):
|
| 23 |
+
print(f"❌ Dataset no encontrado: {dataset_path}")
|
| 24 |
+
print("💡 Ejecuta primero: python fix_structure.py")
|
| 25 |
+
return
|
| 26 |
+
|
| 27 |
+
# Configuraciones de entrenamiento
|
| 28 |
+
configs = [
|
| 29 |
+
{
|
| 30 |
+
"name": "nano_quick",
|
| 31 |
+
"model": "yolov8n-cls.pt",
|
| 32 |
+
"epochs": 30,
|
| 33 |
+
"imgsz": 224,
|
| 34 |
+
"batch": 32
|
| 35 |
+
},
|
| 36 |
+
{
|
| 37 |
+
"name": "small_balanced",
|
| 38 |
+
"model": "yolov8s-cls.pt",
|
| 39 |
+
"epochs": 60,
|
| 40 |
+
"imgsz": 256,
|
| 41 |
+
"batch": 16
|
| 42 |
+
},
|
| 43 |
+
{
|
| 44 |
+
"name": "medium_accurate",
|
| 45 |
+
"model": "yolov8m-cls.pt",
|
| 46 |
+
"epochs": 100,
|
| 47 |
+
"imgsz": 320,
|
| 48 |
+
"batch": 8
|
| 49 |
+
}
|
| 50 |
+
]
|
| 51 |
+
|
| 52 |
+
best_accuracy = 0
|
| 53 |
+
best_model = None
|
| 54 |
+
|
| 55 |
+
for i, config in enumerate(configs, 1):
|
| 56 |
+
print(f"\n{i}️⃣ MODELO: {config['name']}")
|
| 57 |
+
print("=" * 40)
|
| 58 |
+
|
| 59 |
+
try:
|
| 60 |
+
# Cargar modelo
|
| 61 |
+
model = YOLO(config["model"])
|
| 62 |
+
print(f"📥 Modelo cargado: {config['model']}")
|
| 63 |
+
|
| 64 |
+
# Entrenar
|
| 65 |
+
print(f"⏰ Iniciando entrenamiento...")
|
| 66 |
+
results = model.train(
|
| 67 |
+
data=dataset_path,
|
| 68 |
+
epochs=config["epochs"],
|
| 69 |
+
imgsz=config["imgsz"],
|
| 70 |
+
batch=config["batch"],
|
| 71 |
+
device=device,
|
| 72 |
+
project="pollinator_final",
|
| 73 |
+
name=config["name"],
|
| 74 |
+
patience=20,
|
| 75 |
+
save=True,
|
| 76 |
+
verbose=False,
|
| 77 |
+
plots=True
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
# Evaluar
|
| 81 |
+
print(f"📊 Evaluando en test set...")
|
| 82 |
+
test_results = model.val(split='test')
|
| 83 |
+
accuracy = float(test_results.top1) * 100
|
| 84 |
+
|
| 85 |
+
print(f"✅ Entrenamiento completado")
|
| 86 |
+
print(f"🎯 Precisión: {accuracy:.2f}%")
|
| 87 |
+
|
| 88 |
+
if accuracy > best_accuracy:
|
| 89 |
+
best_accuracy = accuracy
|
| 90 |
+
best_model = f"pollinator_final/{config['name']}/weights/best.pt"
|
| 91 |
+
|
| 92 |
+
# Verificar objetivo
|
| 93 |
+
if accuracy >= 90:
|
| 94 |
+
print(f"🎉 ¡OBJETIVO ALCANZADO! {accuracy:.2f}% ≥ 90%")
|
| 95 |
+
break
|
| 96 |
+
else:
|
| 97 |
+
print(f"⚠️ Faltan {90-accuracy:.2f}% para objetivo")
|
| 98 |
+
|
| 99 |
+
except Exception as e:
|
| 100 |
+
print(f"❌ Error: {e}")
|
| 101 |
+
continue
|
| 102 |
+
|
| 103 |
+
# Resultados finales
|
| 104 |
+
print(f"\n" + "=" * 50)
|
| 105 |
+
print("📊 RESULTADOS FINALES")
|
| 106 |
+
print("=" * 50)
|
| 107 |
+
print(f"🏆 Mejor precisión: {best_accuracy:.2f}%")
|
| 108 |
+
|
| 109 |
+
if best_accuracy >= 90:
|
| 110 |
+
print(f"✅ OBJETIVO ALCANZADO!")
|
| 111 |
+
else:
|
| 112 |
+
print(f"❌ Objetivo no alcanzado")
|
| 113 |
+
print(f"💡 Recomendación: Entrenar modelo YOLOv8l o YOLOv8x")
|
| 114 |
+
|
| 115 |
+
if best_model:
|
| 116 |
+
print(f"📁 Mejor modelo: {best_model}")
|
| 117 |
+
|
| 118 |
+
# Crear script de predicción simple
|
| 119 |
+
pred_script = f'''#!/usr/bin/env python3
|
| 120 |
+
from ultralytics import YOLO
|
| 121 |
+
|
| 122 |
+
# Cargar modelo entrenado
|
| 123 |
+
model = YOLO('{best_model}')
|
| 124 |
+
|
| 125 |
+
# Función para clasificar
|
| 126 |
+
def classify_insect(image_path):
|
| 127 |
+
results = model(image_path, verbose=False)
|
| 128 |
+
probs = results[0].probs
|
| 129 |
+
|
| 130 |
+
classes = [
|
| 131 |
+
'Acmaeodera Flavomarginata', 'Acromyrmex Octospinosus',
|
| 132 |
+
'Adelpha Basiloides', 'Adelpha Iphicleola', 'Aedes Aegypti',
|
| 133 |
+
'Agrius Cingulata', 'Anaea Aidea', 'Anartia fatima',
|
| 134 |
+
'Anartia jatrophae', 'Anoplolepis Gracilipes'
|
| 135 |
+
]
|
| 136 |
+
|
| 137 |
+
top_class = classes[probs.top1]
|
| 138 |
+
confidence = probs.top1conf.item() * 100
|
| 139 |
+
|
| 140 |
+
print(f"🔍 Predicción: {{top_class}}")
|
| 141 |
+
print(f"📊 Confianza: {{confidence:.1f}}%")
|
| 142 |
+
|
| 143 |
+
return top_class, confidence
|
| 144 |
+
|
| 145 |
+
# Ejemplo de uso
|
| 146 |
+
if __name__ == "__main__":
|
| 147 |
+
image_path = input("Ruta de imagen: ")
|
| 148 |
+
if image_path:
|
| 149 |
+
classify_insect(image_path)
|
| 150 |
+
'''
|
| 151 |
+
|
| 152 |
+
with open('predict_final.py', 'w') as f:
|
| 153 |
+
f.write(pred_script)
|
| 154 |
+
|
| 155 |
+
print(f"✅ Script de predicción: predict_final.py")
|
| 156 |
+
|
| 157 |
+
return best_accuracy
|
| 158 |
+
|
| 159 |
+
if __name__ == "__main__":
|
| 160 |
+
final_accuracy = main()
|
| 161 |
+
print(f"\n🎯 Entrenamiento completado. Precisión final: {final_accuracy:.2f}%")
|