Skip to content

Add KeyClass weak supervision for clinical note classification - #1408

Open
amintorabi88 wants to merge 16 commits into
sunlabuiuc:masterfrom
amintorabi88:A1_Classifying_Unstructured
Open

amintorabi88 wants to merge 16 commits into
sunlabuiuc:masterfrom
amintorabi88:A1_Classifying_Unstructured

Conversation

@amintorabi88

@amintorabi88 amintorabi88 commented Nov 8, 2026 •

Copy link
Copy Markdown

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 from BaseModel. It trains on soft weak labels with binary cross-entropy through the multilabel label processor, accepts an optional per-note sample_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's Trainer: the loss uses the soft weak labels, while the returned y_true is binary so the multilabel metrics can score it. That is the gold labels when the batch has them under the optional gold_key, so Trainer.evaluate reports 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 top top_k rules 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 from encode_stress_prompts in pyhealth/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. KeywordLabeler only needs an object with encode(texts), so any encoder can replace it.
    • vote_diagnostics, snorkel_memory_gb, nltk_english_stopwords: helpers.
  • No new dependencies. NLTK (keyword mining) and Snorkel (the optional label model) are imported only when used; without them the functions raise an ImportError with the install command, which is also on the KeyClass docs page.
  • The docs and notebook point to 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 as category_ids and its labels as gold_key for 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:

  • Example notebook on synthetic notes, three seeds each: phrase rules beat single-word rules (test F1 0.79 vs 0.64); the rule budget has a sweet spot (top_k=30 gives F1 0.79, 300 gives 0.65); input standardization raises F1 from 0.69 to 0.79.
  • MIMIC-III v1.4, 19 ICD-9 categories, BlueBERT embeddings, all 39,443 training notes, evaluated on 13,271 held-out notes: sample-averaged F1 0.493 [0.490, 0.496], precision 0.436, recall 0.660, compared with 0.456 for always predicting categories with training prevalence of at least 50% and 0.625 reported in the paper. The paper's self-training step lowered F1 to 0.260 on this multilabel task by concentrating each note's scores on one category, so the classifier before self-training is our main result. MIMIC-III cannot be redistributed, so these numbers come from an offline run with our course reproduction scripts (cohort and split, pipeline, evaluation), which use a standalone copy of this PR's code and are not part of the PR. The 1-gram ablation was run on synthetic notes only, not on MIMIC-III.

Files to Review:

  • pyhealth/models/keyclass.py: the KeyClass model
  • pyhealth/weak_supervision/keyclass.py: note cleaning, labeling functions, vote aggregation, confident-note selection
  • pyhealth/weak_supervision/encoders.py: ClinicalTextEncoder
  • pyhealth/weak_supervision/__init__.py, pyhealth/models/__init__.py: exports
  • tests/core/test_keyclass.py: unit tests on synthetic data, including training and evaluation with Trainer
  • examples/synthetic_icd9_keyclass.ipynb: full pipeline and ablations on synthetic notes (about 1 minute on a CPU), plus documented MIMIC-III results
  • docs/api/models/pyhealth.models.KeyClass.rst, docs/api/models.rst: API documentation, with installation and MIMIC-III data sections

Testing: python -m pytest tests/core/test_keyclass.py runs 23 tests on synthetic data in under a second, with 100% line coverage of the four KeyClass files. They include Trainer training and evaluation with weak labels only and with gold labels, and ClinicalTextEncoder tests 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

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.
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.
@github-actions

github-actions Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

Test Coverage

Total: 88.19% (57243 / 64907 lines)

Modified file Coverage Lines
pyhealth/models/__init__.py 100.00% 121 / 121
pyhealth/models/keyclass.py 100.00% 68 / 68
pyhealth/weak_supervision/__init__.py 100.00% 9 / 9
pyhealth/weak_supervision/encoders.py 100.00% 25 / 25
pyhealth/weak_supervision/keyclass.py 100.00% 148 / 148

Workflow run · 94643ee

@amintorabi88
amintorabi88 marked this pull request as ready for review November 28, 2026 00:02
Cover input validation, optional Snorkel and NLTK paths, and clinical text encoding with a locally initialized BERT model.
@solarsys solarsys added the status: manual Pending maintainer's review label Nov 28, 2026
@solarsys

Copy link
Copy Markdown
Collaborator

/review

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previous review

Reviewed commit 25410d1

Comment thread pyhealth/models/keyclass.py Outdated
logits, targets, reduction="none"
).mean(dim=1)
loss = (per_note * weights).mean()
result.update(y_true=targets, loss=loss)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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",

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. Trainer compatibility. KeyClass.forward returns the soft weak labels as y_true. With the default multilabel metrics, Trainer.evaluate would 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_true or 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.
  2. Overlap with an existing encoder. ClinicalTextEncoder appears to duplicate the Hugging Face loading, batching, truncation and masked mean pooling in encode_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.
Comment thread pyhealth/models/keyclass.py Outdated
logits, targets, reduction="none"
).mean(dim=1)
loss = (per_note * weights).mean()
result.update(y_true=targets, loss=loss)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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",

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@amintorabi88

Copy link
Copy Markdown
Author

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?

@solarsys

Copy link
Copy Markdown
Collaborator

/review

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 ClinicalTextEncoder doesn't reuse clip_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_weight through the input schema, as the notebook does.

Reviewed commit 1ebfbec

@solarsys

Copy link
Copy Markdown
Collaborator

Why this PR has status: manual: it edits pyproject.toml, adding a keyclass extra with snorkel and nltk. Any file outside docs/ examples/ pyhealth/ test-resources/ tests/ sends a PR to manual review, because adding dependencies is a maintainer decision. Everything else is self-contained, and the AI review already suggests approve.

To make it eligible for automatic review:

  • Drop the pyproject.toml change. Keep the snorkel and nltk imports optional, raise an ImportError that says what to install when they're missing, and give the install command on the KeyClass docs page.
  • If you think the extra is really needed, say why here, and a maintainer will decide.

Related: #1663 (merged today) adds MIMIC3ICD9CategoryClassification, the 19-category MIMIC-III task from the same paper. You may want to point your docs or example at it.

Once that's pushed, we'll switch the label to status: automatic and request a fresh AI review. If the AI review approves, it merges the PR.

@amintorabi88

Copy link
Copy Markdown
Author

Thanks. Done in 94643ee: the pyproject.toml change is dropped. NLTK and Snorkel stay optional imports that raise an ImportError with the install command, and the KeyClass docs page now has an Installation section with it. The docs and notebook also point to MIMIC3ICD9CategoryClassification from #1663, including how to use its labels for evaluation through gold_key. The PR now only touches docs/, examples/, pyhealth/ and tests/.

Copy link
Copy Markdown
Collaborator

/review


Generated by Claude Code

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed commit 94643ee

import numpy as np


class ClinicalTextEncoder:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 existing FrozenTextEncoder in pyhealth/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 with encode_stress_prompts, and they don't mention FrozenTextEncoder. They also don't mention that encode_stress_prompts already offers pooling="masked_mean". Please state in the description what ClinicalTextEncoder does that FrozenTextEncoder cannot, for example how it handles empty input, truncation or the encode(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_key is configured but missing from a batch, KeyClass silently falls back to the thresholded weak labels as y_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 MIMIC3ICD9CategoryClassification would help.

Reviewed commit 94643ee

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

status: manual Pending maintainer's review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants