Repository navigation
Add ARMR medication recommendation model (IJCAI 2025) #1371
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
Merged
Merged
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
7090d8c
Add ARMR medication recommendation model (IJCAI 2025)
solarsys ecd70c7
ARMR: make the time decay reach the score; share DDI/history helpers
solarsys 27012ac
GAMENet: drop the unused batch_to_multihot import
solarsys 6bf16ad
ARMR notebook: train-split graphs, upstream install, refreshed outputs
solarsys 9aba5ef
Use the shared ddi_adjacency in SafeDrug, MICRON and MoleRec; ARMR vi…
solarsys 787c221
ARMR: graph_dataset for the co-occurrence graph; DDI helper tests
solarsys 22723b9
Merge remote-tracking branch 'upstream/master' into feat/armr
solarsys 3f4689f
ARMR: per-set Eq. 11 softmax; shared co-occurrence graph helper
solarsys 2766dce
Merge remote-tracking branch 'upstream/master' into feat/armr
solarsys dde9990
ARMR: cite the paper's Table 3; skip network doctests; Trainer test
solarsys bf56c27
Merge upstream/master into feat/armr
solarsys 55ab41b
ARMR: require graph_dataset when use_graph=True
solarsys 8dcb493
Merge upstream/master into feat/armr
solarsys 364c3a2
Share the GCN adjacency normalization between GAMENet and ARMR
solarsys ad3127b
GAMENet: add a usage example to the GCN docstring
solarsys 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
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,27 @@ | ||
| pyhealth.models.ARMR | ||
| =================================== | ||
|
|
||
| ARMR (Wu et al., "ARMR: Adaptively Responsive Network for Medication | ||
| Recommendation", IJCAI 2025) for the drug-recommendation tasks | ||
| (:class:`~pyhealth.tasks.DrugRecommendationMIMIC3`, | ||
| :class:`~pyhealth.tasks.DrugRecommendationMIMIC4`). It needs ``conditions``, | ||
| ``procedures`` and ``drugs_hist`` in the input schema and predicts ``drugs``. | ||
| With the drug graphs (``use_graph=True``, the default) pass the training split | ||
| as ``graph_dataset``, for example ``ARMR(train, graph_dataset=train)``, so the | ||
| co-occurrence graph never sees evaluation labels; otherwise ARMR raises a | ||
| ``ValueError``. ``use_graph=False`` needs no ``graph_dataset``. | ||
|
|
||
| Example notebook: ``examples/armr_mimic3_drug_recommendation.ipynb``. | ||
|
|
||
| .. autoclass:: pyhealth.models.ARMR | ||
| :members: | ||
| :undoc-members: | ||
| :show-inheritance: | ||
|
|
||
| .. autoclass:: pyhealth.models.armr.PiecewiseTemporalLearning | ||
| :members: | ||
| :show-inheritance: | ||
|
|
||
| .. autoclass:: pyhealth.models.armr.SelectiveSSM | ||
| :members: | ||
| :show-inheritance: |
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,352 @@ | ||
| { | ||
| "cells": [ | ||
| { | ||
| "cell_type": "markdown", | ||
| "id": "9f447d62", | ||
| "metadata": {}, | ||
| "source": [ | ||
| "# ARMR in PyHealth: medication recommendation on MIMIC-III\n", | ||
| "\n", | ||
| "[](https://colab.research.google.com/github/solarsys/PyHealth/blob/feat/armr/examples/armr_mimic3_drug_recommendation.ipynb)\n", | ||
| "\n", | ||
| "This notebook runs **ARMR** (Feiyue Wu, Tianxing Wu and Shenqi Jing, *ARMR: Adaptively Responsive Network for Medication Recommendation*, IJCAI 2025, [arXiv:2507.04428](https://arxiv.org/abs/2507.04428)) as implemented in PyHealth (`pyhealth.models.ARMR`), and compares it with PyHealth's GAMENet, SafeDrug and RETAIN on the same task, split and metrics.\n", | ||
| "\n", | ||
| "ARMR has three parts:\n", | ||
| "- **Piecewise temporal learning.** The most recent visits go through a feedforward network and the earlier ones through a Mamba block; the recent states attend over the distant ones.\n", | ||
| "- **Adaptively responsive module.** The medication history is split into drugs that were reused and drugs that were new at each visit. Each drug's embedding is weighted by attention over the drugs the patient took before if it is one of them, and over the drugs never taken otherwise; a learned, time-decayed score for past use is added to the drug's score.\n", | ||
| "- **Joint recommendation.** A direct score from the patient representation is fused with the cosine similarity between the patient and each weighted drug embedding. The loss is 0.7 × BCE + 0.3 × multi-label margin.\n", | ||
| "\n", | ||
| "**How to use it.** Part 1 runs end to end on PyHealth's open synthetic MIMIC-III, with no credentials. Part 2 repeats the experiment on real MIMIC-III v1.4: set `MIMIC3_ROOT` to your copy (PhysioNet credentials required) and run it." | ||
| ] | ||
| }, | ||
| { | ||
| "cell_type": "markdown", | ||
| "id": "d77f3458", | ||
| "metadata": {}, | ||
| "source": [ | ||
| "## Setup\n", | ||
| "\n", | ||
| "On Colab this installs PyHealth from the pull request that adds ARMR ([#1371](https://github.com/sunlabuiuc/PyHealth/pull/1371)). After it is merged, install `pyhealth` from PyPI or from `master` instead." | ||
| ] | ||
| }, | ||
| { | ||
| "cell_type": "code", | ||
| "execution_count": 1, | ||
| "id": "dfbb0f34", | ||
| "metadata": { | ||
| "execution": { | ||
| "iopub.execute_input": "2026-11-03T15:37:00.887981Z", | ||
| "iopub.status.busy": "2026-11-03T15:37:00.887518Z", | ||
| "iopub.status.idle": "2026-11-03T15:37:00.900591Z", | ||
| "shell.execute_reply": "2026-11-03T15:37:00.899424Z" | ||
| } | ||
| }, | ||
| "outputs": [], | ||
| "source": [ | ||
| "import sys\n", | ||
| "import subprocess\n", | ||
| "\n", | ||
| "if \"google.colab\" in sys.modules:\n", | ||
| " subprocess.run(\n", | ||
| " [sys.executable, \"-m\", \"pip\", \"install\", \"-q\",\n", | ||
| " \"git+https://github.com/sunlabuiuc/PyHealth@refs/pull/1371/head\"],\n", | ||
| " check=True,\n", | ||
| " )" | ||
| ] | ||
| }, | ||
| { | ||
| "cell_type": "code", | ||
| "execution_count": 2, | ||
| "id": "ef9a1fcf", | ||
| "metadata": { | ||
| "execution": { | ||
| "iopub.execute_input": "2026-11-03T15:37:00.903702Z", | ||
| "iopub.status.busy": "2026-11-03T15:37:00.903455Z", | ||
| "iopub.status.idle": "2026-11-03T15:37:05.861164Z", | ||
| "shell.execute_reply": "2026-11-03T15:37:05.860718Z" | ||
| } | ||
| }, | ||
| "outputs": [], | ||
| "source": [ | ||
| "import random\n", | ||
| "\n", | ||
| "import numpy as np\n", | ||
| "import pandas as pd\n", | ||
| "import torch\n", | ||
| "\n", | ||
| "from pyhealth.datasets import MIMIC3Dataset, get_dataloader, split_by_patient\n", | ||
| "from pyhealth.metrics import ddi_rate_score\n", | ||
| "from pyhealth.models import ARMR, GAMENet, RETAIN, SafeDrug\n", | ||
| "from pyhealth.models.utils import ddi_adjacency\n", | ||
| "from pyhealth.tasks import DrugRecommendationMIMIC3\n", | ||
| "from pyhealth.trainer import Trainer\n", | ||
| "\n", | ||
| "METRICS = [\"jaccard_samples\", \"pr_auc_samples\", \"f1_samples\"]\n", | ||
| "\n", | ||
| "\n", | ||
| "def seed_everything(seed: int) -> None:\n", | ||
| " random.seed(seed)\n", | ||
| " np.random.seed(seed)\n", | ||
| " torch.manual_seed(seed)\n", | ||
| "\n", | ||
| "\n", | ||
| "def ddi_matrix(samples) -> np.ndarray:\n", | ||
| " \"\"\"Drug-drug interactions between the task's ATC-3 drugs (as GAMENet and SafeDrug).\"\"\"\n", | ||
| " return ddi_adjacency(samples.output_processors[\"drugs\"].label_vocab).numpy()\n", | ||
| "\n", | ||
| "\n", | ||
| "def load_samples(root: str, dev: bool = False):\n", | ||
| " \"\"\"Loads MIMIC-III and builds PyHealth's drug-recommendation samples.\"\"\"\n", | ||
| " dataset = MIMIC3Dataset(\n", | ||
| " root=root,\n", | ||
| " tables=[\"DIAGNOSES_ICD\", \"PROCEDURES_ICD\", \"PRESCRIPTIONS\"],\n", | ||
| " dev=dev,\n", | ||
| " )\n", | ||
| " return dataset.set_task(DrugRecommendationMIMIC3())\n", | ||
| "\n", | ||
| "\n", | ||
| "MODELS = {\n", | ||
| " # ARMR's defaults follow the paper; lr 2e-4 is the authors' setting.\n", | ||
| " # `s` is the training split; ARMR builds its drug co-occurrence graph\n", | ||
| " # from graph_dataset, so test-patient labels stay out of it.\n", | ||
| " \"ARMR\": (lambda s: ARMR(s, embedding_dim=64, n_recent=3, graph_dataset=s), 2e-4),\n", | ||
| " \"GAMENet\": (lambda s: GAMENet(s), 1e-3),\n", | ||
| " \"SafeDrug\": (lambda s: SafeDrug(s), 1e-3),\n", | ||
| " \"RETAIN\": (lambda s: RETAIN(s), 1e-3),\n", | ||
| "}\n", | ||
| "\n", | ||
| "\n", | ||
| "def compare(samples, epochs: int, seed: int = 42, batch_size: int = 64):\n", | ||
| " \"\"\"Trains each model on one patient-level split and scores it on the test patients.\"\"\"\n", | ||
| " train, val, test = split_by_patient(samples, [0.7, 0.1, 0.2], seed=seed)\n", | ||
| " loaders = (\n", | ||
| " get_dataloader(train, batch_size=batch_size, shuffle=True),\n", | ||
| " get_dataloader(val, batch_size=batch_size, shuffle=False),\n", | ||
| " get_dataloader(test, batch_size=batch_size, shuffle=False),\n", | ||
| " )\n", | ||
| " ddi = ddi_matrix(samples)\n", | ||
| " rows = {}\n", | ||
| " for name, (make, lr) in MODELS.items():\n", | ||
| " seed_everything(seed)\n", | ||
| " # models see the training patients only: ARMR's and GAMENet's drug\n", | ||
| " # co-occurrence graphs are built from the samples they are given\n", | ||
| " trainer = Trainer(model=make(train), metrics=METRICS, enable_logging=False)\n", | ||
| " trainer.train(\n", | ||
| " train_dataloader=loaders[0], val_dataloader=loaders[1], epochs=epochs,\n", | ||
| " optimizer_params={\"lr\": lr}, monitor=\"jaccard_samples\",\n", | ||
| " )\n", | ||
| " scores = trainer.evaluate(loaders[2])\n", | ||
| " # DDI rate of the recommended sets (probability >= 0.5)\n", | ||
| " _, y_prob, _ = trainer.inference(loaders[2])\n", | ||
| " recommended = [np.flatnonzero(row >= 0.5) for row in y_prob]\n", | ||
| " rows[name] = {\n", | ||
| " \"Jaccard\": scores[\"jaccard_samples\"],\n", | ||
| " \"PRAUC\": scores[\"pr_auc_samples\"],\n", | ||
| " \"F1\": scores[\"f1_samples\"],\n", | ||
| " \"DDI rate\": ddi_rate_score(recommended, ddi),\n", | ||
| " }\n", | ||
| " return (pd.DataFrame(rows).T * 100).round(2)" | ||
| ] | ||
| }, | ||
| { | ||
| "cell_type": "markdown", | ||
| "id": "0ae6ab06", | ||
| "metadata": {}, | ||
| "source": [ | ||
| "## Part 1: open synthetic MIMIC-III (no credentials)\n", | ||
| "\n", | ||
| "PyHealth hosts a synthetic MIMIC-III with the real schema. It is useful for checking that everything runs; its scores say nothing about the paper's results. Three epochs take a few minutes on a CPU. That is too short for ARMR, which trains at the authors' learning rate (2e-4, five times lower than the baselines'), so it trails here; the comparison that matters is Part 2's. Also, GAMENet's drug co-occurrence graph is all zeros on PyHealth's processed samples (a known GAMENet issue, separate from this notebook), so only its DDI graph is active here and the comparison with GAMENet is not like-for-like." | ||
| ] | ||
| }, | ||
| { | ||
| "cell_type": "code", | ||
| "execution_count": 3, | ||
| "id": "b38a21cf", | ||
| "metadata": { | ||
| "execution": { | ||
| "iopub.execute_input": "2026-11-03T15:37:05.863069Z", | ||
| "iopub.status.busy": "2026-11-03T15:37:05.862784Z", | ||
| "iopub.status.idle": "2026-11-03T15:38:59.735066Z", | ||
| "shell.execute_reply": "2026-11-03T15:38:59.734372Z" | ||
| } | ||
| }, | ||
| "outputs": [ | ||
| { | ||
| "name": "stdout", | ||
| "output_type": "stream", | ||
| "text": [ | ||
| "1858 samples\n" | ||
| ] | ||
| }, | ||
| { | ||
| "data": { | ||
| "text/html": [ | ||
| "<div>\n", | ||
| "<style scoped>\n", | ||
| " .dataframe tbody tr th:only-of-type {\n", | ||
| " vertical-align: middle;\n", | ||
| " }\n", | ||
| "\n", | ||
| " .dataframe tbody tr th {\n", | ||
| " vertical-align: top;\n", | ||
| " }\n", | ||
| "\n", | ||
| " .dataframe thead th {\n", | ||
| " text-align: right;\n", | ||
| " }\n", | ||
| "</style>\n", | ||
| "<table border=\"1\" class=\"dataframe\">\n", | ||
| " <thead>\n", | ||
| " <tr style=\"text-align: right;\">\n", | ||
| " <th></th>\n", | ||
| " <th>Jaccard</th>\n", | ||
| " <th>PRAUC</th>\n", | ||
| " <th>F1</th>\n", | ||
| " <th>DDI rate</th>\n", | ||
| " </tr>\n", | ||
| " </thead>\n", | ||
| " <tbody>\n", | ||
| " <tr>\n", | ||
| " <th>ARMR</th>\n", | ||
| " <td>24.48</td>\n", | ||
| " <td>46.57</td>\n", | ||
| " <td>36.35</td>\n", | ||
| " <td>6.66</td>\n", | ||
| " </tr>\n", | ||
| " <tr>\n", | ||
| " <th>GAMENet</th>\n", | ||
| " <td>30.48</td>\n", | ||
| " <td>56.40</td>\n", | ||
| " <td>43.62</td>\n", | ||
| " <td>8.67</td>\n", | ||
| " </tr>\n", | ||
| " <tr>\n", | ||
| " <th>SafeDrug</th>\n", | ||
| " <td>29.99</td>\n", | ||
| " <td>54.08</td>\n", | ||
| " <td>43.58</td>\n", | ||
| " <td>6.39</td>\n", | ||
| " </tr>\n", | ||
| " <tr>\n", | ||
| " <th>RETAIN</th>\n", | ||
| " <td>28.86</td>\n", | ||
| " <td>54.02</td>\n", | ||
| " <td>41.45</td>\n", | ||
| " <td>7.19</td>\n", | ||
| " </tr>\n", | ||
| " </tbody>\n", | ||
| "</table>\n", | ||
| "</div>" | ||
| ], | ||
| "text/plain": [ | ||
| " Jaccard PRAUC F1 DDI rate\n", | ||
| "ARMR 24.48 46.57 36.35 6.66\n", | ||
| "GAMENet 30.48 56.40 43.62 8.67\n", | ||
| "SafeDrug 29.99 54.08 43.58 6.39\n", | ||
| "RETAIN 28.86 54.02 41.45 7.19" | ||
| ] | ||
| }, | ||
| "execution_count": 3, | ||
| "metadata": {}, | ||
| "output_type": "execute_result" | ||
| } | ||
| ], | ||
| "source": [ | ||
| "synthetic = load_samples(\"https://storage.googleapis.com/pyhealth/Synthetic_MIMIC-III\")\n", | ||
| "print(f\"{len(synthetic)} samples\")\n", | ||
| "synthetic_results = compare(synthetic, epochs=3)\n", | ||
| "synthetic_results" | ||
| ] | ||
| }, | ||
| { | ||
| "cell_type": "markdown", | ||
| "id": "46e581d1", | ||
| "metadata": {}, | ||
| "source": [ | ||
| "## Part 2: MIMIC-III v1.4 (credentialed)\n", | ||
| "\n", | ||
| "Set `MIMIC3_ROOT` to the folder with `ADMISSIONS.csv.gz`, `DIAGNOSES_ICD.csv.gz`, `PROCEDURES_ICD.csv.gz` and `PRESCRIPTIONS.csv.gz` (for example a mounted Google Drive folder).\n", | ||
| "\n", | ||
| "The paper reports ARMR's results (mean ± std over runs, in %) in its Table 3 (\"The comparison results on MIMIC-III and MIMIC-IV datasets\"):\n", | ||
| "\n", | ||
| "| Dataset | Jaccard | PRAUC | F1 |\n", | ||
| "|---|---|---|---|\n", | ||
| "| MIMIC-III | 54.51 ± 0.13 | 79.63 ± 0.28 | 69.59 ± 0.29 |\n", | ||
| "| MIMIC-IV | 51.74 ± 0.14 | 76.95 ± 0.21 | 67.12 ± 0.18 |\n", | ||
| "\n", | ||
| "Section 5.1 of the paper defines the metrics: Jaccard is the intersection over the union of the recommended and true drug sets, F1 the harmonic mean of precision and recall, and PRAUC the area under the precision-recall curve, each averaged over the evaluation records. Here they are PyHealth's `jaccard_samples`, `f1_samples` and `pr_auc_samples` (averaged over the test samples, one per visit), shown ×100.\n", | ||
| "\n", | ||
| "The paper follows the preprocessing of Chen et al. (2023, Carmen): ATC level-3 drugs, 131 of them, with 6,350 MIMIC-III patients (15,032 visits) in its Table 2. PyHealth's `DrugRecommendationMIMIC3` uses its own filtering and drug vocabulary, so expect the same ordering of models, not identical numbers." | ||
| ] | ||
| }, | ||
| { | ||
| "cell_type": "code", | ||
| "execution_count": 4, | ||
| "id": "13e4d4ce", | ||
| "metadata": { | ||
| "execution": { | ||
| "iopub.execute_input": "2026-11-03T15:38:59.737786Z", | ||
| "iopub.status.busy": "2026-11-03T15:38:59.737651Z", | ||
| "iopub.status.idle": "2026-11-03T15:38:59.740429Z", | ||
| "shell.execute_reply": "2026-11-03T15:38:59.739963Z" | ||
| } | ||
| }, | ||
| "outputs": [ | ||
| { | ||
| "name": "stdout", | ||
| "output_type": "stream", | ||
| "text": [ | ||
| "Set MIMIC3_ROOT to run the experiment on MIMIC-III.\n" | ||
| ] | ||
| } | ||
| ], | ||
| "source": [ | ||
| "MIMIC3_ROOT = \"\" # e.g. \"/content/drive/MyDrive/mimic-iii-clinical-database-1.4\"\n", | ||
| "\n", | ||
| "if MIMIC3_ROOT:\n", | ||
| " mimic3 = load_samples(MIMIC3_ROOT)\n", | ||
| " print(f\"{len(mimic3)} samples\")\n", | ||
| " mimic3_results = compare(mimic3, epochs=50)\n", | ||
| " display(mimic3_results)\n", | ||
| "else:\n", | ||
| " print(\"Set MIMIC3_ROOT to run the experiment on MIMIC-III.\")" | ||
| ] | ||
| }, | ||
| { | ||
| "cell_type": "markdown", | ||
| "id": "4207a928", | ||
| "metadata": {}, | ||
| "source": [ | ||
| "## Notes for reproducing the paper\n", | ||
| "\n", | ||
| "- `ARMR(..., use_graph=True)` (the default) adds GCN embeddings of the drug co-occurrence and drug-drug interaction graphs to the drug embeddings, as the authors' released code does. `use_graph=False` gives the equations exactly as written in the paper. With the graphs, pass the training split as `graph_dataset` so the co-occurrence graph never sees evaluation labels (ARMR raises a `ValueError` if it is missing).\n", | ||
| "- Three details the paper leaves open, and the choices made: Eq. 9's time decay is one learned scale and rate, added to each drug's score (in Eq. 11 it would only rescale a drug's embedding, which the cosine similarity ignores); Eq. 11's attention gives a weight per embedding feature; the \"recent\" segment is the N visits closest to the prediction.\n", | ||
| "- Questions or corrections: please open an issue at https://github.com/sunlabuiuc/PyHealth or write on the PyHealth Discord." | ||
| ] | ||
| } | ||
| ], | ||
| "metadata": { | ||
| "accelerator": "GPU", | ||
| "colab": { | ||
| "provenance": [] | ||
| }, | ||
| "kernelspec": { | ||
| "display_name": "Python 3", | ||
| "name": "python3" | ||
| }, | ||
| "language_info": { | ||
| "codemirror_mode": { | ||
| "name": "ipython", | ||
| "version": 3 | ||
| }, | ||
| "file_extension": ".py", | ||
| "mimetype": "text/x-python", | ||
| "name": "python", | ||
| "nbconvert_exporter": "python", | ||
| "pygments_lexer": "ipython3", | ||
| "version": "3.13.5" | ||
| } | ||
| }, | ||
| "nbformat": 4, | ||
| "nbformat_minor": 5 | ||
| } | ||
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] Colab badge and install cell point at different repositories
The badge links to solarsys/PyHealth on branch feat/armr, but the setup cell installs git+https://github.com/sunlabuiuc/PyHealth@refs/pull/1371/head. Users who click the badge may run a different copy of the code than the one the setup cell installs. Point both at the same repository, for example the sunlabuiuc PR ref or the merged branch once this lands.