Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/api/models.rst
Original file line number Diff line number Diff line change
Expand Up @@ -392,6 +392,7 @@ API Reference
models/pyhealth.models.TextEmbedding
models/pyhealth.models.BIOT
models/pyhealth.models.LaBraM
models/pyhealth.models.BrainNetworkTransformer
models/pyhealth.models.unified_multimodal_embedding_docs
models/pyhealth.models.califorest
models/pyhealth.models.XGBoostModel
Expand Down
38 changes: 38 additions & 0 deletions docs/api/models/pyhealth.models.BrainNetworkTransformer.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
pyhealth.models.BrainNetworkTransformer
=======================================

Overview
--------

Brain Network Transformer (BNT) classifies a brain network given as a square
connectivity matrix. Each region is a node whose features are its row of the
matrix; a transformer runs over the nodes, and an orthonormal clustering
readout (OCRead) pools them into soft clusters before a small classifier. It
takes the ``connectivity`` field of
:class:`~pyhealth.tasks.ABIDEAutismClassification` and reads the number of
nodes from the data. The default 100 clusters need at least 100 features per
node, so they suit cc200 and larger atlases; for a smaller graph, pass
``layer_sizes`` with fewer clusters.

The defaults are the authors' configuration: two transformer layers with 4
heads, the second pooling the nodes into 100 clusters with frozen orthonormal
centres. The attention weights of the last forward pass are available from
:meth:`~pyhealth.models.BrainNetworkTransformer.get_attention_weights`, and
the cluster assignments from ``forward(..., return_assignments=True)``.

``examples/fmri/abide_autism_bnt.py`` trains it on ABIDE next to the GCN and
logistic regression baselines, and ``examples/fmri/bnt_parity_check.py``
compares this implementation with the official one. The parity check needs a
clone of the official repository and ``omegaconf``, so it is not run in CI.

Paper: X. Kan, W. Dai, H. Cui, Z. Zhang, Y. Guo, C. Yang, `Brain Network
Transformer <https://arxiv.org/abs/2210.06681>`_, NeurIPS 2022. Official
code: https://github.com/Wayfear/BrainNetworkTransformer (MIT License).

API Reference
-------------

.. autoclass:: pyhealth.models.BrainNetworkTransformer
:members:
:undoc-members:
:show-inheritance:
234 changes: 234 additions & 0 deletions examples/fmri/abide_autism_bnt.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,234 @@
"""ABIDE I autism vs. control with Brain Network Transformer, and two baselines.

Author: Axel Coiffard-Donaty
Paper: X. Kan, W. Dai, H. Cui, Z. Zhang, Y. Guo, C. Yang. "Brain Network
Transformer". NeurIPS 2022. https://arxiv.org/abs/2210.06681
Description: Trains ``BrainNetworkTransformer`` on the cc200 connectivity
matrices of ``ABIDEAutismClassification``, and, for comparison on the
same splits, the ``BrainGCN`` of ``abide_autism_gcn.py`` and PyHealth's
``LogisticRegression`` on the upper triangle. For each seed the scans are
split by patient 70/10/20 (one scan per subject), the model is trained
for ``--epochs`` epochs, the epoch with the best validation AUROC is
kept, and the test set is scored at that epoch. The script prints the
test AUROC, accuracy, sensitivity and specificity (threshold 0.5) of
every seed, then their mean and standard deviation.

Training follows the authors' configuration for BNT: Adam, learning
rate 1e-4, weight decay 1e-4, batch size 16, 200 epochs, and continuous
mixup of the inputs and labels during training. Known differences with
the official run: the learning rate stays constant (the official run
decays it from 1e-4 to 1e-5 with a cosine schedule), PyHealth's
``Trainer`` exempts the biases from weight decay (the official run
decays every parameter; the layer norm weights are decayed in both), the
split is
stratified by neither site nor label, and the cohort is PyHealth's
(1,035 C-PAC scans) rather than the authors' preprocessed file (1,009
subjects). The baselines keep the settings of their own examples
(``abide_autism_gcn.py`` and ``abide_autism_logistic_regression.py``:
Adam, learning rate 1e-3, no weight decay, batch size 32) with the same
epochs, splits and selection rule; mixup is applied to BNT only, as in
the paper. ``--lr``, ``--weight-decay`` and ``--batch-size`` override
the settings of the chosen model.

Data: ABIDE Preprocessed (CC BY-NC-SA 3.0, non-commercial),
http://preprocessed-connectomes-project.org/abide/ ; ``--download``
fetches it from the open ``fcp-indi`` S3 bucket (about 430 MB).

Usage:
python examples/fmri/abide_autism_bnt.py --root /data/abide --download \\
--model bnt --seeds 0 1 2 3 4
python examples/fmri/abide_autism_bnt.py --root /data/abide \\
--model gcn --seeds 0 1 2 3 4
"""

