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..944f3d3889 --- /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/derm/medfair_ham10000.py b/examples/derm/medfair_ham10000.py new file mode 100644 index 0000000000..c4537edbdc --- /dev/null +++ b/examples/derm/medfair_ham10000.py @@ -0,0 +1,254 @@ +"""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/derm/medfair_ham10000.py --root /path/to/isic2018_task3 \\ + --cache-dir /path/to/cache --attribute sex --epochs 15 + +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 + +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"].get(f"auc_{g}", np.nan)) 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] + 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") + ) + 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) + ) + # 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)) + } + 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 + } + + 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))}." + ) + 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..2c917f66a7 100644 --- a/pyhealth/datasets/ham10000.py +++ b/pyhealth/datasets/ham10000.py @@ -50,6 +50,13 @@ 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. 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 each of those images is its own patient. Every event has a ``split`` @@ -89,15 +96,23 @@ 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 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. - ``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 +198,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 @@ -232,6 +256,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 @@ -239,9 +277,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"]] @@ -252,6 +289,36 @@ def _lesion_ids(self) -> pd.DataFrame: f"{HAM10000_BASE_URL}." ) + def _demographics(self) -> pd.DataFrame | None: + """Return ``image``, ``age``, ``sex``, ``localization``, or None.""" + 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 + if not {"age", "sex"} <= set(meta.columns): + logger.warning( + "%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 = 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"] + ] + def prepare_metadata(self) -> None: """Write the metadata CSV, one row per image, to ``metadata_dir``. @@ -291,9 +358,23 @@ def prepare_metadata(self) -> None: "patient.", n_missing, ) + 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 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 +402,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/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..51ec117475 --- /dev/null +++ b/pyhealth/metrics/fairness_selection.py @@ -0,0 +1,108 @@ +"""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 not np.isfinite(scores).all(): + raise ValueError( + "scores contain NaN or inf; 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. + + Raises: + 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]])) + 1 + """ + scores = _check(scores) + 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: + """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. + 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). + + 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..0aeb3016c0 --- /dev/null +++ b/pyhealth/metrics/group_fairness.py @@ -0,0 +1,220 @@ +"""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``. + + 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)) + 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, 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 + the two subgroups of a binary attribute. + + 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 + 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"``. Tuning needs at least one + positive label, and is skipped (NaN) when no requested metric + uses the threshold. + + Returns: + Dictionary from metric name to value. + + Raises: + 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]) + >>> 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) + 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( + 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)}.") + + 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: + 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) + 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]) + 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..fd2efcc139 --- /dev/null +++ b/pyhealth/sampler/group_sampler.py @@ -0,0 +1,212 @@ +"""Subgroup resampling (Idrissi et al., CLeaR 2022), a MEDFAIR baseline.""" + +import functools +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 + + +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: 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, ``num_samples`` is not + positive, or ``seed`` is negative. + + 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)}." + ) + 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) + if self.seed < 0: + raise ValueError(f"seed must be non-negative, got {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]: + rng = np.random.default_rng(np.random.SeedSequence([self.seed, self.epoch])) + self.epoch += 1 + 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: + 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 _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, + 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. + + 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. + + 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 + """ + 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: + 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=_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..1db7ba240d --- /dev/null +++ b/pyhealth/tasks/ham10000_malignancy.py @@ -0,0 +1,131 @@ +"""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 + +import numpy as np + +from .base_task import BaseTask + +logger = logging.getLogger(__name__) + +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, 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, + 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, 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 + >>> 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)) + 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( + "age_bins must be positive, strictly increasing whole years, " + f"got {age_bins!r}." + ) + 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"}) + } + + 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)): + if not self._warned: + logger.warning( + "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 + 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..8da3bb57d7 --- /dev/null +++ b/tests/core/test_fairness_selection.py @@ -0,0 +1,65 @@ +"""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) + 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__": + 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..af8fde0a34 --- /dev/null +++ b/tests/core/test_group_fairness_metrics.py @@ -0,0 +1,172 @@ +"""Tests for pyhealth.metrics.group_fairness.""" + +import unittest +import warnings + +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_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) + + 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_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) + 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_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"]) + + 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_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]) + 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..584c6c59d7 --- /dev/null +++ b/tests/core/test_group_sampler.py @@ -0,0 +1,159 @@ +"""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_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) + a.set_epoch(1) + 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([]) + + 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): + GroupBalancedSampler(SEXES, num_samples=n) + + +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) + 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): + 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]) + with self.assertRaises(ValueError): + get_group_balanced_dataloader( + 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") + + +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..ef5694ba4b --- /dev/null +++ b/tests/core/test_ham10000_malignancy_task.py @@ -0,0 +1,208 @@ +"""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.sampler import get_group_balanced_dataloader +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_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=()) + 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): + 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_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) + 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" + 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): + 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) + 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) + + +if __name__ == "__main__": + unittest.main()