Skip to content

[BTY-62] MEDFAIR: subgroup fairness metrics, fairness-aware model selection and resampling, with a HAM10000 setup - #1560

Merged
solarsys merged 13 commits into
sunlabuiuc:masterfrom
sanniheruwala:bty-62-medfair
Dec 1, 2026
Merged

solarsys merged 13 commits into
sunlabuiuc:masterfrom
sanniheruwala:bty-62-medfair

Conversation

@sanniheruwala

@sanniheruwala sanniheruwala commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Contributor: Sanni Heruwala (@sanniheruwala)

Contribution type: Metrics + sampler + task (bounty BTY-62, MEDFAIR imaging fairness benchmark)

Paper: Zong, Yang and Hospedales. MEDFAIR: Benchmarking Fairness for Medical Imaging. ICLR 2023. https://arxiv.org/abs/2210.01725

What this adds

MEDFAIR's main finding is that how you pick the final model matters about as much as which debiasing method you use. So this PR brings over its evaluation and model-selection pieces plus its strongest simple baseline, and wires them to HAM10000, one of the datasets MEDFAIR benchmarks.

  • group_fairness_metrics_fn: overall and per-subgroup AUC, accuracy, ECE, BCE, FPR/FNR, TPR at 80% TNR, worst-group AUC, AUC gap and equalized odds. The threshold is either tuned for max F1 as in MEDFAIR, or passed in (tune on val, apply to test). ECE reuses ece_confidence_binary.
    It is a separate function rather than an extension of subgroup_metrics: that one wraps binary_metrics_fn per group at its fixed threshold, withholds small cells and returns a nested per-attribute dict. MEDFAIR needs FPR/FNR, EqOdd and TPR at 80% TNR at a tuned operating point, plus flat metric_group keys that the selection functions and result tables read directly. Adding that to subgroup_metrics would change its signature and return shape for existing callers.
  • dto_select and minimax_pareto_select: MEDFAIR's two fairness-aware selection rules over per-group validation AUC. The minimax rule takes an optional fixed reference group, which is how MEDFAIR applies it across methods.
  • GroupBalancedSampler / get_group_balanced_dataloader: subgroup (or subgroup x class) resampling. PyHealth sample datasets are iterable, so the loader puts a random-access view in front of them; batches look the same as from get_dataloader. Groups can be given directly to avoid decoding every image once. Draws depend only on (seed, epoch), so runs with different seeds don't replay each other.
  • HAM10000Dataset reads age, sex and body site from the Dataverse HAM10000_metadata.csv when it is in root. That file lists the training images only, so the ISIC 2018 validation and test splits have no demographics; the task is meant for a split of the training set, as in MEDFAIR. Without the file those attributes are empty. A tab-separated copy (the default Dataverse download) is ignored with a warning, and only raises, with a hint, when it has to stand in for a missing groupings CSV. Metadata cached before this change lacks the new columns and is rebuilt once; editing the Dataverse file also triggers a rebuild.
  • HAM10000MalignancyClassification: MEL + AKIEC vs. the rest, rows without age/sex dropped (9,948 images, as in the paper), and sex, age, age_group on every sample. Age bins include their upper edge: the default (60,) is MEDFAIR's binary attribute, and (19, 39, 59, 79) its five-group one.

Deviations from the MEDFAIR code, on purpose

  • ECE uses fixed equal-width bins on [0, 1]. MEDFAIR bins over the observed range of the predictions, so its per-group ECEs use different bins per group.
  • Per-group FPR/FNR use the F1-tuned threshold, as the paper describes. The MEDFAIR code uses 0.5 there.
  • The example tunes the threshold on val and applies it to test. MEDFAIR tunes it separately on each split.
  • I only expose EqOdd. MEDFAIR's code swaps the labels of the two equal-opportunity terms relative to the paper, and EqOdd is unaffected by that.
  • The MEDFAIR repo has no licence, so everything here is written from the paper and its definitions, not copied.

