Download pipeline/splitter.py from FaustDerLegende/Micro_component_dataset: direct link, hf CLI and curl.
- Browser
- Download file 4.25 kB
-
https://huggingface.co/datasets/FaustDerLegende/Micro_component_dataset/resolve/main/pipeline/splitter.py
- Command line
-
hf download hf://datasets/FaustDerLegende/Micro_component_dataset/pipeline/splitter.py
-
curl -L -o splitter.py https://huggingface.co/datasets/FaustDerLegende/Micro_component_dataset/resolve/main/pipeline/splitter.py
4.25 kB
| """Dataset Splitter Engine. | |
| Stratified, cluster-aware train / val / test dataset partitioning: | |
| - Prevents data leakage by ensuring all images in the same visual `cluster_id` | |
| are assigned to the SAME split (train, val, or test). | |
| - Maintains balanced class distributions across splits according to target ratios (e.g. 70 / 15 / 15). | |
| - Exports organized image & label directories under `data/splits/` for YOLOv8 model training. | |
| """ | |
| from __future__ import annotations | |
| import logging | |
| import random | |
| import shutil | |
| from collections import defaultdict | |
| from pathlib import Path | |
| from typing import Sequence | |
| from .manifest import Manifest | |
| log = logging.getLogger(__name__) | |
| def create_cluster_splits( | |
| manifest: Manifest, | |
| train_ratio: float = 0.70, | |
| val_ratio: float = 0.15, | |
| test_ratio: float = 0.15, | |
| seed: int = 42, | |
| ) -> dict[str, list[dict]]: | |
| """Partition valid images into cluster-isolated train/val/test splits.""" | |
| random.seed(seed) | |
| rows = manifest.images(statuses=["deduped", "kept", "validated", "normalized"]) | |
| if not rows: | |
| log.warning("splitter: no valid images found to split") | |
| return {"train": [], "val": [], "test": []} | |
| clusters: dict[str, list[dict]] = defaultdict(list) | |
| for r in rows: | |
| cid = r["cluster_id"] or r["image_id"] | |
| clusters[cid].append(r) | |
| cluster_items = list(clusters.items()) | |
| random.shuffle(cluster_items) | |
| total_count = len(rows) | |
| target_train = int(total_count * train_ratio) | |
| target_val = int(total_count * val_ratio) | |
| splits: dict[str, list[dict]] = {"train": [], "val": [], "test": []} | |
| current_train = 0 | |
| current_val = 0 | |
| for cid, members in cluster_items: | |
| mem_len = len(members) | |
| if current_train < target_train: | |
| splits["train"].extend(members) | |
| current_train += mem_len | |
| elif current_val < target_val: | |
| splits["val"].extend(members) | |
| current_val += mem_len | |
| else: | |
| splits["test"].extend(members) | |
| return splits | |
| def run( | |
| manifest: Manifest, | |
| cfg: dict, | |
| data_dir: Path, | |
| splits_dir: Path, | |
| train_ratio: float = 0.70, | |
| val_ratio: float = 0.15, | |
| test_ratio: float = 0.15, | |
| copy_files: bool = True, | |
| seed: int = 42, | |
| ) -> dict[str, int]: | |
| """Execute cluster-isolated dataset split and write image & label files to splits directory.""" | |
| splits = create_cluster_splits( | |
| manifest, train_ratio=train_ratio, val_ratio=val_ratio, test_ratio=test_ratio, seed=seed | |
| ) | |
| stats = { | |
| "train": len(splits["train"]), | |
| "val": len(splits["val"]), | |
| "test": len(splits["test"]), | |
| "total_split": sum(len(s) for s in splits.values()), | |
| } | |
| if not stats["total_split"]: | |
| log.warning("splitter: 0 images split") | |
| return stats | |
| with manifest.transaction(): | |
| for split_name, members in splits.items(): | |
| for m in members: | |
| manifest.update_image(m["image_id"], split=split_name) | |
| auto_labels_dir = data_dir / "annotated_auto" / "labels" | |
| if copy_files: | |
| for split_name, members in splits.items(): | |
| dst_img_dir = splits_dir / split_name / "images" | |
| dst_lbl_dir = splits_dir / split_name / "labels" | |
| dst_img_dir.mkdir(parents=True, exist_ok=True) | |
| dst_lbl_dir.mkdir(parents=True, exist_ok=True) | |
| for m in members: | |
| src_rel = m.get("norm_path") or m.get("orig_path") | |
| if not src_rel: | |
| continue | |
| src_path = data_dir / src_rel | |
| if src_path.exists(): | |
| dst_path = dst_img_dir / src_path.name | |
| if not dst_path.exists(): | |
| shutil.copy2(src_path, dst_path) | |
| # Copy matching label file if available | |
| label_name = f"{src_path.stem}.txt" | |
| src_label = auto_labels_dir / label_name | |
| if src_label.exists(): | |
| dst_label = dst_lbl_dir / label_name | |
| if not dst_label.exists(): | |
| shutil.copy2(src_label, dst_label) | |
| log.info("splitter split summary: %s", stats) | |
| return stats | |