Download training/train.py from FaustDerLegende/Micro_component_dataset: direct link, hf CLI and curl.
- Browser
- Download file 6.34 kB
-
https://huggingface.co/datasets/FaustDerLegende/Micro_component_dataset/resolve/main/training/train.py
- Command line
-
hf download hf://datasets/FaustDerLegende/Micro_component_dataset/training/train.py
-
curl -L -o train.py https://huggingface.co/datasets/FaustDerLegende/Micro_component_dataset/resolve/main/training/train.py
6.34 kB
| """Custom YOLOv8 Training & Export Script for E-Waste Cannibalization Index. | |
| Supports training on local splits (`splits/data.yaml`), Hugging Face dataset structures, | |
| and exporting quantized TFLite INT8 models. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import logging | |
| import os | |
| import sys | |
| from pathlib import Path | |
| import yaml | |
| from ultralytics import YOLO | |
| # Enforce all cache and runs directories to reside strictly within workspace | |
| workspace_dir = Path(__file__).resolve().parent.parent | |
| cache_dir = (workspace_dir / "data" / "cache").resolve() | |
| cache_dir.mkdir(parents=True, exist_ok=True) | |
| runs_dir = (workspace_dir / "data" / "runs").resolve() | |
| runs_dir.mkdir(parents=True, exist_ok=True) | |
| os.environ["TORCH_HOME"] = str(cache_dir) | |
| os.environ["HF_HOME"] = str(cache_dir) | |
| os.environ["ULTRALYTICS_CONFIG_DIR"] = str(cache_dir) | |
| logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s") | |
| log = logging.getLogger(__name__) | |
| CONFIG_PATH = workspace_dir / "training" / "train_config.yaml" | |
| def load_train_config(config_file: Path = CONFIG_PATH) -> dict: | |
| if config_file.exists(): | |
| with open(config_file, "r", encoding="utf-8") as f: | |
| return yaml.safe_load(f) | |
| return { | |
| "data": "splits/data.yaml", | |
| "model": "yolov8n.pt", | |
| "imgsz": 960, | |
| "epochs": 50, | |
| "batch": 8, | |
| "copy_paste": 0.8, | |
| "cls": 2.5, | |
| } | |
| def run_training(config_override: dict | None = None, push_model_repo: str | None = None) -> dict: | |
| cfg = load_train_config() | |
| if config_override: | |
| cfg.update(config_override) | |
| log.info("Loaded training configuration: %s", cfg) | |
| model_name = cfg.get("model", "yolov8n.pt") | |
| # Resolve dataset yaml path | |
| raw_data_path = cfg.get("data", "splits/data.yaml") | |
| data_path_obj = Path(raw_data_path) | |
| if not data_path_obj.is_absolute(): | |
| data_path_obj = (workspace_dir / raw_data_path).resolve() | |
| if not data_path_obj.exists(): | |
| hf_dataset_yaml = workspace_dir / "huggingface_dataset" / "data.yaml" | |
| if hf_dataset_yaml.exists(): | |
| data_path_obj = hf_dataset_yaml.resolve() | |
| data_yaml = str(data_path_obj) | |
| epochs = int(cfg.get("epochs", 50)) | |
| imgsz = int(cfg.get("imgsz", 960)) | |
| batch_size = int(cfg.get("batch", 8)) | |
| log.info("Initializing YOLO model backbone: %s", model_name) | |
| model = YOLO(model_name) | |
| # Train model with Copy-Paste synthetic augmentation and elevated class loss gain | |
| log.info("Starting YOLOv8 fine-tuning on %s (%d epochs, imgsz=%d)...", data_yaml, epochs, imgsz) | |
| results = model.train( | |
| data=data_yaml, | |
| epochs=epochs, | |
| imgsz=imgsz, | |
| batch=batch_size, | |
| copy_paste=float(cfg.get("copy_paste", 0.8)), | |
| mosaic=float(cfg.get("mosaic", 1.0)), | |
| mixup=float(cfg.get("mixup", 0.15)), | |
| box=float(cfg.get("box", 7.5)), | |
| cls=float(cfg.get("cls", 2.5)), | |
| dfl=float(cfg.get("dfl", 1.5)), | |
| project=str(runs_dir), | |
| name="ewaste_purity_v1", | |
| exist_ok=True, | |
| verbose=True, | |
| ) | |
| # Validate trained model on test split | |
| log.info("Validating trained model on test split...") | |
| metrics = model.val(data=data_yaml, split="test", imgsz=imgsz) | |
| maps_per_class = metrics.box.maps.tolist() if hasattr(metrics.box, "maps") else [] | |
| mp = float(metrics.box.mp) if hasattr(metrics.box, "mp") else 0.0 | |
| mr = float(metrics.box.mr) if hasattr(metrics.box, "mr") else 0.0 | |
| map50 = float(metrics.box.map50) if hasattr(metrics.box, "map50") else 0.0 | |
| map95 = float(metrics.box.map) if hasattr(metrics.box, "map") else 0.0 | |
| eval_summary = { | |
| "mean_precision": round(mp, 4), | |
| "mean_recall": round(mr, 4), | |
| "mAP_50": round(map50, 4), | |
| "mAP_50_95": round(map95, 4), | |
| "maps_per_class": maps_per_class, | |
| } | |
| eval_file = workspace_dir / "reports" / "model_eval_summary.json" | |
| eval_file.parent.mkdir(parents=True, exist_ok=True) | |
| eval_file.write_text(json.dumps(eval_summary, indent=2), encoding="utf-8") | |
| log.info("Saved evaluation summary to %s", eval_file) | |
| # Export model to INT8 TFLite format | |
| try: | |
| log.info("Exporting trained model to TFLite format...") | |
| model.export(format="tflite", int8=True, imgsz=imgsz) | |
| log.info("TFLite export successful!") | |
| except Exception as exc: | |
| log.warning("TFLite export deferred: %s", exc) | |
| # Optional model upload to Hugging Face Hub | |
| if push_model_repo: | |
| try: | |
| from huggingface_hub import HfApi | |
| api = HfApi() | |
| api.create_repo(repo_id=push_model_repo, repo_type="model", exist_ok=True) | |
| best_weights = runs_dir / "ewaste_purity_v1" / "weights" / "best.pt" | |
| if best_weights.exists(): | |
| api.upload_file( | |
| path_or_fileobj=str(best_weights), | |
| path_in_repo="model.pt", | |
| repo_id=push_model_repo, | |
| repo_type="model", | |
| ) | |
| log.info("Uploaded best model weights to Hugging Face Hub: %s", push_model_repo) | |
| except Exception as exc: | |
| log.warning("Could not upload model to Hugging Face Hub: %s", exc) | |
| return eval_summary | |
| def main(): | |
| parser = argparse.ArgumentParser(description="Custom YOLOv8 Training Script for E-Waste Cannibalization Index") | |
| parser.add_argument("-e", "--epochs", type=int, default=50, help="Number of training epochs") | |
| parser.add_argument("-b", "--batch", type=int, default=8, help="Training batch size") | |
| parser.add_argument("-i", "--imgsz", type=int, default=960, help="Input image size") | |
| parser.add_argument("-m", "--model", type=str, default="yolov8n.pt", help="YOLOv8 backbone model") | |
| parser.add_argument("-d", "--data", type=str, default="splits/data.yaml", help="Path to data.yaml specification") | |
| parser.add_argument("--push-model-to-hf", type=str, help="HF Hub model repository ID to upload trained weights") | |
| args = parser.parse_args() | |
| override = { | |
| "epochs": args.epochs, | |
| "batch": args.batch, | |
| "imgsz": args.imgsz, | |
| "model": args.model, | |
| "data": args.data, | |
| } | |
| run_training(override, push_model_repo=args.push_model_to_hf) | |
| if __name__ == "__main__": | |
| main() | |