Files to review

  • pyhealth/metrics/group_fairness.py, pyhealth/metrics/fairness_selection.py
  • pyhealth/sampler/group_sampler.py
  • pyhealth/tasks/ham10000_malignancy.py, pyhealth/datasets/ham10000.py (+ yaml)
  • examples/derm/medfair_ham10000.py: ERM vs. resampling over an lr x seed grid. It picks a learning rate per selection rule from seed-averaged val scores (minimax judged on the ERM-worst group, as in MEDFAIR) and prints test mean (std). It runs as a synthetic smoke test with no arguments, or on the real data with --root.
  • Tests: tests/core/test_group_fairness_metrics.py, test_fairness_selection.py, test_group_sampler.py, test_ham10000_malignancy_task.py. Synthetic data, about 15 s; the existing HAM10000 tests still pass.
  • Docs: new pages under docs/api/metrics, docs/api/sampler, docs/api/tasks, and the three index files.

Next: a follow-up with GroupDRO, and the same setup for PAD-UFES-20 (which has Fitzpatrick skin type) and ISIC 2019.

@github-actions github-actions Bot mentioned this pull request Nov 20, 2026
@github-actions

github-actions Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

Test Coverage

Total: 89.13% (63783 / 71562 lines)

Modified file Coverage Lines
pyhealth/datasets/ham10000.py 94.48% 137 / 145
pyhealth/metrics/__init__.py 100.00% 21 / 21
pyhealth/metrics/fairness_selection.py 100.00% 27 / 27
pyhealth/metrics/group_fairness.py 100.00% 97 / 97
pyhealth/sampler/__init__.py 100.00% 5 / 5
pyhealth/sampler/group_sampler.py 100.00% 83 / 83
pyhealth/tasks/__init__.py 98.68% 149 / 151
pyhealth/tasks/ham10000_malignancy.py 100.00% 42 / 42

Workflow run · 5f1c85a

@solarsys solarsys added the status: manual Pending maintainer's review label Nov 21, 2026
@solarsys

Copy link
Copy Markdown
Collaborator

/review

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previous review

Reviewed commit adf81e6

Comment thread pyhealth/sampler/group_sampler.py Resolved
Comment thread pyhealth/metrics/group_fairness.py Resolved
Comment thread examples/medfair_ham10000.py Resolved
Comment thread examples/derm/medfair_ham10000.py Resolved
Comment thread examples/derm/medfair_ham10000.py Resolved
Comment thread tests/core/test_group_sampler.py Resolved

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previous review

AI Review

suggestion: approve
decision: human review

Thank you for this contribution, Sanni. It brings MEDFAIR's subgroup fairness metrics, its DTO and minimax-Pareto model selection, a group-balanced sampler and dataloader, HAM10000 demographics, a malignancy task and a runnable example. The code looks correct and complete, and the description explains the deliberate deviations from MEDFAIR clearly. Every new link between components is named in the description with a reason: the shared collate helper, the reuse of ece_confidence_binary, and the task reading the dataset's new columns.

Coverage meets the bar. The whole repository is at 86.09%, against 60%. The new files are at 100% (group_fairness.py, fairness_selection.py, ham10000_malignancy.py) and 95.6% (group_sampler.py). ham10000.py is at 93.9%. pyhealth/datasets/utils.py shows 49% for the whole file, but that is existing code. The new _sample_collate_fn helper is exercised by the sampler tests.

Core part of the codebase: the change edits get_dataloader in pyhealth/datasets/utils.py, a shared utility. Its collate setup moves into a new _sample_collate_fn helper, which the new loader also uses. It looks behaviour-preserving to me. Because it changes shared code that other components rely on, it can't be approved automatically, and a maintainer will want to take a look.

Optional suggestions:

  • pyhealth.sampler now imports from pyhealth.datasets. This sits in an import cycle with datasets/imaging/patches.py that works only because of import order. A lazy import, or putting the helper somewhere neutral, would make it sturdier.
  • In docs/api/tasks/pyhealth.tasks.HAM10000MalignancyClassification.rst the title underline is shorter than the title, which makes Sphinx warn. Please extend it.
  • The MEDFAIR figures quoted in the example docstring are good to keep, but a short note on where in the paper they come from would help readers.

Reviewed commit adf81e6

@sanniheruwala

sanniheruwala commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for the review. Pushed 79ce294 and afc7260, rebased on current master. Replied inline on each point; summary:

  • Dropped the get_dataloader refactor. The PR no longer touches pyhealth/datasets/utils.py; the sampler builds its own collate function and imports the padding helper lazily, so pyhealth.sampler doesn't import pyhealth.datasets at load time anymore (no cycle with datasets/imaging/patches.py either way round).
  • Fixed the title underline on the task page.
  • The example now cites the exact source of the MEDFAIR numbers (appendix Table A9, arXiv 2210.01725v2, in-distribution, minimax Pareto).

