Repository navigation
Add KeyClass weak supervision for clinical note classification - #1408
amintorabi88 wants to merge 16 commits into
Conversation
Add phrase mining and labeling functions, majority and optional Snorkel vote aggregation, a frozen clinical text encoder, and the KeyClass classifier. Include tests, a synthetic example, and API documentation.
Add an offline synthetic-data walkthrough for phrase mining, vote aggregation, classifier training, and inference. Add paper attribution to KeyClass modules and remove the explicit weak_supervision export list.
Introduce keyword-based labeling functions, vote aggregation, a multilabel KeyClass model, and an optional Snorkel integration. Add API documentation, a tutorial, and tests.
…torabi88/PyHealth into A1_Classifying_Unstructured
Use a multilabel processor for KeyClass output metadata, activation, and loss while preserving dense soft targets. Export KeyClass from the models package and extend its tests.
Add note cleaning, NLTK stopwords, balanced sample selection, and Snorkel memory safeguards. Standardize model inputs and support confidence-weighted loss.
Add type annotations and expanded documentation for the KeyClass model and weak-supervision pipeline. Clarify Snorkel installation guidance and handle damaged stopwords corpus files in tests.
Add an overview of the weak-supervision pipeline, a usage example, and API documentation for KeyClass and related utilities.
Demonstrate label-free classification of synthetic discharge notes and compare rule n-grams, rule budgets, and embedding standardization across three seeds. Include recorded metrics, findings, and MIMIC-III reproduction results.
Add usage examples to weak-supervision docstrings, narrow `min_df` to `float`, and remove the KeyClass tutorial notebook.
Test CoverageTotal: 88.19% (57243 / 64907 lines)
|
Cover input validation, optional Snorkel and NLTK paths, and clinical text encoding with a locally initialized BERT model.
|
/review |
| logits, targets, reduction="none" | ||
| ).mean(dim=1) | ||
| loss = (per_note * weights).mean() | ||
| result.update(y_true=targets, loss=loss) |
There was a problem hiding this comment.
Fixed in 1ebfbec. The loss still uses the soft weak labels, but y_true is now binary. If the batch has gold labels under the new optional gold_key, those are y_true, so Trainer.evaluate reports agreement with gold labels. Otherwise y_true is the weak labels thresholded at 1/categories. Our weak labels sum to one per note, so a 0.5 threshold would almost never mark a category. New tests run Trainer.train with a validation split and Trainer.evaluate in both cases, and check that gold labels do not change the loss.
| import numpy as np | ||
|
|
||
|
|
||
| class ClinicalTextEncoder: |
There was a problem hiding this comment.
Kept separate on purpose; the reason is now in the class docstring and the PR description. encode_stress_prompts reloads the model on every call, averages over padding by default, and rejects empty input. KeyClass encodes phrases, descriptions and notes with one loaded model, needs padding excluded so embeddings do not depend on batch size, and can get empty sets of phrases or notes. KeywordLabeler only needs an object with encode(texts), so any encoder can be used instead.
| "780-799 have no Table 4 category and were excluded. MIMIC-III requires\n", | ||
| "credentialed PhysioNet access, so these runs are not part of this notebook.\n", | ||
| "\n", | ||
| "**Full run.** All 39,443 training notes; phrases kept if they occur in more\n", |
There was a problem hiding this comment.
Added a note in 1ebfbec. MIMIC-III cannot be redistributed, so these numbers come from an offline run of our course reproduction scripts (cohort and split, pipeline with self-training, evaluation). Those scripts use a standalone copy of this PR's code and are not part of the PR. The 1-gram line now says the ablation was not done on MIMIC-III; the n-gram comparison is on synthetic notes only.
There was a problem hiding this comment.
Previous review
AI Review
suggestion: need change
decision: human review
Thank you for this contribution. KeyClass adds a label-free pipeline for classifying clinical notes: keyword rules mined from category descriptions, vote aggregation, and a multilabel MLP on frozen embeddings. The code is clearly written. Coverage is well above the bar: 100% on each new file and 87.15% for the whole repository. The new package and model don't change any shared code.
To get this merged:
- Trainer compatibility.
KeyClass.forwardreturns the soft weak labels asy_true. With the default multilabel metrics,Trainer.evaluatewould pass non-binary targets to sklearn, which I expect to fail. The notebook uses a custom loop, so this path isn't exercised. Please do one of the following:- Add a test that runs the Trainer on the model.
- Make evaluation work with soft labels, for example by thresholding
y_trueor by letting the evaluation pass gold labels. - State clearly in the docstring and docs that Trainer evaluation isn't supported, and show the intended evaluation path.
- Overlap with an existing encoder.
ClinicalTextEncoderappears to duplicate the Hugging Face loading, batching, truncation and masked mean pooling inencode_stress_prompts(pyhealth/models/clip_stress_utils.py). Please say in the description how it differs, or why a separate encoder is needed. If the two are meant to share code, please say that and why. If not, keeping them separate is fine once the difference is explained.
Optional suggestions:
- The description says 11 tests, but the file has about 20. Please update the count.
- The MIMIC-III numbers in the notebook (the full run and self-training) can't be regenerated from code in this PR. Consider adding a short script or a note saying how they were produced.
- The MIMIC 1-gram ablation is marked pending. You could remove that line or add the result.
Reviewed commit 25410d1
Use optional gold labels or thresholded weak labels for Trainer metrics while retaining soft labels for the loss. Add integration tests and clarify encoder design and experiment provenance.
| logits, targets, reduction="none" | ||
| ).mean(dim=1) | ||
| loss = (per_note * weights).mean() | ||
| result.update(y_true=targets, loss=loss) |
There was a problem hiding this comment.
Fixed in 1ebfbec. The loss still uses the soft weak labels, but y_true is now binary. If the batch has gold labels under the new optional gold_key, those are y_true, so Trainer.evaluate reports agreement with gold labels. Otherwise y_true is the weak labels thresholded at 1/categories. Our weak labels sum to one per note, so a 0.5 threshold would almost never mark a category. New tests run Trainer.train with a validation split and Trainer.evaluate in both cases, and check that gold labels do not change the loss.
| import numpy as np | ||
|
|
||
|
|
||
| class ClinicalTextEncoder: |
There was a problem hiding this comment.
Kept separate on purpose; the reason is now in the class docstring and the PR description. encode_stress_prompts reloads the model on every call, averages over padding by default, and rejects empty input. KeyClass encodes phrases, descriptions and notes with one loaded model, needs padding excluded so embeddings do not depend on batch size, and can get empty sets of phrases or notes. KeywordLabeler only needs an object with encode(texts), so any encoder can be used instead.
| "780-799 have no Table 4 category and were excluded. MIMIC-III requires\n", | ||
| "credentialed PhysioNet access, so these runs are not part of this notebook.\n", | ||
| "\n", | ||
| "**Full run.** All 39,443 training notes; phrases kept if they occur in more\n", |
There was a problem hiding this comment.
Added a note in 1ebfbec. MIMIC-III cannot be redistributed, so these numbers come from an offline run of our course reproduction scripts (cohort and split, pipeline with self-training, evaluation). Those scripts use a standalone copy of this PR's code and are not part of the PR. The 1-gram line now says the ablation was not done on MIMIC-III; the n-gram comparison is on synthetic notes only.
|
Thanks for the review. All points are addressed in 1ebfbec, and the description is updated (23 tests, 100% coverage on the KeyClass files). Could you run /review again when you have a moment? |
|
/review |
There was a problem hiding this comment.
Previous review
AI Review
suggestion: approve
decision: human review
Thank you for this contribution. It adds KeyClass, a weakly supervised clinical-note classifier, plus a new pyhealth.weak_supervision package. The package covers note cleaning, keyword labeling functions, vote aggregation, confident-note selection and a Hugging Face encoder. It also adds docs, a notebook, tests and a keyclass optional extra.
It looks ready to merge.
- Self-contained: The model and the new package are self-contained. The only changes to existing files are registration: an export in
models/__init__.py, a docs entry and an optional extra. - Sharing: Your description explains why
ClinicalTextEncoderdoesn't reuseclip_stress_utils. The model uses only the shared base class and processors. - Coverage: Coverage is 100% on all four KeyClass files, and 87.5% for the whole repository. Both are above the bar.
- Docs: The docs match the code. The deviations from the paper are stated clearly, as are the limits of the MIMIC-III results.
- Not checked: I couldn't check the MIMIC-III numbers. They come from offline scripts outside this PR.
Optional suggestions:
- The notebook is large because its outputs are embedded. You could clear the HTML table outputs, or keep only the summary tables, to make the diff easier to review.
- You might add a short note in the model docstring on how to pass
sample_weightthrough the input schema, as the notebook does.
Reviewed commit 1ebfbec
|
Why this PR has To make it eligible for automatic review:
Related: #1663 (merged today) adds Once that's pushed, we'll switch the label to |
|
Thanks. Done in 94643ee: the |
|
/review Generated by Claude Code |
| import numpy as np | ||
|
|
||
|
|
||
| class ClinicalTextEncoder: |
There was a problem hiding this comment.
[high] ClinicalTextEncoder near-copies existing FrozenTextEncoder
ClinicalTextEncoder duplicates FrozenTextEncoder in pyhealth/models/clip_stress_utils.py:350. Both load a Hugging Face tokenizer and model once, set eval and requires_grad_(False), tokenize in batches with truncation to max_length, mean-pool over the attention mask, and reject batch_size <= 0 or max_length < 2 with the same message. The differences are that FrozenTextEncoder has a per-text cache and local_files_only, while this class returns a NumPy array from encode(texts) and accepts empty input. The description and docstring (lines 18-26) compare only with encode_stress_prompts, never with FrozenTextEncoder. They also say padding must be excluded, but encode_stress_prompts already offers pooling="masked_mean". Either explain in the description why FrozenTextEncoder cannot serve KeyClass and what the remaining differences are, or drop this class.
| 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: |
There was a problem hiding this comment.
[low] Missing gold_key silently falls back to weak-label scoring
If gold_key is set but absent from the batch (for example a typo in the key or a dataset without that field), forward silently uses the weak labels thresholded at 1/categories as y_true. Trainer.evaluate then reports weak-label agreement under the same metric names as gold-label evaluation. Consider raising a ValueError when gold_key is configured but missing from the batch, or document the fallback as a warning-level behavior.
There was a problem hiding this comment.
AI Review
suggestion: need change
decision: human review
Thank you for this contribution. It adds KeyClass, a weakly supervised multilabel classifier for clinical notes, plus a pyhealth.weak_supervision pipeline (note cleaning, keyword labeling functions, vote aggregation, confident-note selection and an encoder). The tests are thorough, the docs are clear, and the notebook openly states its limits. Coverage is 100% on every changed file under pyhealth/ and 88.19% for the whole repository. Both are above the bar.
You are close. One issue needs resolving.
To get this merged:
ClinicalTextEncoder(pyhealth/weak_supervision/encoders.py) looks like a near-duplicate of the existingFrozenTextEncoderinpyhealth/models/clip_stress_utils.py. That class also loads the model once, freezes it, encodes in batches and mean-pools over the attention mask. The description and docstring compare the new class only withencode_stress_prompts, and they don't mentionFrozenTextEncoder. They also don't mention thatencode_stress_promptsalready offerspooling="masked_mean". Please state in the description whatClinicalTextEncoderdoes thatFrozenTextEncodercannot, for example how it handles empty input, truncation or theencode(texts)interface. If the two really overlap, please either confirm that a separate encoder is intended and say why, or reuse the existing one. Both options are fine. I only need the overlap addressed.
Optional suggestions:
- When
gold_keyis configured but missing from a batch,KeyClasssilently falls back to the thresholded weak labels asy_true. A warning, or a note in the docstring, would make it harder to mistake weak-label agreement for gold-label agreement. - The MIMIC-III results in the notebook come from scripts outside the PR. You already say so clearly. A short note on how a reader could reproduce them with
MIMIC3ICD9CategoryClassificationwould help.
Reviewed commit 94643ee
Contributors (CSE6250 Team A1): Amin Torabi (GT username: mtorabi8); Thien Huan Cao (GT username: tcao79)
Contribution Type: Model
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
Description:
Adds KeyClass, a weakly supervised classifier that assigns diagnostic categories to clinical notes without any labeled notes. As in the paper, it builds keyword labeling functions from short category descriptions, turns their votes into soft weak labels, and trains a multilabel classifier on document embeddings.
pyhealth.models.KeyClass: a four-layer MLP (LeakyReLU, dropout) on frozen document embeddings, inheriting fromBaseModel. It trains on soft weak labels with binary cross-entropy through the multilabel label processor, accepts an optional per-notesample_weight(the authors' confidence-weighted loss), and can store per-dimension input standardization statistics (fit_input_standardization) so saved models rescale new notes the same way. It works with PyHealth'sTrainer: the loss uses the soft weak labels, while the returnedy_trueis binary so the multilabel metrics can score it. That is the gold labels when the batch has them under the optionalgold_key, soTrainer.evaluatereports agreement with gold labels; otherwise the weak labels thresholded at 1 / categories.pyhealth.weak_supervision: the label-free pipeline that produces KeyClass's training labels.clean_note: removes MIMIC de-identification placeholders and digits.KeywordLabeler: mines 1-3 grams with NLTK stopwords, assigns each phrase to its most similar category description by embedding cosine similarity, and keeps the toptop_krules per category.aggregate_votes: majority vote, or Snorkel's label model with a memory check before fitting.confident_balanced_mask: selects confident notes per category for initial training.ClinicalTextEncoder: Hugging Face encoder with masked mean pooling, for example BlueBERT. It is separate fromencode_stress_promptsinpyhealth/models/clip_stress_utils.py, which does a similar pass for another model but reloads the model on every call, averages over padding by default and rejects empty input. KeyClass encodes phrases, descriptions and notes with one loaded model, needs padding excluded so embeddings do not depend on batch size, and gets empty sets of phrases or notes.KeywordLabeleronly needs an object withencode(texts), so any encoder can replace it.vote_diagnostics,snorkel_memory_gb,nltk_english_stopwords: helpers.ImportErrorwith the install command, which is also on the KeyClass docs page.MIMIC3ICD9CategoryClassification(Add MIMIC-III ICD-9 category classification task (KeyClass, Gao et al. MLHC 2022) #1663), which builds the paper's MIMIC-III cohort and 19-category labels; the docs show how to use its categories ascategory_idsand its labels asgold_keyfor evaluation.Differences from the paper, each documented in the docstrings: notes are truncated to 512 tokens instead of the paper's TF-IDF text selection; embeddings are standardized before the classifier (without it, the classifier on BlueBERT embeddings gave nearly the same scores to every note); majority vote is the default label model, which the paper's Table 6 finds on par with Snorkel; and the encoder is not fine-tuned.
Results:
top_k=30 gives F1 0.79, 300 gives 0.65); input standardization raises F1 from 0.69 to 0.79.Files to Review:
pyhealth/models/keyclass.py: the KeyClass modelpyhealth/weak_supervision/keyclass.py: note cleaning, labeling functions, vote aggregation, confident-note selectionpyhealth/weak_supervision/encoders.py:ClinicalTextEncoderpyhealth/weak_supervision/__init__.py,pyhealth/models/__init__.py: exportstests/core/test_keyclass.py: unit tests on synthetic data, including training and evaluation withTrainerexamples/synthetic_icd9_keyclass.ipynb: full pipeline and ablations on synthetic notes (about 1 minute on a CPU), plus documented MIMIC-III resultsdocs/api/models/pyhealth.models.KeyClass.rst,docs/api/models.rst: API documentation, with installation and MIMIC-III data sectionsTesting:
python -m pytest tests/core/test_keyclass.pyruns 23 tests on synthetic data in under a second, with 100% line coverage of the four KeyClass files. They includeTrainertraining and evaluation with weak labels only and with gold labels, andClinicalTextEncodertests on a tiny BERT built in a temporary folder, so nothing is downloaded. The Snorkel test and the real-NLTK-corpus test are skipped when those optional packages are not installed; the other tests use a fake Snorkel label model and a small fixed stopword list./review