From 8c780be7fd40dab7e4d3db619e95e2fb1a300fbf Mon Sep 17 00:00:00 2001 From: Sanni heruwala Date: Sat, 21 Nov 2026 02:18:27 +0530 Subject: [PATCH 01/13] feat: add MEDFAIR subgroup fairness evaluation for imaging (BTY-62) Port the evaluation side of MEDFAIR (Zong et al., ICLR 2023) and its resampling baseline, with HAM10000 as the first benchmark: - group_fairness_metrics_fn: overall and per-subgroup AUC, accuracy, ECE, BCE, FPR/FNR, TPR@80%TNR, worst-group AUC, AUC gap, EqOdd - dto_select / minimax_pareto_select for fairness-aware model selection - GroupBalancedSampler and get_group_balanced_dataloader - HAM10000Dataset reads age/sex/site from the Dataverse metadata - HAM10000MalignancyClassification (MEL+AKIEC vs rest, sex/age fields) - examples/medfair_ham10000.py: ERM vs resampling under three selection rules --- docs/api/metrics.rst | 2 + .../pyhealth.metrics.fairness_selection.rst | 12 + .../pyhealth.metrics.group_fairness.rst | 10 + docs/api/sampler.rst | 3 + .../pyhealth.sampler.GroupBalancedSampler.rst | 12 + docs/api/tasks.rst | 1 + ...tasks.HAM10000MalignancyClassification.rst | 10 + examples/medfair_ham10000.py | 242 ++++++++++++++++++ pyhealth/datasets/configs/ham10000.yaml | 3 + pyhealth/datasets/ham10000.py | 58 ++++- pyhealth/datasets/utils.py | 28 +- pyhealth/metrics/__init__.py | 2 + pyhealth/metrics/fairness_selection.py | 97 +++++++ pyhealth/metrics/group_fairness.py | 197 ++++++++++++++ pyhealth/sampler/__init__.py | 2 + pyhealth/sampler/group_sampler.py | 188 ++++++++++++++ pyhealth/tasks/__init__.py | 3 + pyhealth/tasks/ham10000_malignancy.py | 111 ++++++++ tests/core/test_fairness_selection.py | 61 +++++ tests/core/test_group_fairness_metrics.py | 128 +++++++++ tests/core/test_group_sampler.py | 130 ++++++++++ tests/core/test_ham10000_malignancy_task.py | 158 ++++++++++++ 22 files changed, 1441 insertions(+), 17 deletions(-) create mode 100644 docs/api/metrics/pyhealth.metrics.fairness_selection.rst create mode 100644 docs/api/metrics/pyhealth.metrics.group_fairness.rst create mode 100644 docs/api/sampler/pyhealth.sampler.GroupBalancedSampler.rst create mode 100644 docs/api/tasks/pyhealth.tasks.HAM10000MalignancyClassification.rst create mode 100644 examples/medfair_ham10000.py create mode 100644 pyhealth/metrics/fairness_selection.py create mode 100644 pyhealth/metrics/group_fairness.py create mode 100644 pyhealth/sampler/group_sampler.py create mode 100644 pyhealth/tasks/ham10000_malignancy.py create mode 100644 tests/core/test_fairness_selection.py create mode 100644 tests/core/test_group_fairness_metrics.py create mode 100644 tests/core/test_group_sampler.py create mode 100644 tests/core/test_ham10000_malignancy_task.py diff --git a/docs/api/metrics.rst b/docs/api/metrics.rst index ccfc45a5d8..95a152f132 100644 --- a/docs/api/metrics.rst +++ b/docs/api/metrics.rst @@ -32,6 +32,8 @@ reference includes the ECE definition and formula used by these helpers. metrics/pyhealth.metrics.competing_risks metrics/pyhealth.metrics.prediction_set metrics/pyhealth.metrics.fairness + metrics/pyhealth.metrics.group_fairness + metrics/pyhealth.metrics.fairness_selection metrics/pyhealth.metrics.interpretability metrics/pyhealth.metrics.generative metrics/pyhealth.metrics.survival diff --git a/docs/api/metrics/pyhealth.metrics.fairness_selection.rst b/docs/api/metrics/pyhealth.metrics.fairness_selection.rst new file mode 100644 index 0000000000..f894131922 --- /dev/null +++ b/docs/api/metrics/pyhealth.metrics.fairness_selection.rst @@ -0,0 +1,12 @@ +pyhealth.metrics.fairness_selection +=================================== + +.. automodule:: pyhealth.metrics.fairness_selection + +.. currentmodule:: pyhealth.metrics.fairness_selection + +.. autofunction:: dto_select + +.. autofunction:: pareto_front + +.. autofunction:: minimax_pareto_select diff --git a/docs/api/metrics/pyhealth.metrics.group_fairness.rst b/docs/api/metrics/pyhealth.metrics.group_fairness.rst new file mode 100644 index 0000000000..4fc4189151 --- /dev/null +++ b/docs/api/metrics/pyhealth.metrics.group_fairness.rst @@ -0,0 +1,10 @@ +pyhealth.metrics.group_fairness +=================================== + +.. automodule:: pyhealth.metrics.group_fairness + +.. currentmodule:: pyhealth.metrics.group_fairness + +.. autofunction:: group_fairness_metrics_fn + +.. autofunction:: best_f1_threshold diff --git a/docs/api/sampler.rst b/docs/api/sampler.rst index e1a91f129a..6b97d60886 100644 --- a/docs/api/sampler.rst +++ b/docs/api/sampler.rst @@ -5,8 +5,11 @@ Samplers decide which examples or spatial locations a training step sees. :class:`~pyhealth.sampler.PatchSampler` is used by :class:`~pyhealth.datasets.PatchDataset` for segmentation patch sampling and nnU-Net-style foreground oversampling. +:class:`~pyhealth.sampler.GroupBalancedSampler` resamples training data so +every subgroup of a sensitive attribute is drawn equally often. .. toctree:: :maxdepth: 3 sampler/pyhealth.sampler.PatchSampler + sampler/pyhealth.sampler.GroupBalancedSampler diff --git a/docs/api/sampler/pyhealth.sampler.GroupBalancedSampler.rst b/docs/api/sampler/pyhealth.sampler.GroupBalancedSampler.rst new file mode 100644 index 0000000000..1ba62957dc --- /dev/null +++ b/docs/api/sampler/pyhealth.sampler.GroupBalancedSampler.rst @@ -0,0 +1,12 @@ +pyhealth.sampler.GroupBalancedSampler +===================================== + +Subgroup resampling: draw every sensitive-attribute group, or every +(group, label) cell, equally often during training. + +.. autoclass:: pyhealth.sampler.GroupBalancedSampler + :members: + :undoc-members: + :show-inheritance: + +.. autofunction:: pyhealth.sampler.get_group_balanced_dataloader diff --git a/docs/api/tasks.rst b/docs/api/tasks.rst index 7b975c17fe..655a6e0d2a 100644 --- a/docs/api/tasks.rst +++ b/docs/api/tasks.rst @@ -314,6 +314,7 @@ Available Tasks MIMIC-CXR Study Classification Barttender ChestX-ray14 Classification HAM10000 Skin Lesion Classification + HAM10000 Malignancy with Sensitive Attributes PH2 Artifact Sensitivity Classification Polyp Detection MSD Segmentation diff --git a/docs/api/tasks/pyhealth.tasks.HAM10000MalignancyClassification.rst b/docs/api/tasks/pyhealth.tasks.HAM10000MalignancyClassification.rst new file mode 100644 index 0000000000..22bb5c47c3 --- /dev/null +++ b/docs/api/tasks/pyhealth.tasks.HAM10000MalignancyClassification.rst @@ -0,0 +1,10 @@ +pyhealth.tasks.HAM10000MalignancyClassification +============================================= + +Malignant vs. benign HAM10000 images with sex, age and age group on every +sample, the HAM10000 setup of the MEDFAIR fairness benchmark. + +.. autoclass:: pyhealth.tasks.HAM10000MalignancyClassification + :members: + :undoc-members: + :show-inheritance: diff --git a/examples/medfair_ham10000.py b/examples/medfair_ham10000.py new file mode 100644 index 0000000000..82c35e4a55 --- /dev/null +++ b/examples/medfair_ham10000.py @@ -0,0 +1,242 @@ +"""MEDFAIR on HAM10000: ERM vs. subgroup resampling, three selection rules. + +The HAM10000 experiment of MEDFAIR (Zong, Yang and Hospedales, "MEDFAIR: +Benchmarking Fairness for Medical Imaging", ICLR 2023, +https://arxiv.org/abs/2210.01725). A ResNet-18 learns to tell malignant (MEL, +AKIEC) from benign lesions with plain ERM and with subgroup resampling, for +every learning rate and seed. Per method, a learning rate is then chosen +three ways from validation scores averaged over seeds: best overall AUC, +smallest distance to optimal (DTO) and minimax Pareto, the latter judged on +the group that is worst under ERM, as in MEDFAIR. The table gives the test +scores of each choice as mean (std) over seeds. + +Without ``--root`` the script writes a small synthetic ISIC 2018 layout to a +temporary directory and runs the whole pipeline as a smoke test; its numbers +mean nothing. On the real data (open access, see ``HAM10000Dataset``; put the +Dataverse ``HAM10000_metadata.csv`` next to the ISIC 2018 folders): + + python examples/medfair_ham10000.py --root /path/to/isic2018_task3 \\ + --cache-dir /path/to/cache --attribute sex --epochs 15 + +MEDFAIR reports with sex as the attribute (Table A9, minimax Pareto, mean of +3 seeds): ERM 85.20 overall / 83.12 worst-group AUC / 3.31 gap, resampling +86.94 / 85.04 / 3.09. Its age results use a 4-group binning that is not +published, so they are not directly comparable to ``--attribute age_group``. +""" + +from __future__ import annotations + +import argparse +import tempfile +from pathlib import Path + +import numpy as np +import pandas as pd +import torch +from PIL import Image + +from pyhealth.datasets import HAM10000Dataset, PatientSplit, get_dataloader +from pyhealth.metrics.fairness_selection import dto_select, minimax_pareto_select +from pyhealth.metrics.group_fairness import ( + best_f1_threshold, + group_fairness_metrics_fn, +) +from pyhealth.models import TorchvisionModel +from pyhealth.sampler import get_group_balanced_dataloader +from pyhealth.tasks import HAM10000MalignancyClassification +from pyhealth.trainer import Trainer + +CLASSES = ["MEL", "NV", "BCC", "AKIEC", "BKL", "DF", "VASC"] +REPORTED = ["auc", "worst_auc", "auc_gap"] + + +def write_synthetic_ham10000(root: Path, n_lesions: int, seed: int) -> None: + """Writes random images in the ISIC 2018 Task 3 layout plus Dataverse + metadata. Malignant images are redder, more so for men, so the subgroups + differ in difficulty.""" + rng = np.random.default_rng(seed) + image_dir = root / "ISIC2018_Task3_Training_Input" + gt_dir = root / "ISIC2018_Task3_Training_GroundTruth" + image_dir.mkdir(parents=True) + gt_dir.mkdir() + rows = [] + for i in range(n_lesions): + image = f"ISIC_{i:07d}" + diagnosis = CLASSES[rng.integers(len(CLASSES))] + sex = "male" if rng.random() < 0.55 else "female" + malignant = diagnosis in ("MEL", "AKIEC") + red = 90 + (100 if malignant else 0) * (1.0 if sex == "male" else 0.4) + pixels = rng.normal([red, 90, 120], 30, size=(32, 32, 3)).clip(0, 255) + Image.fromarray(pixels.astype(np.uint8)).save(image_dir / f"{image}.jpg") + rows.append( + { + "image": image, + "lesion_id": f"HAM_{i:07d}", + "diagnosis": diagnosis, + "age": float(rng.choice(np.arange(5, 90, 5))), + "sex": sex, + } + ) + frame = pd.DataFrame(rows) + onehot = {c: (frame["diagnosis"] == c).astype(float) for c in CLASSES} + pd.DataFrame({"image": frame["image"], **onehot}).to_csv( + gt_dir / f"{gt_dir.name}.csv", index=False + ) + frame.assign(diagnosis_confirm_type="histo")[ + ["image", "lesion_id", "diagnosis_confirm_type"] + ].to_csv(root / "ISIC2018_Task3_Training_LesionGroupings.csv", index=False) + frame.rename(columns={"image": "image_id", "diagnosis": "dx"}).assign( + dx_type="histo", localization="back" + ).to_csv(root / "HAM10000_metadata.csv", index=False) + + +def train_one(train, val, train_groups, args, method: str, lr: float, seed: int): + torch.manual_seed(seed) + if method == "resampling": + loader = get_group_balanced_dataloader( + train, args.batch_size, groups=train_groups, seed=seed + ) + else: + loader = get_dataloader(train, args.batch_size, shuffle=True, seed=seed) + model = TorchvisionModel( + dataset=train, + model_name="resnet18", + model_config={"weights": "DEFAULT" if args.pretrained else None}, + ) + trainer = Trainer(model=model, metrics=["roc_auc"], enable_logging=False) + trainer.train( + train_dataloader=loader, + val_dataloader=get_dataloader(val, args.batch_size), + epochs=args.epochs, + optimizer_params={"lr": lr}, + weight_decay=1e-4, + monitor="loss", + monitor_criterion="min", + patience=5, + ) + return trainer + + +def score_run(trainer, val, test, groups, batch_size) -> dict[str, dict]: + """Val and test metrics, the test set at the threshold tuned on val.""" + y_val, p_val, _ = trainer.inference(get_dataloader(val, batch_size)) + y_test, p_test, _ = trainer.inference(get_dataloader(test, batch_size)) + threshold = best_f1_threshold(y_val.ravel(), p_val.ravel()) + return { + "val": group_fairness_metrics_fn( + y_val, p_val, groups["val"], threshold=threshold + ), + "test": group_fairness_metrics_fn( + y_test, p_test, groups["test"], threshold=threshold + ), + } + + +def seed_stats(runs: list[dict], part: str) -> tuple[pd.Series, pd.Series]: + frame = pd.DataFrame([r[part] for r in runs]) + return frame.mean(), frame.std(ddof=0) + + +def select(settings: dict, names: list[str], ref: int | None) -> dict[str, float]: + """Learning rate picked by each rule from seed-averaged val scores.""" + lrs = list(settings) + means = [seed_stats(settings[lr], "val")[0] for lr in lrs] + aucs = np.array([[m.get(f"auc_{g}", np.nan) for g in names] for m in means]) + return { + "overall": lrs[int(np.argmax([m["auc"] for m in means]))], + "dto": lrs[dto_select(aucs)], + "minimax": lrs[minimax_pareto_select(aucs, group=ref)], + } + + +def defined_groups(settings: dict, names: list[str]) -> list[str]: + """Groups with a val AUC in every run; selection needs all of them.""" + runs = [r for rs in settings.values() for r in rs] + return [g for g in names if all(np.isfinite(r["val"][f"auc_{g}"]) for r in runs)] + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--root", help="ISIC 2018 Task 3 root; synthetic if unset") + parser.add_argument("--cache-dir", help="PyHealth cache; temporary if unset") + parser.add_argument("--attribute", default="sex", choices=["sex", "age_group"]) + parser.add_argument("--age-bins", type=int, nargs="+", default=[60]) + parser.add_argument("--image-size", type=int, default=224) + parser.add_argument("--epochs", type=int, default=15) + parser.add_argument("--batch-size", type=int, default=128) + parser.add_argument("--lrs", type=float, nargs="+", default=[1e-3, 1e-4, 1e-5]) + parser.add_argument("--seeds", type=int, nargs="+", default=[0, 1, 2]) + parser.add_argument("--no-pretrained", dest="pretrained", action="store_false") + args = parser.parse_args() + + with tempfile.TemporaryDirectory() as tmp: + root = args.root + if root is None: + root = Path(tmp) / "isic2018" + write_synthetic_ham10000(root, n_lesions=400, seed=0) + args.image_size, args.epochs, args.pretrained = 32, 2, False + args.lrs, args.seeds = [1e-3, 1e-4], [0, 1] + dataset = HAM10000Dataset( + root=str(root), cache_dir=args.cache_dir or str(Path(tmp) / "cache") + ) + task = HAM10000MalignancyClassification( + image_size=args.image_size, age_bins=args.age_bins + ) + train, val, test = dataset.set_task( + task, split=PatientSplit((0.8, 0.1, 0.1), seed=0) + ) + groups = { + name: [part[i][args.attribute] for i in range(len(part))] + for name, part in (("train", train), ("val", val), ("test", test)) + } + names = ["F", "M"] if args.attribute == "sex" else task.age_groups + + results = {} + for method in ("erm", "resampling"): + results[method] = { + lr: [ + score_run( + train_one(train, val, groups["train"], args, method, lr, s), + val, + test, + groups, + args.batch_size, + ) + for s in args.seeds + ] + for lr in args.lrs + } + + kept = [ + g + for g in names + if all(g in defined_groups(r, names) for r in results.values()) + ] + if len(kept) < len(names): + print( + f"Selecting on {kept}; no val AUC for {sorted(set(names) - set(kept))}." + ) + erm_means = [seed_stats(runs, "val")[0] for runs in results["erm"].values()] + erm_best = np.array([[m[f"auc_{g}"] for g in kept] for m in erm_means]).max(0) + ref = int(np.argmin(erm_best)) + + rows = [] + for method, settings in results.items(): + for rule, lr in select(settings, kept, ref).items(): + mean, std = seed_stats(settings[lr], "test") + rows.append( + { + "method": method, + "selection": rule, + "lr": lr, + **{k: f"{mean[k]:.4f} ({std[k]:.4f})" for k in REPORTED}, + } + ) + print(f"Minimax reference group (worst under ERM): {kept[ref]}") + print(pd.DataFrame(rows).to_string(index=False)) + for part in (train, val, test): + part.close() + + +if __name__ == "__main__": + main() diff --git a/pyhealth/datasets/configs/ham10000.yaml b/pyhealth/datasets/configs/ham10000.yaml index 0e4d5c95de..e196dfa7e7 100644 --- a/pyhealth/datasets/configs/ham10000.yaml +++ b/pyhealth/datasets/configs/ham10000.yaml @@ -11,3 +11,6 @@ tables: - "split" - "diagnosis" - "diagnosis_confirm_type" + - "age" + - "sex" + - "localization" diff --git a/pyhealth/datasets/ham10000.py b/pyhealth/datasets/ham10000.py index 5524206b0f..6b745fe4e3 100644 --- a/pyhealth/datasets/ham10000.py +++ b/pyhealth/datasets/ham10000.py @@ -50,6 +50,12 @@ class HAM10000Dataset(BaseDataset): in one part. The images do not identify patients, so a patient with several lesions can still appear in more than one part. + Age, sex and body site of the training images are only in the Harvard + Dataverse ``HAM10000_metadata.csv``. When it is in ``root`` they are + added as ``age``, ``sex`` and ``localization``, which subgroup analyses + such as :class:`~pyhealth.tasks.HAM10000MalignancyClassification` need; + without it these attributes are empty. + The official validation (193) and test (1,512) images are indexed too when ``splits`` asks for them. Their lesion ids were not released, so each of those images is its own patient. Every event has a ``split`` @@ -89,15 +95,18 @@ class reads the ISIC 2018 Task 3 layout below. Or pass ``download=True``, which downloads and unzips the missing files of the requested ``splits`` into ``root``. - Unpack: each zip extracts to a folder of the same name; the zips - can then be deleted. Instead of the lesion groupings CSV, the - Dataverse ``HAM10000_metadata`` file is accepted, saved as - ``HAM10000_metadata.csv`` (``wget -O HAM10000_metadata.csv + can then be deleted. + - Demographics (optional): save the Dataverse ``HAM10000_metadata`` + file as ``HAM10000_metadata.csv`` in ``root`` (``wget -O + HAM10000_metadata.csv "https://dataverse.harvard.edu/api/access/datafile/4338392?format=original"``). + It also replaces the lesion groupings CSV if that is missing. - ``root`` layout (validation and test folders only when ``splits`` asks for them):: isic2018_task3/ <- root ISIC2018_Task3_Training_LesionGroupings.csv + HAM10000_metadata.csv (optional) ISIC2018_Task3_Training_Input/ISIC_0024306.jpg ... ISIC2018_Task3_Training_GroundTruth/ ISIC2018_Task3_Training_GroundTruth.csv @@ -183,7 +192,16 @@ def __init__( ) self.metadata_dir.mkdir(parents=True, exist_ok=True) self.metadata_path = self.metadata_dir / _METADATA_FILE - self._source_key = f"root={self.source_root}|splits={','.join(self.splits)}" + dataverse = self.source_root / _DATAVERSE_METADATA + demographics = ( + f"{dataverse.stat().st_size}:{dataverse.stat().st_mtime_ns}" + if dataverse.exists() + else None + ) + self._source_key = ( + f"root={self.source_root}|splits={','.join(self.splits)}" + f"|demographics={demographics}" + ) marker = self.metadata_dir / "ham10000-source.txt" with FileLock(str(self.metadata_path) + ".lock"): current = marker.read_text().strip() if marker.exists() else None @@ -252,6 +270,29 @@ def _lesion_ids(self) -> pd.DataFrame: f"{HAM10000_BASE_URL}." ) + def _demographics(self) -> pd.DataFrame | None: + """Return ``image``, ``age``, ``sex``, ``localization``, or None.""" + dataverse = self.source_root / _DATAVERSE_METADATA + if not dataverse.exists(): + logger.info("No %s; age and sex are empty.", dataverse) + return None + meta = pd.read_csv(dataverse) + if "image_id" not in meta.columns: + raise ValueError( + f"{dataverse} has no image_id column. Download the CSV with " + "?format=original; the default Dataverse download is " + "tab-separated." + ) + if not {"age", "sex"} <= set(meta.columns): + logger.warning("%s has no age/sex columns; they stay empty.", dataverse) + return None + if "localization" not in meta.columns: + meta["localization"] = None + meta["sex"] = meta["sex"].map({"male": "M", "female": "F"}) + return meta.rename(columns={"image_id": "image"})[ + ["image", "age", "sex", "localization"] + ] + def prepare_metadata(self) -> None: """Write the metadata CSV, one row per image, to ``metadata_dir``. @@ -291,9 +332,15 @@ def prepare_metadata(self) -> None: "patient.", n_missing, ) + demographics = self._demographics() + if demographics is not None: + gt = gt.merge(demographics, on="image", how="left") else: gt["lesion_id"] = None gt["diagnosis_confirm_type"] = None + for column in ("age", "sex", "localization"): + if column not in gt.columns: + gt[column] = None image_dir = self.source_root / _input_dir(split) gt["path"] = [str(image_dir / f"{i}.jpg") for i in gt["image"]] exists = gt["path"].map(lambda p: Path(p).is_file()) @@ -321,6 +368,9 @@ def prepare_metadata(self) -> None: "split": split, "diagnosis": gt["diagnosis"], "diagnosis_confirm_type": gt["diagnosis_confirm_type"], + "age": gt["age"], + "sex": gt["sex"], + "localization": gt["localization"], } ) ) diff --git a/pyhealth/datasets/utils.py b/pyhealth/datasets/utils.py index e0e596d7be..9293ff364c 100644 --- a/pyhealth/datasets/utils.py +++ b/pyhealth/datasets/utils.py @@ -376,6 +376,20 @@ def __iter__(self): return super().__iter__() +def _sample_collate_fn(dataset) -> Callable: + """Collate function for a SampleDataset: fields whose processor defines + ``collate()`` are batched by it, the rest padded or listed.""" + processors = {**dataset.input_processors, **dataset.output_processors} + collators = { + key: processor.collate + for key, processor in processors.items() + if callable(getattr(processor, "collate", None)) + } + if not collators: + return collate_fn_dict_with_padding + return functools.partial(collate_fn_dict_with_padding, collators=collators) + + def get_dataloader( dataset: litdata.StreamingDataset, batch_size: int, @@ -433,25 +447,13 @@ def get_dataloader( "later set_shuffle/set_epoch calls would not reach them. Use " "persistent_workers=False or shuffle=False." ) - # Fields whose processor defines collate() are batched by it. - processors = {**dataset.input_processors, **dataset.output_processors} - collators = { - key: processor.collate - for key, processor in processors.items() - if callable(getattr(processor, "collate", None)) - } - collate_fn = ( - functools.partial(collate_fn_dict_with_padding, collators=collators) - if collators - else collate_fn_dict_with_padding - ) return _SeededDataLoader( dataset, shuffle_samples=shuffle, seed=seed, batch_size=batch_size, generator=generator, - collate_fn=collate_fn, + collate_fn=_sample_collate_fn(dataset), **loader_kwargs, ) if hasattr(dataset, "set_shuffle"): # another iterable dataset, e.g. litdata's diff --git a/pyhealth/metrics/__init__.py b/pyhealth/metrics/__init__.py index df55d63f77..064edfc9de 100644 --- a/pyhealth/metrics/__init__.py +++ b/pyhealth/metrics/__init__.py @@ -27,6 +27,7 @@ expected_discovery_bounds, marginal_association_pvalues, ) +from .group_fairness import group_fairness_metrics_fn from .generative import ( calc_membership_inference, calc_nnaar, @@ -109,6 +110,7 @@ "evaluate_attribution", "evaluate_synthetic_ehr", "fairness_metrics_fn", + "group_fairness_metrics_fn", "integrated_binomial_loglik_td", "integrated_brier_score_td", "iou_score", diff --git a/pyhealth/metrics/fairness_selection.py b/pyhealth/metrics/fairness_selection.py new file mode 100644 index 0000000000..266ad388f8 --- /dev/null +++ b/pyhealth/metrics/fairness_selection.py @@ -0,0 +1,97 @@ +"""Fairness-aware model selection from MEDFAIR (Zong et al., ICLR 2023). + +Two alternatives to picking the candidate with the best overall AUC: + + - distance to optimal (DTO): normalise each subgroup's score by the best + value any candidate reached for it (the utopia point) and pick the + candidate closest to it; + - minimax Pareto: among the Pareto-optimal candidates, pick the one with + the best worst-group score. + +Each function takes per-subgroup validation scores, one row per candidate +and one column per subgroup, higher is better, such as the ``"auc_{group}"`` +values of :func:`~pyhealth.metrics.group_fairness.group_fairness_metrics_fn`. +""" + +import numpy as np + + +def _check(scores: np.ndarray) -> np.ndarray: + scores = np.asarray(scores, dtype=float) + if scores.ndim != 2 or scores.size == 0: + raise ValueError( + f"scores must be a non-empty (n_candidates, n_groups) matrix, " + f"got shape {scores.shape}." + ) + if np.isnan(scores).any(): + raise ValueError("scores contain NaN; drop or impute those groups first.") + return scores + + +def dto_select(scores: np.ndarray) -> int: + """Index of the candidate closest to the utopia point. + + ``DTO_i = || 1 - scores_i / max_j scores_j ||_2``, the utopia point being + the best score of each subgroup over all candidates. + + Args: + scores: Per-subgroup scores of shape (n_candidates, n_groups). + + Returns: + Row index of the candidate with the smallest DTO. + + Examples: + >>> dto_select(np.array([[0.80, 0.70], [0.78, 0.76], [0.85, 0.60]])) + 1 + """ + scores = _check(scores) + return int(np.argmin(np.linalg.norm(1.0 - scores / scores.max(axis=0), axis=1))) + + +def pareto_front(scores: np.ndarray) -> np.ndarray: + """Indices of the candidates no other candidate dominates. + + Candidate ``j`` dominates ``i`` if it scores at least as well on every + subgroup and strictly better on one. Identical candidates are all kept. + + Args: + scores: Per-subgroup scores of shape (n_candidates, n_groups). + + Returns: + Sorted row indices of the Pareto front. + + Examples: + >>> pareto_front(np.array([[0.8, 0.7], [0.75, 0.65], [0.6, 0.9]])) + array([0, 2]) + """ + scores = _check(scores) + geq = (scores[:, None, :] >= scores[None, :, :]).all(axis=2) + gt = (scores[:, None, :] > scores[None, :, :]).any(axis=2) + dominated = (geq & gt).any(axis=0) + return np.flatnonzero(~dominated) + + +def minimax_pareto_select(scores: np.ndarray, group: int | None = None) -> int: + """Pareto-optimal candidate with the best worst-group score. + + Args: + scores: Per-subgroup scores of shape (n_candidates, n_groups). + group: Column of a fixed reference group to maximise instead of each + candidate's own minimum. MEDFAIR fixes it to the group with the + lowest best AUC under ERM, so every method is judged on the same + group. Defaults to None. + + Returns: + Row index of the selected candidate. + + Examples: + >>> scores = np.array([[0.80, 0.70], [0.78, 0.76], [0.85, 0.60]]) + >>> minimax_pareto_select(scores), minimax_pareto_select(scores, group=0) + (1, 2) + """ + scores = _check(scores) + if group is not None and not 0 <= group < scores.shape[1]: + raise ValueError(f"group must be in [0, {scores.shape[1] - 1}], got {group}.") + front = pareto_front(scores) + target = scores[front].min(axis=1) if group is None else scores[front, group] + return int(front[np.argmax(target)]) diff --git a/pyhealth/metrics/group_fairness.py b/pyhealth/metrics/group_fairness.py new file mode 100644 index 0000000000..a8c4ff1a96 --- /dev/null +++ b/pyhealth/metrics/group_fairness.py @@ -0,0 +1,197 @@ +"""Subgroup performance and fairness metrics for binary classifiers. + +The evaluation protocol of MEDFAIR (Zong, Yang and Hospedales, "MEDFAIR: +Benchmarking Fairness for Medical Imaging", ICLR 2023, +https://arxiv.org/abs/2210.01725). +""" + +import warnings +from collections.abc import Hashable, Sequence + +import numpy as np +import pandas as pd +from sklearn.metrics import precision_recall_curve, roc_auc_score, roc_curve + +from .calibration import ece_confidence_binary + +_PER_GROUP = ("auc", "acc", "ece", "bce", "fpr", "fnr", "tpr_at_tnr80") +_SUMMARY = ("worst_auc", "auc_gap", "eqodd") + + +def best_f1_threshold(y_true: np.ndarray, y_prob: np.ndarray) -> float: + """Returns the decision threshold that maximises F1. + + MEDFAIR picks the operating point this way. Tune it on validation data + and pass it to :func:`group_fairness_metrics_fn` for the test set. + + Args: + y_true: Binary labels of shape (n_samples,). + y_prob: Positive-class probabilities of shape (n_samples,). + + Returns: + The threshold ``t`` maximising F1 of ``y_prob >= t``. + + Examples: + >>> best_f1_threshold(np.array([0, 1, 1]), np.array([0.2, 0.6, 0.9])) + 0.6 + """ + precision, recall, thresholds = precision_recall_curve(y_true, y_prob) + with np.errstate(divide="ignore", invalid="ignore"): + f1 = np.nan_to_num(2 * precision * recall / (precision + recall)) + return float(thresholds[np.argmax(f1[:-1])]) + + +def _bce(y_true: np.ndarray, y_prob: np.ndarray) -> float: + p = np.clip(y_prob, 1e-7, 1 - 1e-7) + return float(-np.mean(y_true * np.log(p) + (1 - y_true) * np.log(1 - p))) + + +def _rate(hit: np.ndarray, condition: np.ndarray) -> float: + count = condition.sum() + return float((hit & condition).sum() / count) if count else float("nan") + + +def _score(name: str, y_true, y_prob, y_pred) -> float: + if name in ("auc", "tpr_at_tnr80") and len(np.unique(y_true)) < 2: + return float("nan") + if name == "auc": + return float(roc_auc_score(y_true, y_prob)) + if name == "tpr_at_tnr80": + fpr, tpr, _ = roc_curve(y_true, y_prob) + return float(np.interp(0.2, fpr, tpr)) + if name == "acc": + return float(np.mean(y_pred == y_true)) + if name == "ece": + return float(ece_confidence_binary(y_prob, y_true, bins=10)) + if name == "bce": + return _bce(y_true, y_prob) + positive = y_true == 1 + if name == "fpr": + return _rate(y_pred, ~positive) + return _rate(~y_pred, positive) + + +def group_fairness_metrics_fn( + y_true: np.ndarray, + y_prob: np.ndarray, + groups: Sequence[Hashable], + metrics: list[str] | None = None, + threshold: float | None = None, +) -> dict[str, float]: + """Computes overall and per-subgroup metrics for a binary classifier. + + Per-subgroup values are stored as ``"{metric}_{group}"``, e.g. + ``"auc_F"``, next to the overall value under ``"{metric}"``. Accepted + metric names: + + - ``auc``, ``acc``, ``ece``, ``bce``: ROC AUC, accuracy, expected + calibration error (10 equal-width bins on [0, 1]) and binary + cross-entropy. + - ``fpr``, ``fnr``: false positive / negative rate at ``threshold``. + - ``tpr_at_tnr80``: sensitivity at 80% specificity. + - ``worst_auc``, ``auc_gap``: lowest subgroup AUC, and highest minus + lowest. + - ``eqodd``: equalized odds, ``1 - (|dFPR| + |dTPR|) / 2`` between + the two subgroups of a binary attribute. + + A subgroup with a single class has no AUC; it gets NaN with a warning and + is left out of ``worst_auc`` and ``auc_gap``. + + Unlike :func:`~pyhealth.metrics.subgroup_metrics`, this reports error + rates and equalized odds at a chosen operating point, with MEDFAIR's + metric set, so results compare directly with that benchmark. + + Args: + y_true: Binary labels of shape (n_samples,). + y_prob: Positive-class probabilities of shape (n_samples,) or + (n_samples, 1). + groups: Sensitive-attribute value of each sample, e.g. ``"F"``/``"M"`` + or an age bin. Missing values are rejected. + metrics: Metric names to compute. Defaults to all of them, with + ``eqodd`` only when there are exactly two subgroups. + threshold: Decision threshold for ``acc``, ``fpr``, ``fnr`` and + ``eqodd``. Defaults to None, which tunes it on the data given + with :func:`best_f1_threshold`, as the MEDFAIR paper does (its + code uses 0.5 for the per-group FPR/FNR). For a clean test + estimate pass the threshold tuned on validation. The value used + is returned as ``"threshold"``. + + Returns: + Dictionary from metric name to value. + + Raises: + ValueError: On mismatched lengths, missing group values, unknown + metric names, or ``eqodd`` with other than two groups. + + Examples: + >>> y_true = np.array([0, 0, 1, 1, 0, 0, 1, 1]) + >>> y_prob = np.array([0.1, 0.4, 0.35, 0.8, 0.2, 0.6, 0.7, 0.9]) + >>> groups = np.array(["M"] * 4 + ["F"] * 4) + >>> s = group_fairness_metrics_fn(y_true, y_prob, groups, threshold=0.5) + >>> s["auc_M"], s["auc_F"], s["auc_gap"], s["eqodd"] + (0.75, 1.0, 0.25, 0.5) + """ + y_true = np.asarray(y_true).reshape(-1).astype(int) + y_prob = np.asarray(y_prob, dtype=float).reshape(-1) + groups = np.asarray(groups, dtype=object).reshape(-1) + if not len(y_true) == len(y_prob) == len(groups): + raise ValueError( + f"y_true, y_prob and groups must have the same length, got " + f"{len(y_true)}, {len(y_prob)} and {len(groups)}." + ) + if pd.isna(groups).any(): + raise ValueError("groups contain missing values.") + names = sorted(set(groups.tolist()), key=str) + if metrics is None: + metrics = [*_PER_GROUP, "worst_auc", "auc_gap"] + if len(names) == 2: + metrics.append("eqodd") + unknown = set(metrics) - set(_PER_GROUP) - set(_SUMMARY) + if unknown: + raise ValueError(f"Unknown fairness metrics: {sorted(unknown)}.") + if "eqodd" in metrics and len(names) != 2: + raise ValueError(f"eqodd needs exactly two groups, got {len(names)}.") + + if threshold is None: + threshold = best_f1_threshold(y_true, y_prob) + y_pred = y_prob >= threshold + + needed = set(metrics) + if needed & {"worst_auc", "auc_gap"}: + needed.add("auc") + if "eqodd" in needed: + needed |= {"fpr", "fnr"} + + scores: dict[str, float] = {} + for name in (m for m in _PER_GROUP if m in needed): + scores[name] = _score(name, y_true, y_prob, y_pred) + for g in names: + mask = groups == g + scores[f"{name}_{g}"] = _score( + name, y_true[mask], y_prob[mask], y_pred[mask] + ) + + if "auc" in needed: + aucs = np.array([scores[f"auc_{g}"] for g in names]) + undefined = [str(g) for g, a in zip(names, aucs) if np.isnan(a)] + if undefined: + warnings.warn( + f"AUC undefined for single-class groups {undefined}.", stacklevel=2 + ) + defined = aucs[~np.isnan(aucs)] + scores["worst_auc"] = float(defined.min()) if len(defined) else float("nan") + scores["auc_gap"] = ( + float(defined.max() - defined.min()) if len(defined) else float("nan") + ) + if "eqodd" in needed: + a, b = names + d_fpr = abs(scores[f"fpr_{a}"] - scores[f"fpr_{b}"]) + d_tpr = abs((1 - scores[f"fnr_{a}"]) - (1 - scores[f"fnr_{b}"])) + scores["eqodd"] = 1.0 - 0.5 * (d_fpr + d_tpr) + + out = {"threshold": float(threshold)} + for name in metrics: + out[name] = scores[name] + if name in _PER_GROUP: + out.update({f"{name}_{g}": scores[f"{name}_{g}"] for g in names}) + return out diff --git a/pyhealth/sampler/__init__.py b/pyhealth/sampler/__init__.py index 4f3e592a1d..3c2aacc976 100644 --- a/pyhealth/sampler/__init__.py +++ b/pyhealth/sampler/__init__.py @@ -1,3 +1,5 @@ from .patch_sampler import PatchLocation as PatchLocation from .patch_sampler import PatchSampler as PatchSampler from .sage_sampler import NeighborSampler as NeighborSampler +from .group_sampler import GroupBalancedSampler as GroupBalancedSampler +from .group_sampler import get_group_balanced_dataloader as get_group_balanced_dataloader diff --git a/pyhealth/sampler/group_sampler.py b/pyhealth/sampler/group_sampler.py new file mode 100644 index 0000000000..282efdad77 --- /dev/null +++ b/pyhealth/sampler/group_sampler.py @@ -0,0 +1,188 @@ +"""Subgroup resampling (Idrissi et al., CLeaR 2022), a MEDFAIR baseline.""" + +from collections.abc import Hashable, Iterator, Sequence +from typing import Any + +import numpy as np +import pandas as pd +import torch +from torch.utils.data import DataLoader, Dataset, Sampler + +from ..datasets.utils import _sample_collate_fn + + +def _hashable(value: Any) -> Hashable: + if isinstance(value, (torch.Tensor, np.ndarray, np.generic)): + value = value.tolist() + if isinstance(value, list): + return value[0] if len(value) == 1 else tuple(value) + return value + + +class GroupBalancedSampler(Sampler[int]): + """Draws indices with replacement so every group is equally likely. + + Each sample gets weight ``1 / |group|``. With ``labels`` the groups are + the (group, label) cells, which also balances the classes within each + group (MEDFAIR's subgroup x class resampling). + + The draws of a pass depend only on ``seed`` and the epoch, which + advances after every pass and can be set with :meth:`set_epoch`. + + Args: + groups: Group of each sample, e.g. its sex or age bin. + labels: Optional label of each sample, to balance the (group, label) + cells. Defaults to None. + num_samples: Indices drawn per pass. Defaults to ``len(groups)``. + seed: Seed of the draws. Defaults to 0. + + Raises: + ValueError: If ``groups`` is empty, has missing values, or differs + in length from ``labels``. + + Examples: + >>> sampler = GroupBalancedSampler(["F", "F", "F", "M"], seed=0) + >>> sampler.weights.tolist() + [0.3333333333333333, 0.3333333333333333, 0.3333333333333333, 1.0] + >>> len(sampler) + 4 + """ + + def __init__( + self, + groups: Sequence[Hashable], + labels: Sequence[Hashable] | None = None, + num_samples: int | None = None, + seed: int = 0, + ) -> None: + groups = [_hashable(g) for g in groups] + if not groups: + raise ValueError("groups is empty.") + if any(pd.isna(g) for g in groups if not isinstance(g, tuple)): + raise ValueError("groups contain missing values.") + keys: list = groups + if labels is not None: + if len(labels) != len(groups): + raise ValueError( + f"groups and labels differ in length: " + f"{len(groups)} vs {len(labels)}." + ) + keys = list(zip(groups, (_hashable(y) for y in labels))) + codes: dict = {} + cells = np.array([codes.setdefault(k, len(codes)) for k in keys]) + self.weights = torch.as_tensor( + 1.0 / np.bincount(cells)[cells], dtype=torch.double + ) + self.num_samples = len(cells) if num_samples is None else int(num_samples) + self.seed = int(seed) + self.epoch = 0 + + def set_epoch(self, epoch: int) -> None: + """Sets the epoch of the next pass. + + Examples: + >>> GroupBalancedSampler(["F", "M"]).set_epoch(3) + """ + self.epoch = int(epoch) + + def __iter__(self) -> Iterator[int]: + state = np.random.SeedSequence([self.seed, self.epoch]).generate_state(1) + generator = torch.Generator().manual_seed(int(state[0])) + self.epoch += 1 + draws = torch.multinomial( + self.weights, self.num_samples, replacement=True, generator=generator + ) + return iter(draws.tolist()) + + def __len__(self) -> int: + return self.num_samples + + +class _IndexView(Dataset): + """Random-access view of a (streaming) sample dataset.""" + + def __init__(self, dataset: Any) -> None: + self.dataset = dataset + + def __len__(self) -> int: + return len(self.dataset) + + def __getitem__(self, index: int) -> Any: + return self.dataset[index] + + +def get_group_balanced_dataloader( + dataset: Any, + batch_size: int, + group_key: str | None = None, + label_key: str | None = None, + groups: Sequence[Hashable] | None = None, + labels: Sequence[Hashable] | None = None, + num_samples: int | None = None, + seed: int | None = None, + **loader_kwargs: Any, +) -> DataLoader: + """Training loader that resamples a sample dataset by subgroup. + + A drop-in replacement for :func:`~pyhealth.datasets.get_dataloader` on the + training split. Give the groups either as a sample field (``group_key``, + read from every sample once, which decodes its inputs too) or directly + (``groups``, in dataset order); likewise for the optional labels. + + Args: + dataset: A :class:`~pyhealth.datasets.SampleDataset`. + batch_size: Samples per batch. + group_key: Sample field holding the sensitive attribute. + label_key: Sample field holding the label, to balance the + (group, label) cells. Defaults to None. + groups: Group of each sample, instead of ``group_key``. + labels: Label of each sample, instead of ``label_key``. + num_samples: Samples drawn per epoch. Defaults to ``len(dataset)``. + seed: Seed of the draws. Default None draws one from torch's random + generator, so ``torch.manual_seed`` controls it. + **loader_kwargs: Forwarded to ``DataLoader``, e.g. ``num_workers``. + + Returns: + A ``DataLoader`` whose ``sampler`` is a :class:`GroupBalancedSampler`. + + Raises: + ValueError: Unless exactly one of ``group_key`` and ``groups`` is + given, if both ``label_key`` and ``labels`` are, or if + ``groups`` does not match the dataset length. + KeyError: If a sample lacks ``group_key`` or ``label_key``. + + Examples: + >>> loader = get_group_balanced_dataloader( # doctest: +SKIP + ... train_ds, batch_size=64, group_key="sex", seed=0 + ... ) + >>> trainer.train(train_dataloader=loader, ...) # doctest: +SKIP + """ + if (group_key is None) == (groups is None): + raise ValueError("Pass exactly one of group_key and groups.") + if label_key is not None and labels is not None: + raise ValueError("Pass at most one of label_key and labels.") + keys = [k for k in (group_key, label_key) if k is not None] + if keys: + columns = {k: [] for k in keys} + for i in range(len(dataset)): + sample = dataset[i] + for k in keys: + columns[k].append(sample[k]) + groups = columns[group_key] if group_key is not None else groups + labels = columns[label_key] if label_key is not None else labels + if len(groups) != len(dataset): + raise ValueError( + f"Got {len(groups)} groups for a dataset of {len(dataset)} samples." + ) + if seed is None: + seed = int(torch.randint(0, 2**31 - 1, ()).item()) + sampler = GroupBalancedSampler( + groups, labels=labels, num_samples=num_samples, seed=seed + ) + return DataLoader( + _IndexView(dataset), + batch_size=batch_size, + sampler=sampler, + collate_fn=_sample_collate_fn(dataset), + **loader_kwargs, + ) diff --git a/pyhealth/tasks/__init__.py b/pyhealth/tasks/__init__.py index 1cad4e864a..5eec2bb4c6 100644 --- a/pyhealth/tasks/__init__.py +++ b/pyhealth/tasks/__init__.py @@ -41,6 +41,9 @@ from .ham10000_classification import ( HAM10000Classification as HAM10000Classification, ) +from .ham10000_malignancy import ( + HAM10000MalignancyClassification as HAM10000MalignancyClassification, +) from .ph2_artifact_classification import ( PH2ArtifactClassification as PH2ArtifactClassification, ) diff --git a/pyhealth/tasks/ham10000_malignancy.py b/pyhealth/tasks/ham10000_malignancy.py new file mode 100644 index 0000000000..e50d432f30 --- /dev/null +++ b/pyhealth/tasks/ham10000_malignancy.py @@ -0,0 +1,111 @@ +"""Malignant vs. benign HAM10000 task with sensitive attributes (MEDFAIR).""" + +import itertools +import math +from collections.abc import Sequence +from typing import Any, ClassVar + +import numpy as np + +from .base_task import BaseTask + +MALIGNANT = frozenset({"MEL", "AKIEC"}) + + +def _age_labels(edges: tuple[int, ...]) -> list[str]: + inner = [f"({lo}, {hi}]" for lo, hi in itertools.pairwise(edges)] + return [f"<={edges[0]}", *inner, f">{edges[-1]}"] + + +class HAM10000MalignancyClassification(BaseTask): + """Binary malignancy classification of HAM10000 images, with subgroups. + + Works with :class:`~pyhealth.datasets.HAM10000Dataset` when the Dataverse + ``HAM10000_metadata.csv`` is in its root, since age and sex come from it; + without it no samples are produced. + + The HAM10000 setup of MEDFAIR (Zong et al., ICLR 2023): melanoma (MEL) + and actinic keratosis / intraepithelial carcinoma (AKIEC) are malignant, + the other five diagnoses benign, following Maron et al. (2019). Images + with an unknown age or sex are dropped, leaving 9,948 of the 10,015 + training images. MEDFAIR splits them 80/10/10 by lesion; + ``PatientSplit((0.8, 0.1, 0.1))`` follows the same protocol. About 14% + of the images are malignant, so report AUC rather than accuracy. + + Each sample also has: + + - ``sex``: ``"F"`` or ``"M"``. + - ``age``: age in years, rounded to 5 in HAM10000. + - ``age_group``: the bin of ``age`` given by ``age_bins``, each bin + including its upper edge. The default ``(60,)`` gives ``"<=60"`` and + ``">60"``, MEDFAIR's binary age attribute. Its five-group attribute + (0-19, 20-39, 40-59, 60-79, 80+) is ``(19, 39, 59, 79)``. + + Args: + image_size: Side length of the square input image. Defaults to 224. + age_bins: Increasing upper edges of the age groups. Defaults to + ``(60,)``. + + Examples: + >>> from pyhealth.datasets import HAM10000Dataset, PatientSplit + >>> from pyhealth.tasks import HAM10000MalignancyClassification + >>> dataset = HAM10000Dataset(root="/path/to/isic2018") # doctest: +SKIP + >>> train, val, test = dataset.set_task( # doctest: +SKIP + ... HAM10000MalignancyClassification(), + ... split=PatientSplit((0.8, 0.1, 0.1), seed=0), + ... ) + >>> HAM10000MalignancyClassification(age_bins=(19, 39, 59, 79)).age_groups + ['<=19', '(19, 39]', '(39, 59]', '(59, 79]', '>79'] + """ + + task_name: str = "HAM10000MalignancyClassification" + input_schema: ClassVar[dict[str, Any]] = { + "image": ("image", {"image_size": 224, "mode": "RGB"}) + } + output_schema: ClassVar[dict[str, Any]] = {"malignant": "binary"} + + def __init__(self, image_size: int = 224, age_bins: Sequence[int] = (60,)) -> None: + super().__init__() + edges = tuple(int(e) for e in age_bins) + increasing = all(a < b for a, b in itertools.pairwise(edges)) + if not edges or not increasing or edges[0] <= 0: + raise ValueError( + f"age_bins must be positive and strictly increasing, got {age_bins!r}." + ) + self.image_size = int(image_size) + self.age_bins = edges + self.age_groups = _age_labels(edges) + self.input_schema = { + "image": ("image", {"image_size": self.image_size, "mode": "RGB"}) + } + + def __call__(self, patient: Any) -> list[dict[str, Any]]: + """Build one sample per image of the lesion with known age and sex. + + Args: + patient: A PyHealth ``Patient`` with ``ham10000`` events. + + Returns: + Samples with ``patient_id``, ``image_id``, ``image`` (the JPEG + path), ``malignant`` (0 or 1), ``sex``, ``age`` and ``age_group``. + """ + samples = [] + for event in patient.get_events(event_type="ham10000"): + sex = getattr(event, "sex", None) + age = getattr(event, "age", None) + if sex not in ("F", "M") or age is None or math.isnan(float(age)): + continue + age = float(age) + group = int(np.searchsorted(self.age_bins, age, side="left")) + samples.append( + { + "patient_id": patient.patient_id, + "image_id": event.image_id, + "image": event.path, + "malignant": int(event.diagnosis in MALIGNANT), + "sex": sex, + "age": age, + "age_group": self.age_groups[group], + } + ) + return samples diff --git a/tests/core/test_fairness_selection.py b/tests/core/test_fairness_selection.py new file mode 100644 index 0000000000..c04d71ff24 --- /dev/null +++ b/tests/core/test_fairness_selection.py @@ -0,0 +1,61 @@ +"""Tests for pyhealth.metrics.fairness_selection.""" + +import unittest + +import numpy as np + +from pyhealth.metrics.fairness_selection import ( + dto_select, + minimax_pareto_select, + pareto_front, +) + +# rows: candidate models, columns: per-group validation AUC +SCORES = np.array( + [ + [0.80, 0.70], + [0.78, 0.76], + [0.85, 0.60], + [0.75, 0.74], + ] +) + + +class TestFairnessSelection(unittest.TestCase): + def test_dto_select(self): + distances = np.linalg.norm(1 - SCORES / SCORES.max(axis=0), axis=1) + self.assertEqual(dto_select(SCORES), int(np.argmin(distances))) + self.assertEqual(dto_select(SCORES), 1) + + def test_dto_prefers_utopia(self): + scores = np.array([[0.9, 0.5], [0.6, 0.8], [0.9, 0.8]]) + self.assertEqual(dto_select(scores), 2) + + def test_pareto_front_drops_dominated(self): + np.testing.assert_array_equal(pareto_front(SCORES), [0, 1, 2]) + + def test_pareto_front_keeps_ties(self): + scores = np.array([[0.8, 0.8], [0.8, 0.8], [0.7, 0.7]]) + np.testing.assert_array_equal(pareto_front(scores), [0, 1]) + + def test_minimax_maximises_worst_group(self): + self.assertEqual(minimax_pareto_select(SCORES), 1) + + def test_minimax_reference_group(self): + self.assertEqual(minimax_pareto_select(SCORES, group=0), 2) + + def test_single_candidate(self): + self.assertEqual(dto_select(SCORES[:1]), 0) + self.assertEqual(minimax_pareto_select(SCORES[:1]), 0) + + def test_rejects_bad_input(self): + with self.assertRaises(ValueError): + dto_select(np.array([0.8, 0.7])) + with self.assertRaises(ValueError): + dto_select(np.array([[0.8, np.nan]])) + with self.assertRaises(ValueError): + minimax_pareto_select(SCORES, group=2) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/core/test_group_fairness_metrics.py b/tests/core/test_group_fairness_metrics.py new file mode 100644 index 0000000000..ce39fd47fa --- /dev/null +++ b/tests/core/test_group_fairness_metrics.py @@ -0,0 +1,128 @@ +"""Tests for pyhealth.metrics.group_fairness.""" + +import unittest + +import numpy as np +from sklearn.metrics import log_loss + +from pyhealth.metrics.group_fairness import ( + best_f1_threshold, + group_fairness_metrics_fn, +) + + +class TestGroupFairnessMetrics(unittest.TestCase): + def setUp(self): + self.y_true = np.array([0, 0, 1, 1, 0, 0, 1, 1]) + self.y_prob = np.array([0.1, 0.4, 0.35, 0.8, 0.2, 0.6, 0.7, 0.9]) + self.groups = np.array(["M"] * 4 + ["F"] * 4) + + def score(self, **kwargs): + return group_fairness_metrics_fn( + self.y_true, self.y_prob, self.groups, threshold=0.5, **kwargs + ) + + def test_auc_per_group_worst_and_gap(self): + s = self.score() + self.assertAlmostEqual(s["auc"], 0.875) + self.assertAlmostEqual(s["auc_M"], 0.75) + self.assertAlmostEqual(s["auc_F"], 1.0) + self.assertAlmostEqual(s["worst_auc"], 0.75) + self.assertAlmostEqual(s["auc_gap"], 0.25) + + def test_threshold_metrics(self): + s = self.score() + self.assertAlmostEqual(s["acc"], 0.75) + self.assertAlmostEqual(s["fpr_M"], 0.0) + self.assertAlmostEqual(s["fnr_M"], 0.5) + self.assertAlmostEqual(s["fpr_F"], 0.5) + self.assertAlmostEqual(s["fnr_F"], 0.0) + self.assertAlmostEqual(s["fpr"], 0.25) + self.assertAlmostEqual(s["fnr"], 0.25) + self.assertEqual(s["threshold"], 0.5) + + def test_equalized_odds(self): + self.assertAlmostEqual(self.score()["eqodd"], 0.5) + + def test_eqodd_needs_two_groups(self): + groups = np.array(["a", "a", "b", "b", "c", "c", "c", "c"]) + s = group_fairness_metrics_fn(self.y_true, self.y_prob, groups) + self.assertNotIn("eqodd", s) + with self.assertRaises(ValueError): + group_fairness_metrics_fn( + self.y_true, self.y_prob, groups, metrics=["eqodd"] + ) + + def test_bce_matches_sklearn(self): + s = self.score(metrics=["bce"]) + self.assertAlmostEqual(s["bce"], log_loss(self.y_true, self.y_prob)) + self.assertAlmostEqual(s["bce_M"], log_loss(self.y_true[:4], self.y_prob[:4])) + self.assertNotIn("auc", s) + + def test_tpr_at_tnr80(self): + s = self.score(metrics=["tpr_at_tnr80"]) + self.assertAlmostEqual(s["tpr_at_tnr80_F"], 1.0) + self.assertAlmostEqual(s["tpr_at_tnr80_M"], 0.5) + + def test_ece(self): + groups = np.array(["a"] * 4 + ["b"] * 4) + y_true = np.array([1, 1, 1, 0, 1, 0, 0, 0]) + y_prob = np.array([0.9] * 4 + [0.25] * 4) + s = group_fairness_metrics_fn(y_true, y_prob, groups, metrics=["ece"]) + self.assertAlmostEqual(s["ece_a"], 0.15) + self.assertAlmostEqual(s["ece_b"], 0.0) + + def test_missing_groups_raise(self): + for missing in (None, float("nan")): + groups = ["M"] * 7 + [missing] + with self.assertRaises(ValueError): + group_fairness_metrics_fn(self.y_true, self.y_prob, groups) + + def test_mixed_type_groups(self): + groups = [1, 1, 1, 1, "x", "x", "x", "x"] + s = group_fairness_metrics_fn(self.y_true, self.y_prob, groups, threshold=0.5) + self.assertAlmostEqual(s["auc_1"], 0.75) + self.assertAlmostEqual(s["auc_x"], 1.0) + + def test_tuned_threshold_when_none(self): + s = group_fairness_metrics_fn(self.y_true, self.y_prob, self.groups) + self.assertAlmostEqual(s["threshold"], 0.7) + + def test_single_class_group_gives_nan_auc(self): + groups = np.array(["a", "a", "b", "b", "b", "b", "b", "b"]) + with self.assertWarns(UserWarning): + s = group_fairness_metrics_fn( + self.y_true, self.y_prob, groups, metrics=["auc", "worst_auc"] + ) + self.assertTrue(np.isnan(s["auc_a"])) + self.assertAlmostEqual(s["worst_auc"], s["auc_b"]) + + def test_integer_groups(self): + groups = np.array([0] * 4 + [1] * 4) + s = group_fairness_metrics_fn(self.y_true, self.y_prob, groups, threshold=0.5) + self.assertAlmostEqual(s["auc_0"], 0.75) + + def test_shape_mismatch_raises(self): + with self.assertRaises(ValueError): + group_fairness_metrics_fn(self.y_true, self.y_prob, self.groups[:-1]) + + def test_unknown_metric_raises(self): + with self.assertRaises(ValueError): + self.score(metrics=["auroc"]) + + def test_accepts_column_vector_probs(self): + s = group_fairness_metrics_fn( + self.y_true, self.y_prob[:, None], self.groups, threshold=0.5 + ) + self.assertAlmostEqual(s["auc"], 0.875) + + +class TestHelpers(unittest.TestCase): + def test_best_f1_threshold(self): + y_true = np.array([0, 0, 1, 1, 0, 0, 1, 1]) + y_prob = np.array([0.1, 0.4, 0.35, 0.8, 0.2, 0.6, 0.7, 0.9]) + self.assertAlmostEqual(best_f1_threshold(y_true, y_prob), 0.7) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/core/test_group_sampler.py b/tests/core/test_group_sampler.py new file mode 100644 index 0000000000..0e1b71e388 --- /dev/null +++ b/tests/core/test_group_sampler.py @@ -0,0 +1,130 @@ +"""Tests for GroupBalancedSampler and get_group_balanced_dataloader.""" + +import unittest +from collections import Counter + +import numpy as np +import torch + +from pyhealth.datasets import create_sample_dataset +from pyhealth.sampler import GroupBalancedSampler, get_group_balanced_dataloader + +SEXES = ["F"] * 6 + ["M"] * 2 +LABELS = [0, 0, 0, 0, 1, 1, 0, 1] + + +def _dataset(): + samples = [ + {"patient_id": f"p{i}", "x": [float(i)], "y": y, "sex": s} + for i, (s, y) in enumerate(zip(SEXES, LABELS)) + ] + return create_sample_dataset(samples, {"x": "tensor"}, {"y": "binary"}) + + +class TestGroupBalancedSampler(unittest.TestCase): + def test_weights_are_inverse_group_size(self): + sampler = GroupBalancedSampler(SEXES) + expected = [1 / 6] * 6 + [1 / 2] * 2 + torch.testing.assert_close( + sampler.weights, torch.tensor(expected, dtype=torch.double) + ) + + def test_group_by_label_cells(self): + sampler = GroupBalancedSampler(SEXES, labels=LABELS) + self.assertAlmostEqual(float(sampler.weights[0]), 1 / 4) + self.assertAlmostEqual(float(sampler.weights[4]), 1 / 2) + self.assertAlmostEqual(float(sampler.weights[6]), 1.0) + + def test_draws_groups_evenly(self): + sampler = GroupBalancedSampler(SEXES, num_samples=4000, seed=0) + counts = Counter(SEXES[i] for i in sampler) + self.assertEqual(len(sampler), 4000) + self.assertAlmostEqual(counts["M"] / 4000, 0.5, delta=0.03) + + def test_reproducible_and_changes_per_epoch(self): + a = GroupBalancedSampler(SEXES, seed=3) + b = GroupBalancedSampler(SEXES, seed=3) + first = list(a) + self.assertEqual(first, list(b)) + self.assertNotEqual(first, list(a)) + + def test_seeds_do_not_overlap_across_epochs(self): + a = GroupBalancedSampler(SEXES, num_samples=64, seed=0) + b = GroupBalancedSampler(SEXES, num_samples=64, seed=1) + list(a) + self.assertNotEqual(list(a), list(b)) + + def test_set_epoch_replays_a_pass(self): + sampler = GroupBalancedSampler(SEXES, seed=5) + first = list(sampler) + sampler.set_epoch(0) + self.assertEqual(list(sampler), first) + + def test_tensor_and_numpy_groups(self): + expected = GroupBalancedSampler(SEXES).weights + codes = [int(s == "M") for s in SEXES] + for groups in ( + torch.tensor(codes), + np.array(codes), + [torch.tensor(c) for c in codes], + ): + torch.testing.assert_close(GroupBalancedSampler(groups).weights, expected) + + def test_rejects_missing_groups(self): + for missing in (None, float("nan")): + with self.assertRaises(ValueError): + GroupBalancedSampler(["F", "M", missing]) + + def test_rejects_mismatched_labels(self): + with self.assertRaises(ValueError): + GroupBalancedSampler(SEXES, labels=LABELS[:-1]) + with self.assertRaises(ValueError): + GroupBalancedSampler([]) + + +class TestGroupBalancedDataloader(unittest.TestCase): + def setUp(self): + self.dataset = _dataset() + + def tearDown(self): + self.dataset.close() + + def test_batches_keep_raw_fields_and_balance(self): + loader = get_group_balanced_dataloader( + self.dataset, batch_size=50, group_key="sex", num_samples=2000, seed=0 + ) + sexes = [s for batch in loader for s in batch["sex"]] + self.assertEqual(len(sexes), 2000) + self.assertAlmostEqual(sexes.count("M") / 2000, 0.5, delta=0.04) + batch = next(iter(loader)) + self.assertEqual(tuple(batch["x"].shape), (50, 1)) + + def test_label_key_reads_processed_label(self): + loader = get_group_balanced_dataloader( + self.dataset, batch_size=4, group_key="sex", label_key="y", seed=0 + ) + self.assertAlmostEqual(float(loader.sampler.weights[6]), 1.0) + + def test_groups_given_directly(self): + loader = get_group_balanced_dataloader( + self.dataset, batch_size=4, groups=SEXES, labels=LABELS, seed=0 + ) + self.assertAlmostEqual(float(loader.sampler.weights[6]), 1.0) + + def test_bad_arguments_raise(self): + with self.assertRaises(ValueError): + get_group_balanced_dataloader(self.dataset, 4) + with self.assertRaises(ValueError): + get_group_balanced_dataloader( + self.dataset, 4, group_key="sex", groups=SEXES + ) + with self.assertRaises(ValueError): + get_group_balanced_dataloader(self.dataset, 4, groups=SEXES[:-1]) + + def test_missing_key_raises(self): + with self.assertRaises(KeyError): + get_group_balanced_dataloader(self.dataset, 4, group_key="age") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/core/test_ham10000_malignancy_task.py b/tests/core/test_ham10000_malignancy_task.py new file mode 100644 index 0000000000..48820aecc9 --- /dev/null +++ b/tests/core/test_ham10000_malignancy_task.py @@ -0,0 +1,158 @@ +"""Tests for HAM10000MalignancyClassification and HAM10000 demographics.""" + +import shutil +import tempfile +import unittest +from pathlib import Path + +import pandas as pd + +from pyhealth.datasets import HAM10000Dataset +from pyhealth.tasks import HAM10000MalignancyClassification +from tests.core.test_ham10000_dataset import _TRAIN, make_ham10000_root + +# image -> (age, sex); ISIC_0000007 has no age, ISIC_0000006 an unknown sex +_DEMOGRAPHICS = { + "ISIC_0000001": (65.0, "male"), + "ISIC_0000002": (65.0, "male"), + "ISIC_0000003": (30.0, "female"), + "ISIC_0000004": (60.0, "female"), + "ISIC_0000005": (80.0, "male"), + "ISIC_0000006": (45.0, "unknown"), + "ISIC_0000007": (None, "female"), + "ISIC_0000008": (70.0, "female"), + "ISIC_0000009": (50.0, "male"), +} + + +def write_dataverse_metadata(root: Path) -> None: + pd.DataFrame( + { + "lesion_id": [r[2] for r in _TRAIN], + "image_id": [r[0] for r in _TRAIN], + "dx": [r[1].lower() for r in _TRAIN], + "dx_type": "histo", + "age": [_DEMOGRAPHICS[r[0]][0] for r in _TRAIN], + "sex": [_DEMOGRAPHICS[r[0]][1] for r in _TRAIN], + "localization": "back", + } + ).to_csv(root / "HAM10000_metadata.csv", index=False) + + +class TestHAM10000MalignancyClassification(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.tmp = Path(tempfile.mkdtemp()) + root = cls.tmp / "isic2018" + make_ham10000_root(root) + write_dataverse_metadata(root) + cls.dataset = HAM10000Dataset(root=str(root), cache_dir=str(cls.tmp / "cache")) + + @classmethod + def tearDownClass(cls): + shutil.rmtree(cls.tmp, ignore_errors=True) + + def _samples(self, **kwargs): + samples = self.dataset.set_task( + HAM10000MalignancyClassification(image_size=16, **kwargs) + ) + rows = {samples[i]["image_id"]: samples[i] for i in range(len(samples))} + samples.close() + return rows + + def test_dataset_reads_demographics(self): + events = self.dataset.get_patient("HAM_1").get_events(event_type="ham10000") + self.assertEqual(events[0].sex, "M") + self.assertEqual(float(events[0].age), 65.0) + self.assertEqual(events[0].localization, "back") + + def test_drops_missing_demographics(self): + rows = self._samples() + self.assertEqual( + sorted(rows), + [ + "ISIC_0000001", + "ISIC_0000002", + "ISIC_0000003", + "ISIC_0000004", + "ISIC_0000005", + "ISIC_0000008", + ], + ) + + def test_malignant_label_is_mel_or_akiec(self): + rows = self._samples() + malignant = {k for k, v in rows.items() if int(v["malignant"]) == 1} + self.assertEqual(malignant, {"ISIC_0000001", "ISIC_0000002", "ISIC_0000008"}) + + def test_sensitive_attributes(self): + rows = self._samples() + self.assertEqual(rows["ISIC_0000003"]["sex"], "F") + self.assertEqual(rows["ISIC_0000001"]["age"], 65.0) + self.assertEqual(rows["ISIC_0000004"]["age_group"], "<=60") + self.assertEqual(rows["ISIC_0000001"]["age_group"], ">60") + + def test_custom_age_bins(self): + rows = self._samples(age_bins=(19, 39, 59, 79)) + self.assertEqual(rows["ISIC_0000003"]["age_group"], "(19, 39]") + self.assertEqual(rows["ISIC_0000004"]["age_group"], "(59, 79]") + self.assertEqual(rows["ISIC_0000005"]["age_group"], ">79") + + def test_bad_age_bins_raise(self): + with self.assertRaises(ValueError): + HAM10000MalignancyClassification(age_bins=()) + with self.assertRaises(ValueError): + HAM10000MalignancyClassification(age_bins=(60, 40)) + + +class TestHAM10000DemographicsFile(unittest.TestCase): + def setUp(self): + self.tmp = Path(tempfile.mkdtemp()) + self.root = self.tmp / "isic2018" + make_ham10000_root(self.root) + write_dataverse_metadata(self.root) + + def tearDown(self): + shutil.rmtree(self.tmp, ignore_errors=True) + + def _sex(self, metadata_dir): + dataset = HAM10000Dataset( + root=str(self.root), + cache_dir=str(self.tmp / "cache"), + metadata_dir=str(metadata_dir), + ) + return dataset.get_patient("HAM_1").get_events(event_type="ham10000")[0].sex + + def test_edited_file_rebuilds_metadata(self): + metadata_dir = self.tmp / "meta" + self.assertEqual(self._sex(metadata_dir), "M") + path = self.root / "HAM10000_metadata.csv" + frame = pd.read_csv(path).assign(sex="female") + frame.to_csv(path, index=False) + self.assertEqual(self._sex(metadata_dir), "F") + + def test_tab_separated_file_raises(self): + path = self.root / "HAM10000_metadata.csv" + pd.read_csv(path).to_csv(path, sep="\t", index=False) + with self.assertRaises(ValueError): + HAM10000Dataset(root=str(self.root), cache_dir=str(self.tmp / "cache")) + + +class TestHAM10000WithoutDemographics(unittest.TestCase): + def test_columns_empty_and_task_yields_nothing(self): + tmp = Path(tempfile.mkdtemp()) + try: + make_ham10000_root(tmp / "isic2018") + dataset = HAM10000Dataset( + root=str(tmp / "isic2018"), cache_dir=str(tmp / "cache") + ) + event = dataset.get_patient("HAM_1").get_events(event_type="ham10000")[0] + self.assertIsNone(event.sex) + task = HAM10000MalignancyClassification(image_size=16) + self.assertEqual(task(dataset.get_patient("HAM_1")), []) + finally: + shutil.rmtree(tmp, ignore_errors=True) + + +if __name__ == "__main__": + unittest.main() From dc6b009657425409aefdbde94b3914e742ff4c55 Mon Sep 17 00:00:00 2001 From: Sanni heruwala Date: Sun, 22 Nov 2026 14:04:38 +0530 Subject: [PATCH 02/13] fix: keep group sampler off shared dataloader code Build the collate function inside the sampler module and import the padding helper lazily, so pyhealth.sampler no longer imports pyhealth.datasets at load time (datasets.imaging imports the sampler package). Also fix the task page underline and cite the exact MEDFAIR table quoted in the example. --- ...tasks.HAM10000MalignancyClassification.rst | 2 +- examples/medfair_ham10000.py | 9 +++--- pyhealth/datasets/utils.py | 28 +++++++++---------- pyhealth/sampler/group_sampler.py | 18 ++++++++++-- 4 files changed, 34 insertions(+), 23 deletions(-) diff --git a/docs/api/tasks/pyhealth.tasks.HAM10000MalignancyClassification.rst b/docs/api/tasks/pyhealth.tasks.HAM10000MalignancyClassification.rst index 22bb5c47c3..944f3d3889 100644 --- a/docs/api/tasks/pyhealth.tasks.HAM10000MalignancyClassification.rst +++ b/docs/api/tasks/pyhealth.tasks.HAM10000MalignancyClassification.rst @@ -1,5 +1,5 @@ pyhealth.tasks.HAM10000MalignancyClassification -============================================= +=============================================== Malignant vs. benign HAM10000 images with sex, age and age group on every sample, the HAM10000 setup of the MEDFAIR fairness benchmark. diff --git a/examples/medfair_ham10000.py b/examples/medfair_ham10000.py index 82c35e4a55..0a99175e46 100644 --- a/examples/medfair_ham10000.py +++ b/examples/medfair_ham10000.py @@ -18,10 +18,11 @@ python examples/medfair_ham10000.py --root /path/to/isic2018_task3 \\ --cache-dir /path/to/cache --attribute sex --epochs 15 -MEDFAIR reports with sex as the attribute (Table A9, minimax Pareto, mean of -3 seeds): ERM 85.20 overall / 83.12 worst-group AUC / 3.31 gap, resampling -86.94 / 85.04 / 3.09. Its age results use a 4-group binning that is not -published, so they are not directly comparable to ``--attribute age_group``. +MEDFAIR reports with sex as the attribute (appendix Table A9 of +arXiv:2210.01725v2, in-distribution, minimax Pareto, mean of 3 seeds): ERM +85.20 overall / 83.12 worst-group AUC / 3.31 gap, resampling 86.94 / 85.04 / +3.09. Its age results use a 4-group binning that is not published, so they +are not directly comparable to ``--attribute age_group``. """ from __future__ import annotations diff --git a/pyhealth/datasets/utils.py b/pyhealth/datasets/utils.py index 9293ff364c..e0e596d7be 100644 --- a/pyhealth/datasets/utils.py +++ b/pyhealth/datasets/utils.py @@ -376,20 +376,6 @@ def __iter__(self): return super().__iter__() -def _sample_collate_fn(dataset) -> Callable: - """Collate function for a SampleDataset: fields whose processor defines - ``collate()`` are batched by it, the rest padded or listed.""" - processors = {**dataset.input_processors, **dataset.output_processors} - collators = { - key: processor.collate - for key, processor in processors.items() - if callable(getattr(processor, "collate", None)) - } - if not collators: - return collate_fn_dict_with_padding - return functools.partial(collate_fn_dict_with_padding, collators=collators) - - def get_dataloader( dataset: litdata.StreamingDataset, batch_size: int, @@ -447,13 +433,25 @@ def get_dataloader( "later set_shuffle/set_epoch calls would not reach them. Use " "persistent_workers=False or shuffle=False." ) + # Fields whose processor defines collate() are batched by it. + processors = {**dataset.input_processors, **dataset.output_processors} + collators = { + key: processor.collate + for key, processor in processors.items() + if callable(getattr(processor, "collate", None)) + } + collate_fn = ( + functools.partial(collate_fn_dict_with_padding, collators=collators) + if collators + else collate_fn_dict_with_padding + ) return _SeededDataLoader( dataset, shuffle_samples=shuffle, seed=seed, batch_size=batch_size, generator=generator, - collate_fn=_sample_collate_fn(dataset), + collate_fn=collate_fn, **loader_kwargs, ) if hasattr(dataset, "set_shuffle"): # another iterable dataset, e.g. litdata's diff --git a/pyhealth/sampler/group_sampler.py b/pyhealth/sampler/group_sampler.py index 282efdad77..db901e6195 100644 --- a/pyhealth/sampler/group_sampler.py +++ b/pyhealth/sampler/group_sampler.py @@ -1,5 +1,6 @@ """Subgroup resampling (Idrissi et al., CLeaR 2022), a MEDFAIR baseline.""" +import functools from collections.abc import Hashable, Iterator, Sequence from typing import Any @@ -8,8 +9,6 @@ import torch from torch.utils.data import DataLoader, Dataset, Sampler -from ..datasets.utils import _sample_collate_fn - def _hashable(value: Any) -> Hashable: if isinstance(value, (torch.Tensor, np.ndarray, np.generic)): @@ -111,6 +110,19 @@ def __getitem__(self, index: int) -> Any: return self.dataset[index] +def _collate_fn(dataset: Any): + # Imported here: pyhealth.datasets.imaging imports this package. + from ..datasets.utils import collate_fn_dict_with_padding + + processors = {**dataset.input_processors, **dataset.output_processors} + collators = { + key: processor.collate + for key, processor in processors.items() + if callable(getattr(processor, "collate", None)) + } + return functools.partial(collate_fn_dict_with_padding, collators=collators) + + def get_group_balanced_dataloader( dataset: Any, batch_size: int, @@ -183,6 +195,6 @@ def get_group_balanced_dataloader( _IndexView(dataset), batch_size=batch_size, sampler=sampler, - collate_fn=_sample_collate_fn(dataset), + collate_fn=_collate_fn(dataset), **loader_kwargs, ) From 2f0c41165df34870bb417de22b999d13e802aeba Mon Sep 17 00:00:00 2001 From: Sanni heruwala Date: Sun, 22 Nov 2026 14:18:18 +0530 Subject: [PATCH 03/13] refactor: move MEDFAIR example to examples/derm, clarify sampler test Put the example next to the other HAM10000 scripts, note that it reads each split's groups in a single pass, and rename the seed/epoch test after what it checks. --- examples/{ => derm}/medfair_ham10000.py | 4 +++- tests/core/test_group_sampler.py | 5 +++-- 2 files changed, 6 insertions(+), 3 deletions(-) rename examples/{ => derm}/medfair_ham10000.py (97%) diff --git a/examples/medfair_ham10000.py b/examples/derm/medfair_ham10000.py similarity index 97% rename from examples/medfair_ham10000.py rename to examples/derm/medfair_ham10000.py index 0a99175e46..7d49a448fc 100644 --- a/examples/medfair_ham10000.py +++ b/examples/derm/medfair_ham10000.py @@ -15,7 +15,7 @@ mean nothing. On the real data (open access, see ``HAM10000Dataset``; put the Dataverse ``HAM10000_metadata.csv`` next to the ISIC 2018 folders): - python examples/medfair_ham10000.py --root /path/to/isic2018_task3 \\ + python examples/derm/medfair_ham10000.py --root /path/to/isic2018_task3 \\ --cache-dir /path/to/cache --attribute sex --epochs 15 MEDFAIR reports with sex as the attribute (appendix Table A9 of @@ -186,6 +186,8 @@ def main() -> None: train, val, test = dataset.set_task( task, split=PatientSplit((0.8, 0.1, 0.1), seed=0) ) + # Reading a field decodes the whole cached sample, so collect the + # groups in one pass per split and reuse them for every run. groups = { name: [part[i][args.attribute] for i in range(len(part))] for name, part in (("train", train), ("val", val), ("test", test)) diff --git a/tests/core/test_group_sampler.py b/tests/core/test_group_sampler.py index 0e1b71e388..ac16b88e0d 100644 --- a/tests/core/test_group_sampler.py +++ b/tests/core/test_group_sampler.py @@ -48,10 +48,11 @@ def test_reproducible_and_changes_per_epoch(self): self.assertEqual(first, list(b)) self.assertNotEqual(first, list(a)) - def test_seeds_do_not_overlap_across_epochs(self): + def test_next_epoch_differs_from_next_seed(self): + # seed + epoch seeding made seed 0 / epoch 1 replay seed 1 / epoch 0 a = GroupBalancedSampler(SEXES, num_samples=64, seed=0) b = GroupBalancedSampler(SEXES, num_samples=64, seed=1) - list(a) + a.set_epoch(1) self.assertNotEqual(list(a), list(b)) def test_set_epoch_replays_a_pass(self): From f99c90248cf8016fb0aae22f7b530f2438a7f01d Mon Sep 17 00:00:00 2001 From: Sanni heruwala Date: Sun, 22 Nov 2026 19:46:34 +0530 Subject: [PATCH 04/13] fix: validate Dataverse metadata before either reader uses it Read and check HAM10000_metadata.csv in one place, so a tab-separated download gets the format hint whether or not the groupings CSV is present. Document the one-time metadata rebuild, how tpr_at_tnr80 is interpolated, and how the group-balanced loader differs from get_dataloader. --- pyhealth/datasets/ham10000.py | 39 +++++++++++++-------- pyhealth/metrics/group_fairness.py | 4 ++- pyhealth/sampler/group_sampler.py | 6 ++-- tests/core/test_ham10000_malignancy_task.py | 7 ++++ 4 files changed, 38 insertions(+), 18 deletions(-) diff --git a/pyhealth/datasets/ham10000.py b/pyhealth/datasets/ham10000.py index 6b745fe4e3..ca9b12b974 100644 --- a/pyhealth/datasets/ham10000.py +++ b/pyhealth/datasets/ham10000.py @@ -54,7 +54,8 @@ class HAM10000Dataset(BaseDataset): Dataverse ``HAM10000_metadata.csv``. When it is in ``root`` they are added as ``age``, ``sex`` and ``localization``, which subgroup analyses such as :class:`~pyhealth.tasks.HAM10000MalignancyClassification` need; - without it these attributes are empty. + without it these attributes are empty. Metadata cached by earlier + versions lacks these columns and is rebuilt once. The official validation (193) and test (1,512) images are indexed too when ``splits`` asks for them. Their lesion ids were not released, so @@ -250,6 +251,20 @@ def _download(self) -> None: f"(first line: {first_line[:80]!r})." ) + def _dataverse_metadata(self) -> pd.DataFrame | None: + """Return the Dataverse metadata table, or None if it is not in root.""" + path = self.source_root / _DATAVERSE_METADATA + if not path.exists(): + return None + meta = pd.read_csv(path) + if "image_id" not in meta.columns: + raise ValueError( + f"{path} has no image_id column. Download the CSV with " + "?format=original; the default Dataverse download is " + "tab-separated." + ) + return meta + def _lesion_ids(self) -> pd.DataFrame: """Return ``image``, ``lesion_id``, ``diagnosis_confirm_type``.""" groupings = self.source_root / _GROUPINGS_FILE @@ -257,9 +272,8 @@ def _lesion_ids(self) -> pd.DataFrame: return pd.read_csv(groupings)[ ["image", "lesion_id", "diagnosis_confirm_type"] ] - dataverse = self.source_root / _DATAVERSE_METADATA - if dataverse.exists(): - meta = pd.read_csv(dataverse) + meta = self._dataverse_metadata() + if meta is not None: return meta.rename( columns={"image_id": "image", "dx_type": "diagnosis_confirm_type"} )[["image", "lesion_id", "diagnosis_confirm_type"]] @@ -272,19 +286,14 @@ def _lesion_ids(self) -> pd.DataFrame: def _demographics(self) -> pd.DataFrame | None: """Return ``image``, ``age``, ``sex``, ``localization``, or None.""" - dataverse = self.source_root / _DATAVERSE_METADATA - if not dataverse.exists(): - logger.info("No %s; age and sex are empty.", dataverse) + meta = self._dataverse_metadata() + if meta is None: + logger.info("No %s; age and sex are empty.", _DATAVERSE_METADATA) return None - meta = pd.read_csv(dataverse) - if "image_id" not in meta.columns: - raise ValueError( - f"{dataverse} has no image_id column. Download the CSV with " - "?format=original; the default Dataverse download is " - "tab-separated." - ) if not {"age", "sex"} <= set(meta.columns): - logger.warning("%s has no age/sex columns; they stay empty.", dataverse) + logger.warning( + "%s has no age/sex columns; they stay empty.", _DATAVERSE_METADATA + ) return None if "localization" not in meta.columns: meta["localization"] = None diff --git a/pyhealth/metrics/group_fairness.py b/pyhealth/metrics/group_fairness.py index a8c4ff1a96..4ca6f5d32a 100644 --- a/pyhealth/metrics/group_fairness.py +++ b/pyhealth/metrics/group_fairness.py @@ -88,7 +88,9 @@ def group_fairness_metrics_fn( calibration error (10 equal-width bins on [0, 1]) and binary cross-entropy. - ``fpr``, ``fnr``: false positive / negative rate at ``threshold``. - - ``tpr_at_tnr80``: sensitivity at 80% specificity. + - ``tpr_at_tnr80``: sensitivity at 80% specificity, linearly + interpolated on the ROC curve at FPR 0.2 as in MEDFAIR, so it can + sit between two achievable operating points. - ``worst_auc``, ``auc_gap``: lowest subgroup AUC, and highest minus lowest. - ``eqodd``: equalized odds, ``1 - (|dFPR| + |dTPR|) / 2`` between diff --git a/pyhealth/sampler/group_sampler.py b/pyhealth/sampler/group_sampler.py index db901e6195..b27007528b 100644 --- a/pyhealth/sampler/group_sampler.py +++ b/pyhealth/sampler/group_sampler.py @@ -136,8 +136,10 @@ def get_group_balanced_dataloader( ) -> DataLoader: """Training loader that resamples a sample dataset by subgroup. - A drop-in replacement for :func:`~pyhealth.datasets.get_dataloader` on the - training split. Give the groups either as a sample field (``group_key``, + Use it instead of :func:`~pyhealth.datasets.get_dataloader` for the + training split. The order comes from the weighted sampler, so there is + no ``shuffle`` argument, and the epoch is advanced by the sampler rather + than the dataset's own seeding. Give the groups either as a sample field (``group_key``, read from every sample once, which decodes its inputs too) or directly (``groups``, in dataset order); likewise for the optional labels. diff --git a/tests/core/test_ham10000_malignancy_task.py b/tests/core/test_ham10000_malignancy_task.py index 48820aecc9..3a6a4ccf48 100644 --- a/tests/core/test_ham10000_malignancy_task.py +++ b/tests/core/test_ham10000_malignancy_task.py @@ -137,6 +137,13 @@ def test_tab_separated_file_raises(self): with self.assertRaises(ValueError): HAM10000Dataset(root=str(self.root), cache_dir=str(self.tmp / "cache")) + def test_tab_separated_file_raises_without_groupings(self): + path = self.root / "HAM10000_metadata.csv" + pd.read_csv(path).to_csv(path, sep="\t", index=False) + (self.root / "ISIC2018_Task3_Training_LesionGroupings.csv").unlink() + with self.assertRaisesRegex(ValueError, "format=original"): + HAM10000Dataset(root=str(self.root), cache_dir=str(self.tmp / "cache")) + class TestHAM10000WithoutDemographics(unittest.TestCase): def test_columns_empty_and_task_yields_nothing(self): From e180e2dc2bf1de33cc512e88975b79615d0d56d5 Mon Sep 17 00:00:00 2001 From: Sanni heruwala Date: Wed, 25 Nov 2026 20:01:14 +0530 Subject: [PATCH 05/13] fix: ignore a tab-separated Dataverse file when the groupings CSV is present The file is only required when it stands in for the lesion groupings, so keep the error there and fall back to empty age/sex otherwise. Also note the Table A8 numbers and MEDFAIR's age grouping in the example. --- examples/derm/medfair_ham10000.py | 6 ++++-- pyhealth/datasets/ham10000.py | 9 ++++++++- pyhealth/sampler/group_sampler.py | 7 ++++--- tests/core/test_ham10000_malignancy_task.py | 7 ++++--- 4 files changed, 20 insertions(+), 9 deletions(-) diff --git a/examples/derm/medfair_ham10000.py b/examples/derm/medfair_ham10000.py index 7d49a448fc..58b2666636 100644 --- a/examples/derm/medfair_ham10000.py +++ b/examples/derm/medfair_ham10000.py @@ -21,8 +21,10 @@ MEDFAIR reports with sex as the attribute (appendix Table A9 of arXiv:2210.01725v2, in-distribution, minimax Pareto, mean of 3 seeds): ERM 85.20 overall / 83.12 worst-group AUC / 3.31 gap, resampling 86.94 / 85.04 / -3.09. Its age results use a 4-group binning that is not published, so they -are not directly comparable to ``--attribute age_group``. +3.09; Table A8 has ERM under the other two rules. Its age results use four +groups taken from the five bins of its Table A2 (0-20 to 80+) in a way the +paper does not state, so they are not directly comparable to +``--attribute age_group``. """ from __future__ import annotations diff --git a/pyhealth/datasets/ham10000.py b/pyhealth/datasets/ham10000.py index ca9b12b974..688d2eff58 100644 --- a/pyhealth/datasets/ham10000.py +++ b/pyhealth/datasets/ham10000.py @@ -102,6 +102,9 @@ class reads the ISIC 2018 Task 3 layout below. HAM10000_metadata.csv "https://dataverse.harvard.edu/api/access/datafile/4338392?format=original"``). It also replaces the lesion groupings CSV if that is missing. + A tab-separated copy (the default download) is rejected when it + stands in for the groupings CSV; otherwise it is ignored with a + warning. - ``root`` layout (validation and test folders only when ``splits`` asks for them):: @@ -286,7 +289,11 @@ def _lesion_ids(self) -> pd.DataFrame: def _demographics(self) -> pd.DataFrame | None: """Return ``image``, ``age``, ``sex``, ``localization``, or None.""" - meta = self._dataverse_metadata() + try: + meta = self._dataverse_metadata() + except ValueError as err: + logger.warning("%s Age and sex stay empty.", err) + return None if meta is None: logger.info("No %s; age and sex are empty.", _DATAVERSE_METADATA) return None diff --git a/pyhealth/sampler/group_sampler.py b/pyhealth/sampler/group_sampler.py index b27007528b..072328d001 100644 --- a/pyhealth/sampler/group_sampler.py +++ b/pyhealth/sampler/group_sampler.py @@ -139,9 +139,10 @@ def get_group_balanced_dataloader( Use it instead of :func:`~pyhealth.datasets.get_dataloader` for the training split. The order comes from the weighted sampler, so there is no ``shuffle`` argument, and the epoch is advanced by the sampler rather - than the dataset's own seeding. Give the groups either as a sample field (``group_key``, - read from every sample once, which decodes its inputs too) or directly - (``groups``, in dataset order); likewise for the optional labels. + than the dataset's own seeding. Give the groups either as a sample field + (``group_key``, read from every sample once, which decodes its inputs + too) or directly (``groups``, in dataset order); likewise for the + optional labels. Args: dataset: A :class:`~pyhealth.datasets.SampleDataset`. diff --git a/tests/core/test_ham10000_malignancy_task.py b/tests/core/test_ham10000_malignancy_task.py index 3a6a4ccf48..04749c4761 100644 --- a/tests/core/test_ham10000_malignancy_task.py +++ b/tests/core/test_ham10000_malignancy_task.py @@ -131,11 +131,12 @@ def test_edited_file_rebuilds_metadata(self): frame.to_csv(path, index=False) self.assertEqual(self._sex(metadata_dir), "F") - def test_tab_separated_file_raises(self): + def test_tab_separated_file_with_groupings_leaves_sex_empty(self): path = self.root / "HAM10000_metadata.csv" pd.read_csv(path).to_csv(path, sep="\t", index=False) - with self.assertRaises(ValueError): - HAM10000Dataset(root=str(self.root), cache_dir=str(self.tmp / "cache")) + with self.assertLogs("pyhealth.datasets.ham10000", "WARNING") as logs: + self.assertIsNone(self._sex(self.tmp / "meta")) + self.assertIn("format=original", "".join(logs.output)) def test_tab_separated_file_raises_without_groupings(self): path = self.root / "HAM10000_metadata.csv" From 2cb7ad5094811f023bb5748f20bfec44f02a695e Mon Sep 17 00:00:00 2001 From: Sanni heruwala Date: Fri, 27 Nov 2026 13:26:34 +0530 Subject: [PATCH 06/13] test: cover the group loader's remaining branches Also name the exact MEDFAIR table rows the example quotes. --- examples/derm/medfair_ham10000.py | 14 +++++++------- tests/core/test_group_sampler.py | 10 ++++++++++ 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/examples/derm/medfair_ham10000.py b/examples/derm/medfair_ham10000.py index 58b2666636..325b873680 100644 --- a/examples/derm/medfair_ham10000.py +++ b/examples/derm/medfair_ham10000.py @@ -18,13 +18,13 @@ python examples/derm/medfair_ham10000.py --root /path/to/isic2018_task3 \\ --cache-dir /path/to/cache --attribute sex --epochs 15 -MEDFAIR reports with sex as the attribute (appendix Table A9 of -arXiv:2210.01725v2, in-distribution, minimax Pareto, mean of 3 seeds): ERM -85.20 overall / 83.12 worst-group AUC / 3.31 gap, resampling 86.94 / 85.04 / -3.09; Table A8 has ERM under the other two rules. Its age results use four -groups taken from the five bins of its Table A2 (0-20 to 80+) in a way the -paper does not state, so they are not directly comparable to -``--attribute age_group``. +MEDFAIR reports with sex as the attribute (arXiv:2210.01725v2, appendix +Table A9, rows "HAM10000 / Sex", in-distribution, minimax Pareto, mean of 3 +seeds): ERM 85.20 overall / 83.12 worst-group AUC / 3.31 gap, resampling +86.94 / 85.04 / 3.09. Table A8 has ERM under the other two rules. Its age +results use four groups taken from the five bins of its Table A2 (0-20 to +80+) in a way the paper does not state, so they are not directly comparable +to ``--attribute age_group``. """ from __future__ import annotations diff --git a/tests/core/test_group_sampler.py b/tests/core/test_group_sampler.py index ac16b88e0d..7975fd8649 100644 --- a/tests/core/test_group_sampler.py +++ b/tests/core/test_group_sampler.py @@ -111,6 +111,12 @@ def test_groups_given_directly(self): self.dataset, batch_size=4, groups=SEXES, labels=LABELS, seed=0 ) self.assertAlmostEqual(float(loader.sampler.weights[6]), 1.0) + self.assertEqual(len(loader.dataset), len(SEXES)) + + def test_seed_drawn_when_not_given(self): + loader = get_group_balanced_dataloader(self.dataset, 4, groups=SEXES) + self.assertIsInstance(loader.sampler.seed, int) + self.assertEqual(sum(len(b["sex"]) for b in loader), len(SEXES)) def test_bad_arguments_raise(self): with self.assertRaises(ValueError): @@ -121,6 +127,10 @@ def test_bad_arguments_raise(self): ) with self.assertRaises(ValueError): get_group_balanced_dataloader(self.dataset, 4, groups=SEXES[:-1]) + with self.assertRaises(ValueError): + get_group_balanced_dataloader( + self.dataset, 4, groups=SEXES, label_key="y", labels=LABELS + ) def test_missing_key_raises(self): with self.assertRaises(KeyError): From 2c88f7960a7f9713b03c6925e2507c212c09f2d5 Mon Sep 17 00:00:00 2001 From: Sanni heruwala Date: Fri, 27 Nov 2026 14:01:47 +0530 Subject: [PATCH 07/13] docs: point to MEDFAIR's tables instead of quoting their numbers --- examples/derm/medfair_ham10000.py | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/examples/derm/medfair_ham10000.py b/examples/derm/medfair_ham10000.py index 325b873680..18b96c77fd 100644 --- a/examples/derm/medfair_ham10000.py +++ b/examples/derm/medfair_ham10000.py @@ -18,13 +18,12 @@ python examples/derm/medfair_ham10000.py --root /path/to/isic2018_task3 \\ --cache-dir /path/to/cache --attribute sex --epochs 15 -MEDFAIR reports with sex as the attribute (arXiv:2210.01725v2, appendix -Table A9, rows "HAM10000 / Sex", in-distribution, minimax Pareto, mean of 3 -seeds): ERM 85.20 overall / 83.12 worst-group AUC / 3.31 gap, resampling -86.94 / 85.04 / 3.09. Table A8 has ERM under the other two rules. Its age -results use four groups taken from the five bins of its Table A2 (0-20 to -80+) in a way the paper does not state, so they are not directly comparable -to ``--attribute age_group``. +Compare ``--attribute sex`` with the "HAM10000 / Sex" rows of MEDFAIR's +appendix Table A9 (arXiv:2210.01725v2; ERM and resampling, minimax Pareto) +and Table A8 (ERM under each selection rule). Its age results use four +groups taken from the five bins of its Table A2 (0-20 to 80+) in a way the +paper does not state, so they are not directly comparable to +``--attribute age_group``. """ from __future__ import annotations From 0a77892beb5ca9b01cef831a6b5f6cf73246fa23 Mon Sep 17 00:00:00 2001 From: Sanni heruwala Date: Fri, 27 Nov 2026 17:17:59 +0530 Subject: [PATCH 08/13] fix: warn for every metric a single-class subgroup leaves undefined --- pyhealth/metrics/group_fairness.py | 21 ++++++++++++++------- tests/core/test_group_fairness_metrics.py | 18 ++++++++++++++++++ 2 files changed, 32 insertions(+), 7 deletions(-) diff --git a/pyhealth/metrics/group_fairness.py b/pyhealth/metrics/group_fairness.py index 4ca6f5d32a..800adb8c21 100644 --- a/pyhealth/metrics/group_fairness.py +++ b/pyhealth/metrics/group_fairness.py @@ -96,8 +96,10 @@ def group_fairness_metrics_fn( - ``eqodd``: equalized odds, ``1 - (|dFPR| + |dTPR|) / 2`` between the two subgroups of a binary attribute. - A subgroup with a single class has no AUC; it gets NaN with a warning and - is left out of ``worst_auc`` and ``auc_gap``. + A subgroup with a single class gets NaN, with a warning, for AUC and + ``tpr_at_tnr80``, for FPR when it has no negatives or FNR when it has no + positives, and so for ``eqodd``. NaN AUCs are left out of ``worst_auc`` + and ``auc_gap``; the selection functions reject NaN scores. Unlike :func:`~pyhealth.metrics.subgroup_metrics`, this reports error rates and equalized odds at a chosen operating point, with MEDFAIR's @@ -164,6 +166,16 @@ def group_fairness_metrics_fn( if "eqodd" in needed: needed |= {"fpr", "fnr"} + affected = needed & {"auc", "tpr_at_tnr80", "fpr", "fnr"} + one_class = [str(g) for g in names if len(np.unique(y_true[groups == g])) < 2] + if affected and one_class: + warnings.warn( + f"Groups {one_class} have a single class: their AUC and TPR at 80% " + "TNR are NaN, as is FPR without negatives or FNR without positives, " + "and eqodd with them.", + stacklevel=2, + ) + scores: dict[str, float] = {} for name in (m for m in _PER_GROUP if m in needed): scores[name] = _score(name, y_true, y_prob, y_pred) @@ -175,11 +187,6 @@ def group_fairness_metrics_fn( if "auc" in needed: aucs = np.array([scores[f"auc_{g}"] for g in names]) - undefined = [str(g) for g, a in zip(names, aucs) if np.isnan(a)] - if undefined: - warnings.warn( - f"AUC undefined for single-class groups {undefined}.", stacklevel=2 - ) defined = aucs[~np.isnan(aucs)] scores["worst_auc"] = float(defined.min()) if len(defined) else float("nan") scores["auc_gap"] = ( diff --git a/tests/core/test_group_fairness_metrics.py b/tests/core/test_group_fairness_metrics.py index ce39fd47fa..ac7a2b57eb 100644 --- a/tests/core/test_group_fairness_metrics.py +++ b/tests/core/test_group_fairness_metrics.py @@ -1,6 +1,7 @@ """Tests for pyhealth.metrics.group_fairness.""" import unittest +import warnings import numpy as np from sklearn.metrics import log_loss @@ -97,6 +98,23 @@ def test_single_class_group_gives_nan_auc(self): self.assertTrue(np.isnan(s["auc_a"])) self.assertAlmostEqual(s["worst_auc"], s["auc_b"]) + def test_single_class_group_warns_for_rates(self): + groups = np.array(["a", "a", "b", "b", "b", "b", "b", "b"]) + with self.assertWarnsRegex(UserWarning, r"\['a'\]"): + s = group_fairness_metrics_fn( + self.y_true, self.y_prob, groups, metrics=["eqodd"], threshold=0.5 + ) + self.assertTrue(np.isnan(s["eqodd"])) + + def test_no_warning_without_class_dependent_metrics(self): + groups = np.array(["a", "a", "b", "b", "b", "b", "b", "b"]) + with warnings.catch_warnings(): + warnings.simplefilter("error") + s = group_fairness_metrics_fn( + self.y_true, self.y_prob, groups, metrics=["acc"], threshold=0.5 + ) + self.assertIn("acc_a", s) + def test_integer_groups(self): groups = np.array([0] * 4 + [1] * 4) s = group_fairness_metrics_fn(self.y_true, self.y_prob, groups, threshold=0.5) From 5ddc50b3ed972d93268ae64cfd7c990909f10f4f Mon Sep 17 00:00:00 2001 From: Sanni heruwala Date: Fri, 27 Nov 2026 18:12:22 +0530 Subject: [PATCH 09/13] docs: note the training-only demographics and the all-pairs Pareto check --- pyhealth/datasets/ham10000.py | 4 +++- pyhealth/metrics/fairness_selection.py | 2 ++ pyhealth/tasks/ham10000_malignancy.py | 4 +++- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/pyhealth/datasets/ham10000.py b/pyhealth/datasets/ham10000.py index 688d2eff58..5914c12181 100644 --- a/pyhealth/datasets/ham10000.py +++ b/pyhealth/datasets/ham10000.py @@ -101,7 +101,9 @@ class reads the ISIC 2018 Task 3 layout below. file as ``HAM10000_metadata.csv`` in ``root`` (``wget -O HAM10000_metadata.csv "https://dataverse.harvard.edu/api/access/datafile/4338392?format=original"``). - It also replaces the lesion groupings CSV if that is missing. + It covers the training images only, so the validation and test + splits have no age, sex or body site. It also replaces the lesion + groupings CSV if that is missing. A tab-separated copy (the default download) is rejected when it stands in for the groupings CSV; otherwise it is ignored with a warning. diff --git a/pyhealth/metrics/fairness_selection.py b/pyhealth/metrics/fairness_selection.py index 266ad388f8..5d1fe435fe 100644 --- a/pyhealth/metrics/fairness_selection.py +++ b/pyhealth/metrics/fairness_selection.py @@ -53,6 +53,8 @@ def pareto_front(scores: np.ndarray) -> np.ndarray: Candidate ``j`` dominates ``i`` if it scores at least as well on every subgroup and strictly better on one. Identical candidates are all kept. + The comparison is all-pairs, which suits a hyper-parameter grid rather + than thousands of candidates. Args: scores: Per-subgroup scores of shape (n_candidates, n_groups). diff --git a/pyhealth/tasks/ham10000_malignancy.py b/pyhealth/tasks/ham10000_malignancy.py index e50d432f30..e7a6a01106 100644 --- a/pyhealth/tasks/ham10000_malignancy.py +++ b/pyhealth/tasks/ham10000_malignancy.py @@ -22,7 +22,9 @@ class HAM10000MalignancyClassification(BaseTask): Works with :class:`~pyhealth.datasets.HAM10000Dataset` when the Dataverse ``HAM10000_metadata.csv`` is in its root, since age and sex come from it; - without it no samples are produced. + without it no samples are produced. That file covers only the training + images, so the ISIC 2018 validation and test splits give no samples + either; split the training set instead, as below. The HAM10000 setup of MEDFAIR (Zong et al., ICLR 2023): melanoma (MEL) and actinic keratosis / intraepithelial carcinoma (AKIEC) are malignant, From c9b2f3ac5f77b7aa7a326c2dfecf5c5165796225 Mon Sep 17 00:00:00 2001 From: Sanni heruwala Date: Fri, 27 Nov 2026 18:14:49 +0530 Subject: [PATCH 10/13] fix: validate inputs at the edges of the fairness, sampler and HAM10000 code Reject non-binary labels and out-of-range probabilities, non-positive DTO maxima, missing labels, non-positive num_samples, order arguments to the group loader and fractional age bins. Warn about duplicate or missing images in the Dataverse metadata, and stop the example early when no group can be selected on. --- examples/derm/medfair_ham10000.py | 9 ++++---- pyhealth/datasets/ham10000.py | 20 ++++++++++++++++-- pyhealth/metrics/fairness_selection.py | 9 +++++++- pyhealth/metrics/group_fairness.py | 12 ++++++++--- pyhealth/sampler/group_sampler.py | 15 +++++++++++--- pyhealth/tasks/ham10000_malignancy.py | 14 +++++++++---- tests/core/test_fairness_selection.py | 2 ++ tests/core/test_group_fairness_metrics.py | 15 ++++++++++++++ tests/core/test_group_sampler.py | 14 +++++++++++++ tests/core/test_ham10000_malignancy_task.py | 23 +++++++++++++++++++++ 10 files changed, 115 insertions(+), 18 deletions(-) diff --git a/examples/derm/medfair_ham10000.py b/examples/derm/medfair_ham10000.py index 18b96c77fd..f70a5f014c 100644 --- a/examples/derm/medfair_ham10000.py +++ b/examples/derm/medfair_ham10000.py @@ -211,11 +211,10 @@ def main() -> None: for lr in args.lrs } - kept = [ - g - for g in names - if all(g in defined_groups(r, names) for r in results.values()) - ] + defined = [set(defined_groups(r, names)) for r in results.values()] + kept = [g for g in names if all(g in d for d in defined)] + if not kept: + raise SystemExit("No group has a val AUC in every run; nothing to select.") if len(kept) < len(names): print( f"Selecting on {kept}; no val AUC for {sorted(set(names) - set(kept))}." diff --git a/pyhealth/datasets/ham10000.py b/pyhealth/datasets/ham10000.py index 5914c12181..2c917f66a7 100644 --- a/pyhealth/datasets/ham10000.py +++ b/pyhealth/datasets/ham10000.py @@ -304,9 +304,17 @@ def _demographics(self) -> pd.DataFrame | None: "%s has no age/sex columns; they stay empty.", _DATAVERSE_METADATA ) return None + duplicated = meta["image_id"].duplicated() + if duplicated.any(): + logger.warning( + "%s lists %d images more than once; keeping the first row.", + _DATAVERSE_METADATA, + int(duplicated.sum()), + ) + meta = meta[~duplicated] if "localization" not in meta.columns: - meta["localization"] = None - meta["sex"] = meta["sex"].map({"male": "M", "female": "F"}) + meta = meta.assign(localization=None) + meta = meta.assign(sex=meta["sex"].map({"male": "M", "female": "F"})) return meta.rename(columns={"image_id": "image"})[ ["image", "age", "sex", "localization"] ] @@ -352,6 +360,14 @@ def prepare_metadata(self) -> None: ) demographics = self._demographics() if demographics is not None: + unlisted = int((~gt["image"].isin(demographics["image"])).sum()) + if unlisted: + logger.warning( + "%d training images are not in %s; their age and " + "sex stay empty.", + unlisted, + _DATAVERSE_METADATA, + ) gt = gt.merge(demographics, on="image", how="left") else: gt["lesion_id"] = None diff --git a/pyhealth/metrics/fairness_selection.py b/pyhealth/metrics/fairness_selection.py index 5d1fe435fe..aaa163480a 100644 --- a/pyhealth/metrics/fairness_selection.py +++ b/pyhealth/metrics/fairness_selection.py @@ -40,12 +40,19 @@ def dto_select(scores: np.ndarray) -> int: Returns: Row index of the candidate with the smallest DTO. + Raises: + ValueError: If ``scores`` is not a non-empty 2-D matrix, has NaN, or + some group's best score is not positive. + Examples: >>> dto_select(np.array([[0.80, 0.70], [0.78, 0.76], [0.85, 0.60]])) 1 """ scores = _check(scores) - return int(np.argmin(np.linalg.norm(1.0 - scores / scores.max(axis=0), axis=1))) + best = scores.max(axis=0) + if (best <= 0).any(): + raise ValueError("DTO needs a positive best score for every group.") + return int(np.argmin(np.linalg.norm(1.0 - scores / best, axis=1))) def pareto_front(scores: np.ndarray) -> np.ndarray: diff --git a/pyhealth/metrics/group_fairness.py b/pyhealth/metrics/group_fairness.py index 800adb8c21..83c8b1a7a3 100644 --- a/pyhealth/metrics/group_fairness.py +++ b/pyhealth/metrics/group_fairness.py @@ -124,8 +124,9 @@ def group_fairness_metrics_fn( Dictionary from metric name to value. Raises: - ValueError: On mismatched lengths, missing group values, unknown - metric names, or ``eqodd`` with other than two groups. + ValueError: On non-binary labels, probabilities outside [0, 1] or + NaN, mismatched lengths, missing group values, unknown metric + names, or ``eqodd`` with other than two groups. Examples: >>> y_true = np.array([0, 0, 1, 1, 0, 0, 1, 1]) @@ -135,8 +136,13 @@ def group_fairness_metrics_fn( >>> s["auc_M"], s["auc_F"], s["auc_gap"], s["eqodd"] (0.75, 1.0, 0.25, 0.5) """ - y_true = np.asarray(y_true).reshape(-1).astype(int) + y_true = np.asarray(y_true).reshape(-1) y_prob = np.asarray(y_prob, dtype=float).reshape(-1) + if not np.isin(y_true, (0, 1)).all(): + raise ValueError("y_true must contain only 0 and 1.") + if not ((y_prob >= 0) & (y_prob <= 1)).all(): + raise ValueError("y_prob must be probabilities in [0, 1], without NaN.") + y_true = y_true.astype(int) groups = np.asarray(groups, dtype=object).reshape(-1) if not len(y_true) == len(y_prob) == len(groups): raise ValueError( diff --git a/pyhealth/sampler/group_sampler.py b/pyhealth/sampler/group_sampler.py index 072328d001..0b477e484c 100644 --- a/pyhealth/sampler/group_sampler.py +++ b/pyhealth/sampler/group_sampler.py @@ -36,8 +36,9 @@ class GroupBalancedSampler(Sampler[int]): seed: Seed of the draws. Defaults to 0. Raises: - ValueError: If ``groups`` is empty, has missing values, or differs - in length from ``labels``. + ValueError: If ``groups`` is empty, ``groups`` or ``labels`` have + missing values or differ in length, or ``num_samples`` is not + positive. Examples: >>> sampler = GroupBalancedSampler(["F", "F", "F", "M"], seed=0) @@ -66,13 +67,18 @@ def __init__( f"groups and labels differ in length: " f"{len(groups)} vs {len(labels)}." ) - keys = list(zip(groups, (_hashable(y) for y in labels))) + labels = [_hashable(y) for y in labels] + if any(pd.isna(y) for y in labels if not isinstance(y, tuple)): + raise ValueError("labels contain missing values.") + keys = list(zip(groups, labels)) codes: dict = {} cells = np.array([codes.setdefault(k, len(codes)) for k in keys]) self.weights = torch.as_tensor( 1.0 / np.bincount(cells)[cells], dtype=torch.double ) self.num_samples = len(cells) if num_samples is None else int(num_samples) + if self.num_samples <= 0: + raise ValueError(f"num_samples must be positive, got {num_samples}.") self.seed = int(seed) self.epoch = 0 @@ -172,6 +178,9 @@ def get_group_balanced_dataloader( ... ) >>> trainer.train(train_dataloader=loader, ...) # doctest: +SKIP """ + clashing = sorted({"shuffle", "sampler", "batch_sampler"} & set(loader_kwargs)) + if clashing: + raise TypeError(f"{clashing} cannot be set; the group sampler orders the data.") if (group_key is None) == (groups is None): raise ValueError("Pass exactly one of group_key and groups.") if label_key is not None and labels is not None: diff --git a/pyhealth/tasks/ham10000_malignancy.py b/pyhealth/tasks/ham10000_malignancy.py index e7a6a01106..31b61e020e 100644 --- a/pyhealth/tasks/ham10000_malignancy.py +++ b/pyhealth/tasks/ham10000_malignancy.py @@ -45,8 +45,12 @@ class HAM10000MalignancyClassification(BaseTask): Args: image_size: Side length of the square input image. Defaults to 224. - age_bins: Increasing upper edges of the age groups. Defaults to - ``(60,)``. + age_bins: Increasing upper edges of the age groups, in whole years. + Defaults to ``(60,)``. + + Raises: + ValueError: If ``age_bins`` is empty, not strictly increasing, not + whole numbers, or not positive. Examples: >>> from pyhealth.datasets import HAM10000Dataset, PatientSplit @@ -70,9 +74,11 @@ def __init__(self, image_size: int = 224, age_bins: Sequence[int] = (60,)) -> No super().__init__() edges = tuple(int(e) for e in age_bins) increasing = all(a < b for a, b in itertools.pairwise(edges)) - if not edges or not increasing or edges[0] <= 0: + whole = all(e == b for e, b in zip(edges, age_bins)) + if not edges or not increasing or not whole or edges[0] <= 0: raise ValueError( - f"age_bins must be positive and strictly increasing, got {age_bins!r}." + "age_bins must be positive, strictly increasing whole years, " + f"got {age_bins!r}." ) self.image_size = int(image_size) self.age_bins = edges diff --git a/tests/core/test_fairness_selection.py b/tests/core/test_fairness_selection.py index c04d71ff24..0db7134402 100644 --- a/tests/core/test_fairness_selection.py +++ b/tests/core/test_fairness_selection.py @@ -55,6 +55,8 @@ def test_rejects_bad_input(self): dto_select(np.array([[0.8, np.nan]])) with self.assertRaises(ValueError): minimax_pareto_select(SCORES, group=2) + with self.assertRaises(ValueError): + dto_select(np.array([[0.8, 0.0], [0.7, 0.0]])) if __name__ == "__main__": diff --git a/tests/core/test_group_fairness_metrics.py b/tests/core/test_group_fairness_metrics.py index ac7a2b57eb..771de88042 100644 --- a/tests/core/test_group_fairness_metrics.py +++ b/tests/core/test_group_fairness_metrics.py @@ -124,6 +124,21 @@ def test_shape_mismatch_raises(self): with self.assertRaises(ValueError): group_fairness_metrics_fn(self.y_true, self.y_prob, self.groups[:-1]) + def test_bad_labels_or_probs_raise(self): + with self.assertRaises(ValueError): + group_fairness_metrics_fn(self.y_true * 2, self.y_prob, self.groups) + for bad in (1.5, -0.1, np.nan): + y_prob = self.y_prob.copy() + y_prob[0] = bad + with self.assertRaises(ValueError): + group_fairness_metrics_fn(self.y_true, y_prob, self.groups) + + def test_float_labels_accepted(self): + s = group_fairness_metrics_fn( + self.y_true.astype(float), self.y_prob, self.groups, threshold=0.5 + ) + self.assertAlmostEqual(s["auc_M"], 0.75) + def test_unknown_metric_raises(self): with self.assertRaises(ValueError): self.score(metrics=["auroc"]) diff --git a/tests/core/test_group_sampler.py b/tests/core/test_group_sampler.py index 7975fd8649..22c83d9d66 100644 --- a/tests/core/test_group_sampler.py +++ b/tests/core/test_group_sampler.py @@ -82,6 +82,15 @@ def test_rejects_mismatched_labels(self): with self.assertRaises(ValueError): GroupBalancedSampler([]) + def test_rejects_missing_labels(self): + with self.assertRaises(ValueError): + GroupBalancedSampler(SEXES, labels=[*LABELS[:-1], None]) + + def test_rejects_non_positive_num_samples(self): + for n in (0, -1): + with self.assertRaises(ValueError): + GroupBalancedSampler(SEXES, num_samples=n) + class TestGroupBalancedDataloader(unittest.TestCase): def setUp(self): @@ -132,6 +141,11 @@ def test_bad_arguments_raise(self): self.dataset, 4, groups=SEXES, label_key="y", labels=LABELS ) + def test_order_arguments_rejected(self): + for kwargs in ({"shuffle": True}, {"shuffle": False}, {"sampler": None}): + with self.assertRaises(TypeError): + get_group_balanced_dataloader(self.dataset, 4, groups=SEXES, **kwargs) + def test_missing_key_raises(self): with self.assertRaises(KeyError): get_group_balanced_dataloader(self.dataset, 4, group_key="age") diff --git a/tests/core/test_ham10000_malignancy_task.py b/tests/core/test_ham10000_malignancy_task.py index 04749c4761..e900af8205 100644 --- a/tests/core/test_ham10000_malignancy_task.py +++ b/tests/core/test_ham10000_malignancy_task.py @@ -103,6 +103,12 @@ def test_bad_age_bins_raise(self): HAM10000MalignancyClassification(age_bins=()) with self.assertRaises(ValueError): HAM10000MalignancyClassification(age_bins=(60, 40)) + with self.assertRaises(ValueError): + HAM10000MalignancyClassification(age_bins=(60.5,)) + self.assertEqual( + HAM10000MalignancyClassification(age_bins=(60.0,)).age_groups, + ["<=60", ">60"], + ) class TestHAM10000DemographicsFile(unittest.TestCase): @@ -131,6 +137,23 @@ def test_edited_file_rebuilds_metadata(self): frame.to_csv(path, index=False) self.assertEqual(self._sex(metadata_dir), "F") + def test_duplicate_rows_keep_the_first(self): + path = self.root / "HAM10000_metadata.csv" + frame = pd.read_csv(path) + first = frame[frame["image_id"] == "ISIC_0000001"].assign(sex="female") + pd.concat([frame, first]).to_csv(path, index=False) + with self.assertLogs("pyhealth.datasets.ham10000", "WARNING") as logs: + self.assertEqual(self._sex(self.tmp / "meta"), "M") + self.assertIn("more than once", "".join(logs.output)) + + def test_unlisted_images_warn(self): + path = self.root / "HAM10000_metadata.csv" + frame = pd.read_csv(path) + frame[frame["image_id"] != "ISIC_0000001"].to_csv(path, index=False) + with self.assertLogs("pyhealth.datasets.ham10000", "WARNING") as logs: + self.assertIsNone(self._sex(self.tmp / "meta")) + self.assertIn("1 training images are not in", "".join(logs.output)) + def test_tab_separated_file_with_groupings_leaves_sex_empty(self): path = self.root / "HAM10000_metadata.csv" pd.read_csv(path).to_csv(path, sep="\t", index=False) From 0779a21b9f97ee350dd8c5cd1f7ffc4a6a06e35c Mon Sep 17 00:00:00 2001 From: Sanni heruwala Date: Fri, 27 Nov 2026 22:22:16 +0530 Subject: [PATCH 11/13] fix: say why the HAM10000 task skips images, and test the loader on a task dataset The task warns once when it skips images without age or sex, naming the missing Dataverse file. The example checks for that file up front and no longer fails with a KeyError when a group has no val samples. --- examples/derm/medfair_ham10000.py | 11 ++++++++++- pyhealth/tasks/ham10000_malignancy.py | 17 ++++++++++++++--- tests/core/test_ham10000_malignancy_task.py | 21 ++++++++++++++++++++- 3 files changed, 44 insertions(+), 5 deletions(-) diff --git a/examples/derm/medfair_ham10000.py b/examples/derm/medfair_ham10000.py index f70a5f014c..c4537edbdc 100644 --- a/examples/derm/medfair_ham10000.py +++ b/examples/derm/medfair_ham10000.py @@ -154,7 +154,11 @@ def select(settings: dict, names: list[str], ref: int | None) -> dict[str, float def defined_groups(settings: dict, names: list[str]) -> list[str]: """Groups with a val AUC in every run; selection needs all of them.""" runs = [r for rs in settings.values() for r in rs] - return [g for g in names if all(np.isfinite(r["val"][f"auc_{g}"]) for r in runs)] + return [ + g + for g in names + if all(np.isfinite(r["val"].get(f"auc_{g}", np.nan)) for r in runs) + ] def main() -> None: @@ -178,6 +182,11 @@ def main() -> None: write_synthetic_ham10000(root, n_lesions=400, seed=0) args.image_size, args.epochs, args.pretrained = 32, 2, False args.lrs, args.seeds = [1e-3, 1e-4], [0, 1] + elif not (Path(root) / "HAM10000_metadata.csv").exists(): + raise SystemExit( + f"No HAM10000_metadata.csv in {root}; the task needs its age and " + "sex columns (see HAM10000Dataset)." + ) dataset = HAM10000Dataset( root=str(root), cache_dir=args.cache_dir or str(Path(tmp) / "cache") ) diff --git a/pyhealth/tasks/ham10000_malignancy.py b/pyhealth/tasks/ham10000_malignancy.py index 31b61e020e..08a5e5aa99 100644 --- a/pyhealth/tasks/ham10000_malignancy.py +++ b/pyhealth/tasks/ham10000_malignancy.py @@ -1,6 +1,7 @@ """Malignant vs. benign HAM10000 task with sensitive attributes (MEDFAIR).""" import itertools +import logging import math from collections.abc import Sequence from typing import Any, ClassVar @@ -9,6 +10,8 @@ from .base_task import BaseTask +logger = logging.getLogger(__name__) + MALIGNANT = frozenset({"MEL", "AKIEC"}) @@ -22,9 +25,9 @@ class HAM10000MalignancyClassification(BaseTask): Works with :class:`~pyhealth.datasets.HAM10000Dataset` when the Dataverse ``HAM10000_metadata.csv`` is in its root, since age and sex come from it; - without it no samples are produced. That file covers only the training - images, so the ISIC 2018 validation and test splits give no samples - either; split the training set instead, as below. + without it no samples are produced, and a warning says so. That file + covers only the training images, so the ISIC 2018 validation and test + splits give no samples either; split the training set instead, as below. The HAM10000 setup of MEDFAIR (Zong et al., ICLR 2023): melanoma (MEL) and actinic keratosis / intraepithelial carcinoma (AKIEC) are malignant, @@ -83,6 +86,7 @@ def __init__(self, image_size: int = 224, age_bins: Sequence[int] = (60,)) -> No self.image_size = int(image_size) self.age_bins = edges self.age_groups = _age_labels(edges) + self._warned = False self.input_schema = { "image": ("image", {"image_size": self.image_size, "mode": "RGB"}) } @@ -102,6 +106,13 @@ def __call__(self, patient: Any) -> list[dict[str, Any]]: sex = getattr(event, "sex", None) age = getattr(event, "age", None) if sex not in ("F", "M") or age is None or math.isnan(float(age)): + if not self._warned: + logger.warning( + "Skipping HAM10000 images without age or sex; with no " + "HAM10000_metadata.csv in the dataset root that is all " + "of them." + ) + self._warned = True continue age = float(age) group = int(np.searchsorted(self.age_bins, age, side="left")) diff --git a/tests/core/test_ham10000_malignancy_task.py b/tests/core/test_ham10000_malignancy_task.py index e900af8205..ef5694ba4b 100644 --- a/tests/core/test_ham10000_malignancy_task.py +++ b/tests/core/test_ham10000_malignancy_task.py @@ -8,6 +8,7 @@ import pandas as pd from pyhealth.datasets import HAM10000Dataset +from pyhealth.sampler import get_group_balanced_dataloader from pyhealth.tasks import HAM10000MalignancyClassification from tests.core.test_ham10000_dataset import _TRAIN, make_ham10000_root @@ -98,6 +99,19 @@ def test_custom_age_bins(self): self.assertEqual(rows["ISIC_0000004"]["age_group"], "(59, 79]") self.assertEqual(rows["ISIC_0000005"]["age_group"], ">79") + def test_group_loader_on_task_dataset(self): + samples = self.dataset.set_task(HAM10000MalignancyClassification(16)) + try: + loader = get_group_balanced_dataloader( + samples, batch_size=4, group_key="sex", num_samples=8, seed=0 + ) + batches = list(loader) + self.assertEqual(sum(len(b["sex"]) for b in batches), 8) + self.assertEqual(tuple(batches[0]["image"].shape), (4, 3, 16, 16)) + self.assertLessEqual(set(batches[0]["sex"]), {"F", "M"}) + finally: + samples.close() + def test_bad_age_bins_raise(self): with self.assertRaises(ValueError): HAM10000MalignancyClassification(age_bins=()) @@ -180,7 +194,12 @@ def test_columns_empty_and_task_yields_nothing(self): event = dataset.get_patient("HAM_1").get_events(event_type="ham10000")[0] self.assertIsNone(event.sex) task = HAM10000MalignancyClassification(image_size=16) - self.assertEqual(task(dataset.get_patient("HAM_1")), []) + log = "pyhealth.tasks.ham10000_malignancy" + with self.assertLogs(log, "WARNING") as logs: + self.assertEqual(task(dataset.get_patient("HAM_1")), []) + task(dataset.get_patient("HAM_2")) + self.assertEqual(len(logs.output), 1) + self.assertIn("HAM10000_metadata.csv", logs.output[0]) finally: shutil.rmtree(tmp, ignore_errors=True) From 35046b8ce81af63aeabfe9c4c52dd93e27605f4d Mon Sep 17 00:00:00 2001 From: Sanni heruwala Date: Fri, 27 Nov 2026 22:24:29 +0530 Subject: [PATCH 12/13] fix: reject undefined F1 tuning and non-finite selection scores --- pyhealth/metrics/fairness_selection.py | 10 ++++++---- pyhealth/metrics/group_fairness.py | 8 +++++++- tests/core/test_fairness_selection.py | 2 ++ tests/core/test_group_fairness_metrics.py | 4 ++++ 4 files changed, 19 insertions(+), 5 deletions(-) diff --git a/pyhealth/metrics/fairness_selection.py b/pyhealth/metrics/fairness_selection.py index aaa163480a..51ec117475 100644 --- a/pyhealth/metrics/fairness_selection.py +++ b/pyhealth/metrics/fairness_selection.py @@ -23,8 +23,10 @@ def _check(scores: np.ndarray) -> np.ndarray: f"scores must be a non-empty (n_candidates, n_groups) matrix, " f"got shape {scores.shape}." ) - if np.isnan(scores).any(): - raise ValueError("scores contain NaN; drop or impute those groups first.") + if not np.isfinite(scores).all(): + raise ValueError( + "scores contain NaN or inf; drop or impute those groups first." + ) return scores @@ -41,8 +43,8 @@ def dto_select(scores: np.ndarray) -> int: Row index of the candidate with the smallest DTO. Raises: - ValueError: If ``scores`` is not a non-empty 2-D matrix, has NaN, or - some group's best score is not positive. + ValueError: If ``scores`` is not a non-empty 2-D matrix, is not + finite, or some group's best score is not positive. Examples: >>> dto_select(np.array([[0.80, 0.70], [0.78, 0.76], [0.85, 0.60]])) diff --git a/pyhealth/metrics/group_fairness.py b/pyhealth/metrics/group_fairness.py index 83c8b1a7a3..0a05d50441 100644 --- a/pyhealth/metrics/group_fairness.py +++ b/pyhealth/metrics/group_fairness.py @@ -31,10 +31,15 @@ def best_f1_threshold(y_true: np.ndarray, y_prob: np.ndarray) -> float: Returns: The threshold ``t`` maximising F1 of ``y_prob >= t``. + Raises: + ValueError: If ``y_true`` has no positives, where F1 is undefined. + Examples: >>> best_f1_threshold(np.array([0, 1, 1]), np.array([0.2, 0.6, 0.9])) 0.6 """ + if not np.any(np.asarray(y_true) == 1): + raise ValueError("best_f1_threshold needs at least one positive label.") precision, recall, thresholds = precision_recall_curve(y_true, y_prob) with np.errstate(divide="ignore", invalid="ignore"): f1 = np.nan_to_num(2 * precision * recall / (precision + recall)) @@ -118,7 +123,8 @@ def group_fairness_metrics_fn( with :func:`best_f1_threshold`, as the MEDFAIR paper does (its code uses 0.5 for the per-group FPR/FNR). For a clean test estimate pass the threshold tuned on validation. The value used - is returned as ``"threshold"``. + is returned as ``"threshold"``. Tuning needs at least one + positive label. Returns: Dictionary from metric name to value. diff --git a/tests/core/test_fairness_selection.py b/tests/core/test_fairness_selection.py index 0db7134402..8da3bb57d7 100644 --- a/tests/core/test_fairness_selection.py +++ b/tests/core/test_fairness_selection.py @@ -57,6 +57,8 @@ def test_rejects_bad_input(self): minimax_pareto_select(SCORES, group=2) with self.assertRaises(ValueError): dto_select(np.array([[0.8, 0.0], [0.7, 0.0]])) + with self.assertRaises(ValueError): + minimax_pareto_select(np.array([[0.8, np.inf], [0.7, 0.6]])) if __name__ == "__main__": diff --git a/tests/core/test_group_fairness_metrics.py b/tests/core/test_group_fairness_metrics.py index 771de88042..11645ca7cf 100644 --- a/tests/core/test_group_fairness_metrics.py +++ b/tests/core/test_group_fairness_metrics.py @@ -151,6 +151,10 @@ def test_accepts_column_vector_probs(self): class TestHelpers(unittest.TestCase): + def test_best_f1_threshold_needs_a_positive(self): + with self.assertRaises(ValueError): + best_f1_threshold(np.zeros(4), np.array([0.1, 0.2, 0.3, 0.4])) + def test_best_f1_threshold(self): y_true = np.array([0, 0, 1, 1, 0, 0, 1, 1]) y_prob = np.array([0.1, 0.4, 0.35, 0.8, 0.2, 0.6, 0.7, 0.9]) From 5f1c85a0f5e74346613a58da0b81e5fe530c08d6 Mon Sep 17 00:00:00 2001 From: Sanni heruwala Date: Sat, 28 Nov 2026 00:00:15 +0530 Subject: [PATCH 13/13] fix: tune the threshold only when used, draw resamples with numpy Skip F1 tuning when no requested metric needs a threshold. Draw the resampled indices with numpy, which has no 2**24 category limit, and reject a negative seed up front. Reword the task's skip warning so it fits a split that the Dataverse file does not cover. --- pyhealth/metrics/group_fairness.py | 12 +++++++----- pyhealth/sampler/group_sampler.py | 16 ++++++++-------- pyhealth/tasks/ham10000_malignancy.py | 7 ++++--- tests/core/test_group_fairness_metrics.py | 7 +++++++ tests/core/test_group_sampler.py | 4 ++++ 5 files changed, 30 insertions(+), 16 deletions(-) diff --git a/pyhealth/metrics/group_fairness.py b/pyhealth/metrics/group_fairness.py index 0a05d50441..0aeb3016c0 100644 --- a/pyhealth/metrics/group_fairness.py +++ b/pyhealth/metrics/group_fairness.py @@ -124,7 +124,8 @@ def group_fairness_metrics_fn( code uses 0.5 for the per-group FPR/FNR). For a clean test estimate pass the threshold tuned on validation. The value used is returned as ``"threshold"``. Tuning needs at least one - positive label. + positive label, and is skipped (NaN) when no requested metric + uses the threshold. Returns: Dictionary from metric name to value. @@ -168,16 +169,17 @@ def group_fairness_metrics_fn( if "eqodd" in metrics and len(names) != 2: raise ValueError(f"eqodd needs exactly two groups, got {len(names)}.") - if threshold is None: - threshold = best_f1_threshold(y_true, y_prob) - y_pred = y_prob >= threshold - needed = set(metrics) if needed & {"worst_auc", "auc_gap"}: needed.add("auc") if "eqodd" in needed: needed |= {"fpr", "fnr"} + if threshold is None: + uses_threshold = needed & {"acc", "fpr", "fnr"} + threshold = best_f1_threshold(y_true, y_prob) if uses_threshold else np.nan + y_pred = y_prob >= threshold + affected = needed & {"auc", "tpr_at_tnr80", "fpr", "fnr"} one_class = [str(g) for g in names if len(np.unique(y_true[groups == g])) < 2] if affected and one_class: diff --git a/pyhealth/sampler/group_sampler.py b/pyhealth/sampler/group_sampler.py index 0b477e484c..fd2efcc139 100644 --- a/pyhealth/sampler/group_sampler.py +++ b/pyhealth/sampler/group_sampler.py @@ -33,12 +33,12 @@ class GroupBalancedSampler(Sampler[int]): labels: Optional label of each sample, to balance the (group, label) cells. Defaults to None. num_samples: Indices drawn per pass. Defaults to ``len(groups)``. - seed: Seed of the draws. Defaults to 0. + seed: Non-negative seed of the draws. Defaults to 0. Raises: ValueError: If ``groups`` is empty, ``groups`` or ``labels`` have - missing values or differ in length, or ``num_samples`` is not - positive. + missing values or differ in length, ``num_samples`` is not + positive, or ``seed`` is negative. Examples: >>> sampler = GroupBalancedSampler(["F", "F", "F", "M"], seed=0) @@ -80,6 +80,8 @@ def __init__( if self.num_samples <= 0: raise ValueError(f"num_samples must be positive, got {num_samples}.") self.seed = int(seed) + if self.seed < 0: + raise ValueError(f"seed must be non-negative, got {seed}.") self.epoch = 0 def set_epoch(self, epoch: int) -> None: @@ -91,12 +93,10 @@ def set_epoch(self, epoch: int) -> None: self.epoch = int(epoch) def __iter__(self) -> Iterator[int]: - state = np.random.SeedSequence([self.seed, self.epoch]).generate_state(1) - generator = torch.Generator().manual_seed(int(state[0])) + rng = np.random.default_rng(np.random.SeedSequence([self.seed, self.epoch])) self.epoch += 1 - draws = torch.multinomial( - self.weights, self.num_samples, replacement=True, generator=generator - ) + p = self.weights.numpy() + draws = rng.choice(len(p), size=self.num_samples, p=p / p.sum()) return iter(draws.tolist()) def __len__(self) -> int: diff --git a/pyhealth/tasks/ham10000_malignancy.py b/pyhealth/tasks/ham10000_malignancy.py index 08a5e5aa99..1db7ba240d 100644 --- a/pyhealth/tasks/ham10000_malignancy.py +++ b/pyhealth/tasks/ham10000_malignancy.py @@ -108,9 +108,10 @@ def __call__(self, patient: Any) -> list[dict[str, Any]]: if sex not in ("F", "M") or age is None or math.isnan(float(age)): if not self._warned: logger.warning( - "Skipping HAM10000 images without age or sex; with no " - "HAM10000_metadata.csv in the dataset root that is all " - "of them." + "Skipping HAM10000 images without age or sex. They come " + "from the Dataverse HAM10000_metadata.csv, which covers " + "training images only; without it in the dataset root " + "every image is skipped." ) self._warned = True continue diff --git a/tests/core/test_group_fairness_metrics.py b/tests/core/test_group_fairness_metrics.py index 11645ca7cf..af8fde0a34 100644 --- a/tests/core/test_group_fairness_metrics.py +++ b/tests/core/test_group_fairness_metrics.py @@ -85,6 +85,13 @@ def test_mixed_type_groups(self): self.assertAlmostEqual(s["auc_1"], 0.75) self.assertAlmostEqual(s["auc_x"], 1.0) + def test_no_tuning_without_threshold_metrics(self): + y_true = np.zeros(8, dtype=int) + with self.assertWarns(UserWarning): + s = group_fairness_metrics_fn(y_true, self.y_prob, self.groups, ["auc"]) + self.assertTrue(np.isnan(s["threshold"])) + self.assertTrue(np.isnan(s["auc"])) + def test_tuned_threshold_when_none(self): s = group_fairness_metrics_fn(self.y_true, self.y_prob, self.groups) self.assertAlmostEqual(s["threshold"], 0.7) diff --git a/tests/core/test_group_sampler.py b/tests/core/test_group_sampler.py index 22c83d9d66..584c6c59d7 100644 --- a/tests/core/test_group_sampler.py +++ b/tests/core/test_group_sampler.py @@ -86,6 +86,10 @@ def test_rejects_missing_labels(self): with self.assertRaises(ValueError): GroupBalancedSampler(SEXES, labels=[*LABELS[:-1], None]) + def test_rejects_negative_seed(self): + with self.assertRaises(ValueError): + GroupBalancedSampler(SEXES, seed=-1) + def test_rejects_non_positive_num_samples(self): for n in (0, -1): with self.assertRaises(ValueError):