Since the shared-code change is gone, could this go back to status: automatic?

Comment thread pyhealth/sampler/group_sampler.py Resolved
Comment thread pyhealth/metrics/group_fairness.py Resolved
Comment thread examples/medfair_ham10000.py Resolved
Comment thread examples/derm/medfair_ham10000.py Resolved
Comment thread examples/derm/medfair_ham10000.py Resolved
Comment thread tests/core/test_group_sampler.py Resolved

Copy link
Copy Markdown
Collaborator

/review


Generated by Claude Code

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previous review

Reviewed commit afc7260

Comment thread pyhealth/datasets/ham10000.py Resolved
Comment thread pyhealth/datasets/ham10000.py Resolved
Comment thread pyhealth/sampler/group_sampler.py Resolved
Comment thread pyhealth/metrics/group_fairness.py Resolved

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previous review

AI Review

suggestion: approve
decision: human review

Thank you for this contribution, Sanni. It brings MEDFAIR's subgroup fairness metrics, its two fairness-aware selection rules, subgroup resampling and a HAM10000 malignancy setup into PyHealth. It looks ready to merge.

What I checked:

  • Sharing: The description names the one link between components, which is reusing ece_confidence_binary. It also explains why group_fairness_metrics_fn is separate from subgroup_metrics. The HAM10000Dataset demographics change clearly exists to feed the new task.
  • Coverage: The whole repository is at 86.21%, against a 60% bar. Every changed file is above 80%: ham10000.py 93.85%, fairness_selection.py 100%, group_fairness.py 100%, group_sampler.py 95.89% and ham10000_malignancy.py 100%.
  • Docs and tests: The docs match the code, and the tests cover each new function and the demographics path.
  • Scope: The __init__.py edits only add exports.

Optional suggestions:

  • The description says "Without the file nothing changes." The source key now always includes a demographics field, so existing users get a one-time metadata rebuild. A short note in the docs would cover this.
  • The tab-separated-file error in _demographics looks unreachable when the Dataverse CSV is the only metadata source, because _lesion_ids fails first. You could check for this earlier.
  • get_group_balanced_dataloader is described as a drop-in for get_dataloader, but it takes no shuffle argument. You could say so in the docstring.
  • tpr_at_tnr80 linearly interpolates the ROC curve at FPR 0.2. One sentence in the docstring would make that clear.

Reviewed commit afc7260

Comment thread pyhealth/datasets/ham10000.py Resolved
Comment thread pyhealth/datasets/ham10000.py Resolved
Comment thread pyhealth/sampler/group_sampler.py Resolved
Comment thread pyhealth/metrics/group_fairness.py Resolved
@sanniheruwala

Copy link
Copy Markdown
Contributor Author

Addressed the four suggestions from the latest review in ebeb3d3 and replied inline. Two I handled differently from the suggestion, with the reasons in the threads: the one-time metadata rebuild stays (old caches lack the new columns and would otherwise fail to load), and tpr_at_tnr80 keeps MEDFAIR's interpolation so the numbers stay comparable. Rebased on current master, CI rerunning.

Copy link
Copy Markdown
Collaborator

/review


Generated by Claude Code

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previous review

Reviewed commit ebeb3d3

Comment thread pyhealth/datasets/ham10000.py Resolved

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previous review

AI Review

suggestion: approve
decision: human review

Thank you for this contribution. It brings MEDFAIR's evaluation and model-selection pieces to PyHealth: subgroup fairness metrics, DTO and minimax-Pareto selection, a group-balanced sampler and dataloader, and a HAM10000 malignancy task with sex and age attributes. It also adds a runnable ERM-vs-resampling example. The description is clear about the deviations from MEDFAIR. It also explains why group_fairness_metrics_fn is separate from subgroup_metrics and why ece_confidence_binary is reused.

It looks ready to merge. The new modules are self-contained, and the __init__ edits only register exports. Coverage meets the bar: the whole repo is at 86.25% (bar 60%). Every changed file is above 80%: ham10000.py 94%, group_sampler.py 96%, and the other new files 100%.