from __future__ import annotations

import argparse
import sys
from pathlib import Path

import numpy as np

from pyhealth.datasets import ABIDEDataset, PatientSplit, get_dataloader
from pyhealth.models import BrainNetworkTransformer, LogisticRegression
from pyhealth.tasks import ABIDEAutismClassification
from pyhealth.trainer import Trainer

# BrainGCN lives in the GCN example next to this file.
sys.path.insert(0, str(Path(__file__).resolve().parent))
from abide_autism_gcn import BrainGCN

SPLIT_RATIOS = (0.7, 0.1, 0.2) # train / validation / test, by patient
# Authors' configuration (source/conf in the official repository).
EPOCHS = 200
# Optimizer settings per model: BNT follows the authors' configuration; the
# baselines follow their PyHealth examples (Trainer defaults, batch size 32).
SETTINGS = {
"bnt": {"lr": 1e-4, "weight_decay": 1e-4, "batch_size": 16},
"gcn": {"lr": 1e-3, "weight_decay": 0.0, "batch_size": 32},
"logistic_regression": {"lr": 1e-3, "weight_decay": 0.0, "batch_size": 32},
}
MIXUP_ALPHA = 1.0
THRESHOLD = 0.5
# Hidden sizes of the GCN, as in abide_autism_gcn.py.
GCN_DIM = 64


class MixupBrainNetworkTransformer(BrainNetworkTransformer):
"""``BrainNetworkTransformer`` trained with continuous mixup.

In training mode each batch is mixed with a shuffled copy of itself,
inputs and labels alike, with a weight drawn from Beta(alpha, alpha), as
``continus_mixup_data`` does in the official code. Evaluation batches
are left unchanged.

Args:
*args: Positional arguments of the parent class.
alpha: Parameter of the Beta distribution. Default is 1.
seed: Seed of the generator that draws the mixing weights and
permutations.
**kwargs: Keyword arguments of the parent class.
"""

def __init__(self, *args, alpha: float = MIXUP_ALPHA, seed: int = 0, **kwargs):
super().__init__(*args, **kwargs)
self.alpha = alpha
self.rng = np.random.default_rng(seed)

def forward(self, **kwargs):
"""Mix the batch in training mode, then run the model."""
import torch # after pyhealth; see the note in abide_autism_gcn.py

label_key = self.label_keys[0]
if self.training and label_key in kwargs:
lam = float(self.rng.beta(self.alpha, self.alpha))
x = kwargs[self.feature_key]
perm = torch.as_tensor(self.rng.permutation(x.shape[0]))
y = kwargs[label_key].float()
kwargs = dict(kwargs)
kwargs[self.feature_key] = lam * x + (1 - lam) * x[perm]
kwargs[label_key] = lam * y + (1 - lam) * y[perm]
return super().forward(**kwargs)


