Upload audited clean BioHCL-SSSM 256-d codebase, verified weights, 5-fold patient-grouped CV, and 11-variant ablations
bb5e4ec verified Download src/data/dataset.py from unknownBrain/BioHCL-SSSM: direct link, hf CLI and curl.
- Browser
- Download file 9.08 kB
-
https://huggingface.co/unknownBrain/BioHCL-SSSM/resolve/main/src/data/dataset.py
- Command line
-
hf download hf://unknownBrain/BioHCL-SSSM/src/data/dataset.py
-
curl -L -o dataset.py https://huggingface.co/unknownBrain/BioHCL-SSSM/resolve/main/src/data/dataset.py
9.08 kB
| """Leak-free Kermany Pediatric Chest X-Ray dataset loader with Union-Find patient/MD5 grouping.""" | |
| from __future__ import annotations | |
| import hashlib | |
| import os | |
| import re | |
| from pathlib import Path | |
| from typing import Iterator | |
| import albumentations as A | |
| import cv2 | |
| import numpy as np | |
| import pandas as pd | |
| from albumentations.pytorch import ToTensorV2 | |
| from PIL import Image | |
| from sklearn.model_selection import StratifiedGroupKFold | |
| from torch.utils.data import Dataset, WeightedRandomSampler | |
| CLASS_NAMES = ["NORMAL", "PNEUMONIA"] | |
| LABEL_MAP = {name: idx for idx, name in enumerate(CLASS_NAMES)} | |
| IMG_SIZE = 224 | |
| IMAGENET_MEAN = [0.485, 0.456, 0.406] | |
| IMAGENET_STD = [0.229, 0.224, 0.225] | |
| DEFAULT_DATA_CANDIDATES = [ | |
| r"D:\kaggle_cache\datasets\paultimothymooney\chest-xray-pneumonia\versions\2\chest_xray", | |
| r"D:\kaggle_cache\datasets\paultimothymooney\chest-xray-pneumonia\versions\1\chest_xray", | |
| r"D:\kaggle_cache\datasets\paultimothymooney\chest-xray-pneumonia\chest_xray", | |
| ] | |
| def resolve_kermany_root(data_dir: str | os.PathLike[str] | None = None) -> Path: | |
| """Locate the `chest_xray` folder containing `train/`, `val/`, and `test/`.""" | |
| candidates: list[Path] = [] | |
| if data_dir: | |
| candidates.append(Path(data_dir)) | |
| env_dir = os.environ.get("BIOHCL_DATA_DIR") | |
| if env_dir: | |
| candidates.append(Path(env_dir)) | |
| candidates.extend(Path(p) for p in DEFAULT_DATA_CANDIDATES) | |
| for cand in candidates: | |
| if (cand / "train").is_dir() and (cand / "test").is_dir(): | |
| return cand | |
| nested = cand / "chest_xray" | |
| if (nested / "train").is_dir() and (nested / "test").is_dir(): | |
| return nested | |
| raise FileNotFoundError( | |
| "Could not locate Kermany `chest_xray` root with `train/` and `test/`. " | |
| "Pass `--data-dir` or set `BIOHCL_DATA_DIR`." | |
| ) | |
| def extract_base_patient_token(split: str, cls: str, filename: str) -> str: | |
| """Extract canonical patient token preserving Kermany split/series disambiguation. | |
| Kermany `test/PNEUMONIA/` restarts `person1..` numbering independently of `train/`, | |
| so `person` IDs are prefixed by `{split}_` while `NORMAL` `IM-` vs `NORMAL2-IM-` | |
| prefixes are already disjoint across splits. | |
| """ | |
| m_person = re.match(r"^person(\d+)_", filename) | |
| if m_person: | |
| return f"{split}_person_{int(m_person.group(1))}" | |
| m_n2 = re.match(r"^NORMAL2-IM-(\d+)", filename) | |
| if m_n2: | |
| return f"NORMAL2-IM-{int(m_n2.group(1)):04d}" | |
| m_im = re.match(r"^IM-(\d+)", filename) | |
| if m_im: | |
| return f"IM-{int(m_im.group(1)):04d}" | |
| raise ValueError(f"Unrecognized Kermany filename pattern: {split}/{cls}/{filename}") | |
| def compute_md5(path: Path) -> str: | |
| h = hashlib.md5() | |
| with open(path, "rb") as f: | |
| for chunk in iter(lambda: f.read(65536), b""): | |
| h.update(chunk) | |
| return h.hexdigest() | |
| class _UnionFind: | |
| def __init__(self, n: int): | |
| self.parent = list(range(n)) | |
| def find(self, x: int) -> int: | |
| while self.parent[x] != x: | |
| self.parent[x] = self.parent[self.parent[x]] | |
| x = self.parent[x] | |
| return x | |
| def union(self, a: int, b: int) -> None: | |
| ra, rb = self.find(a), self.find(b) | |
| if ra != rb: | |
| self.parent[rb] = ra | |
| def _gather_raw_split(root: Path, split: str) -> pd.DataFrame: | |
| rows = [] | |
| exts = {".jpeg", ".jpg", ".png"} | |
| for cls in CLASS_NAMES: | |
| cls_dir = root / split / cls | |
| if not cls_dir.is_dir(): | |
| continue | |
| for p in sorted(cls_dir.iterdir()): | |
| if p.is_file() and p.suffix.lower() in exts: | |
| rows.append( | |
| { | |
| "path": str(p), | |
| "filename": p.name, | |
| "split_orig": split, | |
| "label_name": cls, | |
| "label": LABEL_MAP[cls], | |
| "raw_patient": extract_base_patient_token(split, cls, p.name), | |
| "md5": compute_md5(p), | |
| } | |
| ) | |
| return pd.DataFrame(rows) | |
| def assign_union_find_groups(df: pd.DataFrame) -> pd.DataFrame: | |
| """Merge records sharing either `raw_patient` OR exact byte `md5` before splitting.""" | |
| df = df.reset_index(drop=True).copy() | |
| uf = _UnionFind(len(df)) | |
| seen_patient: dict[str, int] = {} | |
| seen_md5: dict[str, int] = {} | |
| for idx, row in df.iterrows(): | |
| pat = row["raw_patient"] | |
| md5 = row["md5"] | |
| if pat in seen_patient: | |
| uf.union(idx, seen_patient[pat]) | |
| else: | |
| seen_patient[pat] = idx | |
| if md5 in seen_md5: | |
| uf.union(idx, seen_md5[md5]) | |
| else: | |
| seen_md5[md5] = idx | |
| roots = [uf.find(i) for i in range(len(df))] | |
| root_to_gid = {r: f"G{i:04d}" for i, r in enumerate(sorted(set(roots)))} | |
| df["group_id"] = [root_to_gid[r] for r in roots] | |
| return df | |
| def load_kermany_dataframes( | |
| data_dir: str | os.PathLike[str] | None = None, | |
| ) -> tuple[pd.DataFrame, pd.DataFrame, dict[str, int]]: | |
| """Load `train+val` (grouped via Union-Find) and untouched official `test/`.""" | |
| root = resolve_kermany_root(data_dir) | |
| df_train_raw = _gather_raw_split(root, "train") | |
| df_val_raw = _gather_raw_split(root, "val") | |
| df_trainval = pd.concat([df_train_raw, df_val_raw], ignore_index=True) | |
| df_trainval = assign_union_find_groups(df_trainval) | |
| df_test = _gather_raw_split(root, "test") | |
| df_test = assign_union_find_groups(df_test) | |
| assert len(set(df_trainval["md5"]) & set(df_test["md5"])) == 0, ( | |
| "DATA LEAKAGE: Cross-split exact MD5 collision detected between train+val and test!" | |
| ) | |
| meta = { | |
| "trainval_images": len(df_trainval), | |
| "trainval_groups": df_trainval["group_id"].nunique(), | |
| "test_images": len(df_test), | |
| "test_groups": df_test["group_id"].nunique(), | |
| } | |
| return df_trainval, df_test, meta | |
| def iter_patient_grouped_folds( | |
| df_trainval: pd.DataFrame, n_splits: int = 5, shuffle: bool = True, random_state: int = 42 | |
| ) -> Iterator[tuple[int, pd.DataFrame, pd.DataFrame]]: | |
| """Yield `(fold_idx, df_tr, df_va)` with strict patient-group & MD5 non-overlap assertions.""" | |
| sgkf = StratifiedGroupKFold(n_splits=n_splits, shuffle=shuffle, random_state=random_state) | |
| for fold_idx, (tr_idx, va_idx) in enumerate( | |
| sgkf.split(df_trainval, df_trainval["label"], df_trainval["group_id"]) | |
| ): | |
| df_tr = df_trainval.iloc[tr_idx].reset_index(drop=True) | |
| df_va = df_trainval.iloc[va_idx].reset_index(drop=True) | |
| assert len(set(df_tr["group_id"]) & set(df_va["group_id"])) == 0, ( | |
| f"Fold {fold_idx} patient group overlap detected!" | |
| ) | |
| assert len(set(df_tr["md5"]) & set(df_va["md5"])) == 0, ( | |
| f"Fold {fold_idx} exact MD5 duplicate overlap detected!" | |
| ) | |
| yield fold_idx, df_tr, df_va | |
| def get_transforms(img_size: int = IMG_SIZE) -> tuple[A.Compose, A.Compose]: | |
| train_transform = A.Compose( | |
| [ | |
| A.Resize(img_size, img_size), | |
| A.HorizontalFlip(p=0.5), | |
| A.Rotate(limit=10, p=0.5, border_mode=cv2.BORDER_CONSTANT), | |
| A.Affine( | |
| scale=(0.95, 1.05), | |
| translate_percent=(-0.05, 0.05), | |
| rotate=0, | |
| p=0.3, | |
| border_mode=cv2.BORDER_CONSTANT, | |
| ), | |
| A.RandomBrightnessContrast(brightness_limit=0.15, contrast_limit=0.15, p=0.3), | |
| A.Normalize(mean=IMAGENET_MEAN, std=IMAGENET_STD), | |
| ToTensorV2(), | |
| ] | |
| ) | |
| eval_transform = A.Compose( | |
| [ | |
| A.Resize(img_size, img_size), | |
| A.Normalize(mean=IMAGENET_MEAN, std=IMAGENET_STD), | |
| ToTensorV2(), | |
| ] | |
| ) | |
| return train_transform, eval_transform | |
| def build_weighted_sampler(df_train: pd.DataFrame) -> WeightedRandomSampler: | |
| counts = np.bincount(df_train["label"].to_numpy(), minlength=2) | |
| class_weights = 1.0 / np.maximum(counts, 1) | |
| sample_weights = class_weights[df_train["label"].to_numpy()] | |
| return WeightedRandomSampler( | |
| weights=sample_weights.tolist(), num_samples=len(df_train), replacement=True | |
| ) | |
| def compute_inverse_class_weights(df_train: pd.DataFrame) -> list[float]: | |
| counts = np.bincount(df_train["label"].to_numpy(), minlength=2).astype(np.float64) | |
| total = counts.sum() | |
| weights = total / (2.0 * np.maximum(counts, 1.0)) | |
| return weights.tolist() | |
| class ChestXrayDataset(Dataset): | |
| """RGB Chest X-Ray PyTorch dataset backed by Albumentations transforms.""" | |
| def __init__(self, df: pd.DataFrame, transform: A.Compose | None = None): | |
| self.df = df.reset_index(drop=True) | |
| self.transform = transform | |
| def __len__(self) -> int: | |
| return len(self.df) | |
| def __getitem__(self, idx: int): | |
| row = self.df.iloc[idx] | |
| img = np.array(Image.open(row["path"]).convert("RGB")) | |
| if self.transform is not None: | |
| img = self.transform(image=img)["image"] | |
| return img, int(row["label"]) | |