← Back to the animated process

scripts/train_yolo_seg_pose.py

Implementation snapshot supporting the published lesson. Only cited line ranges are included; this is not a runnable source file. Configuration and recorded examples describe this project snapshot.

… uncited lines omitted …
21def paired_counts(dataset):22    dataset = Path(dataset).resolve()23    result = {}24    for task in ("segmentation", "pose"):25        yaml = dataset / task / "data.yaml"26        if not yaml.is_file():27            raise ValueError(f"Missing {task} dataset YAML: {yaml}")28        result[task] = {}29        for split in ("train", "val"):30            images = list((dataset / task / "images" / split).glob("*"))31            labels = list((dataset / task / "labels" / split).glob("*.txt"))32            masks = list((dataset / task / "masks" / split).glob("*.png"))33            if not images or len(images) != len(labels):34                raise ValueError(35                    f"{task}/{split} has {len(images)} images and {len(labels)} labels")36            if {path.stem for path in images} != {path.stem for path in labels}:37                raise ValueError(f"Unpaired {task}/{split} sample stems")38            if len(masks) != len(images) or {path.stem for path in masks} != {39                    path.stem for path in images}:40                raise ValueError(f"Unpaired {task}/{split} foreground masks")41            result[task][split] = len(images)42    if result["segmentation"] != result["pose"]:43        raise ValueError("Segmentation and pose split counts differ")44    return result454647def train_task(args, task, model_path):48    from ultralytics import YOLO49    from yolo_background_augmentation import (50        BackgroundPoseTrainer, BackgroundSegmentationTrainer)5152    data = args.dataset.resolve() / task / "data.yaml"53    model = YOLO(str(model_path), task="segment" if task == "segmentation" else "pose")54    name = f"{args.name}_{'seg' if task == 'segmentation' else 'pose'}"55    options = dict(56        data=str(data),57        project=str(args.project.resolve()),58        name=name,59        exist_ok=args.exist_ok,60        epochs=args.epochs,61        patience=args.patience,62        batch=args.batch,63        imgsz=args.imgsz,64        device=args.device,65        workers=args.workers,66        optimizer="AdamW",67        lr0=args.lr0,68        freeze=args.freeze,69        seed=args.seed,70        deterministic=True,71        fliplr=0.0,72        close_mosaic=min(10, max(0, args.epochs // 5)),73        cache=args.cache,74        plots=True,75        verbose=True,76    )77    if not args.no_background_augmentation:78        trainer_class = (BackgroundSegmentationTrainer79                         if task == "segmentation" else BackgroundPoseTrainer)80        options["trainer"] = partial(81            trainer_class, background_dir=args.backgrounds,82            background_probability=args.background_probability,83            epoch_repeats=args.epoch_repeats)84    return model.train(**options)