Optional suggestions:

  • HAM10000Dataset now raises a ValueError for a tab-separated HAM10000_metadata.csv even when the lesion groupings CSV is present. Before, that file was ignored in this case. The error message is helpful and the behavior is tested. A one-line note in the description or the dataset docstring would help anyone who already has such a file in root.
  • I couldn't check the MEDFAIR Table A9 numbers quoted in the example docstring against the paper. Please double-check them.
  • There is a stray long line in the get_group_balanced_dataloader docstring ("Give the groups either as a sample field…"). Re-wrapping it would tidy it.

Reviewed commit ebeb3d3

Comment thread pyhealth/datasets/ham10000.py Resolved
Comment thread pyhealth/tasks/ham10000_malignancy.py Resolved
Comment thread pyhealth/metrics/group_fairness.py Resolved
Comment thread pyhealth/sampler/group_sampler.py Resolved
@solarsys

Copy link
Copy Markdown
Collaborator

/review

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previous review

AI Review

suggestion: approve
decision: human review

Thank you for this contribution. It brings MEDFAIR's subgroup fairness metrics, its two fairness-aware selection rules, a group-balanced resampler and a HAM10000 malignancy task with age and sex attributes into PyHealth. It also adds a runnable example.

It looks ready to merge. The code matches the description. The new components stay self-contained: the only link is ECE reuse, which the description names. The new metrics, sampler, task and selection files have 100% test coverage. The modified ham10000.py has 94.5% and the whole repository has 87.1%, so all clear the bar. The docs match the code, and the HAM10000 changes are described, including the one-time metadata rebuild.

Optional suggestions:

  • The example docstring cites specific MEDFAIR table numbers (A8, A9, A2). Double-check them against the paper, or drop the numbers if you're unsure.
  • The HAM10000Dataset docstring could say in one line that the age, sex and localization columns are new, for users who read only that page.

Reviewed commit fe36979

solarsys
solarsys previously approved these changes Dec 1, 2026

@solarsys solarsys left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved by a maintainer. The AI review suggests approve on the current commit, and the build passes.

@solarsys

solarsys commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator

Approved by a maintainer, and ready to merge once it no longer conflicts with master. Recent merges touched the same registration lines in pyhealth/metrics/__init__.py. Please merge master into your branch (or rebase), keep both sides' entries, and push. Once the build passes, comment /review so the AI review runs on the new commit. We'll merge after that.

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
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.
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.
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.
…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.
Also name the exact MEDFAIR table rows the example quotes.
…00 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.
… 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.
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.
@solarsys

solarsys commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator

/review

@sanniheruwala

Copy link
Copy Markdown
Contributor Author

Rebased on master and kept both sides in pyhealth/metrics/__init__.py. The build passes.

/review

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed commit 5f1c85a

Comment thread examples/derm/medfair_ham10000.py Resolved

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI Review

suggestion: approve
decision: human review

Thank you for this contribution, Sanni. It brings MEDFAIR's subgroup fairness metrics, its two fairness-aware selection rules and subgroup resampling into PyHealth. It also adds a HAM10000 malignancy task with sex and age attributes, plus an example script.

It looks ready to merge.

  • Correctness: The code matches the description. The new components are self-contained: they add exports, and they change no base class, Trainer or shared utility. The doctests and test expectations look consistent with the code.
  • Sharing: The links to existing code are named in the description with reasons. That covers reusing ece_confidence_binary and why subgroup_metrics is left unchanged. The sampler's use of the collate function is covered by the description's note about the random-access view that matches get_dataloader batches.
  • Dataset source: The HAM10000 dataset already existed, and the paper link is given.
  • Docs: The docs match the code.
  • Coverage: It meets the bar. The whole repository is at 89.13%, against 60% required. Every changed file is at least 94%, against 80% required.

Optional suggestions:

  • The example cites specific MEDFAIR appendix tables (A8, A9 and A2). Please double-check those table numbers, since they can't be verified from the repository.
  • The example script has no automated test. Its synthetic smoke mode could be run in CI if you want that.

Reviewed commit 5f1c85a

@solarsys solarsys left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved by a maintainer. The AI review suggests approve on the current commit, and the build passes.

@solarsys
solarsys merged commit b7fb004 into sunlabuiuc:master Dec 1, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

status: manual Pending maintainer's review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants