Skip to content
DecadentryPublic

About

Hierarchical label-wise attention (HLAN) for explainable multi-label coding, with label-embedding initialisation and ERASER faithfulness tests. Research use only.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

labelwise

tests DOI License: MIT Python

Hierarchical label-wise attention networks (HLAN) for explainable multi-label coding, with label-embedding initialisation and ERASER faithfulness tests for the explanations.

Research and education use only. labelwise is not a medical device and must not be used to code real patient records or to support clinical decisions.

labelwise is an independent PyTorch implementation of the method of Dong, Suárez-Paniagua, Whiteley and Wu, Explainable automated coding of clinical notes using hierarchical label-wise attention networks and label embedding initialisation, Journal of Biomedical Informatics 116:103728 (2021), doi:10.1016/j.jbi.2021.103728. It adds what is needed to check label-wise explanations: ERASER comprehensiveness and sufficiency (DeYoung et al., ACL 2020), two alternative explainers (gradient x input, leave-one-out occlusion) plus a random reference, synthetic notes with planted evidence, and a public, re-buildable benchmark. The authors' own code (github.com/acadTags/Explainable-Automated-Medical-Coding, TensorFlow 1) was not used or copied. The authors have not reviewed or endorsed this package.

What it does

Part Module
HLAN (label-wise word + sentence attention), HA-GRU-style (shared word, label-wise sentence attention), HAN (shared attention) labelwise.models
Label-embedding (LE) initialisation: skip-gram with negative sampling over training label sets, injected into the label-wise context vectors and output layer labelwise.label_embedding
CPU training with early stopping; micro/macro F1 and AUC, P@k labelwise.train, labelwise.metrics
Token importance per label: attention (word x sentence), gradient x input, leave-one-out occlusion, random labelwise.explain
ERASER comprehensiveness / sufficiency with token deletion, AOPC over 1, 5, 10, 20, 50 % labelwise.faithfulness
Plausibility (token AUPRC) against known evidence labelwise.faithfulness, labelwise.synthetic
Synthetic dental notes with label-specific evidence and negated distractors labelwise.synthetic
PubMed dental corpus builder (16 MeSH major topics, NCBI E-utilities) labelwise.pubmed
CLI: demo, download, train, explain labelwise.cli

Quickstart

pip install torch --index-url https://download.pytorch.org/whl/cpu   # CPU build is enough
pip install "git+https://github.com/Decadentry/labelwise"
labelwise demo                       # trains a small HLAN on synthetic notes (well under a minute on CPU) and explains one label
labelwise demo --model han --method occlusion

Real-text workflow (downloads about 7,600 PubMed abstracts; please respect the NCBI usage policy):

labelwise download --out data/pubmed_dental.jsonl
labelwise train --data data/pubmed_dental.jsonl --out hlan.pt --model hlan --le
labelwise explain --checkpoint hlan.pt --label periodontitis --method attention \
  --text "Periodontitis was associated with deeper probing depths. Clinical attachment loss was measured."

Python:

from labelwise import HLAN, TrainConfig, train_model, explain, faithfulness
model, history = train_model(x_train, y_train, x_val, y_val, vocab_size, TrainConfig(model="hlan", label_embedding_init=True))
scores = explain(model, x_test[0], label=3, method="attention")      # (sentences, words)
print(faithfulness(model, x_test[0], 3, scores)["aopc_comprehensiveness"])

Data

  • PubMed dental MeSH corpus (built by scripts/download_pubmed_dental.py, not redistributed): titles and abstracts of English articles 2015-2024, 50 per label and year sampled from 16 dental MeSH major topics (periodontitis, gingivitis, dental caries, dental implants, peri-implantitis, malocclusion, orthodontic appliances, mouth neoplasms, oral lichen planus, TMJ disorders, root canal therapy, pulpitis, third molar, dentin sensitivity, tooth erosion, cleft palate). Labels are exact: every label's complete PMID set per year is retrieved, so each document carries all of its 16 labels. 7,621 documents; 1,112 have two or more labels. Temporal split: train 2015-2021 (5,164), validation 2022 (775), test 2023-2024 (1,682). Years come from PubMed's [dp] search, which matches both the electronic and the print date; 2,175 documents matched two years and were assigned the later one, so the split boundaries are approximate (no document is in two splits). Sampling a fixed number per label and year balances the labels against their natural frequency and over-represents multi-label articles. MeSH indexing of articles is a public stand-in for clinical coding; abstracts are not clinical notes.
  • Synthetic notes (labelwise.synthetic): 6 labels, 30 % prevalence each, 3-7 neutral sentences, one evidence sentence per positive label and negated mentions ("no signs of attachment loss") for 30 % of the negative labels. No real patient data anywhere.
  • MIMIC-III, used in the paper, needs credentialed access and was not used.

