Repository navigation
Conversation
…ebiasing baselines
Test CoverageTotal: 88.59% (60289 / 68057 lines)
|
|
Why this PR has To help: please comment here on what this PR does that #1560 doesn't. Your ChestX-ray14 task |
|
Thanks for flagging the overlap with #1560! I missed #1560 when checking open PRs. Comparing with #1560, the parts unique to this PR are:
|
|
/review Generated by Claude Code |
| num_groups=self.num_groups, | ||
| step_size=dro_step_size, | ||
| group_counts=group_counts, | ||
| adj=dro_adj, |
There was a problem hiding this comment.
[medium] dro_adj is silently ignored unless group_counts is passed
MEDFAIRModel forwards dro_adj into GroupDROLoss as adj (adj=dro_adj). GroupDROLoss applies the adj / sqrt(n_g) term only when group_counts is also provided. So MEDFAIRModel(..., method="group_dro", dro_adj=1.0) with no group_counts runs with no group-size adjustment and emits no warning, while the MEDFAIRModel docstring (line 272) describes dro_adj as the group-size adjustment. Fix: raise ValueError in MEDFAIRModel.init when dro_adj > 0 and group_counts is None, or state the dependency in the docstring. Add a test for the chosen behavior.
| if raw_age is None: | ||
| return None | ||
| try: | ||
| age = float(raw_age) |
There was a problem hiding this comment.
[low] NaN age is mapped to the oldest group instead of being skipped
float(raw_age) accepts NaN without raising, so a NaN patient_age passes the try/except and falls through every comparison. age_binary then returns 1 and age_multi returns 4, silently putting unknown-age images in the 60+ or 80+ group. Skip non-finite ages, for example with math.isfinite(age) returning None, and add a case with a NaN age to the existing encoding test.
| return WeightedRandomSampler(weights=weights, num_samples=n_draw, replacement=True) | ||
|
|
||
|
|
||
| class MEDFAIRModel(BaseModel): |
There was a problem hiding this comment.
[low] ERM path overlaps TorchvisionModel; the description does not explain why
With method="erm" and backbone resnet18 or densenet121, MEDFAIRModel does what pyhealth/models/torchvision_model.py TorchvisionModel already does: an ImageNet-style backbone with a linear head and BCE loss. The GroupDRO and DomainInd methods are a real extension, so the component is not redundant, but the description should say why these methods are a new class and not an extension of TorchvisionModel, or whether the backbone code can be reused.
| return 4 | ||
|
|
||
|
|
||
| class ChestXray14FairnessClassification(BaseTask): |
There was a problem hiding this comment.
[low] No docs/api pages for the new metric, model and task
Existing PyHealth components have a page under docs/api/ (for example docs/api/tasks/pyhealth.tasks.ChestXray14BinaryClassification.rst and docs/api/metrics/pyhealth.metrics.fairness.rst). The new medfair metric functions, MEDFAIRModel with GroupDROLoss and make_group_balanced_sampler, and ChestXray14FairnessClassification have none. Add matching rst pages and list them in the section indexes.
| train_ds, | ||
| batch_size=args.batch_size, | ||
| sampler=sampler, | ||
| collate_fn=collate_fn_dict, |
There was a problem hiding this comment.
[low] Example batches with collate_fn_dict, which leaves tensors unstacked
collate_fn_dict returns plain lists, so the binary label reaches MEDFAIRModel.forward as a list of per-sample tensors and is converted with torch.as_tensor. The unit tests use get_dataloader, which is the path the rest of the library uses. Use get_dataloader for the training, validation and test loaders, or confirm the example runs on real ChestX-ray14 batches.
There was a problem hiding this comment.
AI Review
suggestion: need change
decision: human review
Thank you for this contribution. The MEDFAIR fairness metrics, checkpoint selection, ERM/GroupDRO/DomainInd baselines, group-balanced sampler and ChestX-ray14 fairness task fill a real gap, and the tests are thorough. Coverage is well above the bar: 88.59% for the repository, and about 97–99% for each added file.
To get this merged:
- In
MEDFAIRModel(pyhealth/models/medfair.py),dro_adjis silently ignored unlessgroup_countsis also passed. A user who setsdro_adj > 0alone gets plain GroupDRO with no warning. Please do one of these:- Raise a
ValueErrorwhendro_adj > 0andgroup_countsisNone. - Compute
group_countsautomatically. - State the requirement clearly in the
MEDFAIRModeldocstring.
- Raise a
Optional suggestions:
- In
_encode_sensitive_attribute, a NaNpatient_ageparses as a float and falls through to group 4 (80+) forage_multi, and to group 1 forage_binary. ReturningNonefor NaN values would skip those samples instead. - Add
docs/api/pages for the new metric, model and task. - The ERM path overlaps with
TorchvisionModel. A sentence in the description on why a separate model is needed would help. - Add a numeric check of the
domain_indlogit summation at inference. - The example batches with
collate_fn_dict, while the tests useget_dataloader. Make sure the example has been run once end to end.
Reviewed commit e65b36f
|
#1560 (MEDFAIR subgroup fairness metrics, fairness-aware model selection and subgroup resampling) is now merged into master. Please rebase this PR on master and keep only what it adds on top of #1560. That includes the parts you listed, such as the in-processing debiasing baselines. Reuse the merged metrics and selection rules where they overlap, instead of adding a second implementation. Once rebased, comment |
Summary
Implements [BTY-62] MEDFAIR Imaging Fairness Benchmark (ICLR 2023) (Zong, Yang, and Hospedales, ICLR 2023, https://arxiv.org/abs/2210.01725; official code: https://github.com/ys-zong/MEDFAIR) for PyHealth's medical imaging tasks.
What this adds
pyhealth/metrics/medfair.py):medfair_metrics_fn: computes overall & per-group ROC-AUC,worst_auc,worst_group,auc_gap, subgroup FPR/FNR and gaps,equalized_odds, sensitivity at fixed specificity (group_tpr_at_specificity,worst_tpr_at_specificity), and subgroup Expected Calibration Error (overall_ece,group_eces) for binary and multi-group sensitive attributes.medfair_model_selection_scoreandselect_best_checkpoint: MEDFAIR checkpoint selection supporting"worst_auc","overall_auc","equalized_odds", and"loss".pyhealth/models/medfair.py):GroupDROLoss: exponentiated-gradient GroupDRO loss (Sagawa et al., ICLR 2020) as benchmarked in MEDFAIR, supporting optional group-size adjustment (adj / sqrt(n_g)) and loss normalization.MEDFAIRModel(BaseModel): PyHealth 2.0 image classifier supportingmethod="erm",method="group_dro", andmethod="domain_ind"(Domain Independent Training with per-group heads andinference_sum_problogit summation) withresnet18,densenet121, orsimple_cnnbackbones, compatible withTrainer.make_group_balanced_sampler: MEDFAIR inverse-frequency resampling (WeightedRandomSampler) over(group, label)strata or groups alone.pyhealth/tasks/medfair_chestxray14.py):ChestXray14FairnessClassification(BaseTask): emits{"patient_id", "image", "sensitive_attr", "label"}fromChestXray14Datasetforsensitive_attribute="sex","age_binary", or"age_multi"(MEDFAIR's 5 age bins).examples/fairness/medfair_chestxray14.py): end-to-end ERM / GroupDRO / DomainInd + resampling training andworst_auccheckpoint selection onChestXray14Dataset.tests/core/test_medfair.py): comprehensive tests for all metrics, model-selection criteria,GroupDROLoss,MEDFAIRModel(erm,group_dro,domain_ind, all backbones,Trainerintegration),make_group_balanced_sampler, andChestXray14FairnessClassification(including end-to-end ontest-resources/core/chestxray14).How it interacts with existing code
pyhealth/metrics/medfair.py,pyhealth/models/medfair.py,pyhealth/tasks/medfair_chestxray14.py) with standard export registrations inpyhealth/{metrics,models,tasks}/__init__.py. No base classes,Trainer, or existing tasks/datasets are modified.Verification
python3 tools/check_pr_rules.py— all PR contribution rules passed (0 issues).pytest tests/core/test_medfair.py— all tests passed.pytest --doctest-modules pyhealth/metrics/medfair.py pyhealth/models/medfair.py pyhealth/tasks/medfair_chestxray14.py— all doctests passed.