Automated Diagnosis Coding Engine for Long Clinical Notes
Machine LearningModel answerLast updated
Design a service that reads long clinical notes, suggests ICD-10 codes with calibrated confidence and cited evidence, and learns from medical coder corrections over time.
Scenario
A health-tech company turns doctor-patient conversations into structured encounter notes. It now wants a service that reads each finished note and proposes diagnosis codes from the ICD-10-CM catalog, so that human medical coders can review suggestions instead of coding from scratch. Suggestions feed billing and risk-adjustment workflows.
What the system must do
- Accept an unstructured clinical note and return a ranked list of ICD-10-CM codes, each with a calibrated confidence score.
- For every suggested code, point to the exact text spans in the note that justify it.
- Expose an API or UI where coders can accept, reject, or manually add codes.
- Fold coder feedback back into the models over time without degrading what the models already do well.
Constraints and assumptions
- Label space: roughly 70,000 billable codes. More than 80% of them appear fewer than 10 times in historical training data, and some never appear.
- Input length: notes commonly run several thousand tokens and can reach tens of thousands, far beyond a 512-token encoder window.
- Latency: suggestions for a standard note should return within about 2 seconds.
- Compliance and safety: the system must meet HIPAA requirements, and it must limit hallucinated codes and over-coding (suggesting codes the documentation does not support).
What to cover in your answer
- How you process long documents (tokenization, chunking, pooling, long-context architectures).
- How you handle the extreme multi-label problem: flat classification versus retrieval against code descriptions versus hierarchical routing.
- How you deal with rare and zero-shot codes.
- Which evaluation metrics you use across frequent, mid-frequency, and rare codes, and how you measure audit risk.
- How the coder feedback loop works: capturing corrections, handling label noise, active learning, and safe model updates.
State your assumptions about traffic and scale, and discuss trade-offs.
Hints
Hint 1
Start with numbers: label count, note length, daily volume, peak QPS, and a latency budget per pipeline stage. Decide early whether precision or recall matters more for billing-sensitive codes.
Hint 2
No single model handles both the head and the tail. Think of a two-stage design: several candidate generators (a classifier for frequent codes, embedding retrieval over code descriptions, hierarchy-based routing) unioned for high recall, followed by a precision-oriented reranker and rule checks.
Hint 3
Make evidence a hard requirement: negated, family-history, or historical mentions should not produce a code. Add a grounding gate that drops any suggestion without a supporting present-tense span.
Hint 4
Evaluate per frequency bucket, not only globally. Micro-F1 is dominated by frequent codes, so also report macro-F1, recall of the candidate stage, and precision on high-risk codes.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify scope and assumptions
- Labels: about 70k billable codes; most have under 10 examples, some none.
- Notes: 2k-8k tokens typical, up to about 20k. Assume 500k notes/day, which is about 6 QPS average and about 30 QPS at peak. Each note has roughly 5-15 gold codes.
- Latency: p95 under 2 s for a standard note. Very long notes go through an async path.
- Output: top-K (about 20) codes with calibrated probability, evidence spans, and a flag for risk-adjustment-relevant codes.
- Safety stance: over-coding creates legal and financial exposure, so precision on billing-sensitive codes matters more than recall. A coder can add a missed code but may not catch a plausible-looking wrong one.
- Compliance: PHI stays in a BAA-covered private network, encrypted at rest and in transit. Training uses de-identified data. Every suggestion and coder action goes to an immutable audit log.
2. Architecture
Preprocessing. Split into sections (HPI, Assessment/Plan, history, family history, medications) and sentences. Run clinical NER plus an assertion classifier that labels each mention as present, negated, possible, historical, or family. Section type is a strong feature: Assessment/Plan is the best signal, family history should suppress codes.
Chunk encoding. Use a domain-pretrained clinical encoder over 512-token windows with about 64 tokens of overlap, aligned to section boundaries, with a section embedding added. Batch all chunks of a note in one GPU pass.
Long-document pooling. Mean-pooling dilutes a diagnosis mentioned once on page 4. Use label-wise attention: each code has a query vector that attends over all chunk representations, as in LAAT/PLM-ICD style models. Alternatives are sparse-attention models (Longformer/BigBird, 4k-16k tokens) and hierarchical transformers (chunk encoder followed by a small document-level transformer). Sparse attention captures cross-chunk context but costs memory and latency. The hierarchical option is a good compromise.
Candidate generation (union, about 200 candidates).
| Generator | Strength | Weakness |
|---|---|---|
| Flat sigmoid head over about 3k head/torso codes | Precise where data is plentiful | Useless for tail; a flat 70k output layer undertrains rare codes |
| Bi-encoder retrieval of chunks against code embeddings (ANN index) | Zero-shot; new codes added by embedding, no retraining | Weak on fine distinctions (laterality, "with/without complication") |
| Hierarchical routing (chapter, category, subcategory) | Shares statistical strength among siblings; cheap pruning | Errors at upper levels cascade down |
Track candidate recall@200 as its own metric: the reranker cannot recover a code that was never generated.
Reranker. A distilled cross-encoder scores (code description, top-3 retrieved chunks) pairs, fused with the head logit, retrieval similarity, and assertion features. This resolves the fine distinctions the bi-encoder misses.
Calibration and rules. Fit temperature or isotonic calibration per frequency bucket, because a single global calibrator misrepresents tail codes. Then apply rules: mutual-exclusion conflicts, age/sex edits, and most-specific-code-wins. A final grounding gate drops any code without a present-assertion evidence span.
Latency budget (about 1.3 s p95): preprocessing/NER 150 ms, encoding 250 ms, ANN 20 ms, head and routing 50 ms, reranking about 400 ms, rules and calibration 50 ms, remainder for network and overhead.
3. Rare and zero-shot codes
- Build code embeddings from the official description, synonyms/index terms, ontology concept names (UMLS/SNOMED), and parent/sibling text. Optionally smooth them over the hierarchy with a graph network.
- Contrastively pretrain the bi-encoder on (mention, concept) pairs from the ontology, which needs no notes for the target code.
- Use LLM-generated synthetic snippets for zero-count codes only to train retrieval, never as evaluation data (leakage and optimistic bias).
- Upweight tail codes with focal loss or inverse-frequency sampling, and mine hard negatives from sibling codes.
- Route low-confidence tail suggestions to mandatory human review rather than auto-accepting.
4. Evidence attribution
Take evidence from the reranker's top chunk, then the best sentence, combined with NER spans linked to the code's concept. This is more faithful than raw attention weights, which are unreliable explanations. Use gradient-based saliency offline for debugging only.
5. Evaluation
- Micro-F1 reflects overall volume but is dominated by frequent codes.
- Macro-F1 exposes tail performance; report it per bucket (head, torso, tail, zero-shot).
- Precision@K / NDCG@K measure the quality of the ranked list a coder actually sees.
- Candidate recall@200 isolates stage-one failures.
- Safety metrics: precision on high-risk codes, ungrounded-suggestion rate (should be about zero), calibration error (ECE) per bucket, and over-coding rate on audited samples.
- Operational metrics: coder acceptance rate, edits per note, time per note.
- Split by patient and by time, not randomly, to avoid leakage and to catch code-set drift.
6. Feedback loop and active learning
- Log every accept/reject/add with coder ID, timestamp, and reason.
- Treat actions as noisy labels. Weight by coder reliability, measured against an audited gold set. Beware automation bias: coders accepting everything inflates agreement, so inject audited control notes.
- Rejections are hard negatives; manual additions are likely recall failures and good candidate-generation training data.
- Active learning: send notes with uncertain scores, tail codes, or high model-coder disagreement for expert review.
- Retrain on a schedule using a replay buffer of past data, with per-bucket regression tests, to avoid catastrophic forgetting. Update the annual code set by adding new embeddings and retiring inactive codes.
- Roll out via shadow mode, then canary, with automatic rollback if precision on risk codes drops.
7. Common mistakes
- Using only a flat 70k-way classifier and ignoring the tail.
- Mean-pooling a long note into one vector.
- Ignoring negation and family history, which causes false codes.
- Reporting only micro-F1 and a single global calibration.
- Using synthetic data in evaluation.
- Training directly on raw coder clicks without noise handling or audits.
- Letting the system emit a code it cannot ground in text.