Skip to content
Open
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/tasks.rst
Original file line number Diff line number Diff line change
Expand Up @@ -284,6 +284,7 @@ Available Tasks
Sleep Staging Sequences (ISRUC) <tasks/pyhealth.tasks.SleepStagingSequenceISRUC>
Sleep Staging (HMC) <tasks/pyhealth.tasks.SleepStagingHMC>
Psychopathology Regression (HBN-EEG) <tasks/pyhealth.tasks.HBNPsychopathologyRegression>
Response Time Regression (HBN-EEG) <tasks/pyhealth.tasks.HBNResponseTimeRegression>
Seizure Onset Zone Localization (HUP iEEG) <tasks/pyhealth.tasks.SOZLocalizationHUP>
Sleep Staging (DREAMT) <tasks/pyhealth.tasks.SleepStagingDREAMT>
Temple University EEG Tasks <tasks/pyhealth.tasks.temple_university_EEG_tasks>
Expand Down
16 changes: 16 additions & 0 deletions docs/api/tasks/pyhealth.tasks.HBNResponseTimeRegression.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
pyhealth.tasks.HBNResponseTimeRegression
========================================

Regression of the response time of each trial of the HBN-EEG contrast
change detection task, from a window of EEG that follows the target
stimulus, as in challenge 1 of the EEG Foundation Challenge 2025. Trials of
a participant are correlated: split by participant.

.. autoclass:: pyhealth.tasks.HBNResponseTimeRegression
:members:
:undoc-members:
:show-inheritance:

.. autofunction:: pyhealth.tasks.hbn_response_time.read_ccd_trials

.. autofunction:: pyhealth.tasks.hbn_response_time.events_file_for
168 changes: 168 additions & 0 deletions examples/eeg/hbn/hbn_response_time_regression.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
"""Regress the response time of contrast change detection trials on HBN-EEG.

Author: Axel Coiffard-Donaty
Paper: S. Y. Shirazi et al. "HBN-EEG: The FAIR implementation of the
Healthy Brain Network (HBN) electroencephalography dataset". bioRxiv,
2024. https://doi.org/10.1101/2024.10.03.615261
Description: ``HBNEEGDataset`` and ``HBNResponseTimeRegression`` cut one
window per trial of the contrast change detection recordings of the
chosen releases, 0.5 to 2.5 s after the target stimulus (129 channels at
100 Hz), labelled with the response time in seconds, as in challenge 1
of the EEG Foundation Challenge 2025. For each seed, participants are
split 60/20/20 with ``PatientSplit``, so no participant is in two parts.
``EEGNet`` (sampling rate 100 Hz) is trained with the mean squared
error, the epoch with the lowest validation loss is kept, and the test
set is scored at that epoch.

Scores are reported per trial, the unit the challenge scores: root mean
square error (RMSE), the RMSE divided by the standard deviation of the
true values (nRMSE, the challenge metric), mean absolute error and
Pearson's correlation. The constant predictor, the mean response time of
the training trials, is scored on the same test trials: a model is
useful only if it does better.

The windows are used as read, in microvolts, without normalization, as
in the challenge starter kit. About 1% of the channel windows of mini
release 1 exceed 1000 uV (often a single channel), against a median
standard deviation of 14 uV; normalization is left to the user.

This is a usage example, not a benchmark: a mini release has 20
participants, and the spread over seeds says more than any single score.

Data: the mini releases of the EEG Foundation Challenge 2025 (CC-BY-SA 4.0),
fetched from the public bucket with ``--download``; the contrast change
detection recordings are 0.68 to 1.06 GB per mini release (releases 1 to
5).

Usage:
python examples/eeg/hbn/hbn_response_time_regression.py \\
--root /data/hbn --download --releases R1 R2 R3 R4 R5 --seeds 0 1 2
"""

from __future__ import annotations

import argparse

import numpy as np

from pyhealth.datasets import HBNEEGDataset, PatientSplit, get_dataloader
from pyhealth.models import EEGNet
from pyhealth.tasks import HBNResponseTimeRegression
from pyhealth.trainer import Trainer

SPLIT_RATIOS = (0.6, 0.2, 0.2) # train / validation / test, by participant
SAMPLING_RATE = 100 # Hz, the rate of the 100 Hz releases
BATCH_SIZE = 64
LEARNING_RATE = 1e-3


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, help="Folder of release folders.")
parser.add_argument("--download", action="store_true")
parser.add_argument("--releases", nargs="+", default=["R1"])
parser.add_argument(
"--min-response-time",
type=float,
default=None,
help="Drop trials faster than this, in seconds. Default: keep all.",
)
parser.add_argument("--seeds", type=int, nargs="+", default=[0])
parser.add_argument("--epochs", type=int, default=20)
parser.add_argument("--device", default=None, help="Default: cuda if available.")
return parser.parse_args()


def scores(y_true: np.ndarray, y_pred: np.ndarray) -> dict[str, float]:
"""RMSE, nRMSE, MAE and Pearson's r.

Args:
y_true: True values.
y_pred: Predictions.

Returns:
The four scores; ``r`` is NaN when the predictions are constant.
"""
rmse = float(np.sqrt(np.mean((y_true - y_pred) ** 2)))
# np.ptp is exactly 0 for constant values; in float32 np.std is not
# (about 1e-7), and np.corrcoef would then divide 0 by 0.
r = (
float(np.corrcoef(y_true, y_pred)[0, 1])
if np.ptp(y_pred) > 0 and np.ptp(y_true) > 0
else float("nan")
)
return {
"rmse": rmse,
"nrmse": rmse / float(np.std(y_true)),
"mae": float(np.mean(np.abs(y_true - y_pred))),
"r": r,
}


def main() -> None:
"""Train and score EEGNet and the constant predictor over the seeds."""
import torch # after pyhealth, as in the other EEG examples

args = parse_args()
dataset = HBNEEGDataset(
root=args.root,
download=args.download,
releases=tuple(args.releases),
download_tasks=("contrastChangeDetection",),
)
task = HBNResponseTimeRegression(min_response_time=args.min_response_time)
rows = []
for seed in args.seeds:
torch.manual_seed(seed)
np.random.seed(seed)
train, val, test = dataset.set_task(
task, split=PatientSplit(ratios=SPLIT_RATIOS, seed=seed)
)
model = EEGNet(dataset=train, sampling_rate=SAMPLING_RATE)
trainer = Trainer(model=model, device=args.device)
trainer.train(
train_dataloader=get_dataloader(
train, batch_size=BATCH_SIZE, shuffle=True, seed=seed
),
val_dataloader=get_dataloader(val, batch_size=BATCH_SIZE),
epochs=args.epochs,
optimizer_params={"lr": LEARNING_RATE},
monitor="loss",
monitor_criterion="min",
)
y_true, y_pred, _ = trainer.inference(
get_dataloader(test, batch_size=BATCH_SIZE)
)
y_true, y_pred = np.ravel(y_true), np.ravel(y_pred)
constant = float(np.mean([float(s["response_time"]) for s in train]))
result = {
"seed": seed,
"n_train_participants": len({s["patient_id"] for s in train}),
"n_test_participants": len({s["patient_id"] for s in test}),
"n_train_trials": len(train),
"n_test_trials": len(y_true),
"model": scores(y_true, y_pred),
"constant": scores(y_true, np.full_like(y_true, constant)),
}
print(f"seed {seed}: {result}")
rows.append(result)

print(f"\nresponse time, releases {args.releases}, test trials:")
for name in ("model", "constant"):
for metric in ("rmse", "nrmse", "mae", "r"):
values = np.array([row[name][metric] for row in rows])
values = values[~np.isnan(values)] # r of the constant is NaN
if len(values) == 0:
print(f" {name:9s} {metric:6s} n/a")
continue
std = np.std(values, ddof=1) if len(values) > 1 else 0.0
print(f" {name:9s} {metric:6s} {np.mean(values):7.3f} +- {std:.3f}")


if __name__ == "__main__":
main()
3 changes: 3 additions & 0 deletions pyhealth/tasks/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -347,6 +347,9 @@
from .hbn_psychopathology import (
HBNPsychopathologyRegression as HBNPsychopathologyRegression,
)
from .hbn_response_time import (
HBNResponseTimeRegression as HBNResponseTimeRegression,
)
from .soz_localization_hup import (
SOZLocalizationHUP as SOZLocalizationHUP,
)
Expand Down
Loading
Loading