def parse_args() -> argparse.Namespace:
"""Parse the command-line arguments.

Returns:
The parsed arguments.
"""
parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
parser.add_argument("--root", required=True)
parser.add_argument("--download", action="store_true")
parser.add_argument("--max-subjects", type=int, default=None)
parser.add_argument(
"--model", choices=("bnt", "gcn", "logistic_regression"), default="bnt"
)
parser.add_argument("--seeds", type=int, nargs="+", default=[0])
parser.add_argument("--epochs", type=int, default=EPOCHS)
parser.add_argument("--lr", type=float, default=None)
parser.add_argument("--weight-decay", type=float, default=None)
parser.add_argument("--batch-size", type=int, default=None)
parser.add_argument("--no-mixup", action="store_true", help="BNT without mixup.")
parser.add_argument("--device", default=None, help="Default: cuda if available.")
return parser.parse_args()


def build_model(name: str, train, seed: int, mixup: bool):
"""Create the model to train.

Args:
name: ``"bnt"``, ``"gcn"`` or ``"logistic_regression"``.
train: The training SampleDataset.
seed: Seed of the mixup generator.
mixup: Use mixup for BNT.

Returns:
The model.
"""
if name == "bnt":
if mixup:
return MixupBrainNetworkTransformer(dataset=train, seed=seed)
return BrainNetworkTransformer(dataset=train)
if name == "gcn":
return BrainGCN(dataset=train, embedding_dim=GCN_DIM, nhid=GCN_DIM)
return LogisticRegression(dataset=train)


def test_scores(trainer: Trainer, loader) -> dict[str, float]:
"""Score the test set at the selected epoch.

Args:
trainer: Trainer holding the selected model.
loader: Test dataloader.

Returns:
AUROC, accuracy, sensitivity and specificity.
"""
from sklearn.metrics import roc_auc_score

y_true, y_prob, _ = trainer.inference(loader)
y_true = np.asarray(y_true).ravel()
y_prob = np.asarray(y_prob).ravel()
y_pred = (y_prob > THRESHOLD).astype(int)
positives, negatives = y_true == 1, y_true == 0
return {
"auroc": float(roc_auc_score(y_true, y_prob)),
"accuracy": float((y_pred == y_true).mean()),
"sensitivity": float((y_pred[positives] == 1).mean()),
"specificity": float((y_pred[negatives] == 0).mean()),
}


def main() -> None:
"""Train and evaluate the chosen model over the seeds."""
import torch # after pyhealth; see the note in abide_autism_gcn.py

args = parse_args()
dataset = ABIDEDataset(
root=args.root, download=args.download, max_subjects=args.max_subjects
)
task = ABIDEAutismClassification(vectorize=args.model == "logistic_regression")
settings = dict(SETTINGS[args.model])
for key in settings:
if getattr(args, key) is not None:
settings[key] = getattr(args, key)
print(f"{args.model}: {settings}")
results = []
for seed in args.seeds:
torch.manual_seed(seed)
np.random.seed(seed)
# One scan per subject, so a patient split does not leak.
train, val, test = dataset.set_task(
task, split=PatientSplit(ratios=SPLIT_RATIOS, seed=seed)
)
print(f"seed {seed}: train={len(train)} val={len(val)} test={len(test)}")
model = build_model(args.model, train, seed, mixup=not args.no_mixup)
trainer = Trainer(model=model, metrics=["roc_auc"], device=args.device)
trainer.train(
train_dataloader=get_dataloader(
train, batch_size=settings["batch_size"], shuffle=True, seed=seed
),
val_dataloader=get_dataloader(val, batch_size=settings["batch_size"]),
epochs=args.epochs,
optimizer_class=torch.optim.Adam,
optimizer_params={"lr": settings["lr"]},
weight_decay=settings["weight_decay"],
monitor="roc_auc",
monitor_criterion="max",
)
test_loader = get_dataloader(test, batch_size=settings["batch_size"])
scores = test_scores(trainer, test_loader)
print(f"seed {seed} test: {scores}")
results.append(scores)

print(f"\n{args.model}, {len(results)} seed(s), test set (%):")
for metric in results[0]:
values = 100 * np.array([r[metric] for r in results])
# Sample standard deviation over seeds; 0 for a single seed.
std = values.std(ddof=1) if len(values) > 1 else 0.0
print(f" {metric:12s} {values.mean():5.1f} +- {std:4.1f}")


if __name__ == "__main__":
main()
Loading
Loading