Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 45 additions & 3 deletions ml/yolov8_DINO/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,49 @@ dataset_biolit/

Poids entraînés → `runs/biolit_v2_bootstrap/weights/`

## Partie 2 — Fine-tuning (à venir)
## Partie 2 — Fine-tuning

Pris en charge par un autre membre de l'équipe.
Entraînement sur des images cropées et annotées manuellement pour améliorer les performances du modèle bootstrap.
Cette étape consiste à améliorer le modèle YOLOv8 obtenu lors du bootstrap en utilisant un dataset plus petit (~1,400 images) mais de meilleure qualité, annoté manuellement.
Le dataset est augmenté artificiellement ×3 sur le train set uniquement (pas sur le validation set) via flips, rotations (±15° et 90°), ajustements de luminosité (±10 %) et léger flou.

### Données

````text
14_Biolit/
├── data/
│ └── manual_annotations/
│ ├── train/...
│ ├── valid/...
│ └── data.yaml

### Modèle de départ

Le fine-tuning part du modèle entraîné lors de la partie 1 :

```text
runs/biolit_v2_bootstrap/weights/best.pt
````

### Lancer le fine-tuning

```bash
python finetune.py
```

### Configuration

Le fichier `configs/finetune.yaml` contient les paramètres principaux :

- chemin vers le modèle bootstrap (`best.pt`)
- chemin vers le dataset manuel (`data.yaml`)
- hyperparamètres d'entraînement (`epochs`, `batch`, `learning rate`)

### Résultat

Les nouveaux poids sont sauvegardés dans :

```text
runs/biolit_v2_finetuned/weights/
```

Ce modèle est ensuite utilisé pour générer les crops finaux ou pour l’inférence.
13 changes: 13 additions & 0 deletions ml/yolov8_DINO/configs/finetune.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
model: runs/biolit_v2_bootstrap/weights/best.pt
data_yaml: ../../data/manual_annotations/data.yaml

epochs: 100
imgsz: 640
batch: 16

optimizer: AdamW
lr0: 0.001

# Sorties
project: runs/
name: biolit_v2_finetuned
69 changes: 69 additions & 0 deletions ml/yolov8_DINO/finetune.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import argparse
import sys
from pathlib import Path

import numpy as np
import torch
import yaml

torch.use_deterministic_algorithms(False)

if not hasattr(np, "trapz"):
np.trapz = np.trapezoid

from ultralytics import YOLO # noqa: E402

sys.path.insert(0, str(Path(__file__).parent))
from utils.logger import get_logger # noqa: E402

log = get_logger("finetune")


def _device():
if torch.cuda.is_available():
return "cuda"
if torch.backends.mps.is_available():
return "mps"
return "cpu"


def _validate_path(path_str: str, label: str) -> Path:
path = Path(path_str)
if not path.exists():
raise FileNotFoundError(f"{label} not found: {path}")
return path


def main():
parser = argparse.ArgumentParser()
parser.add_argument("--config", default="configs/finetune.yaml")
args = parser.parse_args()

with open(args.config, encoding="utf-8") as f:
cfg = yaml.safe_load(f)

device = _device()
log.info("Fine-tuning YOLOv8 | device=%s", device)

weights_path = _validate_path(cfg["model"], "Model weights")
data_yaml_path = _validate_path(cfg["data_yaml"], "data.yaml")

model = YOLO(str(weights_path))
model.train(
data=str(data_yaml_path),
epochs=cfg["epochs"],
imgsz=cfg["imgsz"],
batch=cfg["batch"],
optimizer=cfg["optimizer"],
lr0=cfg["lr0"],
device=device,
project=cfg["project"],
name=cfg["name"],
exist_ok=True,
)

log.info("Fine-tuning terminé.")


if __name__ == "__main__":
main()
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ dependencies = [
"autodistill>=0.1.29",
"autodistill-grounding-dino>=0.1.4",
"autodistill-yolov8>=0.1.4",
"ultralytics",
"supervision>=0.27.0.post2",
"scikit-learn>=1.8.0",
"boto3>=1.42.80",
Expand Down
2 changes: 2 additions & 0 deletions uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading