diff --git a/docs/api/datasets.rst b/docs/api/datasets.rst index bb0c925479..cb2509af8e 100644 --- a/docs/api/datasets.rst +++ b/docs/api/datasets.rst @@ -316,6 +316,7 @@ Available Datasets datasets/pyhealth.datasets.PhysioNetDeIDDataset datasets/pyhealth.datasets.EEGBCIDataset PTB-XL Dataset + PhysioNet 2012 Dataset datasets/pyhealth.datasets.TUABDataset datasets/pyhealth.datasets.TUEVDataset datasets/pyhealth.datasets.ClinVarDataset diff --git a/docs/api/datasets/pyhealth.datasets.PhysioNet2012Dataset.rst b/docs/api/datasets/pyhealth.datasets.PhysioNet2012Dataset.rst new file mode 100644 index 0000000000..c9e2c5e238 --- /dev/null +++ b/docs/api/datasets/pyhealth.datasets.PhysioNet2012Dataset.rst @@ -0,0 +1,36 @@ +pyhealth.datasets.PhysioNet2012Dataset +====================================== + +Overview +-------- + +The PhysioNet/Computing in Cardiology Challenge 2012 dataset holds 12,000 ICU +stays of at least 48 hours (sets a, b and c). Each record has up to 37 +irregularly sampled vital-sign and lab time series from the first 48 hours, +six descriptors recorded on admission, and outcomes (SAPS-I, SOFA, length of +stay, survival and in-hospital death). It is open access, so +``PhysioNet2012Dataset(root, download=True)`` fetches it (about 20 MB). + +For more information see `PhysioNet Challenge 2012 +`_ and Silva et al., +Computing in Cardiology 2012. + +The dataset builds two tables from the raw record files and writes them into +``root``: ``events`` (one row per observation, with ``parameter``, ``value`` +and ``minutes`` since ICU admission) and ``patients`` (descriptors and +outcomes). Use it with :class:`~pyhealth.tasks.PhysioNet2012Forecasting` for +irregular time-series forecasting. + +API Reference +------------- + +.. autoclass:: pyhealth.datasets.PhysioNet2012Dataset + :members: + :undoc-members: + :show-inheritance: + +.. autofunction:: pyhealth.datasets.physionet2012.download_physionet2012 + +.. autofunction:: pyhealth.datasets.physionet2012.prepare_physionet2012 + +.. autofunction:: pyhealth.datasets.physionet2012.read_record diff --git a/docs/api/models.rst b/docs/api/models.rst index 7d47de5769..fb50c8ecf2 100644 --- a/docs/api/models.rst +++ b/docs/api/models.rst @@ -259,4 +259,5 @@ API Reference models/pyhealth.models.XGBoostModel models/pyhealth.models.survival_mdn models/pyhealth.models.ProtoECGNet + models/pyhealth.models.APN diff --git a/docs/api/models/pyhealth.models.APN.rst b/docs/api/models/pyhealth.models.APN.rst new file mode 100644 index 0000000000..01a7aa9704 --- /dev/null +++ b/docs/api/models/pyhealth.models.APN.rst @@ -0,0 +1,28 @@ +pyhealth.models.APN +=================== + +APN: a simple, effective baseline for irregular multivariate time-series +forecasting. Time-Aware Patch Aggregation pools each variable's irregular +observations into adaptive patches with learnable boundaries, a query module +summarizes the patches, and a shallow MLP forecasts the query times +(`Liu et al., AAAI 2026 `_). + +See ``examples/apn_physionet2012_forecasting.ipynb`` for a reproduction of +the paper's PhysioNet 2012 result. + +.. autoclass:: pyhealth.models.APN + :members: + :undoc-members: + :show-inheritance: + +.. autoclass:: pyhealth.models.TimeAwarePatchAggregation + :members: + :undoc-members: + :show-inheritance: + +.. autoclass:: pyhealth.models.LearnableTimeEncoding + :members: + :undoc-members: + :show-inheritance: + +.. autofunction:: pyhealth.models.masked_mse diff --git a/docs/api/tasks.rst b/docs/api/tasks.rst index 03f14872f2..0f1739b714 100644 --- a/docs/api/tasks.rst +++ b/docs/api/tasks.rst @@ -216,6 +216,7 @@ Available Tasks COVID-19 CXR Classification COVID-19 CXR Image Generation PTB-XL Multilabel Classification + PhysioNet 2012 Forecasting DKA Prediction (MIMIC-IV) Drug Recommendation EHR Generation diff --git a/docs/api/tasks/pyhealth.tasks.PhysioNet2012Forecasting.rst b/docs/api/tasks/pyhealth.tasks.PhysioNet2012Forecasting.rst new file mode 100644 index 0000000000..251e1df875 --- /dev/null +++ b/docs/api/tasks/pyhealth.tasks.PhysioNet2012Forecasting.rst @@ -0,0 +1,17 @@ +pyhealth.tasks.PhysioNet2012Forecasting +======================================= + +Irregular multivariate time-series forecasting on PhysioNet 2012, in the +setup of the forecasting benchmarks (GraFITi, Warpformer, APN): from the +first 36 hours of an ICU stay, forecast the values of 36 variables observed +at the next three observation times. Values are hourly means, z-scored, with +outliers beyond 5 standard deviations removed. + +.. autoclass:: pyhealth.tasks.PhysioNet2012Forecasting + :members: + :undoc-members: + :show-inheritance: + +.. autofunction:: pyhealth.tasks.physionet2012_statistics + +.. autofunction:: pyhealth.tasks.physionet2012_benchmark_split diff --git a/examples/apn_physionet2012_forecasting.ipynb b/examples/apn_physionet2012_forecasting.ipynb new file mode 100644 index 0000000000..155203c1df --- /dev/null +++ b/examples/apn_physionet2012_forecasting.ipynb @@ -0,0 +1,295 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# APN on PhysioNet 2012: reproducing irregular time-series forecasting in PyHealth\n", + "\n", + "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/sunlabuiuc/PyHealth/blob/master/examples/apn_physionet2012_forecasting.ipynb)\n", + "\n", + "This notebook reproduces the PhysioNet 2012 result of\n", + "\n", + "> Xvyuan Liu, Xiangfei Qiu, Xingjian Wu, Zhengyu Li, Chenjuan Guo, Jilin Hu, Bin Yang.\n", + "> **Rethinking Irregular Time Series Forecasting: A Simple yet Effective Baseline.** AAAI 2026.\n", + "> [arXiv:2505.11250](https://arxiv.org/abs/2505.11250) \u00b7 [authors' code](https://github.com/decisionintelligence/APN)\n", + "\n", + "with PyHealth's `APN` model, `PhysioNet2012Dataset` and `PhysioNet2012Forecasting` task.\n", + "PhysioNet 2012 is open access (about 20 MB), so the whole experiment runs without credentials.\n", + "A Colab CPU runtime is enough; a GPU makes it faster.\n", + "\n", + "**Setup (as in the paper's benchmark).** From the first 36 hours of an ICU stay, forecast the values of\n", + "36 vital signs and labs observed at the next 3 observation times. Values are hourly means, z-scored per\n", + "variable, with values beyond 5 standard deviations removed; the metric is the MSE (and MAE) over the observed\n", + "targets of the test records, in z-score units. Records are split 81/9/10 by `RecordID` order, as in the benchmark code.\n", + "\n", + "**Paper's numbers on PhysioNet 2012** (Table 2, mean over 5 runs): APN MSE **0.3093**, MAE **0.3650**.\n", + "For context, the best baselines there: Warpformer MSE 0.3056, GraFITi MAE 0.3637." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 1. Install PyHealth\n", + "\n", + "Until the PR is merged, install from its branch. After the merge, use `pip install pyhealth`." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "execution_count": null, + "outputs": [], + "source": [ + "!pip install -q \"git+https://github.com/solarsys/PyHealth@feat/apn\"" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 2. Download PhysioNet 2012 and build the dataset\n", + "\n", + "`download=True` fetches sets a, b and c and their outcomes from PhysioNet into `root`; the first run also\n", + "builds PyHealth's event tables (a few minutes)." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "execution_count": null, + "outputs": [], + "source": [ + "import numpy as np\n", + "import torch\n", + "\n", + "from pyhealth.datasets import PhysioNet2012Dataset, get_dataloader\n", + "from pyhealth.models import APN\n", + "from pyhealth.tasks import (\n", + " PhysioNet2012Forecasting,\n", + " physionet2012_benchmark_split,\n", + " physionet2012_statistics,\n", + ")\n", + "\n", + "ROOT = \"physionet2012\" # raw files and PyHealth's tables go here\n", + "CACHE = \"physionet2012_cache\" # PyHealth's processed cache\n", + "DEVICE = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n", + "\n", + "dataset = PhysioNet2012Dataset(root=ROOT, download=True, cache_dir=CACHE, num_workers=2)\n", + "dataset.stats()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 3. The forecasting task and the benchmark split\n", + "\n", + "The benchmark standardizes with statistics over all records (including the test records). To use the\n", + "training records only, pass their IDs: `physionet2012_statistics(dataset, patient_ids=...)`." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "execution_count": null, + "outputs": [], + "source": [ + "mean, std = physionet2012_statistics(dataset)\n", + "samples = dataset.set_task(PhysioNet2012Forecasting(mean=mean, std=std), num_workers=2)\n", + "train, val, test = physionet2012_benchmark_split(samples)\n", + "print(f\"{len(samples)} records: {len(train)} train, {len(val)} validation, {len(test)} test\")\n", + "\n", + "sample = samples[0]\n", + "print({k: tuple(v.shape) for k, v in sample.items() if hasattr(v, \"shape\")})\n", + "print(\"observed input values:\", int(torch.isfinite(sample[\"x\"]).sum()),\n", + " \"| observed targets:\", int(torch.isfinite(sample[\"y\"]).sum()))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 4. A sanity baseline: last observation carried forward\n", + "\n", + "Each variable's last value in the first 36 hours forecasts all 3 steps (the mean, 0, if it was never observed)." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "execution_count": null, + "outputs": [], + "source": [ + "def score(predict, loader):\n", + " \"\"\"MSE and MAE over all observed targets, pooled as in the benchmark code.\"\"\"\n", + " se = ae = n = 0.0\n", + " for batch in loader:\n", + " y = batch[\"y\"].to(DEVICE)\n", + " pred = predict(batch)\n", + " mask = torch.isfinite(y)\n", + " d = pred[mask] - y[mask]\n", + " se += float((d ** 2).sum()); ae += float(d.abs().sum()); n += d.numel()\n", + " return se / n, ae / n\n", + "\n", + "def locf(batch):\n", + " x = batch[\"x\"].to(DEVICE)\n", + " last = torch.zeros(x.shape[0], x.shape[2], device=DEVICE)\n", + " for t in range(x.shape[1]):\n", + " last = torch.where(torch.isfinite(x[:, t]), x[:, t], last)\n", + " return last.unsqueeze(1).expand(-1, batch[\"y\"].shape[1], -1)\n", + "\n", + "test_loader = get_dataloader(test, batch_size=256)\n", + "locf_mse, locf_mae = score(locf, test_loader)\n", + "print(f\"LOCF test MSE {locf_mse:.4f} MAE {locf_mae:.4f}\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 5. Train APN with the paper's protocol\n", + "\n", + "The paper's PhysioNet 2012 setting: hidden size 24, 20 patches, time encoding of size 8, dropout 0.1,\n", + "Adam with learning rate 0.03 (constant for 2 epochs, then x0.8 per epoch), batch size 32, up to 200 epochs with\n", + "early stopping after 10 epochs without a better validation MSE, and the mean over 5 runs.\n", + "Set `SEEDS = [0, 1, 2, 3, 4]` for the paper's 5 runs (one run takes several minutes on a CPU).\n", + "\n", + "PyHealth's `Trainer` also trains APN (`Trainer(model, metrics=[\"mse\", \"mae\"]).train(...)`), with a constant\n", + "learning rate; the loop below adds the paper's schedule." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "execution_count": null, + "outputs": [], + "source": [ + "import copy\n", + "\n", + "SEEDS = [0]\n", + "MAX_EPOCHS = 200\n", + "\n", + "def train_apn(seed):\n", + " torch.manual_seed(seed); np.random.seed(seed)\n", + " model = APN(train, hidden_dim=24, num_patches=20, time_dim=8, dropout=0.1).to(DEVICE)\n", + " opt = torch.optim.Adam(model.parameters(), lr=0.03)\n", + " sched = torch.optim.lr_scheduler.LambdaLR(opt, lambda e: 1.0 if e < 2 else 0.8 ** (e - 2))\n", + " train_loader = get_dataloader(train, batch_size=32, shuffle=True)\n", + " val_loader = get_dataloader(val, batch_size=256)\n", + " best, best_state, wait = float(\"inf\"), None, 0\n", + " for epoch in range(MAX_EPOCHS):\n", + " model.train()\n", + " for batch in train_loader:\n", + " opt.zero_grad()\n", + " model(**batch)[\"loss\"].backward()\n", + " opt.step()\n", + " sched.step()\n", + " model.eval()\n", + " with torch.no_grad():\n", + " val_mse, _ = score(lambda b: model(**b)[\"forecast\"], val_loader)\n", + " if val_mse < best:\n", + " best, best_state, wait = val_mse, copy.deepcopy(model.state_dict()), 0\n", + " else:\n", + " wait += 1\n", + " if wait >= 10:\n", + " break\n", + " model.load_state_dict(best_state)\n", + " print(f\"seed {seed}: stopped after epoch {epoch}, best validation MSE {best:.4f}\")\n", + " return model\n", + "\n", + "results = []\n", + "for seed in SEEDS:\n", + " model = train_apn(seed)\n", + " model.eval()\n", + " with torch.no_grad():\n", + " results.append(score(lambda b: model(**b)[\"forecast\"], test_loader))\n", + " print(f\"seed {seed}: test MSE {results[-1][0]:.4f} MAE {results[-1][1]:.4f}\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 6. Results next to the paper" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "execution_count": null, + "outputs": [], + "source": [ + "import pandas as pd\n", + "\n", + "res = np.array(results)\n", + "rows = [\n", + " (\"APN, paper (5 runs)\", 0.3093, 0.3650),\n", + " (\"Warpformer, paper (best MSE baseline)\", 0.3056, None),\n", + " (\"GraFITi, paper (best MAE baseline)\", None, 0.3637),\n", + " (f\"APN, PyHealth ({len(SEEDS)} run{'s' if len(SEEDS) > 1 else ''})\", res[:, 0].mean(), res[:, 1].mean()),\n", + " (\"Last observation carried forward, PyHealth\", locf_mse, locf_mae),\n", + "]\n", + "table = pd.DataFrame(rows, columns=[\"Model\", \"Test MSE\", \"Test MAE\"])\n", + "if len(SEEDS) > 1:\n", + " print(f\"APN over {len(SEEDS)} runs: MSE {res[:, 0].mean():.4f} \u00b1 {res[:, 0].std():.4f}, \"\n", + " f\"MAE {res[:, 1].mean():.4f} \u00b1 {res[:, 1].std():.4f}\")\n", + "table.round(4)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Our run (local CPU, 5 seeds, this notebook's protocol)\n", + "\n", + "| Model | Test MSE | Test MAE |\n", + "|---|---|---|\n", + "| APN, paper (5 runs) | 0.3093 | 0.3650 |\n", + "| **APN, PyHealth (5 runs, seeds 0-4)** | **0.3047 \u00b1 0.0006** | **0.3710 \u00b1 0.0006** |\n", + "| Last observation carried forward | 0.4163 | 0.4115 |\n", + "\n", + "Per seed (MSE / MAE): 0.3057 / 0.3717, 0.3042 / 0.3712, 0.3040 / 0.3700, 0.3044 / 0.3704, 0.3052 / 0.3715.\n", + "Each run stopped early, after 36 to 47 epochs. The MSE is slightly lower and the MAE slightly higher than the paper's;\n", + "the differences in the data pipeline listed below are a likely cause." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 7. Notes for the authors: what to check\n", + "\n", + "- **Model** (`pyhealth/models/apn.py`): a reimplementation from the paper. Time-Aware Patch Aggregation with\n", + " learnable left offsets and log-widths per variable and patch, a learned per-variable temperature, soft\n", + " membership `sigmoid((right - t)/tau) * sigmoid((t - left)/tau)` times the observation mask, a weight-normalized\n", + " average of [value, time encoding] per patch, a linear projection with a residual feed-forward layer and\n", + " LayerNorm, sinusoidal patch positions, a learned per-variable query attending over the patches, and a two-layer\n", + " MLP decoder on [summary, encoding of the query time].\n", + "- **Data** (`PhysioNet2012Forecasting`): hourly bins, the 36 variables of the benchmark (Weight excluded), z-scores\n", + " over all records, values at or beyond 5 SD removed, input = hours 0-35, targets = the next 3 hours with an\n", + " observation, times scaled by 48 hours. The benchmark code's tsdm pipeline differs in small details: its time\n", + " scaling (hour / 47 vs. the 35.5 / 48 cutoff) puts the input cutoff at about hour 34.8, and a record's last hourly\n", + " bin is dropped by its parser. These change which points are inputs or targets for some records.\n", + "- **Evaluation:** the MSE and MAE are pooled over all observed test targets, as `utils/metrics.py` in the authors'\n", + " code computes them." + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "name": "python" + }, + "colab": { + "provenance": [] + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} \ No newline at end of file diff --git a/pyhealth/datasets/__init__.py b/pyhealth/datasets/__init__.py index 3a33ed9d5d..ea3a223cd0 100644 --- a/pyhealth/datasets/__init__.py +++ b/pyhealth/datasets/__init__.py @@ -53,6 +53,7 @@ def __init__(self, *args, **kwargs): from .cosmic import COSMICDataset from .covid19_cxr import COVID19CXRDataset from .ptbxl import PTBXLDataset as PTBXLDataset +from .physionet2012 import PhysioNet2012Dataset as PhysioNet2012Dataset from .dreamt import DREAMTDataset from .ehrshot import EHRShotDataset from .eicu import eICUDataset diff --git a/pyhealth/datasets/configs/physionet2012.yaml b/pyhealth/datasets/configs/physionet2012.yaml new file mode 100644 index 0000000000..1d49bb461e --- /dev/null +++ b/pyhealth/datasets/configs/physionet2012.yaml @@ -0,0 +1,29 @@ +version: "1.0.0" # PhysioNet/CinC Challenge 2012, open access +tables: + events: + # Written by PhysioNet2012Dataset from the set-*/ record files. + file_path: "physionet2012-pyhealth-events.csv" + patient_id: "patient_id" + # TIME_ORIGIN plus the elapsed time since ICU admission + timestamp: "time" + timestamp_format: "%Y-%m-%d %H:%M:%S" + attributes: + - "minutes" + - "parameter" + - "value" + patients: + file_path: "physionet2012-pyhealth-patients.csv" + patient_id: "patient_id" + timestamp: null + attributes: + - "set" + - "age" + - "gender" + - "height" + - "icutype" + - "weight" + - "saps_i" + - "sofa" + - "length_of_stay" + - "survival" + - "in_hospital_death" diff --git a/pyhealth/datasets/physionet2012.py b/pyhealth/datasets/physionet2012.py new file mode 100644 index 0000000000..985daedabb --- /dev/null +++ b/pyhealth/datasets/physionet2012.py @@ -0,0 +1,286 @@ +"""PyHealth dataset for the PhysioNet/Computing in Cardiology Challenge 2012. + +Dataset link: + https://physionet.org/content/challenge-2012/1.0.0/ + +Dataset paper: (please cite if you use this dataset) + Ikaro Silva, George Moody, Daniel J. Scott, Leo A. Celi, and Roger G. Mark. + "Predicting In-Hospital Mortality of ICU Patients: The PhysioNet/Computing + in Cardiology Challenge 2012." Computing in Cardiology 39 (2012): 245-248. + +Description: + 12,000 ICU stays of at least 48 hours (sets a, b and c, 4,000 each). Each + record holds up to 37 irregularly sampled time series from the first 48 + hours (vital signs and labs) and five general descriptors recorded on + admission (age, gender, height, ICU type and weight). The data is open access, so it can be downloaded without + credentials (``download=True``). +""" + +from __future__ import annotations + +import logging +import os +import shutil +import tarfile +import time +import urllib.request +from collections.abc import Iterable, Sequence +from datetime import datetime, timedelta +from pathlib import Path + +import pandas as pd + +from .base_dataset import BaseDataset + +logger = logging.getLogger(__name__) + +PHYSIONET2012_URL = "https://physionet.org/files/challenge-2012/1.0.0/" +PHYSIONET2012_SETS = ("a", "b", "c") + +GENERAL_DESCRIPTORS = ("Age", "Gender", "Height", "ICUType", "Weight") +"""Descriptors recorded once on admission, at time 00:00.""" + + +EVENTS_CSV = "physionet2012-pyhealth-events.csv" +PATIENTS_CSV = "physionet2012-pyhealth-patients.csv" + +# Records have elapsed times, not dates; they are placed after this origin. +TIME_ORIGIN = datetime.fromisoformat("2012-01-01") # naive, like PyHealth timestamps +_TIME_FORMAT = "%Y-%m-%d %H:%M:%S" + +_OUTCOME_COLUMNS = { + "SAPS-I": "saps_i", + "SOFA": "sofa", + "Length_of_stay": "length_of_stay", + "Survival": "survival", + "In-hospital_death": "in_hospital_death", +} + + +def download_physionet2012( + root: str | Path, sets: Sequence[str] = PHYSIONET2012_SETS, retries: int = 3 +) -> None: + """Downloads and extracts the challenge records and outcomes into ``root``. + + Files already present are kept. Each file is written to a temporary name + and renamed once complete, and each archive is extracted into a temporary + folder that is renamed once complete, so an interrupted download or + extraction is redone rather than used. + + Args: + root: Directory to download into; ``set-a/`` etc. are created there. + sets: Which record sets to download. + retries: Attempts per file. + + Examples: + >>> download_physionet2012("data/physionet2012") # doctest: +SKIP + """ + root = Path(root) + root.mkdir(parents=True, exist_ok=True) + for name in sets: + for filename in (f"set-{name}.tar.gz", f"Outcomes-{name}.txt"): + _fetch(PHYSIONET2012_URL + filename, root / filename, retries) + _extract(root / f"set-{name}.tar.gz", root / f"set-{name}") + + +def _extract(archive_path: Path, dest: Path) -> None: + """Extracts ``archive_path`` (which holds ``dest.name/``) to ``dest``.""" + if dest.is_dir(): + return + tmp = dest.with_name(f".{dest.name}.partial") + shutil.rmtree(tmp, ignore_errors=True) # left by an interrupted run + tmp.mkdir() + try: + with tarfile.open(archive_path) as archive: + archive.extractall(tmp, filter="data") + os.replace(tmp / dest.name, dest) + finally: + shutil.rmtree(tmp, ignore_errors=True) + + +def _fetch(url: str, dest: Path, retries: int) -> None: + if dest.exists(): + return + tmp = dest.with_name(dest.name + ".part") + for attempt in range(1, retries + 1): + try: + logger.info("Downloading %s", url) + urllib.request.urlretrieve(url, tmp) + os.replace(tmp, dest) + return + except OSError: + tmp.unlink(missing_ok=True) + if attempt == retries: + raise + time.sleep(2 * attempt) + + +def read_record(path: str | Path) -> tuple[str, dict[str, float], list[tuple]]: + """Reads one challenge record file. + + Args: + path: A record file such as ``set-a/132539.txt``. + + Returns: + ``(record_id, descriptors, events)``: the general descriptors (missing + ones, coded ``-1``, as NaN) and the time-series observations as + ``(minutes since admission, parameter, value)``. + + Examples: + >>> record_id, descriptors, events = read_record("set-a/132539.txt") # doctest: +SKIP + >>> events[0] # doctest: +SKIP + (7, 'GCS', 15.0) + """ + record_id = None + descriptors: dict[str, float] = {} + events: list[tuple] = [] + with open(path) as handle: + next(handle) # header: Time,Parameter,Value + for line in handle: + parts = line.strip().split(",") + if len(parts) != 3 or not parts[1]: + continue + stamp, parameter, raw = parts + hours, minutes = stamp.split(":") + elapsed = int(hours) * 60 + int(minutes) + value = float(raw) + if parameter == "RecordID": + record_id = str(int(value)) + elif parameter in GENERAL_DESCRIPTORS and elapsed == 0: + descriptors[parameter] = value if value >= 0 else float("nan") + else: + events.append((elapsed, parameter, value)) + if record_id is None: + raise ValueError(f"{path} has no RecordID") + return record_id, descriptors, events + + +def prepare_physionet2012( + root: str | Path, sets: Iterable[str] = PHYSIONET2012_SETS +) -> None: + """Writes the event and patient tables that the dataset config reads. + + Reads every ``set-*/*.txt`` record (and ``Outcomes-*.txt`` when present) + in ``root`` and writes :data:`EVENTS_CSV` (one row per observation) and + :data:`PATIENTS_CSV` (descriptors and outcomes) next to them. + + Args: + root: Directory with the extracted ``set-a/``, ``set-b/``, ``set-c/``. + sets: The record sets to include; missing ones are skipped. + + Examples: + >>> prepare_physionet2012("data/physionet2012") # doctest: +SKIP + """ + root = Path(root) + events, patients = [], [] + for name in sets: + folder = root / f"set-{name}" + if not folder.is_dir(): + logger.warning("%s not found; set %s is skipped", folder, name) + continue + outcomes = _read_outcomes(root / f"Outcomes-{name}.txt") + for path in sorted(folder.glob("*.txt")): + record_id, descriptors, record_events = read_record(path) + patients.append({ + "patient_id": record_id, + "set": name, + **{k.lower(): descriptors.get(k) for k in GENERAL_DESCRIPTORS}, + **outcomes.get(record_id, {}), + }) + for elapsed, parameter, value in record_events: + stamp = TIME_ORIGIN + timedelta(minutes=elapsed) + events.append( + (record_id, stamp.strftime(_TIME_FORMAT), elapsed, parameter, value) + ) + if not patients: + raise FileNotFoundError( + f"No set-*/ record folders in {root}; download them with " + "download_physionet2012 or PhysioNet2012Dataset(download=True)." + ) + events_df = pd.DataFrame( + events, columns=["patient_id", "time", "minutes", "parameter", "value"] + ) + patients_df = pd.DataFrame(patients) + for column in _OUTCOME_COLUMNS.values(): + if column not in patients_df: + patients_df[column] = float("nan") + _write_csv(events_df, root / EVENTS_CSV) + _write_csv(patients_df, root / PATIENTS_CSV) + + +def _read_outcomes(path: Path) -> dict[str, dict[str, float]]: + if not path.exists(): + return {} + table = pd.read_csv(path).rename(columns=_OUTCOME_COLUMNS) + table["RecordID"] = table["RecordID"].astype(int).astype(str) + return table.set_index("RecordID").to_dict("index") + + +def _write_csv(df: pd.DataFrame, dest: Path) -> None: + tmp = dest.with_name(dest.name + ".tmp") + df.to_csv(tmp, index=False) + os.replace(tmp, dest) + + +class PhysioNet2012Dataset(BaseDataset): + """The PhysioNet/CinC Challenge 2012 ICU dataset. + + Two tables: ``events`` holds every time-series observation (``parameter``, + ``value`` and ``minutes`` since ICU admission; the timestamp is + :data:`TIME_ORIGIN` plus that elapsed time), and ``patients`` holds the + general descriptors (``age``, ``gender``, ``height``, ``icutype``, + ``weight``) and the outcomes (``saps_i``, ``sofa``, ``length_of_stay``, + ``survival``, ``in_hospital_death``). Each record (ICU stay) is one + patient, keyed by its ``RecordID``. + + The tables are built once from the raw record files and written into + ``root`` (:data:`EVENTS_CSV`, :data:`PATIENTS_CSV`). + + Args: + root: Directory with the extracted ``set-a/``, ``set-b/``, ``set-c/`` + folders (and ``Outcomes-*.txt``), or where to download them. + tables: Tables to load. Defaults to ``["events", "patients"]``. + download: Download the open-access files from PhysioNet into + ``root`` if they are missing. + sets: Record sets to include. Changing it after the tables were + written requires deleting them so they are rebuilt. + dataset_name: Name of the dataset. Defaults to ``"physionet2012"``. + config_path: Path to a YAML config. Defaults to the bundled one. + **kwargs: Passed to :class:`~pyhealth.datasets.BaseDataset` + (e.g. ``cache_dir``, ``dev``). + + Examples: + >>> from pyhealth.datasets import PhysioNet2012Dataset + >>> dataset = PhysioNet2012Dataset( + ... root="data/physionet2012", download=True + ... ) # doctest: +SKIP + >>> dataset.stats() # doctest: +SKIP + """ + + def __init__( + self, + root: str, + tables: list[str] | None = None, + download: bool = False, + sets: Sequence[str] = PHYSIONET2012_SETS, + dataset_name: str | None = None, + config_path: str | None = None, + **kwargs, + ) -> None: + root_path = Path(root) + if download: + download_physionet2012(root_path, sets) + if not (root_path / EVENTS_CSV).exists() or not ( + root_path / PATIENTS_CSV + ).exists(): + logger.info("Building the PhysioNet 2012 tables in %s", root_path) + prepare_physionet2012(root_path, sets) + if config_path is None: + config_path = str(Path(__file__).parent / "configs" / "physionet2012.yaml") + super().__init__( + root=str(root_path), + tables=tables or ["events", "patients"], + dataset_name=dataset_name or "physionet2012", + config_path=config_path, + **kwargs, + ) diff --git a/pyhealth/models/__init__.py b/pyhealth/models/__init__.py index 8a176d06f7..6939481111 100644 --- a/pyhealth/models/__init__.py +++ b/pyhealth/models/__init__.py @@ -1,5 +1,11 @@ from .adacare import AdaCare, AdaCareLayer, MultimodalAdaCare from .agent import Agent, AgentLayer +from .apn import ( + APN as APN, + LearnableTimeEncoding as LearnableTimeEncoding, + TimeAwarePatchAggregation as TimeAwarePatchAggregation, + masked_mse as masked_mse, +) from .base_model import BaseModel from .transformer_deid import TransformerDeID from .biot import BIOT diff --git a/pyhealth/models/apn.py b/pyhealth/models/apn.py new file mode 100644 index 0000000000..d85d87a5d3 --- /dev/null +++ b/pyhealth/models/apn.py @@ -0,0 +1,381 @@ +"""APN: adaptive patching for irregular multivariate time-series forecasting. + +Paper: + Xvyuan Liu, Xiangfei Qiu, Xingjian Wu, Zhengyu Li, Chenjuan Guo, Jilin + Hu and Bin Yang. "Rethinking Irregular Time Series Forecasting: A Simple + yet Effective Baseline." AAAI 2026. https://arxiv.org/abs/2505.11250 + +This is a reimplementation from the paper; the authors' code +(https://github.com/decisionintelligence/APN) was used only to confirm +details such as the default sizes. +""" + +from __future__ import annotations + +import math +from collections.abc import Callable +from typing import Any + +import torch +import torch.nn.functional as F +from torch import nn + +from ..datasets import SampleDataset +from .base_model import BaseModel + + +class LearnableTimeEncoding(nn.Module): + """A linear term and ``dim - 1`` learned sinusoids of a time. + + Args: + dim: Output size (at least 2). + + Examples: + >>> import torch + >>> LearnableTimeEncoding(8)(torch.rand(2, 5, 1)).shape + torch.Size([2, 5, 8]) + """ + + def __init__(self, dim: int) -> None: + super().__init__() + if dim < 2: + raise ValueError("The time encoding needs at least 2 dimensions.") + self.linear = nn.Linear(1, 1) + self.periodic = nn.Linear(1, dim - 1) + + def forward(self, t: torch.Tensor) -> torch.Tensor: + """Encodes times ``[..., 1]`` as ``[..., dim]``.""" + return torch.cat([self.linear(t), torch.sin(self.periodic(t))], dim=-1) + + +class TimeAwarePatchAggregation(nn.Module): + """Time-Aware Patch Aggregation (TAPA), the patching module of APN. + + Each variable gets ``num_patches`` patches with learnable boundaries: + the left edge is an offset from evenly spaced initial positions and the + width is learned in log space. An observation's weight in a patch is a + soft indicator of lying inside it, ``sigmoid((right - t) / tau) * + sigmoid((t - left) / tau)``, with a learned per-variable temperature + ``tau``. Each patch is the weight-normalized average of the features of + the observed points, projected and refined by a residual feed-forward + layer. + + Args: + num_variables: Number of variables (channels). + num_patches: Patches per variable. + feature_dim: Size of each observation's feature (value and time + encoding). + hidden_dim: Size of a patch representation. + history: Length of the time span the patches initially cover. + dropout: Dropout in the feed-forward layer. + + Examples: + >>> import torch + >>> tapa = TimeAwarePatchAggregation(3, 4, feature_dim=5, hidden_dim=8) + >>> t = torch.rand(2, 3, 10) + >>> h = tapa(t, torch.randn(2, 3, 10, 5), torch.ones(2, 3, 10)) + >>> h.shape + torch.Size([2, 3, 4, 8]) + """ + + def __init__( + self, + num_variables: int, + num_patches: int, + feature_dim: int, + hidden_dim: int, + history: float = 1.0, + dropout: float = 0.1, + ) -> None: + super().__init__() + self.num_patches = num_patches + self.history = history + width = max(history / num_patches, 1e-6) + centers = torch.linspace(width / 2, history - width / 2, num_patches) + self.register_buffer("initial_left", centers - width / 2) + self.left_offset = nn.Parameter(torch.zeros(num_variables, num_patches)) + self.log_width = nn.Parameter( + torch.full((num_variables, num_patches), math.log(width)) + ) + self.raw_tau = nn.Parameter(torch.zeros(num_variables)) + self.project = nn.Linear(feature_dim, hidden_dim) + self.ffn = nn.Sequential( + nn.Linear(hidden_dim, 2 * hidden_dim), + nn.GELU(), + nn.Dropout(dropout), + nn.Linear(2 * hidden_dim, hidden_dim), + ) + self.norm = nn.LayerNorm(hidden_dim) + + def boundaries(self) -> tuple[torch.Tensor, torch.Tensor]: + """The ``(left, right)`` patch edges, each ``[num_variables, num_patches]``.""" + left = self.initial_left + self.left_offset + right = left + torch.exp(self.log_width) + 1e-6 + return left, right + + def weights(self, t: torch.Tensor, mask: torch.Tensor) -> torch.Tensor: + """Soft patch memberships of observations, ``[B, N, P, L]``. + + Args: + t: Observation times, ``[B, N, L]``. + mask: 1 for observed points, ``[B, N, L]``. + """ + left, right = self.boundaries() + tau = (F.softplus(self.raw_tau) + 1e-6)[None, :, None, None] + t = t.unsqueeze(2) # [B, N, 1, L] + inside = torch.sigmoid((right[None, :, :, None] - t) / tau) * torch.sigmoid( + (t - left[None, :, :, None]) / tau + ) + return inside * mask.unsqueeze(2) + + def forward( + self, t: torch.Tensor, features: torch.Tensor, mask: torch.Tensor + ) -> torch.Tensor: + """Aggregates observations into patches. + + Args: + t: Observation times, ``[B, N, L]``. + features: Observation features, ``[B, N, L, feature_dim]``. + mask: 1 for observed points, ``[B, N, L]``. + + Returns: + Patch representations, ``[B, N, P, hidden_dim]``. + """ + w = self.weights(t, mask) + pooled = torch.einsum("bnpl,bnlf->bnpf", w, features) / ( + w.sum(dim=-1, keepdim=True) + 1e-9 + ) + h = self.project(pooled) + return self.norm(h + self.ffn(h)) + + +def _sinusoidal_positions(length: int, dim: int) -> torch.Tensor: + position = torch.arange(length, dtype=torch.float32).unsqueeze(1) + scale = torch.exp(torch.arange(0, dim, 2).float() * (-math.log(10000.0) / dim)) + table = torch.zeros(length, dim) + table[:, 0::2] = torch.sin(position * scale) + table[:, 1::2] = torch.cos(position * scale)[:, : dim // 2] + return table + + +class APN(BaseModel): + """APN forecaster for irregular multivariate time series (AAAI 2026). + + Every variable is handled on its own (channel-independent). Its + observations, each a value plus a learnable time encoding, are pooled + into adaptive patches by :class:`TimeAwarePatchAggregation`; a learned + per-variable query attends over the patches (with sinusoidal patch + positions) to give one summary vector, and a shallow MLP maps the summary + and the encoding of each query time to a forecast. + + The model reads three inputs and one label from the dataset: + + - ``x``: values ``[B, L, N]``, NaN where not observed; + - ``x_time``: their times ``[B, L]`` (shared by all variables); + - ``y_time``: the times to forecast ``[B, K]``; + - ``y``: the targets ``[B, K, N]``, NaN where not observed. + + :class:`~pyhealth.tasks.PhysioNet2012Forecasting` produces these fields; + other names can be given through ``value_key`` etc. The loss is the mean + squared error over the observed targets. ``y_true`` and ``y_prob`` in the + output are the observed targets and their forecasts, flattened, so the + :class:`~pyhealth.trainer.Trainer` scores the model in ``"regression"`` + mode with the MSE and MAE over all observed targets (use + ``metrics=["mse", "mae"]``). ``forecast`` holds the full ``[B, K, N]`` + forecasts. + + Args: + dataset: The samples; used for the field names and the number of + variables. + hidden_dim: Size of the patch and summary representations + (``d_model``; 24 for PhysioNet 2012 in the paper). + num_patches: Patches per variable (20 for PhysioNet 2012). + time_dim: Size of the time encoding (8). + dropout: Dropout rate (0.1). + history: Time span the patches initially cover, in the units of the + times (1.0 when times are scaled to [0, 1]). + value_key: Input field with the observed values. + time_key: Input field with their times. + query_key: Input field with the times to forecast. + + Examples: + >>> import numpy as np + >>> from pyhealth.datasets import create_sample_dataset + >>> from pyhealth.datasets import get_dataloader + >>> rng = np.random.default_rng(0) + >>> samples = [ + ... {"patient_id": f"p{i}", "x": rng.normal(size=(6, 2)).astype("float32"), + ... "x_time": np.arange(6, dtype="float32") / 8, + ... "y_time": np.array([6, 7], dtype="float32") / 8, + ... "y": rng.normal(size=(2, 2)).astype("float32")} + ... for i in range(4) + ... ] + >>> dataset = create_sample_dataset( + ... samples, + ... {"x": "tensor", "x_time": "tensor", "y_time": "tensor"}, + ... {"y": "tensor"}, + ... ) + >>> model = APN(dataset, hidden_dim=8, num_patches=3, time_dim=4) + >>> batch = next(iter(get_dataloader(dataset, batch_size=4))) + >>> out = model(**batch) + >>> out["forecast"].shape + torch.Size([4, 2, 2]) + """ + + def __init__( + self, + dataset: SampleDataset, + hidden_dim: int = 24, + num_patches: int = 20, + time_dim: int = 8, + dropout: float = 0.1, + history: float = 1.0, + value_key: str = "x", + time_key: str = "x_time", + query_key: str = "y_time", + ) -> None: + super().__init__(dataset) + if len(self.label_keys) != 1: + raise ValueError("APN expects exactly one label field (the targets).") + self.label_key = self.label_keys[0] + self.value_key, self.time_key, self.query_key = value_key, time_key, query_key + # The Trainer scores the flattened observed targets as a regression. + self.mode = "regression" + self.num_variables = self._num_variables(dataset) + self.hidden_dim = hidden_dim + self.num_patches = num_patches + + self.time_encoding = LearnableTimeEncoding(time_dim) + self.patching = TimeAwarePatchAggregation( + self.num_variables, num_patches, 1 + time_dim, hidden_dim, history, dropout + ) + self.register_buffer( + "patch_positions", _sinusoidal_positions(num_patches, hidden_dim) + ) + self.queries = nn.Parameter(torch.randn(self.num_variables, hidden_dim)) + self.summary_norm = nn.LayerNorm(hidden_dim) + self.decoder = nn.Sequential( + nn.Linear(hidden_dim + time_dim, 2 * hidden_dim), + nn.ReLU(), + nn.Dropout(dropout), + nn.Linear(2 * hidden_dim, 1), + ) + + def _num_variables(self, dataset: SampleDataset) -> int: + processor = dataset.input_processors[self.value_key] + size = processor.size() if hasattr(processor, "size") else None + if size: + return int(size) + return int(torch.as_tensor(dataset[0][self.value_key]).shape[-1]) + + def encode( + self, x: torch.Tensor, x_time: torch.Tensor + ) -> torch.Tensor: + """Summarizes each variable's history, ``[B, N, hidden_dim]``. + + Args: + x: Values ``[B, L, N]``, NaN where not observed. + x_time: Times ``[B, L]``. + """ + batch, length, n_vars = x.shape + mask = torch.isfinite(x).transpose(1, 2).float() # [B, N, L] + values = torch.nan_to_num(x, nan=0.0).transpose(1, 2) # [B, N, L] + t = x_time.unsqueeze(1).expand(batch, n_vars, length) + features = torch.cat( + [values.unsqueeze(-1), self.time_encoding(t.unsqueeze(-1))], dim=-1 + ) + patches = self.patching(t, features, mask) + self.patch_positions + scores = torch.einsum("nh,bnph->bnp", self.queries, patches) + attention = torch.softmax(scores / math.sqrt(self.hidden_dim), dim=-1) + summary = torch.einsum("bnp,bnph->bnh", attention, patches) + return self.summary_norm(summary) + + def decode(self, summary: torch.Tensor, y_time: torch.Tensor) -> torch.Tensor: + """Forecasts ``[B, K, N]`` at the query times ``[B, K]``.""" + batch, n_vars, _ = summary.shape + steps = y_time.shape[1] + te = self.time_encoding(y_time.unsqueeze(-1)) # [B, K, T] + inputs = torch.cat( + [ + summary.unsqueeze(2).expand(batch, n_vars, steps, -1), + te.unsqueeze(1).expand(batch, n_vars, steps, -1), + ], + dim=-1, + ) + return self.decoder(inputs).squeeze(-1).transpose(1, 2) + + def forward(self, **kwargs: Any) -> dict[str, torch.Tensor]: + """Forecasts the query times and, with targets, the masked MSE. + + Returns: + A dict with ``forecast`` (``[B, K, N]``), ``logit`` (the same), + and, when the targets are given, ``loss``, ``y_true`` and + ``y_prob`` (the observed targets and their forecasts, flattened) + and ``mask`` (``[B, K, N]``, 1 where a target was observed). + """ + x = kwargs[self.value_key].to(self.device).float() + x_time = kwargs[self.time_key].to(self.device).float() + y_time = kwargs[self.query_key].to(self.device).float() + forecast = self.decode(self.encode(x, x_time), y_time) + out = {"forecast": forecast, "logit": forecast} + if self.label_key in kwargs: + y = kwargs[self.label_key].to(self.device).float() + mask = torch.isfinite(y) + out["loss"] = masked_mse(forecast, y) + out["y_true"] = y[mask] + out["y_prob"] = forecast[mask] + out["mask"] = mask.float() + else: + out["y_prob"] = forecast + return out + + def get_loss_function(self) -> Callable[..., torch.Tensor]: + """Returns :func:`masked_mse`, the loss that :meth:`forward` uses. + + The label is a ``"tensor"`` field, which :class:`BaseModel` cannot map + to a loss, so APN supplies its own. + + Returns: + :func:`masked_mse`. + + Examples: + >>> model.get_loss_function() is masked_mse # doctest: +SKIP + True + """ + return masked_mse + + def prepare_y_prob(self, logits: torch.Tensor) -> torch.Tensor: + """Returns the forecasts unchanged; a regression has no link function. + + Args: + logits: Forecasts of any shape. + + Returns: + ``logits``. + + Examples: + >>> model.prepare_y_prob(torch.zeros(2, 3, 4)).shape # doctest: +SKIP + torch.Size([2, 3, 4]) + """ + return logits + + +def masked_mse(prediction: torch.Tensor, target: torch.Tensor) -> torch.Tensor: + """Mean squared error over the finite entries of ``target``. + + Args: + prediction: Forecasts, any shape. + target: Targets of the same shape, NaN where not observed. + + Returns: + A scalar; 0 (with gradient) when nothing is observed. + + Examples: + >>> import torch + >>> masked_mse(torch.tensor([1.0, 2.0]), torch.tensor([0.0, float("nan")])) + tensor(1.) + """ + mask = torch.isfinite(target) + if not mask.any(): + return prediction.sum() * 0.0 + return ((prediction[mask] - target[mask]) ** 2).mean() diff --git a/pyhealth/tasks/__init__.py b/pyhealth/tasks/__init__.py index 6d4e33a79e..f8bd69c7dd 100644 --- a/pyhealth/tasks/__init__.py +++ b/pyhealth/tasks/__init__.py @@ -16,6 +16,11 @@ COVID19CXRImageGeneration as COVID19CXRImageGeneration, ) from .ptbxl_multilabel_classification import PTBXLMultilabelClassification as PTBXLMultilabelClassification +from .physionet2012_forecasting import ( + PhysioNet2012Forecasting as PhysioNet2012Forecasting, + physionet2012_benchmark_split as physionet2012_benchmark_split, + physionet2012_statistics as physionet2012_statistics, +) from .deid_ner import DeIDNERTask from .dka import DKAPredictionMIMIC4, T1DDKAPredictionMIMIC4 # New exports must use the redundant `X as X` form: this module has no diff --git a/pyhealth/tasks/physionet2012_forecasting.py b/pyhealth/tasks/physionet2012_forecasting.py new file mode 100644 index 0000000000..2bbe94913a --- /dev/null +++ b/pyhealth/tasks/physionet2012_forecasting.py @@ -0,0 +1,263 @@ +"""Irregular time-series forecasting on the PhysioNet 2012 ICU data. + +The setup of the irregular multivariate time-series forecasting benchmarks +(e.g. GraFITi, Warpformer and APN, Liu et al., AAAI 2026, "Rethinking +Irregular Time Series Forecasting: A Simple yet Effective Baseline"): from +the first 36 hours of an ICU stay, forecast the values observed at the next +three observation times. +""" + +from __future__ import annotations + +import math +from collections.abc import Mapping, Sequence +from typing import TYPE_CHECKING, Any, ClassVar + +import numpy as np +import polars as pl + +from .base_task import BaseTask + +if TYPE_CHECKING: + from ..datasets import BaseDataset, SampleDataset + +TIME_SERIES_VARIABLES = ( + "Albumin", "ALP", "ALT", "AST", "Bilirubin", "BUN", "Cholesterol", + "Creatinine", "DiasABP", "FiO2", "GCS", "Glucose", "HCO3", "HCT", "HR", "K", + "Lactate", "Mg", "MAP", "MechVent", "Na", "NIDiasABP", "NIMAP", "NISysABP", + "PaCO2", "PaO2", "pH", "Platelets", "RespRate", "SaO2", "SysABP", "Temp", + "TroponinI", "TroponinT", "Urine", "WBC", +) +"""The 36 time series used by the irregular-forecasting benchmarks. + +Weight is also recorded as a time series, but the benchmarks (and +:class:`PhysioNet2012Forecasting`) leave it out. +""" + + +class PhysioNet2012Forecasting(BaseTask): + """Forecast the next observed values of 36 ICU time series. + + The observations of each variable are averaged within each hour since + ICU admission, z-scored with the given statistics, and values more than + ``outlier_sd`` standard deviations from the mean are dropped. The hours + before ``observation_hours`` form the input, a grid of + ``observation_hours x len(variables)`` values with NaN where nothing was + observed. The targets are the next ``prediction_steps`` hours, at or after + ``observation_hours``, in which any variable was observed, again with NaN + for the unobserved variables. Times are given in units of + ``total_hours`` (hour / 48), as in the benchmarks. + + This follows the PhysioNet 2012 forecasting setup of the benchmarks + (observation window of 36 hours, 3 forecast steps, hourly bins, z-scored + values with outliers beyond 5 SD removed; see + :func:`physionet2012_statistics` and :func:`physionet2012_benchmark_split` + for the normalization and the split). + + Samples have ``x`` (``[observation_hours, V]``), ``x_time`` + (``[observation_hours]``), ``y_time`` (``[prediction_steps]``) and the + label ``y`` (``[prediction_steps, V]``); a missing step is all NaN with + time 0. Stays without an observed input value or without a target are + skipped. Models compute the loss over the observed (finite) targets + only, e.g. :class:`~pyhealth.models.APN`. + + Args: + mean: Per-variable mean used for z-scoring, e.g. from + :func:`physionet2012_statistics`. ``None`` keeps raw values. + std: Per-variable standard deviation; required with ``mean``. + observation_hours: Hours of the stay used as input. + prediction_steps: Number of future observation times to forecast. + variables: Time series to use, in the order of the feature axis. + outlier_sd: Drop z-scores at or beyond this magnitude; ``None`` + keeps all values. Only applies with ``mean`` and ``std``. + total_hours: Scale of the times (``hour / total_hours``). + + Examples: + >>> from pyhealth.datasets import PhysioNet2012Dataset + >>> from pyhealth.tasks import ( + ... PhysioNet2012Forecasting, physionet2012_statistics + ... ) + >>> dataset = PhysioNet2012Dataset(root="data/physionet2012") # doctest: +SKIP + >>> mean, std = physionet2012_statistics(dataset) # doctest: +SKIP + >>> samples = dataset.set_task( + ... PhysioNet2012Forecasting(mean=mean, std=std) + ... ) # doctest: +SKIP + """ + + task_name: str = "PhysioNet2012Forecasting" + input_schema: ClassVar[dict[str, str]] = { + "x": "tensor", "x_time": "tensor", "y_time": "tensor" + } + output_schema: ClassVar[dict[str, str]] = {"y": "tensor"} + + def __init__( + self, + mean: Mapping[str, float] | None = None, + std: Mapping[str, float] | None = None, + observation_hours: int = 36, + prediction_steps: int = 3, + variables: Sequence[str] = TIME_SERIES_VARIABLES, + outlier_sd: float | None = 5.0, + total_hours: float = 48.0, + ) -> None: + super().__init__() + if (mean is None) != (std is None): + raise ValueError("Give both mean and std, or neither.") + self.variables = list(variables) + self.mean = None if mean is None else {v: float(mean[v]) for v in self.variables} + self.std = None if std is None else {v: float(std[v]) for v in self.variables} + self.observation_hours = int(observation_hours) + self.prediction_steps = int(prediction_steps) + self.outlier_sd = outlier_sd + self.total_hours = float(total_hours) + + def __call__(self, patient: Any) -> list[dict[str, Any]]: + events = patient.get_events(event_type="events", return_df=True) + if events.height == 0: + return [] + hourly = _hourly_means(events, self.variables).sort("hour", "parameter") + if hourly.height == 0: + return [] + index = {v: i for i, v in enumerate(self.variables)} + hours = hourly["hour"].to_numpy() + columns = np.array([index[p] for p in hourly["parameter"].to_list()]) + values = hourly["value"].to_numpy().astype(np.float64) + if self.mean is not None: + center = np.array([self.mean[v] for v in self.variables]) + scale = np.array([self.std[v] for v in self.variables]) + values = (values - center[columns]) / scale[columns] + if self.outlier_sd is not None: + keep = np.abs(values) < self.outlier_sd + hours, columns, values = hours[keep], columns[keep], values[keep] + + n_vars = len(self.variables) + x = np.full((self.observation_hours, n_vars), np.nan, dtype=np.float32) + observed = hours < self.observation_hours + x[hours[observed], columns[observed]] = values[observed] + if not np.isfinite(x).any(): + return [] + + future_hours = np.unique(hours[~observed])[: self.prediction_steps] + if len(future_hours) == 0: + return [] + y = np.full((self.prediction_steps, n_vars), np.nan, dtype=np.float32) + y_time = np.zeros(self.prediction_steps, dtype=np.float32) + for step, hour in enumerate(future_hours): + at = hours == hour + y[step, columns[at]] = values[at] + y_time[step] = hour / self.total_hours + x_time = np.arange(self.observation_hours, dtype=np.float32) / self.total_hours + return [{ + "patient_id": patient.patient_id, + "x": x, + "x_time": x_time, + "y_time": y_time, + "y": y, + }] + + +def _hourly_means( + events: pl.DataFrame | pl.LazyFrame, + variables: Sequence[str], + by: Sequence[str] = (), +) -> pl.DataFrame | pl.LazyFrame: + """Mean value per (``by`` columns, hour since admission, variable). + + Shared by the task and :func:`physionet2012_statistics` so both bin the + same way. Works on an eager or a lazy frame of ``events`` rows. + """ + keys = [*by, "hour", "parameter"] + return ( + events.select( + *by, + (pl.col("events/minutes").cast(pl.Int64) // 60).alias("hour"), + pl.col("events/parameter").alias("parameter"), + pl.col("events/value").cast(pl.Float64).alias("value"), + ) + .filter(pl.col("parameter").is_in(list(variables))) + .group_by(keys) + .agg(pl.col("value").mean()) + ) + + +def physionet2012_statistics( + dataset: BaseDataset, + patient_ids: Sequence[str] | None = None, + variables: Sequence[str] = TIME_SERIES_VARIABLES, +) -> tuple[dict[str, float], dict[str, float]]: + """Per-variable mean and standard deviation of the hourly means. + + The forecasting benchmarks standardize with statistics over all records, + including the test records; pass the training ``patient_ids`` to use the + training records only. + + Args: + dataset: A :class:`~pyhealth.datasets.PhysioNet2012Dataset`. + patient_ids: Records to compute the statistics on; all if ``None``. + variables: The time series to describe. + + Returns: + ``(mean, std)``, each a dict keyed by variable (population standard + deviation, ``ddof=0``), rounded to 6 decimals. + + Examples: + >>> mean, std = physionet2012_statistics(dataset) # doctest: +SKIP + >>> round(mean["HR"], 1) # doctest: +SKIP + 86.8 + """ + events = dataset.global_event_df.filter(pl.col("event_type") == "events") + if patient_ids is not None: + events = events.filter(pl.col("patient_id").is_in(list(patient_ids))) + hourly = ( + _hourly_means(events, variables, by=["patient_id"]) + .group_by("parameter") + .agg( + pl.col("value").mean().alias("mean"), + pl.col("value").std(ddof=0).alias("std"), + ) + .collect() + ) + stats = {row["parameter"]: row for row in hourly.iter_rows(named=True)} + missing = [v for v in variables if v not in stats] + if missing: + raise ValueError(f"No observations of {missing}") + # Rounded so repeated runs give the same task (and reuse its cache): the + # parallel aggregation can change the last digits. + mean = {v: round(float(stats[v]["mean"]), 6) for v in variables} + std = {v: round(float(stats[v]["std"]), 6) or 1.0 for v in variables} + return mean, std + + +def physionet2012_benchmark_split( + dataset: SampleDataset, test_size: float = 0.1, val_size: float = 0.1 +) -> tuple[SampleDataset, SampleDataset, SampleDataset]: + """The deterministic split of the forecasting benchmarks. + + Records are ordered by ``RecordID`` (sets a, b, c); the last + ``test_size`` of them are the test set, and the last ``val_size`` of the + rest the validation set, as ``sklearn.model_selection.train_test_split`` + with ``shuffle=False`` does in the benchmark code. + + Args: + dataset: Samples from :class:`PhysioNet2012Forecasting`. + test_size: Fraction of records for testing. + val_size: Fraction of the remaining records for validation. + + Returns: + ``(train, val, test)`` views of ``dataset``. + + Examples: + >>> train, val, test = physionet2012_benchmark_split(samples) # doctest: +SKIP + """ + ids = sorted(dataset.patient_to_index, key=int) + n_test = math.ceil(test_size * len(ids)) + rest, test_ids = ids[: len(ids) - n_test], ids[len(ids) - n_test :] + n_val = math.ceil(val_size * len(rest)) + train_ids, val_ids = rest[: len(rest) - n_val], rest[len(rest) - n_val :] + + def subset(part: list[str]) -> SampleDataset: + return dataset.subset( + [i for pid in part for i in dataset.patient_to_index[pid]] + ) + + return subset(train_ids), subset(val_ids), subset(test_ids) diff --git a/tests/core/test_apn.py b/tests/core/test_apn.py new file mode 100644 index 0000000000..8e4bdb79ba --- /dev/null +++ b/tests/core/test_apn.py @@ -0,0 +1,381 @@ +"""Tests for the PhysioNet 2012 dataset, the forecasting task and APN.""" + +import io +import math +import tarfile +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +import numpy as np +import torch + +from pyhealth.datasets import ( + PhysioNet2012Dataset, + create_sample_dataset, + get_dataloader, +) +from pyhealth.datasets.physionet2012 import ( + EVENTS_CSV, + PATIENTS_CSV, + PHYSIONET2012_URL, + download_physionet2012, + prepare_physionet2012, + read_record, +) +from pyhealth.models import APN, TimeAwarePatchAggregation, masked_mse +from pyhealth.tasks import ( + PhysioNet2012Forecasting, + physionet2012_benchmark_split, + physionet2012_statistics, +) +from pyhealth.trainer import Trainer + +HEADER = "Time,Parameter,Value\n" +DESCRIPTORS = "00:00,Age,54\n00:00,Gender,0\n00:00,Height,-1\n00:00,ICUType,4\n00:00,Weight,80\n" + + +def _record(record_id, lines): + return HEADER + f"00:00,RecordID,{record_id}\n" + DESCRIPTORS + "".join(lines) + + +def _write_fake_root(root: Path) -> None: + """Three records in set-a with outcomes; one has no data after hour 36.""" + folder = root / "set-a" + folder.mkdir(parents=True) + # 132539: HR at hours 0 (two values, averaged), 1 and 35; targets at 36, 37, 40, 41. + (folder / "132539.txt").write_text(_record(132539, [ + "00:10,HR,70\n", "00:40,HR,80\n", "01:05,HR,90\n", "01:05,Temp,37\n", + "35:00,HR,100\n", "36:30,HR,110\n", "37:00,Temp,38\n", "40:00,HR,90\n", + "41:00,HR,95\n", "41:00,Weight,81\n", + ])) + # 132540: a target hour with only Weight (not a forecast variable). + (folder / "132540.txt").write_text(_record(132540, [ + "02:00,HR,60\n", "36:00,Weight,70\n", "38:00,HR,65\n", + ])) + # 132541: nothing after hour 36, so no target and no sample. + (folder / "132541.txt").write_text(_record(132541, ["03:00,HR,75\n"])) + (root / "Outcomes-a.txt").write_text( + "RecordID,SAPS-I,SOFA,Length_of_stay,Survival,In-hospital_death\n" + "132539,6,1,5,-1,0\n132540,16,8,8,-1,0\n132541,10,3,4,3,1\n" + ) + + +class TestPhysioNet2012Dataset(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.tmp = tempfile.TemporaryDirectory() + cls.root = Path(cls.tmp.name) / "p12" + _write_fake_root(cls.root) + cls.dataset = PhysioNet2012Dataset( + root=str(cls.root), cache_dir=Path(cls.tmp.name) / "cache" + ) + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + def test_read_record(self): + record_id, descriptors, events = read_record(self.root / "set-a/132539.txt") + self.assertEqual(record_id, "132539") + self.assertTrue(math.isnan(descriptors["Height"])) # -1 is missing + self.assertEqual(descriptors["Weight"], 80) + self.assertEqual(events[0], (10, "HR", 70.0)) + self.assertIn((41 * 60, "Weight", 81.0), events) # later weights are series + + def test_tables(self): + self.assertTrue((self.root / EVENTS_CSV).exists()) + self.assertTrue((self.root / PATIENTS_CSV).exists()) + self.assertEqual(sorted(self.dataset.unique_patient_ids), + ["132539", "132540", "132541"]) + patient = self.dataset.get_patient("132541") + info = patient.get_events(event_type="patients")[0] + self.assertEqual(float(info.in_hospital_death), 1.0) + self.assertEqual(info.set, "a") + + def test_prepare_requires_records(self): + with tempfile.TemporaryDirectory() as empty, self.assertRaises( + FileNotFoundError + ): + prepare_physionet2012(empty) + + def test_statistics(self): + mean, std = physionet2012_statistics(self.dataset, variables=["HR"]) + # hourly means of HR: 75, 90, 100, 110, 90, 95 | 60, 65 | 75 + hourly = [75, 90, 100, 110, 90, 95, 60, 65, 75] + self.assertAlmostEqual(mean["HR"], np.mean(hourly), places=5) + self.assertAlmostEqual(std["HR"], np.std(hourly), places=5) + only = physionet2012_statistics(self.dataset, ["132540"], variables=["HR"])[0] + self.assertAlmostEqual(only["HR"], 62.5) + + def test_task_windows_and_targets(self): + task = PhysioNet2012Forecasting(variables=["HR", "Temp"]) + samples = {s["patient_id"]: s for p in self.dataset.iter_patients() + for s in task(p)} + self.assertEqual(sorted(samples), ["132539", "132540"]) # 132541: no target + s = samples["132539"] + self.assertEqual(s["x"].shape, (36, 2)) + self.assertEqual(s["x"][0, 0], 75.0) # 70 and 80 averaged in hour 0 + self.assertEqual(s["x"][1, 1], 37.0) + self.assertEqual(s["x"][35, 0], 100.0) + self.assertEqual(np.isfinite(s["x"]).sum(), 4) + np.testing.assert_allclose(s["y_time"], np.array([36, 37, 40]) / 48) + np.testing.assert_array_equal( + s["y"], np.array([[110, np.nan], [np.nan, 38], [90, np.nan]], dtype="f4") + ) + np.testing.assert_allclose(s["x_time"], np.arange(36) / 48) + # 132540: the Weight-only hour is no forecast step; one target, padded. + s = samples["132540"] + np.testing.assert_allclose(s["y_time"], [38 / 48, 0, 0]) + self.assertEqual(np.isfinite(s["y"]).sum(), 1) + + def test_task_normalization_and_outliers(self): + mean, std = {"HR": 90.0, "Temp": 37.0}, {"HR": 5.0, "Temp": 1.0} + task = PhysioNet2012Forecasting(mean, std, variables=["HR", "Temp"]) + (s,) = task(self.dataset.get_patient("132539")) + self.assertAlmostEqual(s["x"][0, 0], (75 - 90) / 5) # -3 SD: kept + self.assertAlmostEqual(s["y"][0, 0], 4.0) # 110 is +4 SD: kept + strict = PhysioNet2012Forecasting(mean, std, variables=["HR", "Temp"], + outlier_sd=3.5) + (s,) = strict(self.dataset.get_patient("132539")) + self.assertTrue(np.isnan(s["y"][0, 0])) # +4 SD dropped + with self.assertRaises(ValueError): + PhysioNet2012Forecasting(mean=mean) + + def test_set_task_and_split(self): + samples = self.dataset.set_task(PhysioNet2012Forecasting(variables=["HR", "Temp"])) + self.assertEqual(len(samples), 2) + train, val, test = physionet2012_benchmark_split(samples, 0.5, 0.0) + self.assertEqual((len(train), len(val), len(test)), (1, 0, 1)) + self.assertEqual(test[0]["patient_id"], "132540") # the last RecordID + self.assertTrue(torch.isnan(samples[0]["y"]).any()) # NaN kept for the mask + + +def _fake_tarball(records: dict[str, str]) -> bytes: + """A gzipped tar holding ``set-a/.txt`` for each record.""" + buffer = io.BytesIO() + with tarfile.open(fileobj=buffer, mode="w:gz") as archive: + for record_id, text in records.items(): + data = text.encode() + info = tarfile.TarInfo(f"set-a/{record_id}.txt") + info.size = len(data) + archive.addfile(info, io.BytesIO(data)) + return buffer.getvalue() + + +class TestPhysioNet2012Download(unittest.TestCase): + """The download and extraction path, with the network patched out.""" + + OUTCOMES = ( + "RecordID,SAPS-I,SOFA,Length_of_stay,Survival,In-hospital_death\n" + "132539,6,1,5,-1,0\n" + ) + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) / "p12" + self.files = { + "set-a.tar.gz": _fake_tarball( + {"132539": _record(132539, ["00:10,HR,70\n", "37:00,HR,80\n"])} + ), + "Outcomes-a.txt": self.OUTCOMES.encode(), + } + self.calls = [] + self.failures = {} # filename -> attempts that fail before success + sleep = mock.patch("pyhealth.datasets.physionet2012.time.sleep") + self.sleep = sleep.start() + self.addCleanup(sleep.stop) + + def _urlretrieve(self, url, filename): + name = url.removeprefix(PHYSIONET2012_URL) + self.calls.append(name) + if self.failures.get(name, 0) > 0: + self.failures[name] -= 1 + Path(filename).write_bytes(b"partial") # a half-written file + raise OSError("connection reset") + Path(filename).write_bytes(self.files[name]) + return filename, None + + def _download(self, **kwargs): + with mock.patch( + "urllib.request.urlretrieve", side_effect=self._urlretrieve + ): + download_physionet2012(self.root, sets=["a"], **kwargs) + + def test_download_and_extract(self): + self._download() + self.assertEqual(self.calls, ["set-a.tar.gz", "Outcomes-a.txt"]) + self.assertEqual((self.root / "Outcomes-a.txt").read_text(), self.OUTCOMES) + record_id, _, events = read_record(self.root / "set-a/132539.txt") + self.assertEqual((record_id, events), ("132539", [(10, "HR", 70.0), + (37 * 60, "HR", 80.0)])) + self.assertEqual( + sorted(p.name for p in self.root.iterdir()), + ["Outcomes-a.txt", "set-a", "set-a.tar.gz"], + ) # no .part files or temporary folders left + + # Files already present are not downloaded again. + self.calls.clear() + self._download() + self.assertEqual(self.calls, []) + + def test_dataset_download(self): + with mock.patch( + "urllib.request.urlretrieve", side_effect=self._urlretrieve + ): + dataset = PhysioNet2012Dataset( + root=str(self.root), + download=True, + sets=["a"], + cache_dir=Path(self.tmp.name) / "cache", + ) + self.assertEqual(dataset.unique_patient_ids, ["132539"]) + + def test_retry_discards_partial_file(self): + self.failures["set-a.tar.gz"] = 2 + self._download(retries=3) + self.assertEqual(self.calls.count("set-a.tar.gz"), 3) + self.assertEqual(self.sleep.call_count, 2) + self.assertTrue((self.root / "set-a/132539.txt").exists()) + self.assertFalse((self.root / "set-a.tar.gz.part").exists()) + + def test_gives_up_after_retries(self): + self.failures["Outcomes-a.txt"] = 5 + with self.assertRaises(OSError): + self._download(retries=2) + self.assertEqual(self.calls.count("Outcomes-a.txt"), 2) + self.assertFalse((self.root / "Outcomes-a.txt").exists()) + self.assertFalse((self.root / "Outcomes-a.txt.part").exists()) + self.assertFalse((self.root / "set-a").exists()) + + def test_interrupted_extraction_is_redone(self): + self.root.mkdir(parents=True) + partial = self.root / ".set-a.partial" / "set-a" + partial.mkdir(parents=True) + (partial / "999999.txt").write_text("truncated") + with ( + mock.patch("tarfile.TarFile.extractall", side_effect=OSError("full")), + self.assertRaises(OSError), + ): + self._download() + self.assertFalse((self.root / "set-a").exists()) # nothing half-made + self.assertFalse((self.root / ".set-a.partial").exists()) + + self._download() + self.assertEqual( + [p.name for p in (self.root / "set-a").iterdir()], ["132539.txt"] + ) + + +def _synthetic_samples(n=64, length=12, steps=3, n_vars=3, seed=0): + """Sine waves with per-sample phase, observed at random points.""" + rng = np.random.default_rng(seed) + samples = [] + total = length + steps + for i in range(n): + phase = rng.uniform(0, 2 * np.pi, size=n_vars) + t = np.arange(total) / total + values = np.sin(2 * np.pi * t[:, None] + phase).astype("float32") + x = values[:length].copy() + x[rng.random(x.shape) < 0.3] = np.nan + samples.append({ + "patient_id": f"p{i}", + "x": x, + "x_time": t[:length].astype("float32"), + "y_time": t[length:].astype("float32"), + "y": values[length:], + }) + return samples + + +def _dataset(samples): + return create_sample_dataset( + samples, + {"x": "tensor", "x_time": "tensor", "y_time": "tensor"}, + {"y": "tensor"}, + ) + + +class TestAPN(unittest.TestCase): + def setUp(self): + torch.manual_seed(0) + + def test_patch_weights_follow_boundaries(self): + tapa = TimeAwarePatchAggregation(1, 2, feature_dim=1, hidden_dim=4) + with torch.no_grad(): + tapa.raw_tau.fill_(-6.0) # sharp edges + left, right = tapa.boundaries() + np.testing.assert_allclose(left[0].tolist(), [0.0, 0.5], atol=1e-6) + np.testing.assert_allclose(right[0].tolist(), [0.5, 1.0], atol=1e-5) + t = torch.tensor([[[0.1, 0.4, 0.7, 0.9]]]) + w = tapa.weights(t, torch.tensor([[[1.0, 1.0, 1.0, 0.0]]])) + self.assertEqual(w.shape, (1, 1, 2, 4)) + np.testing.assert_allclose(w[0, 0].round().tolist(), + [[1, 1, 0, 0], [0, 0, 1, 0]]) # masked point: 0 + + def test_patch_is_weighted_average(self): + tapa = TimeAwarePatchAggregation(1, 1, feature_dim=1, hidden_dim=1) + captured = {} + tapa.project.register_forward_hook( + lambda module, args, out: captured.setdefault("pooled", args[0]) + ) + t = torch.tensor([[[0.2, 0.5, 0.8]]]) + feats = torch.tensor([[[[1.0], [2.0], [9.0]]]]) + tapa(t, feats, torch.tensor([[[1.0, 1.0, 0.0]]])) + w = tapa.weights(t, torch.tensor([[[1.0, 1.0, 0.0]]]))[0, 0, 0] + expected = (w[0] * 1 + w[1] * 2) / (w.sum() + 1e-9) + self.assertAlmostEqual(captured["pooled"].item(), expected.item(), places=5) + + def test_masked_mse(self): + pred = torch.tensor([[1.0, 2.0], [3.0, 4.0]], requires_grad=True) + target = torch.tensor([[0.0, float("nan")], [3.0, float("nan")]]) + loss = masked_mse(pred, target) + self.assertAlmostEqual(loss.item(), 0.5) + loss.backward() + self.assertEqual(pred.grad[0, 1].item(), 0.0) + empty = masked_mse(pred, torch.full((2, 2), float("nan"))) + self.assertEqual(empty.item(), 0.0) + self.assertTrue(empty.requires_grad) + + def test_loss_and_probability_helpers(self): + dataset = _dataset(_synthetic_samples(n=8)) + model = APN(dataset, hidden_dim=8, num_patches=4, time_dim=4) + self.assertIs(model.get_loss_function(), masked_mse) + logits = torch.randn(2, 3, 3) + self.assertIs(model.prepare_y_prob(logits), logits) + + def test_forward_backward_and_inference(self): + dataset = _dataset(_synthetic_samples(n=8)) + model = APN(dataset, hidden_dim=8, num_patches=4, time_dim=4) + self.assertEqual(model.mode, "regression") + self.assertEqual(model.num_variables, 3) + batch = next(iter(get_dataloader(dataset, batch_size=8))) + out = model(**batch) + self.assertEqual(out["forecast"].shape, (8, 3, 3)) + n_obs = int(torch.isfinite(batch["y"]).sum()) + self.assertEqual(out["y_true"].shape, (n_obs,)) + self.assertEqual(out["y_prob"].shape, (n_obs,)) + out["loss"].backward() + self.assertIsNotNone(model.patching.left_offset.grad) + self.assertIsNotNone(model.queries.grad) + unlabeled = {k: v for k, v in batch.items() if k != "y"} + out = model(**unlabeled) + self.assertNotIn("loss", out) + self.assertEqual(out["y_prob"].shape, (8, 3, 3)) + + def test_training_lowers_loss_and_trainer_scores(self): + dataset = _dataset(_synthetic_samples(n=64)) + loader = get_dataloader(dataset, batch_size=16, shuffle=True) + model = APN(dataset, hidden_dim=16, num_patches=4, time_dim=4, dropout=0.0) + trainer = Trainer(model=model, metrics=["mse", "mae"], enable_logging=False) + before = trainer.evaluate(get_dataloader(dataset, batch_size=64))["mse"] + trainer.train(loader, epochs=30, optimizer_params={"lr": 1e-2}) + after = trainer.evaluate(get_dataloader(dataset, batch_size=64)) + self.assertLess(after["mse"], 0.5 * before) + self.assertIn("mae", after) + + +if __name__ == "__main__": + unittest.main()