Repository navigation
[BTY-62] Add MEDFAIR imaging fairness metrics, model selection, and debiasing baselines #1761
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
irvifa
wants to merge
1
commit into
sunlabuiuc:master
Choose a base branch
from
irvifa:bty-62-medfair
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,167 @@ | ||
| """MEDFAIR imaging fairness benchmark example on ChestX-ray14. | ||
|
|
||
| Demonstrates: | ||
| 1. Loading ``ChestXray14Dataset`` with ``ChestXray14FairnessClassification`` | ||
| (emitting demographic ``sensitive_attr`` alongside image and label). | ||
| 2. Training ERM, GroupDRO, and DomainInd baselines via ``MEDFAIRModel`` | ||
| (optionally with MEDFAIR's group-balanced ``make_group_balanced_sampler``). | ||
| 3. Evaluating subgroup fairness with ``medfair_metrics_fn`` and selecting | ||
| the best checkpoint using MEDFAIR's ``worst_auc`` criterion. | ||
|
|
||
| Usage: | ||
| python examples/fairness/medfair_chestxray14.py \ | ||
| --root /path/to/chestxray14 \ | ||
| --disease cardiomegaly \ | ||
| --sensitive sex \ | ||
| --method group_dro \ | ||
| --epochs 5 | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import argparse | ||
|
|
||
| import numpy as np | ||
| import torch | ||
| from torch.utils.data import DataLoader | ||
|
|
||
| from pyhealth.datasets import ChestXray14Dataset, PatientSplit, collate_fn_dict | ||
| from pyhealth.metrics import medfair_metrics_fn, select_best_checkpoint | ||
| from pyhealth.models import MEDFAIRModel, make_group_balanced_sampler | ||
| from pyhealth.tasks import ChestXray14FairnessClassification | ||
|
|
||
|
|
||
| def evaluate_fairness( | ||
| model: MEDFAIRModel, loader: DataLoader | ||
| ) -> dict: | ||
| """Run inference and compute MEDFAIR subgroup fairness metrics.""" | ||
| model.eval() | ||
| y_true_list, y_prob_list, group_list, losses = [], [], [], [] | ||
| with torch.no_grad(): | ||
| for batch in loader: | ||
| out = model(**batch) | ||
| losses.append(float(out["loss"].item())) | ||
| y_true_list.append(out["y_true"].cpu().numpy().reshape(-1)) | ||
| y_prob_list.append(out["y_prob"].cpu().numpy().reshape(-1)) | ||
| groups = batch["sensitive_attr"] | ||
| if torch.is_tensor(groups): | ||
| groups = groups.cpu().numpy() | ||
| group_list.append(np.asarray(groups).reshape(-1)) | ||
|
|
||
| metrics = medfair_metrics_fn( | ||
| y_true=np.concatenate(y_true_list), | ||
| y_prob=np.concatenate(y_prob_list), | ||
| sensitive_attributes=np.concatenate(group_list), | ||
| ) | ||
| metrics["loss"] = float(np.mean(losses)) if losses else float("nan") | ||
| return metrics | ||
|
|
||
|
|
||
| def main() -> None: | ||
| parser = argparse.ArgumentParser(description="MEDFAIR ChestX-ray14 example") | ||
| parser.add_argument("--root", type=str, required=True, help="ChestXray14 root dir") | ||
| parser.add_argument("--disease", type=str, default="cardiomegaly") | ||
| parser.add_argument( | ||
| "--sensitive", | ||
| type=str, | ||
| default="sex", | ||
| choices=["sex", "age_binary", "age_multi"], | ||
| ) | ||
| parser.add_argument( | ||
| "--method", | ||
| type=str, | ||
| default="group_dro", | ||
| choices=["erm", "group_dro", "domain_ind"], | ||
| ) | ||
| parser.add_argument( | ||
| "--backbone", | ||
| type=str, | ||
| default="resnet18", | ||
| choices=["simple_cnn", "resnet18", "densenet121"], | ||
| ) | ||
| parser.add_argument("--resampling", action="store_true") | ||
| parser.add_argument("--epochs", type=int, default=5) | ||
| parser.add_argument("--batch-size", type=int, default=32) | ||
| parser.add_argument("--lr", type=float, default=1e-4) | ||
| parser.add_argument( | ||
| "--selection", | ||
| type=str, | ||
| default="worst_auc", | ||
| choices=["worst_auc", "overall_auc", "equalized_odds", "loss"], | ||
| ) | ||
| args = parser.parse_args() | ||
|
|
||
| dataset = ChestXray14Dataset(root=args.root) | ||
| task = ChestXray14FairnessClassification( | ||
| disease=args.disease, sensitive_attribute=args.sensitive | ||
| ) | ||
| train_ds, val_ds, test_ds = dataset.set_task( | ||
| task, split=PatientSplit((0.7, 0.15, 0.15), seed=42) | ||
| ) | ||
|
|
||
| if args.resampling: | ||
| sampler = make_group_balanced_sampler(train_ds) | ||
| train_loader = DataLoader( | ||
| train_ds, | ||
| batch_size=args.batch_size, | ||
| sampler=sampler, | ||
| collate_fn=collate_fn_dict, | ||
| ) | ||
| else: | ||
| train_loader = DataLoader( | ||
| train_ds, | ||
| batch_size=args.batch_size, | ||
| shuffle=True, | ||
| collate_fn=collate_fn_dict, | ||
| ) | ||
| val_loader = DataLoader( | ||
| val_ds, batch_size=args.batch_size, shuffle=False, collate_fn=collate_fn_dict | ||
| ) | ||
| test_loader = DataLoader( | ||
| test_ds, batch_size=args.batch_size, shuffle=False, collate_fn=collate_fn_dict | ||
| ) | ||
|
|
||
| device = "cuda" if torch.cuda.is_available() else "cpu" | ||
| model = MEDFAIRModel( | ||
| dataset=train_ds, | ||
| method=args.method, | ||
| backbone=args.backbone, | ||
| num_groups=task.num_groups, | ||
| in_channels=1, | ||
| ).to(device) | ||
| optimizer = torch.optim.Adam(model.parameters(), lr=args.lr) | ||
|
|
||
| history = [] | ||
| for epoch in range(1, args.epochs + 1): | ||
| model.train() | ||
| for batch in train_loader: | ||
| optimizer.zero_grad() | ||
| loss = model(**batch)["loss"] | ||
| loss.backward() | ||
| optimizer.step() | ||
|
|
||
| val_metrics = evaluate_fairness(model, val_loader) | ||
| val_metrics["epoch"] = epoch | ||
| val_metrics["state_dict"] = { | ||
| k: v.detach().cpu().clone() for k, v in model.state_dict().items() | ||
| } | ||
| history.append(val_metrics) | ||
| print( | ||
| f"Epoch {epoch}: overall_auc={val_metrics['overall_auc']:.4f} " | ||
| f"worst_auc={val_metrics['worst_auc']:.4f} " | ||
| f"auc_gap={val_metrics['auc_gap']:.4f}" | ||
| ) | ||
|
|
||
| best = select_best_checkpoint(history, criterion=args.selection) | ||
| model.load_state_dict(best["state_dict"]) | ||
| test_metrics = evaluate_fairness(model, test_loader) | ||
| print( | ||
| f"Best epoch ({args.selection}): {best['epoch']} | " | ||
| f"Test overall_auc={test_metrics['overall_auc']:.4f} " | ||
| f"worst_auc={test_metrics['worst_auc']:.4f} " | ||
| f"equalized_odds={test_metrics['equalized_odds']:.4f}" | ||
| ) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[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.