diff --git a/docs/api/models.rst b/docs/api/models.rst index fdb43e83d4..0cfa15c25f 100644 --- a/docs/api/models.rst +++ b/docs/api/models.rst @@ -315,6 +315,7 @@ API Reference models/pyhealth.models.LogisticRegressionWithSummaries models/pyhealth.models.LSTMNextStateBaseline models/pyhealth.models.MLP + models/pyhealth.models.KeyClass models/pyhealth.models.RASCMLP models/pyhealth.models.CNN models/pyhealth.models.camchex diff --git a/docs/api/models/pyhealth.models.KeyClass.rst b/docs/api/models/pyhealth.models.KeyClass.rst new file mode 100644 index 0000000000..f6e18d6c1a --- /dev/null +++ b/docs/api/models/pyhealth.models.KeyClass.rst @@ -0,0 +1,98 @@ +pyhealth.models.KeyClass +=================================== + +KeyClass classifies clinical notes into diagnostic categories without any +human-labeled notes. It builds keyword labeling functions automatically from +short category descriptions, combines their votes into soft weak labels, and +trains a multilabel classifier on frozen document embeddings. + +Paper: Chufan Gao, Mononito Goswami, Jieshi Chen and Artur Dubrawski. +`Classifying Unstructured Clinical Notes via Automatic Weak Supervision +`_. MLHC 2022. + +Installation +------------ + +Mining keyword rules needs NLTK and its English stopword list, and the optional +Snorkel label model needs Snorkel. Neither is a PyHealth dependency; install +them with:: + + pip install "nltk~=3.9.1" "snorkel>=0.10,<0.11" + python -m nltk.downloader stopwords + +Snorkel is needed only for ``aggregate_votes(..., method="snorkel")``. Without +these packages, the functions that need them raise an ``ImportError`` that says +what to install. + +MIMIC-III data +-------------- + +:class:`~pyhealth.tasks.mimic3_icd9_category_classification.MIMIC3ICD9CategoryClassification` builds the paper's +MIMIC-III cohort: one sample per admission with its discharge summary +(``"text"``) and its 19-category ICD-9 labels (``"categories"``). KeyClass +trains without those labels; use ``pyhealth.tasks.ICD9_CATEGORIES`` as +``category_ids`` and, to evaluate against them, pass them as 0/1 vectors in +that order under the model's ``gold_key``. + +Pipeline +-------- + +1. Clean notes with :func:`~pyhealth.weak_supervision.clean_note`. +2. Fit a :class:`~pyhealth.weak_supervision.KeywordLabeler` on training notes and + category descriptions, then vote with + :meth:`~pyhealth.weak_supervision.KeywordLabeler.transform`. +3. Turn votes into soft weak labels with + :func:`~pyhealth.weak_supervision.aggregate_votes`, and pick confident notes with + :func:`~pyhealth.weak_supervision.confident_balanced_mask`. +4. Embed notes, for example with + :class:`~pyhealth.weak_supervision.ClinicalTextEncoder`, and train + :class:`~pyhealth.models.KeyClass` on the embeddings and soft labels. + +.. code-block:: python + + from pyhealth.models import KeyClass + from pyhealth.weak_supervision import ( + ClinicalTextEncoder, KeywordLabeler, aggregate_votes, clean_note, + ) + + notes = [clean_note(text) for text in raw_notes] + encoder = ClinicalTextEncoder( + "bionlp/bluebert_pubmed_mimic_uncased_L-12_H-768_A-12" + ) + labeler = KeywordLabeler(encoder, top_k=300).fit(notes, descriptions) + votes = labeler.transform(notes) + weak_labels, covered = aggregate_votes(votes, len(descriptions)) + # Build a sample dataset with "embedding" and "weak_labels" tensor fields, then: + model = KeyClass(dataset, input_dim=768, category_ids=list(descriptions)) + model.fit_input_standardization(embeddings) + +Model +----- + +.. autoclass:: pyhealth.models.KeyClass + :members: + :undoc-members: + :show-inheritance: + +Weak supervision +---------------- + +.. autoclass:: pyhealth.weak_supervision.KeywordLabeler + :members: + +.. autoclass:: pyhealth.weak_supervision.LabelingFunction + +.. autoclass:: pyhealth.weak_supervision.ClinicalTextEncoder + :members: + +.. autofunction:: pyhealth.weak_supervision.clean_note + +.. autofunction:: pyhealth.weak_supervision.nltk_english_stopwords + +.. autofunction:: pyhealth.weak_supervision.aggregate_votes + +.. autofunction:: pyhealth.weak_supervision.confident_balanced_mask + +.. autofunction:: pyhealth.weak_supervision.snorkel_memory_gb + +.. autofunction:: pyhealth.weak_supervision.vote_diagnostics diff --git a/examples/synthetic_icd9_keyclass.ipynb b/examples/synthetic_icd9_keyclass.ipynb new file mode 100644 index 0000000000..b5fa2bfafb --- /dev/null +++ b/examples/synthetic_icd9_keyclass.ipynb @@ -0,0 +1,1362 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "e1f2681b", + "metadata": {}, + "source": [ + "# KeyClass on synthetic discharge notes: ablation study\n", + "\n", + "**Paper:** Chufan Gao, Mononito Goswami, Jieshi Chen and Artur Dubrawski.\n", + "[Classifying Unstructured Clinical Notes via Automatic Weak Supervision](https://arxiv.org/abs/2206.12088v2).\n", + "MLHC 2022.\n", + "\n", + "KeyClass assigns diagnostic categories to clinical notes **without any labeled\n", + "notes**. It mines frequent phrases, matches each phrase to the closest category\n", + "description to create keyword rules, turns rule votes into soft weak labels, and\n", + "trains a multilabel classifier on document embeddings.\n", + "\n", + "This notebook runs the whole pipeline with PyHealth's `KeyClass` model and\n", + "`pyhealth.weak_supervision` on **synthetic** notes, so it needs no MIMIC access.\n", + "It then varies three settings and measures their effect on a held-out synthetic\n", + "test set:\n", + "\n", + "1. **n-gram range of the keyword rules** (single words vs phrases). This is the\n", + " ablation proposed for our reproduction; the paper does not report it.\n", + "2. **Rule budget** (`top_k` rules per category, and the authors' option to cap\n", + " it at the smallest category).\n", + "3. **Input standardization** of embeddings before the classifier.\n", + "\n", + "The last section documents our results on the real MIMIC-III data.\n", + "\n", + "**Setup:** install PyHealth and NLTK (`pip install -e . \"nltk~=3.9.1\"` from the\n", + "PyHealth repository), then run all cells (about one minute on a CPU). The first\n", + "cell downloads NLTK's stopword list if it is missing." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "1caaa159", + "metadata": { + "execution": { + "iopub.execute_input": "2026-11-27T18:44:57.075730Z", + "iopub.status.busy": "2026-11-27T18:44:57.075638Z", + "iopub.status.idle": "2026-11-27T18:44:57.081784Z", + "shell.execute_reply": "2026-11-27T18:44:57.081270Z" + } + }, + "outputs": [], + "source": [ + "# Author: Amin Torabi\n", + "# Paper title: Classifying Unstructured Clinical Notes via Automatic Weak Supervision\n", + "# Paper link: https://arxiv.org/abs/2206.12088v2\n", + "# Description: KeyClass ablations (rule n-grams, rule budget, input\n", + "# standardization) on synthetic discharge notes.\n", + "\n", + "import warnings\n", + "\n", + "# Set before other imports. NumPy 2.2 with Apple Accelerate reports false\n", + "# divide/overflow warnings from correct matrix products, and NLTK's progress bar\n", + "# warns at import when ipywidgets is missing.\n", + "warnings.filterwarnings(\"ignore\", message=\".*encountered in matmul\")\n", + "warnings.filterwarnings(\"ignore\", message=\"IProgress not found\")" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "4a135ce0", + "metadata": { + "execution": { + "iopub.execute_input": "2026-11-27T18:44:57.083485Z", + "iopub.status.busy": "2026-11-27T18:44:57.083374Z", + "iopub.status.idle": "2026-11-27T18:45:01.561837Z", + "shell.execute_reply": "2026-11-27T18:45:01.561414Z" + } + }, + "outputs": [], + "source": [ + "import nltk\n", + "import numpy as np\n", + "import pandas as pd\n", + "import torch\n", + "from sklearn.feature_extraction.text import HashingVectorizer\n", + "from sklearn.metrics import roc_auc_score\n", + "\n", + "from pyhealth.datasets import create_sample_dataset, get_dataloader\n", + "from pyhealth.models import KeyClass\n", + "from pyhealth.weak_supervision import (\n", + " KeywordLabeler,\n", + " aggregate_votes,\n", + " clean_note,\n", + " confident_balanced_mask,\n", + ")\n", + "\n", + "try:\n", + " nltk.corpus.stopwords.words(\"english\")\n", + "except LookupError:\n", + " nltk.download(\"stopwords\", quiet=True)" + ] + }, + { + "cell_type": "markdown", + "id": "dc5efe3b", + "metadata": {}, + "source": [ + "## Synthetic notes\n", + "\n", + "Six diagnostic categories stand in for the paper's 19 ICD-9 groups. Each has a\n", + "short description (the only supervision KeyClass gets) and a bank of phrases\n", + "used to write notes. Several phrases share a head word across categories\n", + "(\"heart **failure**\", \"respiratory **failure**\", \"renal **failure**\"; \"chronic\n", + "... **disease**\"), so a single word is ambiguous where the whole phrase is not.\n", + "\n", + "Each note has one to three true categories, drawn with uneven prevalence like\n", + "MIMIC-III. It mixes their phrases with filler sentences, MIMIC-style\n", + "de-identification placeholders (`[** ... **]`) and digits. In 30% of notes a\n", + "phrase from a category the note does **not** have appears in a negated or\n", + "family-history sentence (\"ruled out sepsis\"), which keyword rules cannot tell\n", + "apart from a real diagnosis. True labels are used only for evaluation." + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "9e1d39e6", + "metadata": { + "execution": { + "iopub.execute_input": "2026-11-27T18:45:01.563147Z", + "iopub.status.busy": "2026-11-27T18:45:01.562971Z", + "iopub.status.idle": "2026-11-27T18:45:01.589496Z", + "shell.execute_reply": "2026-11-27T18:45:01.589092Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "family history of sepsis. course complicated by coronary artery disease. vital signs stable on day 7 of admission. presented with cardiac arrest. physical exam notable for no acute distress. urinary tract infection managed medically. treated for hypothyroidism. known history of hypertension. follow up with dr [**Last Name (STitle) 123**] in 1 weeks. \n", + "\n", + "Labels per note: 2.86\n" + ] + }, + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
circulatoryrespiratorygenitourinaryinfectiousendocrinemental
prevalence0.720.440.390.270.690.34
\n", + "
" + ], + "text/plain": [ + " circulatory respiratory genitourinary infectious endocrine \\\n", + "prevalence 0.72 0.44 0.39 0.27 0.69 \n", + "\n", + " mental \n", + "prevalence 0.34 " + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "CATEGORIES = {\n", + " \"circulatory\": dict(\n", + " prevalence=0.70,\n", + " description=\"heart cardiac circulatory hypertension coronary artery atrial\",\n", + " phrases=[\n", + " \"heart failure\",\n", + " \"atrial fibrillation\",\n", + " \"coronary artery disease\",\n", + " \"hypertension\",\n", + " \"cardiac arrest\",\n", + " \"aortic stenosis\",\n", + " ],\n", + " ),\n", + " \"respiratory\": dict(\n", + " prevalence=0.45,\n", + " description=\"respiratory lung pulmonary pneumonia airway breathing\",\n", + " phrases=[\n", + " \"respiratory failure\",\n", + " \"pneumonia\",\n", + " \"pulmonary embolism\",\n", + " \"chronic obstructive pulmonary disease\",\n", + " \"pleural effusion\",\n", + " ],\n", + " ),\n", + " \"genitourinary\": dict(\n", + " prevalence=0.40,\n", + " description=\"kidney renal urinary bladder genitourinary\",\n", + " phrases=[\n", + " \"renal failure\",\n", + " \"acute kidney injury\",\n", + " \"urinary tract infection\",\n", + " \"chronic kidney disease\",\n", + " \"hydronephrosis\",\n", + " ],\n", + " ),\n", + " \"infectious\": dict(\n", + " prevalence=0.27,\n", + " description=\"infection sepsis bacterial viral organism\",\n", + " phrases=[\n", + " \"sepsis\",\n", + " \"bacteremia\",\n", + " \"clostridium difficile infection\",\n", + " \"septic shock\",\n", + " \"positive blood cultures\",\n", + " ],\n", + " ),\n", + " \"endocrine\": dict(\n", + " prevalence=0.65,\n", + " description=\"diabetes thyroid metabolic glucose insulin endocrine\",\n", + " phrases=[\n", + " \"diabetes mellitus\",\n", + " \"hypothyroidism\",\n", + " \"hyperlipidemia\",\n", + " \"insulin dependent diabetes\",\n", + " \"thyroid nodule\",\n", + " ],\n", + " ),\n", + " \"mental\": dict(\n", + " prevalence=0.30,\n", + " description=\"depression anxiety psychiatric alcohol substance mental\",\n", + " phrases=[\n", + " \"major depression\",\n", + " \"anxiety disorder\",\n", + " \"alcohol withdrawal\",\n", + " \"substance abuse\",\n", + " \"bipolar disorder\",\n", + " ],\n", + " ),\n", + "}\n", + "NAMES = list(CATEGORIES)\n", + "FILLER = [\n", + " \"patient was admitted to the [**Hospital1 18**] micu on [**2101-3-4**]\",\n", + " \"vital signs stable on day {n} of admission\",\n", + " \"follow up with dr [**Last Name (STitle) 123**] in {n} weeks\",\n", + " \"discharge medications reviewed with the patient and family\",\n", + " \"physical exam notable for no acute distress\",\n", + " \"labs were checked daily and electrolytes repleted\",\n", + " \"patient tolerated a regular diet and ambulated with physical therapy\",\n", + "]\n", + "MENTIONS = [\n", + " \"presented with {p}\",\n", + " \"known history of {p}\",\n", + " \"treated for {p}\",\n", + " \"course complicated by {p}\",\n", + " \"{p} managed medically\",\n", + "]\n", + "NOISE = [\"family history of {p}\", \"ruled out {p}\", \"no evidence of {p}\"]\n", + "\n", + "\n", + "def make_notes(n: int, seed: int) -> list[dict]:\n", + " # Returns n synthetic notes with text, a patient ID and multi-hot labels.\n", + " rng = np.random.default_rng(seed)\n", + " rows = []\n", + " for i in range(n):\n", + " labels = [c for c in NAMES if rng.random() < CATEGORIES[c][\"prevalence\"]]\n", + " labels = labels or [NAMES[rng.integers(len(NAMES))]]\n", + " picks = rng.choice(len(FILLER), rng.integers(3, 6), replace=False)\n", + " sentences = [FILLER[j].format(n=rng.integers(1, 9)) for j in picks]\n", + " for c in labels:\n", + " bank = CATEGORIES[c][\"phrases\"]\n", + " for p in rng.choice(bank, rng.integers(1, 4), replace=False):\n", + " template = MENTIONS[rng.integers(len(MENTIONS))]\n", + " sentences.append(template.format(p=p))\n", + " if rng.random() < 0.3:\n", + " others = [c for c in NAMES if c not in labels] or NAMES\n", + " bank = CATEGORIES[others[rng.integers(len(others))]][\"phrases\"]\n", + " noise = NOISE[rng.integers(len(NOISE))]\n", + " sentences.append(noise.format(p=bank[rng.integers(len(bank))]))\n", + " rng.shuffle(sentences)\n", + " rows.append(\n", + " {\n", + " \"patient_id\": f\"s{seed}-p{i}\",\n", + " \"text\": \". \".join(sentences) + \".\",\n", + " \"labels\": [int(c in labels) for c in NAMES],\n", + " }\n", + " )\n", + " return rows\n", + "\n", + "\n", + "example = make_notes(600, seed=1)\n", + "print(example[0][\"text\"], \"\\n\")\n", + "gold = np.array([r[\"labels\"] for r in example])\n", + "print(f\"Labels per note: {gold.sum(1).mean():.2f}\")\n", + "pd.Series(gold.mean(0).round(2), index=NAMES, name=\"prevalence\").to_frame().T" + ] + }, + { + "cell_type": "markdown", + "id": "0e628802", + "metadata": {}, + "source": [ + "## Encoder\n", + "\n", + "The paper embeds phrases, descriptions and notes with BlueBERT. To keep this\n", + "notebook offline and fast, a hashed **character n-gram** encoder stands in for\n", + "it: phrases that share character sequences with a description score as\n", + "similar. It has no clinical knowledge, so the numbers below show how the\n", + "pipeline's settings behave, not clinical accuracy. For real notes, use\n", + "`pyhealth.weak_supervision.ClinicalTextEncoder` with a BlueBERT checkpoint\n", + "instead; nothing else changes." + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "d0140be5", + "metadata": { + "execution": { + "iopub.execute_input": "2026-11-27T18:45:01.590347Z", + "iopub.status.busy": "2026-11-27T18:45:01.590302Z", + "iopub.status.idle": "2026-11-27T18:45:01.592048Z", + "shell.execute_reply": "2026-11-27T18:45:01.591643Z" + } + }, + "outputs": [], + "source": [ + "class CharNgramEncoder:\n", + " # Offline stand-in for BlueBERT: hashed character 3-5 grams.\n", + "\n", + " def __init__(self, n_features: int = 2**12) -> None:\n", + " self.vectorizer = HashingVectorizer(\n", + " analyzer=\"char_wb\",\n", + " ngram_range=(3, 5),\n", + " n_features=n_features,\n", + " alternate_sign=False,\n", + " )\n", + "\n", + " def encode(self, texts: list[str]) -> np.ndarray:\n", + " return self.vectorizer.transform(list(texts)).toarray().astype(np.float32)" + ] + }, + { + "cell_type": "markdown", + "id": "177e72f4", + "metadata": {}, + "source": [ + "## Pipeline and metrics\n", + "\n", + "`run_keyclass` performs one complete run without gold labels:\n", + "\n", + "1. clean the notes and fit `KeywordLabeler` on the training notes and the six\n", + " descriptions (phrases kept only if they occur in more than 1% of notes);\n", + "2. vote with the rules and aggregate votes by majority (`aggregate_votes`);\n", + "3. select confident covered notes (`confident_balanced_mask`) and weight each\n", + " note's loss by its weak-label confidence;\n", + "4. train PyHealth's `KeyClass` for 20 epochs on the note embeddings;\n", + "5. predict a category when its score is at least 1/6 (the uniform share,\n", + " fixed in advance, as in our MIMIC-III runs).\n", + "\n", + "The paper also self-trains the classifier on its own sharpened predictions.\n", + "This notebook stops before that step: on the full MIMIC-III run, self-training\n", + "collapsed the multilabel predictions (see the last section).\n", + "\n", + "Metrics follow the paper: **precision, recall and F1 averaged over test notes**\n", + "(Table 3), plus macro **AUROC** across categories, which measures ranking quality\n", + "independently of the threshold. **Weak-label AUROC** scores the rules' own soft\n", + "labels against the training notes' true labels, which separates the quality of\n", + "the weak supervision from what the classifier learns from it. Each setting is\n", + "run on three seeds; each seed draws a new synthetic training and test set." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "5435cdff", + "metadata": { + "execution": { + "iopub.execute_input": "2026-11-27T18:45:01.592803Z", + "iopub.status.busy": "2026-11-27T18:45:01.592755Z", + "iopub.status.idle": "2026-11-27T18:45:01.596656Z", + "shell.execute_reply": "2026-11-27T18:45:01.596354Z" + } + }, + "outputs": [], + "source": [ + "def sample_prf(pred: np.ndarray, gold: np.ndarray) -> tuple[float, float, float]:\n", + " # Precision, recall and F1 per note, averaged over notes (paper footnote 4).\n", + " hits = (pred & (gold == 1)).sum(1)\n", + " n_pred = pred.sum(1)\n", + " p = np.divide(hits, n_pred, out=np.zeros(len(gold)), where=n_pred > 0)\n", + " r = hits / gold.sum(1)\n", + " f = np.divide(2 * p * r, p + r, out=np.zeros(len(gold)), where=(p + r) > 0)\n", + " return p.mean(), r.mean(), f.mean()\n", + "\n", + "\n", + "def macro_auroc(scores: np.ndarray, gold: np.ndarray) -> float:\n", + " return float(\n", + " np.mean(\n", + " [\n", + " roc_auc_score(gold[:, c], scores[:, c])\n", + " for c in range(gold.shape[1])\n", + " if 0 < gold[:, c].sum() < len(gold)\n", + " ]\n", + " )\n", + " )\n", + "\n", + "\n", + "def run_keyclass(\n", + " seed: int,\n", + " ngram_range: tuple[int, int] = (1, 3),\n", + " top_k: int = 30,\n", + " equalize_top_k: bool = False,\n", + " standardize: bool = True,\n", + " epochs: int = 20,\n", + ") -> dict:\n", + " # One label-free KeyClass run on a fresh synthetic train/test split.\n", + " train = make_notes(600, seed=2 * seed + 1)\n", + " test = make_notes(300, seed=2 * seed + 2)\n", + " torch.manual_seed(seed)\n", + " encoder = CharNgramEncoder()\n", + " descriptions = {c: CATEGORIES[c][\"description\"] for c in NAMES}\n", + " train_text = [clean_note(r[\"text\"]) for r in train]\n", + " test_text = [clean_note(r[\"text\"]) for r in test]\n", + "\n", + " labeler = KeywordLabeler(\n", + " encoder,\n", + " top_k=top_k,\n", + " ngram_range=ngram_range,\n", + " min_df=0.01,\n", + " equalize_top_k=equalize_top_k,\n", + " ).fit(train_text, descriptions)\n", + " weak, covered = aggregate_votes(labeler.transform(train_text), len(NAMES))\n", + " confident = confident_balanced_mask(weak, covered, max_num=len(train))\n", + "\n", + " x_train, x_test = encoder.encode(train_text), encoder.encode(test_text)\n", + " samples = [\n", + " {\n", + " \"patient_id\": train[i][\"patient_id\"],\n", + " \"embedding\": x_train[i].tolist(),\n", + " \"weak_labels\": weak[i].tolist(),\n", + " \"sample_weight\": float(weak[i].max()),\n", + " }\n", + " for i in np.flatnonzero(confident)\n", + " ]\n", + " dataset = create_sample_dataset(\n", + " samples=samples,\n", + " input_schema={\"embedding\": \"tensor\", \"sample_weight\": \"tensor\"},\n", + " output_schema={\"weak_labels\": \"tensor\"},\n", + " )\n", + " model = KeyClass(dataset, input_dim=x_train.shape[1], category_ids=NAMES)\n", + " if standardize:\n", + " model.fit_input_standardization(x_train)\n", + " optimizer = torch.optim.Adam(model.parameters(), lr=1.5e-3)\n", + " loader = get_dataloader(dataset, batch_size=64, shuffle=True)\n", + " for _ in range(epochs):\n", + " model.train()\n", + " for batch in loader:\n", + " optimizer.zero_grad()\n", + " model(**batch)[\"loss\"].backward()\n", + " optimizer.step()\n", + "\n", + " model.eval()\n", + " with torch.no_grad():\n", + " scores = model(embedding=torch.as_tensor(x_test))[\"y_prob\"].numpy()\n", + " gold_train = np.array([r[\"labels\"] for r in train])\n", + " gold_test = np.array([r[\"labels\"] for r in test])\n", + " precision, recall, f1 = sample_prf(scores >= 1 / len(NAMES), gold_test)\n", + " return {\n", + " \"rules\": len(labeler.lfs_),\n", + " \"weak_label_auroc\": macro_auroc(weak, gold_train),\n", + " \"precision\": precision,\n", + " \"recall\": recall,\n", + " \"f1\": f1,\n", + " \"auroc\": macro_auroc(scores, gold_test),\n", + " \"labeler\": labeler,\n", + " }\n", + "\n", + "\n", + "def ablate(settings: dict[str, dict], seeds=(0, 1, 2)) -> pd.DataFrame:\n", + " # Runs every setting on every seed; returns mean and std per setting.\n", + " rows = []\n", + " for name, kwargs in settings.items():\n", + " for seed in seeds:\n", + " result = run_keyclass(seed, **kwargs)\n", + " result.pop(\"labeler\")\n", + " rows.append({\"setting\": name, **result})\n", + " metrics = [\"rules\", \"weak_label_auroc\", \"precision\", \"recall\", \"f1\", \"auroc\"]\n", + " table = pd.DataFrame(rows).groupby(\"setting\", sort=False)[metrics]\n", + " return table.agg([\"mean\", \"std\"]).round(3)" + ] + }, + { + "cell_type": "markdown", + "id": "3eb05ddb", + "metadata": {}, + "source": [ + "### One baseline run\n", + "\n", + "Settings: rules from 1-3 grams, 30 rules per category, standardized embeddings.\n", + "The table lists each category's highest-scoring rules." + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "f685ee3d", + "metadata": { + "execution": { + "iopub.execute_input": "2026-11-27T18:45:01.597571Z", + "iopub.status.busy": "2026-11-27T18:45:01.597519Z", + "iopub.status.idle": "2026-11-27T18:45:02.113756Z", + "shell.execute_reply": "2026-11-27T18:45:02.113391Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "{'rules': 180, 'weak_label_auroc': 0.896, 'precision': np.float64(0.929), 'recall': np.float64(0.748), 'f1': np.float64(0.801), 'auroc': 0.912}\n" + ] + }, + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
circulatoryrespiratorygenitourinaryinfectiousendocrinemental
0coronary arteryrespiratoryurinaryinfectioninsulin dependent diabetesdepression
1history coronary arterypulmonaryurinary tractinfection vitaldiabetessubstance
2hypertensionhistory pulmonaryhistory urinarysepsisthyroiddepression known
3history hypertensionhistory pneumoniatreated urinarytract infectioninsulinmajor depression
4hypertension labshistory respiratorypresented urinaryinfection knowndiabetes labsdepression managed
5known history hypertensionpneumoniahistory urinary tractinfection vital signshistory diabetesdepression patient
\n", + "
" + ], + "text/plain": [ + " circulatory respiratory genitourinary \\\n", + "0 coronary artery respiratory urinary \n", + "1 history coronary artery pulmonary urinary tract \n", + "2 hypertension history pulmonary history urinary \n", + "3 history hypertension history pneumonia treated urinary \n", + "4 hypertension labs history respiratory presented urinary \n", + "5 known history hypertension pneumonia history urinary tract \n", + "\n", + " infectious endocrine mental \n", + "0 infection insulin dependent diabetes depression \n", + "1 infection vital diabetes substance \n", + "2 sepsis thyroid depression known \n", + "3 tract infection insulin major depression \n", + "4 infection known diabetes labs depression managed \n", + "5 infection vital signs history diabetes depression patient " + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "baseline = run_keyclass(seed=0)\n", + "labeler = baseline.pop(\"labeler\")\n", + "top_rules = {\n", + " c: [lf.phrase for lf in labeler.lfs_ if lf.category_index == i][:6]\n", + " for i, c in enumerate(NAMES)\n", + "}\n", + "print({k: round(v, 3) for k, v in baseline.items()})\n", + "pd.DataFrame(top_rules)" + ] + }, + { + "cell_type": "markdown", + "id": "b993ea1e", + "metadata": {}, + "source": [ + "## Ablation 1: single words vs phrases as rules\n", + "\n", + "Our proposal's hypothesis: phrases give more specific supervision than single\n", + "words, despite covering fewer notes. With `ngram_range=(1, 1)`, a rule like\n", + "\"failure\" must vote for one category even though heart, respiratory and renal\n", + "failure belong to three." + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "id": "b5343d55", + "metadata": { + "execution": { + "iopub.execute_input": "2026-11-27T18:45:02.114655Z", + "iopub.status.busy": "2026-11-27T18:45:02.114590Z", + "iopub.status.idle": "2026-11-27T18:45:06.245669Z", + "shell.execute_reply": "2026-11-27T18:45:06.245325Z" + } + }, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
rulesweak_label_aurocprecisionrecallf1auroc
meanstdmeanstdmeanstdmeanstdmeanstdmeanstd
setting
1-grams93.00.00.7460.0090.5140.0030.9440.0380.6400.0090.6780.015
1-2 grams180.00.00.9090.0040.7630.0400.8200.0160.7570.0270.9080.013
1-3 grams (paper)180.00.00.8960.0100.9250.0150.7430.0070.7930.0150.9100.009
\n", + "
" + ], + "text/plain": [ + " rules weak_label_auroc precision recall \\\n", + " mean std mean std mean std mean \n", + "setting \n", + "1-grams 93.0 0.0 0.746 0.009 0.514 0.003 0.944 \n", + "1-2 grams 180.0 0.0 0.909 0.004 0.763 0.040 0.820 \n", + "1-3 grams (paper) 180.0 0.0 0.896 0.010 0.925 0.015 0.743 \n", + "\n", + " f1 auroc \n", + " std mean std mean std \n", + "setting \n", + "1-grams 0.038 0.640 0.009 0.678 0.015 \n", + "1-2 grams 0.016 0.757 0.027 0.908 0.013 \n", + "1-3 grams (paper) 0.007 0.793 0.015 0.910 0.009 " + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "ablate(\n", + " {\n", + " \"1-grams\": dict(ngram_range=(1, 1)),\n", + " \"1-2 grams\": dict(ngram_range=(1, 2)),\n", + " \"1-3 grams (paper)\": dict(ngram_range=(1, 3)),\n", + " }\n", + ")" + ] + }, + { + "cell_type": "markdown", + "id": "9cc5cfa4", + "metadata": {}, + "source": [ + "## Ablation 2: rule budget\n", + "\n", + "`top_k` sets how many rules each category keeps; the authors' default is 300.\n", + "Their code can also cap every category at the size of the smallest category's\n", + "phrase pool (`equalize_top_k=True`). On a 1,000-note MIMIC-III sample that cap\n", + "cut every category to 22 rules and weakened the labels; here we vary the budget\n", + "directly." + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "id": "3bfef00c", + "metadata": { + "execution": { + "iopub.execute_input": "2026-11-27T18:45:06.246666Z", + "iopub.status.busy": "2026-11-27T18:45:06.246611Z", + "iopub.status.idle": "2026-11-27T18:45:13.484572Z", + "shell.execute_reply": "2026-11-27T18:45:13.484099Z" + } + }, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
rulesweak_label_aurocprecisionrecallf1auroc
meanstdmeanstdmeanstdmeanstdmeanstdmeanstd
setting
top_k=1060.00.0000.8310.0050.8870.0190.6570.0140.7220.0180.8560.009
top_k=30180.00.0000.8960.0100.9250.0150.7430.0070.7930.0150.9100.009
top_k=100600.00.0000.8900.0050.6520.0230.8390.0240.7050.0070.8660.017
top_k=300 (authors' default)1152.06.5570.8020.0060.5220.0060.9700.0040.6510.0050.7510.023
top_k=300, capped at smallest pool764.039.9500.8610.0060.6530.0280.8460.0400.7100.0080.8400.023
\n", + "
" + ], + "text/plain": [ + " rules weak_label_auroc \\\n", + " mean std mean std \n", + "setting \n", + "top_k=10 60.0 0.000 0.831 0.005 \n", + "top_k=30 180.0 0.000 0.896 0.010 \n", + "top_k=100 600.0 0.000 0.890 0.005 \n", + "top_k=300 (authors' default) 1152.0 6.557 0.802 0.006 \n", + "top_k=300, capped at smallest pool 764.0 39.950 0.861 0.006 \n", + "\n", + " precision recall f1 \\\n", + " mean std mean std mean \n", + "setting \n", + "top_k=10 0.887 0.019 0.657 0.014 0.722 \n", + "top_k=30 0.925 0.015 0.743 0.007 0.793 \n", + "top_k=100 0.652 0.023 0.839 0.024 0.705 \n", + "top_k=300 (authors' default) 0.522 0.006 0.970 0.004 0.651 \n", + "top_k=300, capped at smallest pool 0.653 0.028 0.846 0.040 0.710 \n", + "\n", + " auroc \n", + " std mean std \n", + "setting \n", + "top_k=10 0.018 0.856 0.009 \n", + "top_k=30 0.015 0.910 0.009 \n", + "top_k=100 0.007 0.866 0.017 \n", + "top_k=300 (authors' default) 0.005 0.751 0.023 \n", + "top_k=300, capped at smallest pool 0.008 0.840 0.023 " + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "ablate(\n", + " {\n", + " \"top_k=10\": dict(top_k=10),\n", + " \"top_k=30\": dict(top_k=30),\n", + " \"top_k=100\": dict(top_k=100),\n", + " \"top_k=300 (authors' default)\": dict(top_k=300),\n", + " \"top_k=300, capped at smallest pool\": dict(top_k=300, equalize_top_k=True),\n", + " }\n", + ")" + ] + }, + { + "cell_type": "markdown", + "id": "45e9dde2", + "metadata": {}, + "source": [ + "## Ablation 3: input standardization\n", + "\n", + "Mean-pooled BlueBERT vectors of different notes point in almost the same\n", + "direction (average cosine similarity about 0.94 on MIMIC-III), and our\n", + "classifier trained on them raw gave nearly the same scores to every note.\n", + "`KeyClass.fit_input_standardization` stores each dimension's mean and spread\n", + "from the unlabeled training embeddings and rescales every input. The paper and\n", + "the authors' code feed raw embeddings." + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "id": "3bebd32e", + "metadata": { + "execution": { + "iopub.execute_input": "2026-11-27T18:45:13.485507Z", + "iopub.status.busy": "2026-11-27T18:45:13.485451Z", + "iopub.status.idle": "2026-11-27T18:45:16.387418Z", + "shell.execute_reply": "2026-11-27T18:45:16.387084Z" + } + }, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
rulesweak_label_aurocprecisionrecallf1auroc
meanstdmeanstdmeanstdmeanstdmeanstdmeanstd
setting
raw embeddings (paper)180.00.00.8960.010.8220.0240.6650.0220.6930.0240.8010.021
standardized180.00.00.8960.010.9250.0150.7430.0070.7930.0150.9100.009
\n", + "
" + ], + "text/plain": [ + " rules weak_label_auroc precision \\\n", + " mean std mean std mean std \n", + "setting \n", + "raw embeddings (paper) 180.0 0.0 0.896 0.01 0.822 0.024 \n", + "standardized 180.0 0.0 0.896 0.01 0.925 0.015 \n", + "\n", + " recall f1 auroc \n", + " mean std mean std mean std \n", + "setting \n", + "raw embeddings (paper) 0.665 0.022 0.693 0.024 0.801 0.021 \n", + "standardized 0.743 0.007 0.793 0.015 0.910 0.009 " + ] + }, + "execution_count": 9, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "ablate(\n", + " {\n", + " \"raw embeddings (paper)\": dict(standardize=False),\n", + " \"standardized\": dict(standardize=True),\n", + " }\n", + ")" + ] + }, + { + "cell_type": "markdown", + "id": "cb86aa12", + "metadata": {}, + "source": [ + "## Findings on synthetic data\n", + "\n", + "Means over three seeds; each seed is a new synthetic training and test set.\n", + "\n", + "| Ablation | Setting | Weak-label AUROC | Test F1 | Test AUROC |\n", + "|---|---|---|---|---|\n", + "| Rule n-grams | 1-grams | 0.746 | 0.640 | 0.678 |\n", + "| | 1-2 grams | 0.909 | 0.757 | 0.908 |\n", + "| | **1-3 grams (paper)** | 0.896 | **0.793** | **0.910** |\n", + "| Rule budget | top_k=10 | 0.831 | 0.722 | 0.856 |\n", + "| | **top_k=30** | 0.896 | **0.793** | **0.910** |\n", + "| | top_k=100 | 0.890 | 0.705 | 0.866 |\n", + "| | top_k=300 (authors' default) | 0.802 | 0.651 | 0.751 |\n", + "| | top_k=300, capped at smallest pool | 0.861 | 0.710 | 0.840 |\n", + "| Input | raw embeddings (paper) | 0.896 | 0.693 | 0.801 |\n", + "| | **standardized** | 0.896 | **0.793** | **0.910** |\n", + "\n", + "1. **Phrases beat single words.** With 1-gram rules, words shared across\n", + " categories (\"failure\", \"disease\", \"chronic\") must vote for a single category,\n", + " and weak-label AUROC drops from 0.90 to 0.75; test F1 drops from 0.79 to\n", + " 0.64. This supports our proposal's hypothesis. The synthetic notes were\n", + " built with shared head words, so this shows the mechanism rather than its\n", + " size on real notes.\n", + "2. **The rule budget has a sweet spot.** Too few rules (10 per category) miss\n", + " notes (recall 0.66); too many add low-quality rules built from filler text,\n", + " and with 300 per category almost every candidate phrase becomes a rule\n", + " (F1 0.65). Capping at the smallest category trims those rules here, but on a\n", + " 1,000-note MIMIC-III sample the same cap left only 22 rules per category and\n", + " hurt. The right\n", + " budget depends on how many good phrases each category has, so the authors'\n", + " default of 300 is not a universal choice.\n", + "3. **Standardizing embeddings helps the classifier.** The weak labels are\n", + " identical in both rows, yet F1 rises from 0.69 to 0.79 and AUROC from 0.80\n", + " to 0.91, matching what we saw with BlueBERT on MIMIC-III.\n", + "\n", + "These numbers come from a character n-gram encoder and simple synthetic notes.\n", + "They show how the settings act on the pipeline, not clinical performance." + ] + }, + { + "cell_type": "markdown", + "id": "458b6be3", + "metadata": {}, + "source": [ + "## Results on MIMIC-III\n", + "\n", + "We applied the same pipeline to MIMIC-III v1.4 discharge summaries with the 19\n", + "ICD-9 categories of the paper's Table 4, using BlueBERT\n", + "(`bionlp/bluebert_pubmed_mimic_uncased_L-12_H-768_A-12`) embeddings. Data:\n", + "52,714 admissions from 41,118 patients, split 75/25 by patient (39,443 training,\n", + "13,271 test). Labels: 5.8 categories per admission on average; symptom codes\n", + "780-799 have no Table 4 category and were excluded. PyHealth's\n", + "`MIMIC3ICD9CategoryClassification` task builds the same kind of cohort (one\n", + "sample per admission with its discharge summary and 19-category labels), so\n", + "it is the starting point for running this pipeline on MIMIC-III in PyHealth.\n", + "\n", + "**How these numbers were produced.** MIMIC-III requires credentialed PhysioNet\n", + "access and may not be redistributed, so these runs cannot be repeated from this\n", + "notebook. We ran them offline with our course reproduction scripts, which are\n", + "not part of this PR: one builds the cohort and the patient-level split from the\n", + "MIMIC-III CSV files, one runs the pipeline, and one computes the metrics and\n", + "bootstrap intervals. The pipeline script runs the same steps as this notebook\n", + "with a standalone copy of this PR's weak-supervision and model code, and adds\n", + "the paper's self-training step. The numbers below are copied from its output\n", + "files.\n", + "\n", + "**Full run.** All 39,443 training notes; phrases kept if they occur in more\n", + "than 0.1% of notes (the paper's threshold), giving 157,636 candidates and\n", + "5,679 rules (up to 300 per category) that cover 99.5% of notes. Majority-vote weak\n", + "labels; 6,481 confident notes for initial training; standardized embeddings;\n", + "20 epochs; then 98 rounds of self-training. A category is predicted when its\n", + "score is at least 1/19, a rule fixed before training. Training took about\n", + "19 minutes on one GPU.\n", + "\n", + "**Held-out test set, all 13,271 notes:**\n", + "\n", + "| Method | Precision | Recall | F1 [95% CI] | Labels/note | Macro AUROC |\n", + "|---|---|---|---|---|---|\n", + "| **KeyClass, ours, before self-training** | 0.436 | 0.660 | **0.493** [0.490, 0.496] | 8.8 | 0.668 |\n", + "| KeyClass, ours, after self-training | 0.652 | 0.179 | 0.260 [0.257, 0.264] | 1.5 | 0.650 |\n", + "| KeyClass, ours, 1,000-note sample, after self-training | 0.353 | 0.754 | 0.456 [0.454, 0.458] | 12.4 | 0.610 |\n", + "| Categories with training prevalence of at least 50% (uses gold labels) | 0.663 | 0.381 | 0.456 [0.453, 0.460] | 3.0 | - |\n", + "| KeyClass, paper Table 3 | 0.507 | 0.896 | 0.625 | - | - |\n", + "\n", + "1. **More training data helps.** Going from 1,000 to 39,443 training notes\n", + " raised F1 from 0.456 to 0.493 and AUROC from 0.61 to 0.67. Before\n", + " self-training, the model beats the prevalence baseline, whose intervals do\n", + " not overlap with ours, but stays below the paper's 0.625.\n", + "2. **Self-training collapsed the multilabel predictions.** Following the paper,\n", + " self-training sharpens each note's scores as one distribution over\n", + " categories. Repeated for 98 rounds, it moved almost all of each note's\n", + " weight onto one category: on training notes the median top score reached\n", + " 0.98, and test predictions fell to 1.5 categories per note (true notes have 5.8), and recall dropped\n", + " from 0.66 to 0.18. With only 2 rounds on the 1,000-note sample the effect\n", + " did not show. The paper's self-training results (its Table 6) are on\n", + " single-label datasets; for this multilabel task we report the model before\n", + " self-training as our main result. We did not tune the number of rounds,\n", + " because choosing it from test results would leak test information.\n", + "3. **Per category** (before self-training, against the paper's Table 4), we do\n", + " better on neoplasms (F1 0.32 vs 0.03), perinatal conditions (0.87 vs 0.00)\n", + " and infectious diseases (0.50 vs 0.49), and worse on circulatory (0.70 vs\n", + " 0.92), endocrine (0.71 vs 0.86), supplementary V codes (0.69 vs 0.83) and\n", + " external causes (0.52 vs 0.61).\n", + "\n", + "**Diagnostics on a 1,000-note training sample** (gold labels used only to\n", + "measure, before the full run):\n", + "\n", + "- Capping the rule budget at the smallest category left 22 rules per category,\n", + " because in BlueBERT space External causes won only 22 phrases. Removing the\n", + " cap (300 per category) raised weak-label AUROC from 0.57 to 0.70. On the full\n", + " training set every category reached about 300 rules, and External causes went\n", + " from F1 0.00 on the sample to 0.52.\n", + "- Standardizing embeddings raised classifier F1 from 0.37 to 0.47 (mean of\n", + " three seeds) and made results stable across seeds.\n", + "\n", + "**Not done:** the 1-gram vs 1-3-gram ablation on MIMIC-III. The n-gram\n", + "comparison in this notebook is on synthetic notes only." + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "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.15" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/pyhealth/models/__init__.py b/pyhealth/models/__init__.py index e54a5616bf..e6a2e23f79 100644 --- a/pyhealth/models/__init__.py +++ b/pyhealth/models/__init__.py @@ -56,6 +56,7 @@ from .joint_seq_image import ( JointSeqImage as JointSeqImage, ) +from .keyclass import KeyClass as KeyClass from .logistic_regression import LogisticRegression from .concept_bottleneck import ( ConceptBottleneckModel as ConceptBottleneckModel, diff --git a/pyhealth/models/keyclass.py b/pyhealth/models/keyclass.py new file mode 100644 index 0000000000..bcf7d559be --- /dev/null +++ b/pyhealth/models/keyclass.py @@ -0,0 +1,240 @@ +# Author: Amin Torabi +# Paper title: Classifying Unstructured Clinical Notes via Automatic Weak Supervision +# Paper link: https://arxiv.org/abs/2206.12088v2 +# Description: Multilabel MLP trained on fixed clinical text embeddings. + +from collections.abc import Hashable, Sequence +from typing import Any + +import numpy as np +import torch +from torch import nn + +from pyhealth.datasets import SampleDataset +from pyhealth.processors import LabelProcessor, MultiLabelProcessor + +from .base_model import BaseModel + + +class KeyClass(BaseModel): + """KeyClass downstream classifier for weakly labeled clinical notes. + + Paper: Chufan Gao, Mononito Goswami, Jieshi Chen and Artur Dubrawski. + Classifying Unstructured Clinical Notes via Automatic Weak Supervision. + MLHC 2022. https://arxiv.org/abs/2206.12088v2 + + A four-linear-layer MLP (LeakyReLU and dropout after each hidden layer) that + maps frozen document embeddings to one score per category. It is trained + with binary cross-entropy on the soft weak labels produced by + :class:`pyhealth.weak_supervision.KeywordLabeler` and + :func:`pyhealth.weak_supervision.aggregate_votes`, so no gold labels are + needed. Embeddings are computed outside the model, which allows any encoder + and caching; encoder fine-tuning is not included. + + Both the embedding and the soft-label fields must use the ``"tensor"`` + processor: a multilabel token processor would read probability values as + category tokens. ``category_ids`` fixes the output order regardless of + which categories appear in a batch. + + Inputs are standardized per dimension with stored statistics, which are the + identity until :meth:`fit_input_standardization` is called. Mean-pooled + BlueBERT vectors share one dominant direction, and the MLP trained on them + raw collapsed to near-constant scores. The statistics are buffers, so a + saved model scales new notes the same way. The paper and the authors' code + feed raw embeddings; this is a documented deviation. + + The loss uses the soft weak labels, but the returned ``"y_true"`` is + binary so that :class:`pyhealth.trainer.Trainer` can score it with the + multilabel metrics. When the batch has gold labels under ``gold_key``, + those are ``"y_true"``, so ``Trainer.evaluate`` reports agreement with the + gold labels. Otherwise ``"y_true"`` marks each category whose weak label + is at least ``1 / categories``, the paper's prediction threshold for scores + that sum to one, and the metrics measure agreement with the weak labels. + + Args: + dataset: The sample dataset the model is trained on. + input_dim: Dimension of the document embeddings. + category_ids: Category IDs in output order; at least two, unique. + hidden_dims: Widths of the hidden layers. + dropout: Dropout probability after each hidden layer. + feature_key: Batch field holding the embeddings. + label_key: Batch field holding the soft weak labels. + gold_key: Optional batch field holding gold 0/1 labels of shape + ``[batch, categories]`` in ``category_ids`` order. They are used + only as ``"y_true"`` for evaluation, never in the loss. + + Attributes: + network: The MLP mapping standardized embeddings to logits. + input_mean: Per-dimension mean subtracted from inputs. + input_scale: Per-dimension scale inputs are divided by. + + Raises: + ValueError: If there are fewer than two or duplicate category IDs, or a + layer dimension is not positive. + + Example: + >>> from pyhealth.datasets import create_sample_dataset, get_dataloader + >>> samples = [ + ... {"patient_id": "p0", "embedding": [0.1, 0.2], + ... "weak_labels": [1.0, 0.0]}, + ... {"patient_id": "p1", "embedding": [0.3, 0.1], + ... "weak_labels": [0.4, 0.6]}, + ... ] + >>> dataset = create_sample_dataset( + ... samples=samples, + ... input_schema={"embedding": "tensor"}, + ... output_schema={"weak_labels": "tensor"}, + ... ) + >>> model = KeyClass(dataset, input_dim=2, category_ids=["cardiac", "resp"]) + >>> _ = model.fit_input_standardization([[0.1, 0.2], [0.3, 0.1]]) + >>> batch = next(iter(get_dataloader(dataset, batch_size=2))) + >>> model(**batch)["y_prob"].shape + torch.Size([2, 2]) + """ + + def __init__( + self, + dataset: SampleDataset, + input_dim: int, + category_ids: Sequence[Hashable], + hidden_dims: Sequence[int] = (256, 128, 64), + dropout: float = 0.5, + feature_key: str = "embedding", + label_key: str = "weak_labels", + gold_key: str | None = None, + ) -> None: + super().__init__(dataset) + self.category_ids = tuple(category_ids) + if len(self.category_ids) < 2 or len(set(self.category_ids)) != len( + self.category_ids + ): + raise ValueError("Provide at least two unique category IDs in output order") + if input_dim < 1 or not hidden_dims or any(d < 1 for d in hidden_dims): + raise ValueError("Layer dimensions must be positive") + self._target_processor = MultiLabelProcessor(labels=self.category_ids) + self.feature_key, self.label_key = feature_key, label_key + self.gold_key = gold_key + self.feature_keys, self.label_keys = [feature_key], [label_key] + self.register_buffer("input_mean", torch.zeros(input_dim)) + self.register_buffer("input_scale", torch.ones(input_dim)) + layers = [] + for width in hidden_dims: + layers.extend( + [nn.Linear(input_dim, width), nn.LeakyReLU(), nn.Dropout(dropout)] + ) + input_dim = width + layers.append(nn.Linear(input_dim, len(self.category_ids))) + self.network = nn.Sequential(*layers) + + @property + def label_processors(self) -> dict[str, LabelProcessor]: + """Describes model outputs without tokenizing dense soft targets. + + The dataset keeps its tensor processor; this multilabel processor + supplies the mode, output size, loss and metrics ``BaseModel`` expects. + + Returns: + A mapping from ``label_key`` to the multilabel processor. + """ + return {self.label_key: self._target_processor} + + def fit_input_standardization( + self, embeddings: torch.Tensor | np.ndarray | Sequence[Sequence[float]] + ) -> "KeyClass": + """Stores the per-dimension mean and spread of training embeddings. + + Uses no labels. Constant dimensions keep a scale of 1. + + Args: + embeddings: Training embeddings of shape ``[notes, input_dim]``. + + Returns: + The model, for chaining. + + Raises: + ValueError: If the shape is wrong, there are fewer than two + embeddings, or values are not finite. + """ + embeddings = torch.as_tensor(embeddings, dtype=torch.float32) + if embeddings.ndim != 2 or embeddings.shape[1] != len(self.input_mean): + raise ValueError("Embeddings must have shape [notes, input_dim]") + if len(embeddings) < 2 or not torch.isfinite(embeddings).all(): + raise ValueError("Need at least two finite embeddings") + scale = embeddings.std(dim=0, unbiased=False) + with torch.no_grad(): + self.input_mean.copy_(embeddings.mean(dim=0)) + self.input_scale.copy_( + torch.where(scale > 0, scale, torch.ones_like(scale)) + ) + return self + + def forward(self, **kwargs: Any) -> dict[str, torch.Tensor]: + """Scores a batch and, when soft labels are given, computes the loss. + + Args: + **kwargs: A batch. ``kwargs[feature_key]`` holds embeddings of shape + ``[batch, input_dim]``. Optional ``kwargs[label_key]`` holds soft + labels in [0, 1] of shape ``[batch, categories]``. Optional + ``kwargs["sample_weight"]`` holds nonnegative per-note weights + of shape ``[batch]``; each note's loss is scaled by its weight, + as in the authors' noise-aware loss. Optional + ``kwargs[gold_key]`` holds gold 0/1 labels used as ``"y_true"``. + + Returns: + A dict with ``"logit"`` and ``"y_prob"`` (sigmoid scores), both of + shape ``[batch, categories]``. When soft labels are given it also + has the scalar ``"loss"`` and the binary ``"y_true"``: the gold + labels if present, otherwise the weak labels thresholded at + ``1 / categories``. + + Raises: + ValueError: If embeddings, labels or weights have the wrong shape, + soft labels are not finite probabilities, or gold labels are + not 0/1. + """ + embedding = torch.as_tensor( + kwargs[self.feature_key], dtype=torch.float32, device=self.device + ) + if embedding.ndim != 2: + raise ValueError("Embeddings must have shape [batch, dimension]") + logits = self.network((embedding - self.input_mean) / self.input_scale) + result = {"logit": logits, "y_prob": self.label_processor.activation(logits)} + if self.label_key in kwargs: + targets = torch.as_tensor( + kwargs[self.label_key], dtype=logits.dtype, device=self.device + ) + if ( + targets.shape != logits.shape + or not torch.isfinite(targets).all() + or ((targets < 0) | (targets > 1)).any() + ): + raise ValueError( + "Targets must match logits and contain probabilities in [0, 1]" + ) + weights = kwargs.get("sample_weight") + if weights is None: + loss = self.label_processor.loss(logits, targets) + else: + weights = torch.as_tensor( + weights, dtype=logits.dtype, device=self.device + ) + if weights.shape != logits.shape[:1] or (weights < 0).any(): + raise ValueError("sample_weight must be nonnegative, one per row") + per_note = self.label_processor.loss( + logits, targets, reduction="none" + ).mean(dim=1) + loss = (per_note * weights).mean() + if self.gold_key is not None and self.gold_key in kwargs: + y_true = torch.as_tensor( + kwargs[self.gold_key], dtype=logits.dtype, device=self.device + ) + if ( + y_true.shape != logits.shape + or not torch.isin(y_true, y_true.new_tensor([0.0, 1.0])).all() + ): + raise ValueError("Gold labels must match logits and be 0 or 1") + else: + threshold = 1 / len(self.category_ids) + y_true = (targets >= threshold).to(logits.dtype) + result.update(y_true=y_true, loss=loss) + return result diff --git a/pyhealth/weak_supervision/__init__.py b/pyhealth/weak_supervision/__init__.py new file mode 100644 index 0000000000..682fbfa73b --- /dev/null +++ b/pyhealth/weak_supervision/__init__.py @@ -0,0 +1,11 @@ +"""Automatic keyword supervision, independent of gold diagnosis labels.""" + +from .encoders import ClinicalTextEncoder as ClinicalTextEncoder +from .keyclass import KeywordLabeler as KeywordLabeler +from .keyclass import LabelingFunction as LabelingFunction +from .keyclass import aggregate_votes as aggregate_votes +from .keyclass import clean_note as clean_note +from .keyclass import confident_balanced_mask as confident_balanced_mask +from .keyclass import nltk_english_stopwords as nltk_english_stopwords +from .keyclass import snorkel_memory_gb as snorkel_memory_gb +from .keyclass import vote_diagnostics as vote_diagnostics diff --git a/pyhealth/weak_supervision/encoders.py b/pyhealth/weak_supervision/encoders.py new file mode 100644 index 0000000000..da7c2f7293 --- /dev/null +++ b/pyhealth/weak_supervision/encoders.py @@ -0,0 +1,94 @@ +"""Text encoders for KeyClass: ``encode(texts)`` returns a finite ``[N, D]`` array.""" + +from collections.abc import Iterable + +import numpy as np + + +class ClinicalTextEncoder: + """Frozen Hugging Face encoder with masked mean pooling. + + Embeds phrases, category descriptions and notes for KeyClass. Each text is + truncated to ``max_length`` tokens (special tokens included), and token + vectors are averaged over the attention mask. The KeyClass paper uses + BlueBERT; notes are truncated rather than reduced with the paper's TF-IDF + text selection. The model is loaded, and downloaded if needed, only when + the encoder is constructed. + + This is a small class rather than a call to + ``pyhealth.models.clip_stress_utils.encode_stress_prompts``, which does a + similar Hugging Face pass for a different model. That helper loads the + model on every call, averages over padding by default, and rejects empty + input. KeyClass encodes three sets of texts (phrases, descriptions and + notes) with one loaded model, needs padding excluded so the result does + not depend on batch size, and gets empty sets of phrases or notes. The + ``encode(texts)`` method is the only interface ``KeywordLabeler`` needs, + so any object with that method can replace this class. + + Args: + model_name: Hugging Face model ID or local snapshot directory, for + example ``"bionlp/bluebert_pubmed_mimic_uncased_L-12_H-768_A-12"``. + batch_size: Texts encoded per forward pass. + max_length: Maximum tokens per text, including special tokens. + device: Torch device, for example ``"cpu"``, ``"cuda"`` or ``"mps"``. + + Raises: + ValueError: If ``batch_size`` is not positive or ``max_length < 2``. + + Example: + >>> name = "bionlp/bluebert_pubmed_mimic_uncased_L-12_H-768_A-12" + >>> encoder = ClinicalTextEncoder(name) + >>> encoder.encode(["acute renal failure", "pneumonia"]).shape + (2, 768) + """ + + def __init__( + self, + model_name: str, + batch_size: int = 16, + max_length: int = 512, + device: str = "cpu", + ) -> None: + from transformers import AutoModel, AutoTokenizer + + if batch_size < 1 or max_length < 2: + raise ValueError("batch_size must be positive and max_length >= 2") + self.tokenizer = AutoTokenizer.from_pretrained(model_name) + self.model = AutoModel.from_pretrained(model_name).to(device).eval() + self.model.requires_grad_(False) + self.batch_size = batch_size + self.max_length = max_length + self.device = device + + def encode(self, texts: Iterable[str]) -> np.ndarray: + """Embeds texts with masked mean pooling. + + Args: + texts: Texts to embed. + + Returns: + A float32 array of shape ``[len(texts), hidden_size]``; empty input + gives shape ``[0, hidden_size]``. + """ + import torch + + texts = list(texts) + chunks = [] + with torch.inference_mode(): + for start in range(0, len(texts), self.batch_size): + tokens = self.tokenizer( + texts[start : start + self.batch_size], + padding=True, + truncation=True, + max_length=self.max_length, + return_tensors="pt", + ).to(self.device) + hidden = self.model(**tokens).last_hidden_state + mask = tokens["attention_mask"].unsqueeze(-1) + pooled = (hidden * mask).sum(1) / mask.sum(1).clamp_min(1) + chunks.append(pooled.cpu().numpy()) + return ( + np.concatenate(chunks) + if chunks + else np.empty((0, self.model.config.hidden_size), dtype=np.float32) + ) diff --git a/pyhealth/weak_supervision/keyclass.py b/pyhealth/weak_supervision/keyclass.py new file mode 100644 index 0000000000..6dd84ca35e --- /dev/null +++ b/pyhealth/weak_supervision/keyclass.py @@ -0,0 +1,517 @@ +# Author: Amin Torabi +# Paper title: Classifying Unstructured Clinical Notes via Automatic Weak Supervision +# Paper link: https://arxiv.org/abs/2206.12088v2 +# Description: Note cleaning, automatic phrase mining, labeling-function generation, +# categorical weak-label aggregation, and confident-sample selection. + +import math +import re +from collections.abc import Iterable, Mapping +from dataclasses import dataclass +from functools import lru_cache +from typing import Any, Protocol + +import numpy as np +from sklearn.feature_extraction.text import CountVectorizer +from sklearn.metrics.pairwise import cosine_similarity + +_DEID_PLACEHOLDER = re.compile(r"\[\*\*.*?\*\*\]", re.DOTALL) +_DIGITS = re.compile(r"\d+") +# CountVectorizer's default tokens are 2+ word characters. Stopwords that can never +# equal such a token ("a", "don't") have no effect, so dropping them changes nothing +# except silencing sklearn's inconsistent-stopword warning. +_TOKEN = re.compile(r"\w\w+") + + +class TextEncoder(Protocol): + """Any object that embeds texts, such as :class:`ClinicalTextEncoder`. + + Example: + >>> class LengthEncoder: + ... def encode(self, texts): + ... return np.array([[len(t), 1.0] for t in texts]) + >>> LengthEncoder().encode(["sepsis", "pneumonia"]).shape + (2, 2) + """ + + def encode(self, texts: list[str]) -> np.ndarray: + """Embeds texts. + + Args: + texts: Texts to embed. + + Returns: + A finite float array of shape ``[len(texts), dimension]``. + """ + ... + + +@lru_cache(maxsize=1) +def nltk_english_stopwords() -> tuple[str, ...]: + """Returns NLTK's English stopwords, as the KeyClass authors use them. + + The list is NLTK corpus data, installed separately from the package with + ``python -m nltk.downloader stopwords``, and it differs across NLTK releases. + Entries that can never match a ``CountVectorizer`` token (single letters, + contractions such as "don't") are dropped. The result is cached. + + Returns: + Sorted, unique stopwords. + + Raises: + ImportError: If NLTK is not installed. + LookupError: If the NLTK stopwords corpus has not been downloaded. + + Example: + >>> words = nltk_english_stopwords() + >>> "not" in words, "don't" in words + (True, False) + """ + try: + from nltk.corpus import stopwords + except ImportError as exc: + raise ImportError( + 'KeywordLabeler needs NLTK; pip install "nltk~=3.9.1"' + ) from exc + try: + words = stopwords.words("english") + except LookupError as exc: + raise LookupError( + "NLTK stopwords corpus not found; run: python -m nltk.downloader stopwords" + ) from exc + return tuple(sorted({w for w in words if _TOKEN.fullmatch(w)})) + + +def clean_note(text: str) -> str: + """Removes MIMIC de-identification placeholders and digits, then lowercases. + + Placeholders such as ``[**Hospital1 18**]`` otherwise become phrases like + "hospital1" or "namepattern1 md" that fire on nearly every note. The + authors' MIMIC loader also lowercases and strips digits before mining and + encoding. + + Args: + text: A raw clinical note. + + Returns: + The cleaned note with whitespace collapsed to single spaces. + + Example: + >>> clean_note("Seen at [**Hospital1 18**]. ASA 81 mg") + 'seen at . asa mg' + """ + text = _DEID_PLACEHOLDER.sub(" ", text) + text = _DIGITS.sub(" ", text.lower()) + return " ".join(text.split()) + + +@dataclass(frozen=True) +class LabelingFunction: + """A keyword rule: vote for one category whenever a phrase occurs. + + Attributes: + phrase: The mined n-gram that triggers the vote. + category_index: Column of the category it votes for, in + ``KeywordLabeler.category_ids_`` order. + similarity: Cosine similarity between the phrase and the category + description embeddings. + + Example: + >>> LabelingFunction("heart failure", category_index=0, similarity=0.82) + LabelingFunction(phrase='heart failure', category_index=0, similarity=0.82) + """ + + phrase: str + category_index: int + similarity: float + + +class KeywordLabeler: + """Builds KeyClass labeling functions from category descriptions alone. + + Mines frequent 1-3 grams from training notes, embeds them together with the + category descriptions, assigns each phrase to its most similar description, + and keeps the top ``top_k`` phrases per category as keyword rules. No gold + labels are used. + + Mining follows the authors' code: NLTK English stopwords and unicode accent + stripping inside ``CountVectorizer``, so stopwords are dropped before + n-grams are formed and negations ("no", "not") are not modeled. By default + each category keeps its own top ``top_k``, as the paper describes. + + Args: + encoder: Object with ``encode(texts) -> [len(texts), dimension]`` array. + top_k: Maximum rules kept per category. + ngram_range: Smallest and largest n-gram length to mine. + min_df: A float in (0, 1) keeps phrases in strictly more than + ``min_df * notes`` notes (the paper's rule); an int is an inclusive + minimum note count. + equalize_top_k: If True, caps ``top_k`` at the smallest nonempty + category pool (the authors' ``min_topk`` option). With raw BlueBERT + vectors one category can win only a few phrases, which then shrinks + every category's rule set. + max_candidates: If set, ``fit`` raises before encoding when mining finds + more candidate phrases than this. + + Attributes: + category_ids_: Category IDs in output column order, set by ``fit``. + lfs_: The fitted :class:`LabelingFunction` rules. + min_count_: Minimum note count implied by ``min_df``. + effective_top_k_: Rules kept per category after any equalization. + vectorizer_: The fitted ``CountVectorizer``. + + Raises: + ValueError: If ``top_k`` is not a positive integer. + + Example: + >>> from sklearn.feature_extraction.text import HashingVectorizer + >>> class CharEncoder: + ... def encode(self, texts): + ... vectorizer = HashingVectorizer( + ... analyzer="char_wb", ngram_range=(3, 4), n_features=256, + ... alternate_sign=False, + ... ) + ... return vectorizer.transform(texts).toarray() + 1e-3 + >>> notes = ["heart failure noted", "pneumonia on chest film", + ... "heart failure, pneumonia"] + >>> descriptions = {"cardiac": "heart cardiac", "resp": "pneumonia lung"} + >>> labeler = KeywordLabeler(CharEncoder(), top_k=2, min_df=1) + >>> labeler = labeler.fit(notes, descriptions) + >>> [(lf.phrase, lf.category_index) for lf in labeler.lfs_] + [('heart', 0), ('heart failure', 0), ('pneumonia', 1), ('pneumonia chest', 1)] + >>> labeler.transform(notes) # one column per rule; -1 means abstain + array([[ 0, 0, -1, -1], + [-1, -1, 1, 1], + [ 0, 0, 1, -1]]) + """ + + def __init__( + self, + encoder: TextEncoder, + top_k: int = 300, + ngram_range: tuple[int, int] = (1, 3), + min_df: float = 0.001, + equalize_top_k: bool = False, + max_candidates: int | None = None, + ) -> None: + if not isinstance(top_k, int) or top_k < 1: + raise ValueError("top_k must be a positive integer") + self.encoder = encoder + self.top_k = top_k + self.ngram_range = ngram_range + self.min_df = min_df + self.equalize_top_k = equalize_top_k + self.max_candidates = max_candidates + + def _min_count(self, n_texts: int) -> int: + """Converts ``min_df`` into an inclusive minimum note count. + + Args: + n_texts: Number of training notes. + + Returns: + The smallest note count a phrase needs to be kept. + + Raises: + ValueError: If ``min_df`` is neither a float in (0, 1) nor a + positive int. + """ + if isinstance(self.min_df, float): + if not 0 < self.min_df < 1: + raise ValueError("A float min_df must lie in (0, 1)") + return math.floor(self.min_df * n_texts) + 1 + if isinstance(self.min_df, int) and self.min_df >= 1: + return self.min_df + raise ValueError("min_df must be a float in (0, 1) or a positive int") + + def fit( + self, texts: Iterable[str], descriptions: Mapping[Any, str] + ) -> "KeywordLabeler": + """Mines phrases from training notes and builds the keyword rules. + + Args: + texts: Training notes, already cleaned (see :func:`clean_note`). + descriptions: Ordered mapping from category ID to description text. + Its order fixes the output columns. + + Returns: + The fitted labeler. + + Raises: + ValueError: If there are no notes, fewer than two categories, an + empty description, too many candidate phrases, or invalid + encoder output. + """ + texts = list(texts) + if not texts or len(descriptions) < 2: + raise ValueError("Need training notes and at least two categories") + if any(not isinstance(x, str) or not x.strip() for x in descriptions.values()): + raise ValueError("Category descriptions must be nonempty strings") + self.category_ids_ = tuple(descriptions) + self.min_count_ = self._min_count(len(texts)) + self.vectorizer_ = CountVectorizer( + ngram_range=self.ngram_range, + min_df=self.min_count_, + stop_words=list(nltk_english_stopwords()), + strip_accents="unicode", + ) + self.vectorizer_.fit(texts) + phrases = self.vectorizer_.get_feature_names_out() + if self.max_candidates is not None and len(phrases) > self.max_candidates: + raise ValueError( + f"{len(phrases)} candidate phrases exceed max_candidates=" + f"{self.max_candidates}; raise min_df for small samples" + ) + vectors = np.asarray( + self.encoder.encode(list(phrases) + list(descriptions.values())) + ) + if ( + vectors.ndim != 2 + or vectors.shape[0] != len(phrases) + len(descriptions) + or not np.isfinite(vectors).all() + or (np.linalg.norm(vectors, axis=1) == 0).any() + ): + raise ValueError( + "Encoder must return finite, nonzero vectors, one per text" + ) + scores = cosine_similarity(vectors[: len(phrases)], vectors[len(phrases) :]) + owners = scores.argmax(axis=1) + pools = np.bincount(owners, minlength=len(descriptions)) + k = self.top_k + if self.equalize_top_k and (pools > 0).any(): + k = min(k, int(pools[pools > 0].min())) + self.effective_top_k_ = k + self.lfs_ = [] + for category in range(len(descriptions)): + indices = np.flatnonzero(owners == category) + ranked = sorted(indices, key=lambda i: (-scores[i, category], phrases[i])) + self.lfs_.extend( + LabelingFunction(str(phrases[i]), category, float(scores[i, category])) + for i in ranked[:k] + ) + return self + + def transform(self, texts: Iterable[str]) -> np.ndarray: + """Applies the fitted rules to notes. + + Args: + texts: Notes, cleaned the same way as the training notes. + + Returns: + An int64 array of shape ``[notes, rules]``: -1 where a rule abstains, + otherwise the column index of the category it votes for. + + Raises: + RuntimeError: If called before :meth:`fit`. + """ + if not hasattr(self, "lfs_"): + raise RuntimeError("Fit KeywordLabeler on training notes first") + texts = list(texts) + votes = np.full((len(texts), len(self.lfs_)), -1, dtype=np.int64) + if not texts or not self.lfs_: + return votes + columns = [self.vectorizer_.vocabulary_[lf.phrase] for lf in self.lfs_] + categories = np.array([lf.category_index for lf in self.lfs_], dtype=np.int64) + hits = self.vectorizer_.transform(texts)[:, columns].tocoo() + present = hits.data > 0 + rows, lf_columns = hits.row[present], hits.col[present] + votes[rows, lf_columns] = categories[lf_columns] + return votes + + +def _validate_votes(votes: np.ndarray, n_classes: int) -> np.ndarray: + """Checks a vote matrix and returns it as an array. + + Args: + votes: Integer array of shape ``[notes, rules]`` with -1 or a category. + n_classes: Number of categories. + + Returns: + The votes as a NumPy array. + + Raises: + ValueError: If the shape, dtype or values are invalid. + """ + votes = np.asarray(votes) + if n_classes < 2 or votes.ndim != 2 or not np.issubdtype(votes.dtype, np.integer): + raise ValueError("Need an integer [notes, LFs] matrix and >= 2 classes") + if ((votes < -1) | (votes >= n_classes)).any(): + raise ValueError("Votes must be -1 or category indices") + return votes + + +def snorkel_memory_gb(n_rows: int, n_lfs: int, n_classes: int) -> float: + """Estimates peak host memory for Snorkel's ``LabelModel.fit``. + + Snorkel one-hot encodes the votes into a dense float64 + ``[rows, rules * classes]`` matrix, then forms its float64 Gram matrix and a + float32 copy on the host before moving it to the device. Memory therefore + grows with the square of ``rules * classes``, and a GPU does not avoid it. + + Args: + n_rows: Number of notes passed to Snorkel. + n_lfs: Number of labeling functions. + n_classes: Number of categories. + + Returns: + Estimated memory in gigabytes. + + Example: + >>> round(snorkel_memory_gb(945, 5700, 19)) # 300 rules x 19 categories + 142 + """ + width = n_lfs * n_classes + return (n_rows * width * 8 + width * width * (8 + 4)) / 1e9 + + +def aggregate_votes( + votes: np.ndarray, + n_classes: int, + method: str = "majority", + seed: int = 0, + max_memory_gb: float | None = None, + device: str = "cpu", + **fit_kwargs: Any, +) -> tuple[np.ndarray, np.ndarray]: + """Turns rule votes into one categorical weak label per note. + + The majority baseline normalizes vote counts, preserving ties. Snorkel fits + a categorical label model on covered notes only; it is never silently + replaced by the baseline. Notes no rule covers get a uniform distribution + and must be excluded from initial training through the returned mask. + + Args: + votes: Integer array of shape ``[notes, rules]`` from + :meth:`KeywordLabeler.transform`. + n_classes: Number of categories. + method: ``"majority"`` or ``"snorkel"``. + seed: Random seed for Snorkel. + max_memory_gb: If set, refuses Snorkel when :func:`snorkel_memory_gb` + exceeds it. + device: Snorkel ``LabelModel`` device, for example ``"cuda:0"``. + **fit_kwargs: Passed to Snorkel's ``LabelModel.fit``. + + Returns: + A tuple ``(probabilities, covered)``: float32 ``[notes, n_classes]`` + rows summing to one, and a bool ``[notes]`` mask of notes with at least + one vote. + + Raises: + ValueError: If the votes or method are invalid, or Snorkel lacks rules + or covered notes. + MemoryError: If Snorkel would exceed ``max_memory_gb``. + ImportError: If Snorkel is requested but not installed. + + Example: + >>> p, covered = aggregate_votes(np.array([[0, 1, 1], [-1, -1, -1]]), 2) + >>> p.astype(float).round(2).tolist(), covered.tolist() + ([[0.33, 0.67], [0.5, 0.5]], [True, False]) + """ + votes = _validate_votes(votes, n_classes) + covered = (votes != -1).any(axis=1) + probabilities = np.full((len(votes), n_classes), 1 / n_classes) + if method not in ("majority", "snorkel"): + raise ValueError("method must be majority or snorkel") + if method == "snorkel" and max_memory_gb is not None: + needed = snorkel_memory_gb(int(covered.sum()), votes.shape[1], n_classes) + if needed > max_memory_gb: + raise MemoryError( + f"Snorkel needs about {needed:.1f} GB for {votes.shape[1]} LFs x " + f"{n_classes} classes (limit {max_memory_gb} GB); use fewer LFs " + "or majority voting" + ) + if method == "majority": + counts = np.stack([(votes == c).sum(axis=1) for c in range(n_classes)], axis=1) + probabilities[covered] = counts[covered] / counts[covered].sum( + axis=1, keepdims=True + ) + else: + if votes.shape[1] < 3 or not covered.any(): + raise ValueError("Snorkel needs >= 3 LFs and covered training rows") + try: + from snorkel.labeling.model import LabelModel + except ImportError as exc: + raise ImportError( + 'Snorkel is not installed; pip install "snorkel>=0.10,<0.11"' + ) from exc + model = LabelModel(cardinality=n_classes, device=device, verbose=False) + model.fit(L_train=votes[covered], seed=seed, **fit_kwargs) + probabilities[covered] = model.predict_proba(L=votes[covered]) + if not np.allclose(probabilities.sum(axis=1), 1, atol=1e-5): + raise ValueError("Categorical weak labels must sum to one per note") + return probabilities.astype(np.float32), covered + + +def confident_balanced_mask( + probabilities: np.ndarray, covered: np.ndarray, max_num: int +) -> np.ndarray: + """Selects the most confident covered notes for initial training. + + Mirrors the authors' ``get_balanced_data_mask`` with uniform class balance: + for each category keep the ``max_num // categories`` covered notes with the + highest weak probability for it, then take the union. Uncovered notes are + never selected because their weak label is only the uniform prior. + + Args: + probabilities: Weak labels of shape ``[notes, categories]``. + covered: Bool mask of shape ``[notes]`` from :func:`aggregate_votes`. + max_num: Total note budget, split evenly across categories. + + Returns: + A bool mask of shape ``[notes]`` marking the selected notes. + + Raises: + ValueError: If the shapes do not match or ``max_num`` is smaller than + the number of categories. + + Example: + >>> p = np.array([[0.9, 0.1], [0.6, 0.4], [0.2, 0.8]]) + >>> confident_balanced_mask(p, np.array([True, True, True]), max_num=2) + array([ True, False, True]) + """ + probabilities = np.asarray(probabilities) + covered = np.asarray(covered, dtype=bool) + if probabilities.ndim != 2 or covered.shape != (len(probabilities),): + raise ValueError("Need [notes, categories] probabilities and a covered mask") + if max_num < probabilities.shape[1]: + raise ValueError("max_num must allow at least one note per category") + per_class = max_num // probabilities.shape[1] + candidates = np.flatnonzero(covered) + mask = np.zeros(len(probabilities), dtype=bool) + for category in range(probabilities.shape[1]): + order = np.argsort(-probabilities[candidates, category], kind="stable") + mask[candidates[order[:per_class]]] = True + return mask + + +def vote_diagnostics(votes: np.ndarray, n_classes: int) -> dict[str, Any]: + """Summarizes how much of the corpus the rules cover. + + Notes voted for by several categories may reflect true comorbidity, not + rule conflict. + + Args: + votes: Integer array of shape ``[notes, rules]``. + n_classes: Number of categories. + + Returns: + A dict with ``"coverage"`` (share of notes with any vote), + ``"cross_category_fraction"`` (share voted for by more than one + category) and ``"lf_coverage"`` (per-rule share of notes it fires on). + + Example: + >>> d = vote_diagnostics(np.array([[0, 1], [-1, -1], [0, -1]]), 2) + >>> round(d["coverage"], 2), round(d["cross_category_fraction"], 2) + (0.67, 0.33) + """ + votes = _validate_votes(votes, n_classes) + present = np.stack([(votes == c).any(axis=1) for c in range(n_classes)], axis=1) + return { + "coverage": float(present.any(axis=1).mean()) if len(votes) else 0.0, + "cross_category_fraction": float((present.sum(axis=1) > 1).mean()) + if len(votes) + else 0.0, + "lf_coverage": (votes != -1).mean(axis=0) + if len(votes) + else np.zeros(votes.shape[1]), + } diff --git a/tests/core/test_keyclass.py b/tests/core/test_keyclass.py new file mode 100644 index 0000000000..98f29b2c89 --- /dev/null +++ b/tests/core/test_keyclass.py @@ -0,0 +1,520 @@ +import importlib.util +import tempfile +import types +import unittest +from pathlib import Path +from unittest import mock + +import numpy as np +import torch + +from pyhealth.datasets import create_sample_dataset, get_dataloader +from pyhealth.models import KeyClass +from pyhealth.weak_supervision import ( + ClinicalTextEncoder, + KeywordLabeler, + aggregate_votes, + clean_note, + confident_balanced_mask, + nltk_english_stopwords, + snorkel_memory_gb, + vote_diagnostics, +) + +# Small stand-in for the NLTK corpus so unit tests need no download. +STOPWORDS = ("and", "at", "by", "no", "not", "the") + + +def corpus_available() -> bool: + """Returns whether NLTK and a readable English stopwords corpus are installed.""" + try: + from nltk.corpus import stopwords + + stopwords.words("english") + except (ImportError, LookupError, OSError): # OSError: damaged corpus files + return False + return True + + +class MockEncoder: + def encode(self, texts): + return np.array( + [[1 + t.count("heart"), 1 + t.count("lung")] for t in texts], dtype=float + ) + + +class TestKeyClass(unittest.TestCase): + def setUp(self): + patcher = mock.patch( + "pyhealth.weak_supervision.keyclass.nltk_english_stopwords", + return_value=STOPWORDS, + ) + patcher.start() + self.addCleanup(patcher.stop) + + def test_mining_and_boundaries(self): + labeler = KeywordLabeler(MockEncoder(), top_k=4, min_df=1).fit( + ["heart failure", "lung disease", "heart lung"], + {"cardiac": "heart", "resp": "lung"}, + ) + self.assertEqual(labeler.category_ids_, ("cardiac", "resp")) + self.assertTrue(any(lf.phrase == "heart failure" for lf in labeler.lfs_)) + votes = labeler.transform(["HEART failure", "heartland", "", "heart lung"]) + self.assertTrue((votes[0] != -1).any()) + self.assertTrue((votes[1:3] == -1).all()) + self.assertEqual(labeler.transform([]).shape, (0, len(labeler.lfs_))) + self.assertGreater(vote_diagnostics(votes, 2)["cross_category_fraction"], 0) + # Transform must not learn new phrases from held-out notes. + self.assertNotIn("heartland", labeler.vectorizer_.vocabulary_) + + def test_majority_abstention_and_validation(self): + probabilities, covered = aggregate_votes( + np.array([[0, 1, -1], [-1, -1, -1], [1, 1, 0]]), 2 + ) + np.testing.assert_allclose( + probabilities, [[0.5, 0.5], [0.5, 0.5], [1 / 3, 2 / 3]] + ) + self.assertEqual(covered.tolist(), [True, False, True]) + with self.assertRaises(ValueError): + aggregate_votes(np.array([[2]]), 2) + p, mask = aggregate_votes(np.empty((2, 0), dtype=int), 2) + self.assertFalse(mask.any()) + np.testing.assert_allclose(p, 0.5) + + def test_pyhealth_batch_and_gradients(self): + samples = [ + { + "patient_id": str(i), + "embedding": [1.0, float(i)], + "weak_labels": [0.2, 0.8], + } + for i in range(2) + ] + dataset = create_sample_dataset( + samples=samples, + input_schema={"embedding": "tensor"}, + output_schema={"weak_labels": "tensor"}, + ) + model = KeyClass(dataset, 2, ["cardiac", "resp"], hidden_dims=(8, 8, 4)) + batch = next(iter(get_dataloader(dataset, batch_size=2))) + result = model(**batch) + self.assertEqual(model.mode, "multilabel") + self.assertEqual(model.label_processor.output_size(), 2) + self.assertEqual(model.label_processor.label_vocab, {"cardiac": 0, "resp": 1}) + self.assertEqual(list(model.label_processors), ["weak_labels"]) + self.assertEqual(result["y_prob"].shape, (2, 2)) + result["loss"].backward() + self.assertTrue(torch.isfinite(model.network[0].weight.grad).all()) + model.eval() + self.assertNotIn("loss", model(embedding=batch["embedding"])) + with self.assertRaises(ValueError): + model(embedding=batch["embedding"], weak_labels=[[2.0, 0.0], [0.0, 1.0]]) + + def test_clean_note_and_stopwords(self): + text = ( + "Seen by [**First Name4 (NamePattern1) **] at [**Hospital1 18**].\nASA 81" + ) + self.assertEqual(clean_note(text), "seen by at . asa") + labeler = KeywordLabeler(MockEncoder(), ngram_range=(1, 2), min_df=1) + labeler.fit(["no heart failure", "lung not clear"], {"c": "heart", "r": "lung"}) + # Stopwords are removed before n-grams are formed, as in the authors' code. + self.assertIn("heart failure", labeler.vectorizer_.vocabulary_) + self.assertNotIn("no", labeler.vectorizer_.vocabulary_) + self.assertIn("lung clear", labeler.vectorizer_.vocabulary_) + + def test_missing_nltk_corpus_message(self): + nltk_english_stopwords.cache_clear() + self.addCleanup(nltk_english_stopwords.cache_clear) + corpus = mock.Mock() + corpus.words.side_effect = LookupError + with ( + mock.patch.dict( + "sys.modules", {"nltk.corpus": mock.Mock(stopwords=corpus)} + ), + self.assertRaisesRegex(LookupError, "nltk.downloader stopwords"), + ): + nltk_english_stopwords() + + @unittest.skipUnless(corpus_available(), "NLTK stopwords corpus not installed") + def test_real_nltk_stopwords(self): + nltk_english_stopwords.cache_clear() + self.addCleanup(nltk_english_stopwords.cache_clear) + words = nltk_english_stopwords() + self.assertIn("not", words) + self.assertNotIn("don't", words) # cannot match a CountVectorizer token + self.assertTrue(all(len(w) > 1 for w in words)) + + def test_strict_min_df_and_candidate_cap(self): + texts = ["heart failure"] * 2 + ["lung disease"] * 3 + labeler = KeywordLabeler(MockEncoder(), ngram_range=(1, 1), min_df=0.4) + labeler.fit(texts, {"cardiac": "heart", "resp": "lung"}) + self.assertEqual(labeler.min_count_, 3) # more than 40% of 5 notes + self.assertEqual(set(labeler.vectorizer_.vocabulary_), {"lung", "disease"}) + with self.assertRaises(ValueError): + KeywordLabeler(MockEncoder(), min_df=1, max_candidates=1).fit( + texts, {"cardiac": "heart", "resp": "lung"} + ) + + def test_top_k_budget_and_vectorized_votes(self): + texts = ["heart failure acute", "heart murmur", "lung disease", "heart lung"] + descriptions = {"cardiac": "heart", "resp": "lung"} + uncapped = KeywordLabeler(MockEncoder(), top_k=50, min_df=1).fit( + texts, descriptions + ) + pools = np.bincount([lf.category_index for lf in uncapped.lfs_], minlength=2) + self.assertGreater(pools.max(), pools.min()) + capped = KeywordLabeler( + MockEncoder(), top_k=50, min_df=1, equalize_top_k=True + ).fit(texts, descriptions) + self.assertEqual(capped.effective_top_k_, pools.min()) + votes = uncapped.transform(texts) + counts = uncapped.vectorizer_.transform(texts) + for j, lf in enumerate(uncapped.lfs_): + column = uncapped.vectorizer_.vocabulary_[lf.phrase] + expected = counts[:, column].toarray().ravel() > 0 + np.testing.assert_array_equal(votes[:, j] == lf.category_index, expected) + + def test_confident_mask_and_snorkel_guard(self): + p = np.array([[0.9, 0.1], [0.8, 0.2], [0.4, 0.6], [0.5, 0.5], [0.1, 0.9]]) + covered = np.array([True, True, True, False, True]) + mask = confident_balanced_mask(p, covered, 2) + np.testing.assert_array_equal(mask, [True, False, False, False, True]) + self.assertGreater(snorkel_memory_gb(945, 5700, 19), 140) + with self.assertRaises(MemoryError): + aggregate_votes( + np.array([[0, 1, -1], [1, 1, 0]]), 2, "snorkel", max_memory_gb=1e-9 + ) + + def test_standardization_and_sample_weights(self): + samples = [ + { + "patient_id": str(i), + "embedding": [1.0, 10.0 * i], + "weak_labels": [0.2, 0.8], + } + for i in range(3) + ] + dataset = create_sample_dataset( + samples=samples, + input_schema={"embedding": "tensor"}, + output_schema={"weak_labels": "tensor"}, + ) + model = KeyClass(dataset, 2, ["cardiac", "resp"], hidden_dims=(4, 4, 4)).eval() + x = torch.tensor([[1.0, 0.0], [1.0, 10.0], [1.0, 20.0]]) + y = torch.tensor([[0.2, 0.8], [1.0, 0.0], [0.5, 0.5]]) + torch.testing.assert_close(model(embedding=x)["logit"], model.network(x)) + model.fit_input_standardization(x) + self.assertEqual(float(model.input_scale[0]), 1.0) # constant dimension + scaled = (x - x.mean(0)) / torch.tensor([1.0, x[:, 1].std(unbiased=False)]) + torch.testing.assert_close(model(embedding=x)["logit"], model.network(scaled)) + plain = model(embedding=x, weak_labels=y)["loss"] + ones = model(embedding=x, weak_labels=y, sample_weight=torch.ones(3))["loss"] + torch.testing.assert_close(plain, ones) + zeros = model(embedding=x, weak_labels=y, sample_weight=torch.zeros(3)) + self.assertEqual(zeros["loss"].item(), 0.0) + with self.assertRaises(ValueError): + model(embedding=x, weak_labels=y, sample_weight=torch.ones(2)) + restored = KeyClass(dataset, 2, ["cardiac", "resp"], hidden_dims=(4, 4, 4)) + restored.load_state_dict(model.state_dict()) + torch.testing.assert_close( + restored.eval()(embedding=x)["logit"], model(embedding=x)["logit"] + ) + + @unittest.skipUnless( + importlib.util.find_spec("snorkel"), "optional Snorkel not installed" + ) + def test_real_snorkel(self): + votes = np.tile([[0, 0, -1], [1, -1, 1], [0, 1, 0], [1, 1, 1]], (10, 1)) + votes = np.vstack([votes, [-1, -1, -1]]) + p, covered = aggregate_votes( + votes, 2, method="snorkel", n_epochs=20, progress_bar=False + ) + self.assertTrue(np.isfinite(p).all()) + np.testing.assert_allclose(p.sum(axis=1), 1, atol=1e-6) + self.assertFalse(covered[-1]) + np.testing.assert_allclose(p[-1], [0.5, 0.5]) + + +def tiny_dataset(): + """A two-sample dataset with 2-dimensional embeddings and 2 categories.""" + samples = [ + {"patient_id": str(i), "embedding": [1.0, float(i)], "weak_labels": [0.5, 0.5]} + for i in range(2) + ] + return create_sample_dataset( + samples=samples, + input_schema={"embedding": "tensor"}, + output_schema={"weak_labels": "tensor"}, + ) + + +class FakeLabelModel: + """Stands in for Snorkel's LabelModel so its code path runs without Snorkel.""" + + normalize = True + + def __init__(self, cardinality, device, verbose): + self.cardinality, self.device = cardinality, device + + def fit(self, L_train, seed, **kwargs): + self.fit_rows, self.fit_kwargs = len(L_train), kwargs + + def predict_proba(self, L): + scores = np.arange(1, len(L) * self.cardinality + 1, dtype=float) + scores = scores.reshape(len(L), self.cardinality) + return scores / scores.sum(1, keepdims=True) if self.normalize else scores + + +def fake_snorkel(label_model): + """sys.modules entries that make ``snorkel.labeling.model`` importable.""" + module = types.ModuleType("snorkel.labeling.model") + module.LabelModel = label_model + return { + "snorkel": types.ModuleType("snorkel"), + "snorkel.labeling": types.ModuleType("snorkel.labeling"), + "snorkel.labeling.model": module, + } + + +class TestValidationAndOptionalPaths(unittest.TestCase): + def setUp(self): + patcher = mock.patch( + "pyhealth.weak_supervision.keyclass.nltk_english_stopwords", + return_value=STOPWORDS, + ) + patcher.start() + self.addCleanup(patcher.stop) + + def test_model_rejects_bad_configuration_and_inputs(self): + dataset = tiny_dataset() + with self.assertRaises(ValueError): + KeyClass(dataset, 2, ["cardiac"]) + with self.assertRaises(ValueError): + KeyClass(dataset, 2, ["cardiac", "cardiac"]) + with self.assertRaises(ValueError): + KeyClass(dataset, 2, ["cardiac", "resp"], hidden_dims=(4, 0)) + model = KeyClass(dataset, 2, ["cardiac", "resp"], hidden_dims=(4,)) + with self.assertRaises(ValueError): + model.fit_input_standardization(torch.ones(3, 5)) + with self.assertRaises(ValueError): + model.fit_input_standardization(torch.ones(1, 2)) + with self.assertRaises(ValueError): + model.fit_input_standardization([[1.0, float("nan")], [2.0, 3.0]]) + with self.assertRaises(ValueError): + model(embedding=torch.ones(2)) + + def test_labeler_rejects_bad_settings_and_inputs(self): + descriptions = {"cardiac": "heart", "resp": "lung"} + with self.assertRaises(ValueError): + KeywordLabeler(MockEncoder(), top_k=0) + with self.assertRaises(ValueError): + KeywordLabeler(MockEncoder(), min_df=1.5).fit(["heart"], descriptions) + with self.assertRaises(ValueError): + KeywordLabeler(MockEncoder(), min_df=0).fit(["heart"], descriptions) + labeler = KeywordLabeler(MockEncoder(), min_df=1) + with self.assertRaises(ValueError): + labeler.fit([], descriptions) + with self.assertRaises(ValueError): + labeler.fit(["heart"], {"cardiac": "heart"}) + with self.assertRaises(ValueError): + labeler.fit(["heart"], {"cardiac": "heart", "resp": " "}) + with self.assertRaises(RuntimeError): + KeywordLabeler(MockEncoder()).transform(["heart"]) + + class ZeroEncoder: + def encode(self, texts): + return np.zeros((len(texts), 2)) + + with self.assertRaises(ValueError): + KeywordLabeler(ZeroEncoder(), min_df=1).fit(["heart"], descriptions) + + def test_vote_and_mask_validation(self): + with self.assertRaises(ValueError): + aggregate_votes(np.array([[0.5, 1.0]]), 2) + with self.assertRaises(ValueError): + aggregate_votes(np.array([[0, 1]]), 2, method="vote") + with self.assertRaises(ValueError): + confident_balanced_mask(np.ones((3, 2)), np.ones(2, dtype=bool), 4) + with self.assertRaises(ValueError): + confident_balanced_mask(np.ones((3, 2)), np.ones(3, dtype=bool), 1) + + def test_snorkel_path_without_snorkel_installed(self): + votes = np.array([[0, 0, -1], [1, -1, 1], [-1, -1, -1]]) + with mock.patch.dict("sys.modules", fake_snorkel(FakeLabelModel)): + p, covered = aggregate_votes(votes, 2, method="snorkel", n_epochs=5) + self.assertEqual(covered.tolist(), [True, True, False]) + np.testing.assert_allclose(p.sum(axis=1), 1, atol=1e-6) + np.testing.assert_allclose(p[-1], [0.5, 0.5]) # uncovered: uniform + with self.assertRaises(ValueError): # fewer than 3 rules + aggregate_votes(votes[:, :2], 2, method="snorkel") + + class UnnormalizedLabelModel(FakeLabelModel): + normalize = False + + with ( + mock.patch.dict("sys.modules", fake_snorkel(UnnormalizedLabelModel)), + self.assertRaisesRegex(ValueError, "sum to one"), + ): + aggregate_votes(votes, 2, method="snorkel") + with ( + mock.patch.dict("sys.modules", {"snorkel.labeling.model": None}), + self.assertRaisesRegex(ImportError, "Snorkel is not installed"), + ): + aggregate_votes(votes, 2, method="snorkel") + + def test_nltk_stopwords_filtering_and_missing_package(self): + nltk_english_stopwords.cache_clear() + self.addCleanup(nltk_english_stopwords.cache_clear) + corpus = mock.Mock() + corpus.words.return_value = ["the", "a", "don't", "not", "the"] + with mock.patch.dict( + "sys.modules", {"nltk.corpus": mock.Mock(stopwords=corpus)} + ): + self.assertEqual(nltk_english_stopwords(), ("not", "the")) + nltk_english_stopwords.cache_clear() + with ( + mock.patch.dict("sys.modules", {"nltk": None, "nltk.corpus": None}), + self.assertRaisesRegex(ImportError, "pip install"), + ): + nltk_english_stopwords() + + +class TestTrainerIntegration(unittest.TestCase): + """Trains and evaluates KeyClass with PyHealth's Trainer and its metrics.""" + + @staticmethod + def dataset(with_gold): + rng = np.random.default_rng(0) + samples = [] + for i in range(12): + category = i % 3 + weak = np.full(3, 0.1) + weak[category] = 0.8 + sample = { + "patient_id": str(i), + "embedding": (np.eye(3)[category] + 0.1 * rng.normal(size=3)).tolist(), + "weak_labels": weak.tolist(), + } + if with_gold: + gold = np.eye(3)[category] + gold[(category + 1) % 3] = i % 2 # some notes have two diagnoses + sample["gold_labels"] = gold.tolist() + samples.append(sample) + output_schema = {"weak_labels": "tensor"} + if with_gold: + output_schema["gold_labels"] = "tensor" + return create_sample_dataset( + samples=samples, + input_schema={"embedding": "tensor"}, + output_schema=output_schema, + ) + + def train_and_evaluate(self, with_gold): + from pyhealth.trainer import Trainer + + torch.manual_seed(0) + dataset = self.dataset(with_gold) + model = KeyClass( + dataset, + 3, + ["cardiac", "resp", "renal"], + hidden_dims=(8,), + gold_key="gold_labels" if with_gold else None, + ) + loader = get_dataloader(dataset, batch_size=4) + trainer = Trainer( + model=model, + metrics=["f1_samples", "roc_auc_macro"], + enable_logging=False, + ) + trainer.train(train_dataloader=loader, val_dataloader=loader, epochs=2) + y_true, _, _ = trainer.inference(loader) + return trainer.evaluate(loader), y_true + + def test_trainer_with_weak_labels_only(self): + scores, y_true = self.train_and_evaluate(with_gold=False) + # Weak labels at or above 1/3 become the binary y_true for the metrics. + np.testing.assert_array_equal(y_true, np.eye(3)[np.arange(12) % 3]) + for key in ("loss", "f1_samples", "roc_auc_macro"): + self.assertTrue(np.isfinite(scores[key]), key) + + def test_trainer_scores_against_gold_labels(self): + scores, y_true = self.train_and_evaluate(with_gold=True) + expected = np.eye(3)[np.arange(12) % 3] + expected[np.arange(12), (np.arange(12) + 1) % 3] = np.arange(12) % 2 + np.testing.assert_array_equal(y_true, expected) + for key in ("loss", "f1_samples", "roc_auc_macro"): + self.assertTrue(np.isfinite(scores[key]), key) + + def test_gold_labels_do_not_change_the_loss(self): + dataset = self.dataset(with_gold=True) + batch = next(iter(get_dataloader(dataset, batch_size=4))) + model = KeyClass(dataset, 3, ["a", "b", "c"], gold_key="gold_labels").eval() + weak_only = {k: v for k, v in batch.items() if k != "gold_labels"} + torch.testing.assert_close(model(**batch)["loss"], model(**weak_only)["loss"]) + with self.assertRaises(ValueError): + model(**{**batch, "gold_labels": batch["gold_labels"] * 0.5}) + with self.assertRaises(ValueError): + model(**{**batch, "gold_labels": batch["gold_labels"][:, :2]}) + + +class TestClinicalTextEncoder(unittest.TestCase): + """Runs the encoder on a tiny randomly initialized BERT; nothing is downloaded.""" + + VOCAB = ( + "[PAD]", "[UNK]", "[CLS]", "[SEP]", "[MASK]", "heart", "failure", "renal", + "sepsis", "pneumonia", "acute", "chronic", "the", "patient", "with", + ) # fmt: skip + + @classmethod + def setUpClass(cls): + from transformers import BertConfig, BertModel, BertTokenizer + + cls._tmp = tempfile.TemporaryDirectory() + path = Path(cls._tmp.name) + (path / "vocab.txt").write_text("\n".join(cls.VOCAB) + "\n") + BertTokenizer(str(path / "vocab.txt")).save_pretrained(path) + torch.manual_seed(0) + config = BertConfig( + vocab_size=len(cls.VOCAB), + hidden_size=8, + num_hidden_layers=1, + num_attention_heads=2, + intermediate_size=16, + max_position_embeddings=32, + ) + BertModel(config).save_pretrained(path) + cls.model_dir = str(path) + + @classmethod + def tearDownClass(cls): + cls._tmp.cleanup() + + def test_output_shape_and_empty_input(self): + encoder = ClinicalTextEncoder(self.model_dir, batch_size=2) + out = encoder.encode(["heart failure", "sepsis", "acute renal failure"]) + self.assertEqual(out.shape, (3, 8)) + self.assertEqual(out.dtype, np.float32) + self.assertTrue(np.isfinite(out).all()) + self.assertEqual(encoder.encode([]).shape, (0, 8)) + + def test_padding_does_not_change_embeddings(self): + texts = ["sepsis", "the patient with acute chronic renal failure", "heart"] + one_at_a_time = ClinicalTextEncoder(self.model_dir, batch_size=1) + padded_batch = ClinicalTextEncoder(self.model_dir, batch_size=3) + np.testing.assert_allclose( + one_at_a_time.encode(texts), padded_batch.encode(texts), atol=1e-5 + ) + + def test_truncation_ignores_text_past_max_length(self): + texts = ["heart failure sepsis", "heart failure pneumonia acute"] + short = ClinicalTextEncoder(self.model_dir, max_length=4).encode(texts) + np.testing.assert_allclose(short[0], short[1], atol=1e-6) + full = ClinicalTextEncoder(self.model_dir, max_length=32).encode(texts) + self.assertFalse(np.allclose(full[0], full[1])) + + def test_rejects_invalid_arguments(self): + with self.assertRaises(ValueError): + ClinicalTextEncoder(self.model_dir, batch_size=0) + with self.assertRaises(ValueError): + ClinicalTextEncoder(self.model_dir, max_length=1)