Results

All numbers are produced by experiments/*.py and stored in results/*.json; tables are regenerated by experiments/make_figures.py (docs/results_tables.md). CPU only (2 cores), embedding 100, BiGRU 2 x 64, Adam 2e-3, batch 32, up to 10 epochs with early stopping on validation micro-F1 (patience 2), threshold 0.5. Inputs are truncated to 16 sentences x 40 words (46 % of abstracts lose some text, 6 % of all tokens); the TF-IDF baseline sees the full text. Sentences are split at terminal punctuation.

Coding performance, PubMed dental test years 2023-2024 (n = 1,682)

Model Seeds Micro-F1 Macro-F1 Micro-AUC Macro-AUC P@1
TF-IDF + logistic regression - 0.809 0.808 0.997 0.996 0.963
HAN 1 0.921 0.926 0.997 0.996 0.956
HA-GRU 1 0.920 0.923 0.997 0.996 0.960
HLAN 3 0.905 ± 0.002 0.910 ± 0.003 0.992 ± 0.001 0.991 ± 0.000 0.952 ± 0.003
HLAN + LE 3 0.913 ± 0.011 0.919 ± 0.009 0.995 ± 0.001 0.994 ± 0.002 0.957 ± 0.004

(mean ± SD over seeds.) On this small, mostly single-label task (85 % of documents have one label) HLAN did not outperform the simpler HAN and HA-GRU. This comparison is confounded by training length: all HLAN runs stopped early at epoch 6, while HAN and HA-GRU reached the 10-epoch cap (HAN was still improving), so it does not show that HLAN is worse. LE initialisation raised HLAN's micro-F1 by 0.008 on average (per seed: 0.916 vs 0.904, 0.901 vs 0.907, 0.922 vs 0.905), the same direction as in the paper but not a consistent effect here; LE runs also trained longer (8-10 epochs). The TF-IDF model ranks labels as well as the neural models (AUC) but its probabilities are poorly placed for the fixed 0.5 threshold. Absolute values are not comparable with the paper (MIMIC-III discharge summaries, other labels).

Are the explanations faithful? PubMed test sample (60 documents, 65 gold-positive document-label pairs)

Model Explainer AOPC comprehensiveness (95 % CI) AOPC sufficiency (95 % CI)
HLAN attention 0.748 (0.692 to 0.804) -0.018 (-0.034 to -0.001)
HLAN grad_input 0.537 (0.457 to 0.617) -0.052 (-0.083 to -0.020)
HLAN occlusion 0.483 (0.401 to 0.565) -0.077 (-0.113 to -0.041)
HLAN random 0.052 (0.032 to 0.072) 0.533 (0.461 to 0.604)
HLAN + LE attention 0.785 (0.739 to 0.831) -0.020 (-0.042 to 0.002)
HA-GRU attention 0.651 (0.586 to 0.716) 0.017 (-0.004 to 0.038)
HAN attention 0.571 (0.498 to 0.644) 0.010 (-0.004 to 0.023)

(Full table with all explainers: docs/results_tables.md. Intervals are normal-approximation 95 % CIs over document-label pairs and ignore that pairs from the same document are correlated.) Pairs are all gold-positive document-label pairs, whether or not the model predicted the label. Deleting the 1-50 % of tokens that HLAN's own label-wise attention ranks highest lowered the label probability by 0.75 on average (mean starting probability 0.875), more than gradient x input, leave-one-out occlusion or random deletion; keeping only those tokens preserved the prediction (sufficiency near 0 or negative). Comprehensiveness depends on each model's starting probability, so between-model differences are indicative only.

HLAN faithfulness by rationale size

Do the explanations point to the right evidence? Synthetic notes (120 test notes, seed 0)

Smaller models here (embedding 50, BiGRU 2 x 32, up to 8 epochs); 2,000 training notes.

Model Explainer AUPRC vs evidence sentence same, notes with >= 2 labels AUPRC vs bracketed key tokens
HLAN attention 0.897 0.896 0.329
HA-GRU attention 0.656 0.646 0.401
HAN attention 0.223 0.211 0.141
any random 0.206 0.202 0.095

All three models classify the synthetic notes perfectly (micro-F1 1.000). HLAN's label-wise attention located each label's own evidence sentence best (AUPRC 0.897); gradient x input and occlusion also did well on HLAN and HA-GRU (0.63-0.72, full table in docs/results_tables.md). HAN's attention is shared by all labels by construction, so its near-random score is expected. With one seed on template text this is consistent with, not proof of, the paper's claim that label-wise attention gives label-specific explanations. Token AUPRC against the hand-marked key phrases is low for every method because the models also use other words of the evidence sentences that are unique to each label in the templates (a limitation of the generator).

Limitations

  • PubMed abstracts and MeSH major topics are a public proxy, not clinical notes or ICD codes; 16 labels only, one sample of about 50 documents per label-year, one test period.
  • Few seeds (3 for HLAN variants, 1 for the others); faithfulness on 60 test documents.
  • ERASER metrics measure the model's dependence on the highlighted tokens, not whether a clinician would accept the explanation; plausibility was checked only on synthetic text.
  • Word embeddings are trained from scratch (the paper used word2vec pre-trained on MIMIC-III); LE uses our own skip-gram implementation instead of gensim, and label vectors are L2-normalised and rescaled to the norm of the random initialisation before injection.
  • NLM introduced automated MeSH indexing in 2022, so test-year labels may be partly machine-assigned while most training labels were assigned by human indexers.
  • Synthetic notes can have up to 19 sentences but models read 16, so an evidence sentence is occasionally cut.
  • labelwise demo trains for 4 epochs only; HAN needs more epochs than HLAN to fit the synthetic notes.
  • Bidirectional GRUs run over padding (no sequence packing), so predictions change slightly with the padded size.
  • Trained checkpoints are not distributed because the abstracts are copyrighted; re-train with the scripts.

Reproduce

pip install -e ".[dev,figures]"
python scripts/download_pubmed_dental.py
python experiments/run_pubmed_performance.py      # ~1 h on 2 CPU cores
python experiments/run_pubmed_faithfulness.py
python experiments/run_synthetic.py
python experiments/make_figures.py
python -m pytest -q

Intended use

Teaching and research on explainable multi-label text classification: comparing explanation methods, checking whether attention explanations are faithful, and building label-specific explanations for coding tasks. Not for coding real health records, billing or clinical decisions.

How to cite

Please cite the software and the paper it implements:

Boustani Hezarani H. labelwise: hierarchical label-wise attention networks with faithfulness evaluation of label-wise explanations (v1.0.0). Zenodo. doi:10.5281/zenodo.24662933 (all versions; v1.0.0: 10.5281/zenodo.24662934)

Dong H, Suárez-Paniagua V, Whiteley W, Wu H. Explainable automated coding of clinical notes using hierarchical label-wise attention networks and label embedding initialisation. J Biomed Inform. 2021;116:103728. doi:10.1016/j.jbi.2021.103728

A short technical note is in docs/technical_note.pdf.

Acknowledgements

Method: Dong et al. (2021). Faithfulness metrics: DeYoung et al., ERASER (ACL 2020). Data: US National Library of Medicine (PubMed, MeSH) via NCBI E-utilities.

Licence

MIT © 2026 Hossein Boustani Hezarani / Decadentry.

About

Hierarchical label-wise attention (HLAN) for explainable multi-label coding, with label-embedding initialisation and ERASER faithfulness tests. Research use only.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages