{ "cells": [ { "cell_type": "markdown", "id": "7215a5aa", "metadata": {}, "source": [ "# ICD-Codable Sentence Classification — Weak Supervision + Bio_ClinicalBERT\n", "\n", "**CSCE 633 Final Project**\n", "\n", "Binary classifier for *\"does this clinical text chunk contain ICD-codable medical information?\"* The 20 provided labels are themselves BERT-generated and noisy, so we treat them as one weak source among several rather than gold ground truth.\n", "\n", "## Pipeline\n", "\n", "1. **Mine MIMIC-III** (`NOTEEVENTS.csv`) for ~10k discharge-summary chunks shaped like the test inputs\n", "2. **Apply labeling functions** — heuristics that vote `1`, `0`, or abstain on each chunk\n", "3. **Aggregate with Snorkel's `LabelModel`** to get probabilistic training labels that account for LF accuracy and correlation\n", "4. **Fine-tune Bio_ClinicalBERT** on the soft labels (binary cross-entropy)\n", "5. **Predict** on `test{01,02,03}_text_only.csv` → write Gradescope-shaped CSVs\n", "\n", "The 20 provided labels are **never used for training**, only as a sanity-check oracle (with the caveat that they are themselves noisy).\n", "\n", "## Run order\n", "\n", "Run cells top to bottom. Cells in **Section 1** must be edited to point at your local MIMIC-III install. Cells in **Section 6** (training) need a GPU; everything else runs comfortably on CPU.\n" ] }, { "cell_type": "markdown", "id": "43774d01", "metadata": {}, "source": [ "## Section 0 — Install dependencies\n", "\n", "Run this once. If you're on Colab, this also installs Snorkel and the right transformers version.\n" ] }, { "cell_type": "code", "execution_count": null, "id": "5085c1bb", "metadata": {}, "outputs": [], "source": [ "# !pip install -q numpy pandas scikit-learn snorkel torch transformers datasets pyarrow tqdm\n", "# Uncomment above on first run. Comment out afterwards to skip the slow pip step.\n" ] }, { "cell_type": "markdown", "id": "2515e3dd", "metadata": {}, "source": [ "## Section 1 — Configuration\n", "\n", "**Edit the paths below before running.**\n" ] }, { "cell_type": "code", "execution_count": null, "id": "76f6aacd", "metadata": {}, "outputs": [], "source": [ "from pathlib import Path\n", "\n", "# ----- EDIT THESE -----------------------------------------------------------\n", "MIMIC_NOTEEVENTS_PATH = Path(\"./noteevents.csv\") # <-- EDIT\n", "PROJECT_FILES_DIR = Path(\"./project_files\") # contains the provided test/train CSVs\n", "# ---------------------------------------------------------------------------\n", "\n", "# Working directories (created automatically)\n", "WORK_DIR = Path(\"./icd_work\")\n", "DATA_DIR = WORK_DIR / \"data\"\n", "OUTPUT_DIR = WORK_DIR / \"outputs\"\n", "MODEL_DIR = OUTPUT_DIR / \"bert_model\"\n", "for d in (DATA_DIR, OUTPUT_DIR):\n", " d.mkdir(parents=True, exist_ok=True)\n", "\n", "# Cached intermediate artifacts\n", "MIMIC_CHUNKS_PATH = DATA_DIR / \"mimic_chunks.parquet\"\n", "LF_VOTES_PATH = DATA_DIR / \"lf_votes.npy\"\n", "SOFT_LABELS_PATH = DATA_DIR / \"soft_labels.npy\"\n", "TRAINING_SET_PATH = DATA_DIR / \"training_set.parquet\"\n", "\n", "# Mining hyperparameters\n", "N_MIMIC_NOTES_TO_SCAN = 6000\n", "CHUNK_TARGET_WORDS = 110\n", "CHUNK_MIN_WORDS = 40\n", "CHUNK_MAX_WORDS = 180\n", "CHUNKS_PER_NOTE_CAP = 8\n", "RANDOM_SEED = 42\n", "\n", "# Snorkel\n", "LABEL_MODEL_EPOCHS = 500\n", "LABEL_MODEL_LR = 0.01\n", "DROP_ALL_ABSTAIN = True\n", "\n", "# Bio_ClinicalBERT\n", "BERT_MODEL_NAME = \"emilyalsentzer/Bio_ClinicalBERT\"\n", "MAX_SEQ_LEN = 256\n", "BATCH_SIZE = 16\n", "EVAL_BATCH_SIZE = 32\n", "LEARNING_RATE = 2e-5\n", "NUM_EPOCHS = 3\n", "WARMUP_RATIO = 0.1\n", "WEIGHT_DECAY = 0.01\n", "\n", "# Decision threshold for binary prediction at inference time\n", "DECISION_THRESHOLD = 0.5\n", "\n", "print(f\"MIMIC NOTEEVENTS: {MIMIC_NOTEEVENTS_PATH} exists={MIMIC_NOTEEVENTS_PATH.exists()}\")\n", "print(f\"Project files: {PROJECT_FILES_DIR} exists={PROJECT_FILES_DIR.exists()}\")\n", "print(f\"Work dir: {WORK_DIR.resolve()}\")\n" ] }, { "cell_type": "markdown", "id": "76fed1d0", "metadata": {}, "source": [ "## Section 2 — Labeling functions\n", "\n", "Each LF takes a chunk of clinical text and votes:\n", "\n", "* `1` → contains ICD-codable medical info (positive)\n", "* `0` → does NOT contain ICD-codable medical info (negative)\n", "* `-1` → abstain\n", "\n", "**Design philosophy.** Each LF encodes ONE narrow, interpretable signal. Snorkel's `LabelModel` learns each LF's accuracy from agreement statistics across many examples, so noisy LFs are fine as long as they're better than random and not perfectly correlated.\n", "\n", "**Signals observed in the 20 training examples:**\n", "\n", "*Positive cues:* `Discharge Diagnosis:` sections, `# DiagnosisName:` problem-list markers, past-tense treatment narratives, dense diagnosis vocabulary\n", "\n", "*Negative cues:* mostly numbers + lab units, imaging-finding narratives (\"arteriogram shows...\"), pharmacy dispensing lines (`Disp:*N Tablet(s)*`), microbiology susceptibility tables, vital-sign clusters\n" ] }, { "cell_type": "code", "execution_count": null, "id": "737b0baf", "metadata": {}, "outputs": [], "source": [ "import re\n", "import numpy as np\n", "\n", "ABSTAIN = -1\n", "NEG = 0\n", "POS = 1\n", "\n", "# ---------------------------------------------------------------------------\n", "# Vocabulary\n", "# ---------------------------------------------------------------------------\n", "DIAGNOSIS_TERMS = [\n", " # cardio\n", " \"myocardial infarction\", \"MI\", \"STEMI\", \"NSTEMI\", \"CAD\",\n", " \"coronary artery disease\", \"cardiogenic shock\", \"atrial fibrillation\",\n", " \"afib\", \"CHF\", \"heart failure\", \"cardiomyopathy\", \"endocarditis\",\n", " \"pericarditis\", \"hypertension\", \"HTN\", \"hyperlipidemia\", \"hypercalcemia\",\n", " \"hyperparathyroidism\", \"hypothyroidism\",\n", " # renal\n", " \"ESRD\", \"CKD\", \"AKI\", \"acute kidney injury\", \"chronic kidney disease\",\n", " \"renal failure\", \"nephropathy\",\n", " # pulm\n", " \"pneumonia\", \"COPD\", \"asthma\", \"pulmonary embolism\", \"PE\", \"ARDS\",\n", " \"respiratory failure\", \"atelectasis\",\n", " # neuro\n", " \"stroke\", \"CVA\", \"SAH\", \"subarachnoid hemorrhage\", \"ICH\", \"seizure\",\n", " \"hydrocephalus\", \"aneurysm\", \"encephalopathy\", \"dementia\",\n", " # GI\n", " \"GI bleed\", \"cirrhosis\", \"pancreatitis\", \"cholecystitis\", \"hepatitis\",\n", " \"obstruction\",\n", " # endo\n", " \"diabetes\", \"DM\", \"DKA\", \"hyperglycemia\", \"hypoglycemia\",\n", " # heme/onc\n", " \"anemia\", \"thrombocytopenia\", \"leukemia\", \"lymphoma\", \"neutropenia\",\n", " # infectious\n", " \"sepsis\", \"bacteremia\", \"UTI\", \"cellulitis\", \"osteomyelitis\", \"MRSA\",\n", " \"MSSA\", \"abscess\",\n", " # trauma / orthopedic\n", " \"fracture\", \"femur fracture\", \"hip fracture\", \"motor vehicle crash\",\n", " \"MVC\", \"MVA\",\n", " # other\n", " \"paraplegia\", \"gangrene\", \"ulcer\", \"intracranial hypertension\",\n", " \"pyrexia\",\n", "]\n", "\n", "_DX_RE = re.compile(\n", " r\"\\b(\" + \"|\".join(re.escape(t.lower()) for t in DIAGNOSIS_TERMS) + r\")\\b\",\n", " re.IGNORECASE,\n", ")\n", "\n", "POSITIVE_SECTION_PATTERNS = [\n", " r\"discharge diagnosis\\s*:\",\n", " r\"primary diagnosis\\s*:\",\n", " r\"secondary diagnosis\\s*:\",\n", " r\"chief complaint\\s*:\",\n", " r\"history of present illness\\s*:\",\n", " r\"past medical history\\s*:\",\n", " r\"discharge instructions\\s*:\",\n", " r\"hospital course\\s*:\",\n", " r\"active issues\\s*:\",\n", " r\"problem list\\s*:\",\n", " r\"assessment and plan\\s*:\",\n", " r\"admitting diagnosis\\s*:\",\n", "]\n", "_POS_SECTION_RE = re.compile(\"|\".join(POSITIVE_SECTION_PATTERNS), re.IGNORECASE)\n", "\n", "_PROBLEM_MARKER_RE = re.compile(r\"(^|\\n)\\s*#\\s*[A-Za-z][^:\\n]{1,60}:\")\n", "\n", "_NEG_SECTION_RE = re.compile(\n", " r\"(reason for( this)? examination|comparison\\s*:|technique\\s*:|indication\\s*:)\",\n", " re.IGNORECASE,\n", ")\n", "\n", "_DISP_RE = re.compile(r\"disp\\s*:\\s*\\*\\s*\\d\", re.IGNORECASE)\n", "\n", "_LAB_UNITS_RE = re.compile(\n", " r\"\\b(mg/d[lL]|mEq/L|K/uL|mmol/L|g/d[lL]|mcg/mL|ng/mL|IU/L|U/L|\"\n", " r\"mm\\s*Hg|bpm|%)\\b\"\n", ")\n", "\n", "_VITALS_CLUSTER_RE = re.compile(\n", " r\"\\b(BP|HR|RR|Sat|SpO2|T|Temp)\\b\\s*\\d\", re.IGNORECASE\n", ")\n", "\n", "_IMAGING_MEASUREMENT_RE = re.compile(r\"\\b\\d+(\\.\\d+)?\\s*(mm|cm)\\b\", re.IGNORECASE)\n", "\n", "_RAD_TECHNIQUE_RE = re.compile(\n", " r\"\\b(microcatheter|microwire|guidewire|french catheter|ultrasoft|\"\n", " r\"target coil|arteriogram|fluoroscop)\", re.IGNORECASE\n", ")\n", "\n", "_RAD_NARRATIVE_RE = re.compile(\n", " r\"\\b(catheterized|filming|coiled|embolization|arteriogram shows|\"\n", " r\"injection|exchanged out|advanced|deployed)\\b\",\n", " re.IGNORECASE,\n", ")\n", "\n", "_DISCHARGE_COND_RE = re.compile(\n", " r\"(mental status\\s*:|level of consciousness\\s*:|activity status\\s*:)\",\n", " re.IGNORECASE,\n", ")\n", "\n", "\n", "def _word_count(text):\n", " return len(text.split())\n", "\n", "\n", "def _digit_density(text):\n", " toks = text.split()\n", " if not toks:\n", " return 0.0\n", " digity = sum(\n", " 1 for t in toks\n", " if sum(c.isdigit() for c in t) >= max(1, len(t) // 2)\n", " )\n", " return digity / len(toks)\n" ] }, { "cell_type": "markdown", "id": "24ce62fe", "metadata": {}, "source": [ "### Section 2.1 — The labeling functions themselves\n" ] }, { "cell_type": "code", "execution_count": null, "id": "21cf1c4d", "metadata": {}, "outputs": [], "source": [ "# ====== Positive LFs ========================================================\n", "\n", "def lf_discharge_diagnosis_section(text):\n", " \"\"\"Discharge / primary / secondary / admitting diagnosis sections.\"\"\"\n", " if re.search(r\"(discharge|primary|secondary|admitting)\\s+diagnosis\\s*:\",\n", " text, re.IGNORECASE):\n", " return POS\n", " return ABSTAIN\n", "\n", "\n", "def lf_problem_list_marker(text):\n", " \"\"\"'# CAD:', '# ESRD on HD:' style problem-list entries.\"\"\"\n", " if len(_PROBLEM_MARKER_RE.findall(text)) >= 1:\n", " return POS\n", " return ABSTAIN\n", "\n", "\n", "def lf_positive_section_header(text):\n", " \"\"\"Any of several diagnosis/HPI/PMH/course headers.\"\"\"\n", " if _POS_SECTION_RE.search(text):\n", " return POS\n", " return ABSTAIN\n", "\n", "\n", "def lf_diagnosis_vocabulary_dense(text):\n", " \"\"\"Multiple distinct named diagnoses → codable.\"\"\"\n", " hits = set(m.group(0).lower() for m in _DX_RE.finditer(text))\n", " if len(hits) >= 2:\n", " return POS\n", " return ABSTAIN\n", "\n", "\n", "def lf_diagnosis_vocabulary_any(text):\n", " \"\"\"At least one named diagnosis — weak positive signal.\"\"\"\n", " if _DX_RE.search(text):\n", " return POS\n", " return ABSTAIN\n", "\n", "\n", "def lf_treatment_narrative(text):\n", " \"\"\"Past-tense treatment/procedure narrative.\"\"\"\n", " patterns = [\n", " r\"\\bwas (started|continued|treated|given|placed|admitted|transferred|dialyzed|extubated|intubated|weaned)\\b\",\n", " r\"\\bunderwent\\b\",\n", " r\"\\bs/p\\s+\\w+\",\n", " r\"\\bstatus\\s+post\\b\",\n", " ]\n", " hits = sum(1 for p in patterns if re.search(p, text, re.IGNORECASE))\n", " if hits >= 2:\n", " return POS\n", " return ABSTAIN\n", "\n", "\n", "# ====== Negative LFs ========================================================\n", "\n", "def lf_lab_unit_density(text):\n", " \"\"\"Lots of lab units relative to length → mostly lab data → negative.\"\"\"\n", " n_units = len(_LAB_UNITS_RE.findall(text))\n", " n_words = _word_count(text)\n", " if n_words == 0:\n", " return ABSTAIN\n", " if n_units >= 4 and n_units / n_words > 0.04:\n", " return NEG\n", " return ABSTAIN\n", "\n", "\n", "def lf_high_digit_density(text):\n", " \"\"\"If >25% of tokens are mostly digits, it's mostly numerical data.\"\"\"\n", " if _digit_density(text) > 0.25:\n", " return NEG\n", " return ABSTAIN\n", "\n", "\n", "def lf_dispensing_line(text):\n", " \"\"\"'Disp:*N Tablet(s)*' lines are pharmacy fulfillment, not diagnoses.\"\"\"\n", " if len(_DISP_RE.findall(text)) >= 2:\n", " return NEG\n", " return ABSTAIN\n", "\n", "\n", "def lf_radiology_technique(text):\n", " \"\"\"Pure radiology technique / device mechanics — describes procedure\n", " machinery, not a codable diagnosis. Allows DX vocab to coexist.\"\"\"\n", " tech_hits = len(_RAD_TECHNIQUE_RE.findall(text))\n", " narrative_hits = len(_RAD_NARRATIVE_RE.findall(text))\n", " if tech_hits + narrative_hits >= 3:\n", " return NEG\n", " return ABSTAIN\n", "\n", "\n", "def lf_imaging_measurements_only(text):\n", " \"\"\"Lots of mm/cm measurements with no diagnosis vocabulary.\"\"\"\n", " n_meas = len(_IMAGING_MEASUREMENT_RE.findall(text))\n", " has_dx = bool(_DX_RE.search(text))\n", " if n_meas >= 4 and not has_dx:\n", " return NEG\n", " return ABSTAIN\n", "\n", "\n", "def lf_negative_section_header(text):\n", " \"\"\"'COMPARISON:', 'TECHNIQUE:', 'INDICATION:' alone → procedural metadata.\"\"\"\n", " if _NEG_SECTION_RE.search(text) and not _POS_SECTION_RE.search(text):\n", " if not _DX_RE.search(text):\n", " return NEG\n", " return ABSTAIN\n", "\n", "\n", "def lf_no_findings_impression(text):\n", " \"\"\"IMPRESSION sections that are only 'no evidence of...' / 'unchanged'.\"\"\"\n", " if re.search(r\"\\bimpression\\s*:\", text, re.IGNORECASE):\n", " if re.search(\n", " r\"(no evidence|unchanged|stable|no acute|normal appearance|\"\n", " r\"decreased|no new)\",\n", " text, re.IGNORECASE,\n", " ) and not _DX_RE.search(text):\n", " return NEG\n", " return ABSTAIN\n", "\n", "\n", "def lf_discharge_condition_checklist(text):\n", " \"\"\"'Mental Status: Clear / Activity: Out of bed' checklist content.\"\"\"\n", " if _DISCHARGE_COND_RE.search(text) and not _DX_RE.search(text):\n", " if not _POS_SECTION_RE.search(text):\n", " return NEG\n", " return ABSTAIN\n", "\n", "\n", "def lf_imaging_finding_narrative(text):\n", " \"\"\"Radiology IMPRESSION/FINDINGS narratives describing imaging\n", " observations rather than asserting a diagnosis.\"\"\"\n", " finding_cues = re.findall(\n", " r\"\\b(arteriogram shows|no evidence of|caliber|stable ventricular|\"\n", " r\"impression\\s*:|comparison\\s*:|widely patent|filling defect|\"\n", " r\"interval (placement|change)|no acute|appears patent)\\b\",\n", " text, re.IGNORECASE,\n", " )\n", " if len(finding_cues) >= 2 and not _POS_SECTION_RE.search(text):\n", " return NEG\n", " return ABSTAIN\n", "\n", "\n", "def lf_med_adjustment_narrative(text):\n", " \"\"\"Discharge med-adjustment narratives describe medication changes,\n", " not diagnoses. Negative IF no diagnosis section is present.\"\"\"\n", " cues = re.findall(\n", " r\"\\b(please (stop|continue|start) taking|increase\\s+\\w+\\s+to|\"\n", " r\"discontinue|decrease\\s+\\w+\\s+to|please have repeat|\"\n", " r\"the following changes to your)\\b\",\n", " text, re.IGNORECASE,\n", " )\n", " if len(cues) >= 2 and not _POS_SECTION_RE.search(text):\n", " return NEG\n", " return ABSTAIN\n", "\n", "\n", "def lf_med_dispensing_or_dosing_dense(text):\n", " \"\"\"Numbered medication dispensing/dosing list — strong negative pattern.\"\"\"\n", " n_sig = len(re.findall(r\"\\bSig\\s*:\", text, re.IGNORECASE))\n", " n_disp = len(_DISP_RE.findall(text))\n", " n_numbered = len(re.findall(r\"^\\s*\\d{1,2}\\.\\s\", text, re.MULTILINE))\n", " if n_sig + n_disp >= 3 or (n_sig >= 2 and n_numbered >= 2):\n", " return NEG\n", " return ABSTAIN\n", "\n", "\n", "def lf_vitals_cluster(text):\n", " \"\"\"Cluster of vital-sign abbreviations + values → vitals/triage data.\"\"\"\n", " if len(_VITALS_CLUSTER_RE.findall(text)) >= 3:\n", " return NEG\n", " return ABSTAIN\n", "\n", "\n", "def lf_micro_susceptibility_table(text):\n", " \"\"\"Microbiology susceptibility tables → not a diagnosis on their own.\"\"\"\n", " if re.search(\n", " r\"(STAPH|STREP|ENTEROCOCC|KLEBSIELLA|E\\.?\\s*COLI|PSEUDOMONAS).{0,300}-{2,}.{0,20}\\b[SRI]\\b\",\n", " text, re.DOTALL,\n", " ):\n", " return NEG\n", " return ABSTAIN\n", "\n", "\n", "ALL_LFS = [\n", " lf_discharge_diagnosis_section,\n", " lf_problem_list_marker,\n", " lf_positive_section_header,\n", " lf_diagnosis_vocabulary_dense,\n", " lf_diagnosis_vocabulary_any,\n", " lf_treatment_narrative,\n", " lf_lab_unit_density,\n", " lf_high_digit_density,\n", " lf_dispensing_line,\n", " lf_radiology_technique,\n", " lf_imaging_measurements_only,\n", " lf_negative_section_header,\n", " lf_no_findings_impression,\n", " lf_discharge_condition_checklist,\n", " lf_imaging_finding_narrative,\n", " lf_med_adjustment_narrative,\n", " lf_med_dispensing_or_dosing_dense,\n", " lf_vitals_cluster,\n", " lf_micro_susceptibility_table,\n", "]\n", "LF_NAMES = [lf.__name__ for lf in ALL_LFS]\n", "\n", "\n", "def apply_lfs(texts):\n", " \"\"\"Apply all LFs to a list/Series of texts. Returns (n_texts, n_lfs) array.\"\"\"\n", " n = len(texts)\n", " L = np.full((n, len(ALL_LFS)), ABSTAIN, dtype=np.int8)\n", " for i, t in enumerate(texts):\n", " for j, lf in enumerate(ALL_LFS):\n", " try:\n", " L[i, j] = lf(t)\n", " except Exception:\n", " L[i, j] = ABSTAIN\n", " return L\n", "\n", "print(f\"Defined {len(ALL_LFS)} labeling functions\")\n" ] }, { "cell_type": "markdown", "id": "80b43247", "metadata": {}, "source": [ "### Section 2.2 — Sanity check the LFs on the 20 seed examples\n", "\n", "Look at coverage (what fraction of seeds each LF voted on) and agreement (how often the LF was correct *when it voted*). LFs with low coverage but high agreement are gold; LFs with high coverage and ~50% agreement are noise.\n", "\n", "**Caveat:** the 20 seed labels are themselves noisy, so disagreement here doesn't necessarily mean the LF is wrong.\n" ] }, { "cell_type": "code", "execution_count": null, "id": "8fdcf3f7", "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "\n", "seed_df = pd.read_csv(PROJECT_FILES_DIR / \"train_data-text_and_labels.csv\")\n", "print(f\"Loaded {len(seed_df)} seed examples\")\n", "print(f\"Label distribution: {seed_df['label'].value_counts().to_dict()}\")\n", "\n", "L_seed = apply_lfs(seed_df[\"text\"].tolist())\n", "y_seed = seed_df[\"label\"].values\n", "\n", "print()\n", "print(f\"{'LF':<42} {'cov':>5} {'agree':>10}\")\n", "print(\"-\" * 60)\n", "for j, name in enumerate(LF_NAMES):\n", " col = L_seed[:, j]\n", " voting = col != ABSTAIN\n", " if voting.sum() == 0:\n", " print(f\"{name:<42} {0:>5d} {'never':>10}\")\n", " continue\n", " agree = (col[voting] == y_seed[voting]).mean()\n", " print(f\"{name:<42} {voting.sum():>5d} {agree:>10.2%}\")\n", "\n", "# Quick majority-vote score\n", "preds_mv = np.where(\n", " (L_seed == 1).sum(1) > (L_seed == 0).sum(1), 1,\n", " np.where((L_seed == 0).sum(1) > (L_seed == 1).sum(1), 0, 1)\n", ")\n", "print(f\"\\nNaive majority-vote agreement with seed labels: {(preds_mv == y_seed).mean():.2%}\")\n" ] }, { "cell_type": "markdown", "id": "d210af95", "metadata": {}, "source": [ "## Section 3 — Mine MIMIC-III for training chunks\n", "\n", "Stream `NOTEEVENTS.csv` (it's ~4GB, can't fit in memory), reservoir-sample notes from `Discharge summary` / `Radiology` / `Physician` categories, then chunk each note into ~110-word excerpts that match the shape of the test inputs.\n", "\n", "This cell takes ~5-10 minutes the first time, then caches to `data/mimic_chunks.parquet` so subsequent runs skip it.\n" ] }, { "cell_type": "code", "execution_count": null, "id": "a4a8fb94", "metadata": {}, "outputs": [], "source": [ "import random\n", "from tqdm.auto import tqdm\n", "\n", "NOTE_CATEGORIES = {\"Discharge summary\", \"Radiology\", \"Physician \"}\n", "\n", "\n", "def split_into_blocks(text):\n", " text = text.replace(\"\\r\\n\", \"\\n\").replace(\"\\r\", \"\\n\")\n", " text = re.sub(r\"\\n{3,}\", \"\\n\\n\", text)\n", " return [b.strip() for b in text.split(\"\\n\\n\") if b.strip()]\n", "\n", "\n", "def build_chunks_from_blocks(blocks):\n", " chunks, cur, cur_words = [], [], 0\n", " for blk in blocks:\n", " bw = len(blk.split())\n", " if bw > CHUNK_MAX_WORDS:\n", " words = blk.split()\n", " for i in range(0, len(words), CHUNK_TARGET_WORDS):\n", " slice_text = \" \".join(words[i : i + CHUNK_TARGET_WORDS])\n", " if len(slice_text.split()) >= CHUNK_MIN_WORDS:\n", " chunks.append(slice_text)\n", " continue\n", " if cur and cur_words + bw > CHUNK_MAX_WORDS:\n", " chunk_text = \"\\n\\n\".join(cur)\n", " if len(chunk_text.split()) >= CHUNK_MIN_WORDS:\n", " chunks.append(chunk_text)\n", " cur, cur_words = [], 0\n", " cur.append(blk)\n", " cur_words += bw\n", " if cur_words >= CHUNK_TARGET_WORDS:\n", " chunks.append(\"\\n\\n\".join(cur))\n", " cur, cur_words = [], 0\n", " if cur:\n", " chunk_text = \"\\n\\n\".join(cur)\n", " if len(chunk_text.split()) >= CHUNK_MIN_WORDS:\n", " chunks.append(chunk_text)\n", " return chunks\n" ] }, { "cell_type": "code", "execution_count": null, "id": "069c9ee4", "metadata": {}, "outputs": [], "source": [ "if MIMIC_CHUNKS_PATH.exists():\n", " print(f\"Cached chunks found at {MIMIC_CHUNKS_PATH} — skipping mining.\")\n", " print(\"(Delete that file if you want to re-mine.)\")\n", " chunks_df = pd.read_parquet(MIMIC_CHUNKS_PATH)\n", "else:\n", " if not MIMIC_NOTEEVENTS_PATH.exists():\n", " raise FileNotFoundError(\n", " f\"NOTEEVENTS.csv not found at {MIMIC_NOTEEVENTS_PATH}. \"\n", " \"Edit MIMIC_NOTEEVENTS_PATH in Section 1.\"\n", " )\n", "\n", " print(f\"Streaming {MIMIC_NOTEEVENTS_PATH}...\")\n", " rng = random.Random(RANDOM_SEED)\n", " sampled_notes = []\n", " seen_in_category = 0\n", "\n", " reader = pd.read_csv(\n", " MIMIC_NOTEEVENTS_PATH,\n", " usecols=[\"ROW_ID\", \"CATEGORY\", \"TEXT\"],\n", " chunksize=50_000,\n", " low_memory=False,\n", " )\n", "\n", " for batch in tqdm(reader, desc=\"scanning NOTEEVENTS\"):\n", " batch = batch[batch[\"CATEGORY\"].isin(NOTE_CATEGORIES)]\n", " for row_id, text in zip(batch[\"ROW_ID\"], batch[\"TEXT\"]):\n", " if not isinstance(text, str) or len(text) < 200:\n", " continue\n", " seen_in_category += 1\n", " if len(sampled_notes) < N_MIMIC_NOTES_TO_SCAN:\n", " sampled_notes.append((int(row_id), text))\n", " else:\n", " j = rng.randint(0, seen_in_category - 1)\n", " if j < N_MIMIC_NOTES_TO_SCAN:\n", " sampled_notes[j] = (int(row_id), text)\n", " if seen_in_category > 10 * N_MIMIC_NOTES_TO_SCAN:\n", " break\n", "\n", " print(f\"Sampled {len(sampled_notes)} notes. Chunking...\")\n", " rows = []\n", " chunk_id = 0\n", " for note_id, text in tqdm(sampled_notes, desc=\"chunking\"):\n", " blocks = split_into_blocks(text)\n", " chunks = build_chunks_from_blocks(blocks)\n", " if len(chunks) > CHUNKS_PER_NOTE_CAP:\n", " chunks = rng.sample(chunks, CHUNKS_PER_NOTE_CAP)\n", " for c in chunks:\n", " rows.append({\"chunk_id\": chunk_id, \"note_id\": note_id, \"text\": c})\n", " chunk_id += 1\n", "\n", " chunks_df = pd.DataFrame(rows)\n", " chunks_df.to_parquet(MIMIC_CHUNKS_PATH, index=False)\n", " print(f\"Wrote {MIMIC_CHUNKS_PATH}\")\n", "\n", "print(f\"\\nTotal chunks: {len(chunks_df):,}\")\n", "print(\"Word count distribution:\")\n", "print(chunks_df['text'].str.split().str.len().describe())\n" ] }, { "cell_type": "markdown", "id": "2ef42734", "metadata": {}, "source": [ "## Section 4 — Apply LFs to mined chunks\n" ] }, { "cell_type": "code", "execution_count": null, "id": "5fb361a4", "metadata": {}, "outputs": [], "source": [ "print(\"Applying labeling functions to mined chunks...\")\n", "L = apply_lfs(chunks_df[\"text\"].tolist())\n", "np.save(LF_VOTES_PATH, L)\n", "print(f\"Saved LF votes → {LF_VOTES_PATH} shape={L.shape}\")\n", "\n", "print(\"\\nLF coverage on mined chunks:\")\n", "print(f\"{'name':<42} {'cov':>6} {'pos':>6} {'neg':>6}\")\n", "print(\"-\" * 64)\n", "for j, name in enumerate(LF_NAMES):\n", " col = L[:, j]\n", " cov = (col != ABSTAIN).mean()\n", " pos = (col == 1).mean()\n", " neg = (col == 0).mean()\n", " print(f\"{name:<42} {cov:>6.2%} {pos:>6.2%} {neg:>6.2%}\")\n", "\n", "abstain_all = (L == ABSTAIN).all(axis=1)\n", "print(f\"\\nChunks where every LF abstained: {abstain_all.sum():,} ({abstain_all.mean():.2%})\")\n" ] }, { "cell_type": "markdown", "id": "d4cee79e", "metadata": {}, "source": [ "## Section 5 — Aggregate LF votes with Snorkel's LabelModel\n", "\n", "`LabelModel` learns each LF's accuracy *without gold labels* by exploiting agreement/disagreement statistics across all the chunks. The output is a probability `P(label=1 | LF votes)` for each chunk — calibrated soft labels we can train on.\n" ] }, { "cell_type": "code", "execution_count": null, "id": "929243a2", "metadata": {}, "outputs": [], "source": [ "from snorkel.labeling.model import LabelModel\n", "\n", "print(\"Fitting Snorkel LabelModel...\")\n", "label_model = LabelModel(cardinality=2, verbose=False)\n", "label_model.fit(\n", " L_train=L,\n", " n_epochs=LABEL_MODEL_EPOCHS,\n", " lr=LABEL_MODEL_LR,\n", " seed=RANDOM_SEED,\n", ")\n", "\n", "probs = label_model.predict_proba(L)\n", "p_pos = probs[:, 1].astype(np.float32)\n", "np.save(SOFT_LABELS_PATH, p_pos)\n", "\n", "# Build training set\n", "chunks_df = chunks_df.reset_index(drop=True)\n", "chunks_df[\"soft_label\"] = p_pos\n", "\n", "if DROP_ALL_ABSTAIN:\n", " keep = ~abstain_all\n", " train_df = chunks_df[keep].reset_index(drop=True)\n", " print(f\"\\nKept {len(train_df):,} chunks after dropping all-abstain ({(~keep).sum():,} dropped).\")\n", "else:\n", " train_df = chunks_df\n", "\n", "train_df.to_parquet(TRAINING_SET_PATH, index=False)\n", "\n", "# Soft label distribution\n", "print(\"\\nSoft-label distribution (kept rows):\")\n", "bins = [0, 0.2, 0.4, 0.5, 0.6, 0.8, 1.01]\n", "counts, edges = np.histogram(train_df[\"soft_label\"], bins=bins)\n", "for c, lo, hi in zip(counts, edges[:-1], edges[1:]):\n", " print(f\" [{lo:.2f}, {hi:.2f}): {c:,}\")\n" ] }, { "cell_type": "markdown", "id": "f555c9ca", "metadata": {}, "source": [ "### Section 5.1 — Sanity-check LabelModel against the seed examples\n", "\n", "Apply LFs to the 20 seeds and run them through the *same fitted* LabelModel. Disagreement is informative but not dispositive — the seed labels are noisy too.\n" ] }, { "cell_type": "code", "execution_count": null, "id": "639e7e87", "metadata": {}, "outputs": [], "source": [ "seed_probs = label_model.predict_proba(L_seed)[:, 1]\n", "seed_preds = (seed_probs >= 0.5).astype(int)\n", "\n", "print(f\"LabelModel agreement with seed labels: {(seed_preds == y_seed).mean():.2%}\")\n", "print()\n", "print(\"Per-row LabelModel output:\")\n", "for i in range(len(seed_df)):\n", " mark = \"✓\" if seed_preds[i] == y_seed[i] else \"✗\"\n", " print(f\" row {i:2d}: seed={y_seed[i]} LM_p={seed_probs[i]:.2f} pred={seed_preds[i]} {mark}\")\n" ] }, { "cell_type": "markdown", "id": "98c56852", "metadata": {}, "source": [ "## Section 6 — Fine-tune Bio_ClinicalBERT on soft labels\n", "\n", "**Key design choice:** train with binary cross-entropy against the *soft* label (probability), not hard 0/1. This preserves LabelModel's uncertainty — chunks where LFs disagreed contribute less gradient signal than chunks where they all agreed.\n", "\n", "Bio_ClinicalBERT is downloaded from HuggingFace once and cached locally (~440MB). Fully offline thereafter.\n", "\n", "**Runtime:** ~20-40 min on a single GPU. Skip this section if you want to evaluate the rule-based baseline only.\n" ] }, { "cell_type": "code", "execution_count": null, "id": "5f8e22c6", "metadata": {}, "outputs": [], "source": [ "import torch\n", "from torch.utils.data import Dataset, DataLoader\n", "from torch.optim import AdamW\n", "from transformers import (\n", " AutoTokenizer,\n", " AutoModelForSequenceClassification,\n", " get_linear_schedule_with_warmup,\n", ")\n", "\n", "device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n", "print(f\"Device: {device}\")\n", "if device == \"cpu\":\n", " print(\"WARNING: training on CPU will take hours. Consider Colab GPU.\")\n" ] }, { "cell_type": "code", "execution_count": null, "id": "a2cdfa5d", "metadata": {}, "outputs": [], "source": [ "class SoftLabelDataset(Dataset):\n", " def __init__(self, texts, soft_labels, tokenizer):\n", " assert len(texts) == len(soft_labels)\n", " self.texts = texts\n", " self.labels = soft_labels.astype(np.float32)\n", " self.tokenizer = tokenizer\n", "\n", " def __len__(self):\n", " return len(self.texts)\n", "\n", " def __getitem__(self, idx):\n", " enc = self.tokenizer(\n", " self.texts[idx],\n", " truncation=True,\n", " padding=\"max_length\",\n", " max_length=MAX_SEQ_LEN,\n", " return_tensors=\"pt\",\n", " )\n", " return {\n", " \"input_ids\": enc[\"input_ids\"].squeeze(0),\n", " \"attention_mask\": enc[\"attention_mask\"].squeeze(0),\n", " \"soft_label\": torch.tensor(self.labels[idx], dtype=torch.float32),\n", " }\n", "\n", "\n", "def soft_bce_loss(logits, soft_labels):\n", " \"\"\"Binary cross-entropy against soft targets. logits is (B, 2).\"\"\"\n", " logit_pos = logits[:, 1] - logits[:, 0]\n", " return torch.nn.functional.binary_cross_entropy_with_logits(\n", " logit_pos, soft_labels\n", " )\n" ] }, { "cell_type": "code", "execution_count": null, "id": "b00bc3bf", "metadata": {}, "outputs": [], "source": [ "# Optional: drop low-confidence rows (soft label in [0.4, 0.6])\n", "FILTER_CONFIDENT = False\n", "VAL_FRAC = 0.1\n", "\n", "torch.manual_seed(RANDOM_SEED)\n", "np.random.seed(RANDOM_SEED)\n", "\n", "train_df_use = train_df.copy()\n", "if FILTER_CONFIDENT:\n", " before = len(train_df_use)\n", " train_df_use = train_df_use[\n", " (train_df_use[\"soft_label\"] < 0.4) | (train_df_use[\"soft_label\"] > 0.6)\n", " ].reset_index(drop=True)\n", " print(f\"Filtered to confident rows: {before:,} → {len(train_df_use):,}\")\n", "\n", "perm = np.random.permutation(len(train_df_use))\n", "n_val = max(200, int(len(train_df_use) * VAL_FRAC))\n", "val_idx, train_idx = perm[:n_val], perm[n_val:]\n", "train_split = train_df_use.iloc[train_idx].reset_index(drop=True)\n", "val_split = train_df_use.iloc[val_idx].reset_index(drop=True)\n", "print(f\"train: {len(train_split):,} val: {len(val_split):,}\")\n" ] }, { "cell_type": "code", "execution_count": null, "id": "0fbbdc3f", "metadata": {}, "outputs": [], "source": [ "print(f\"Loading {BERT_MODEL_NAME} (downloads ~440MB on first call)...\")\n", "tokenizer = AutoTokenizer.from_pretrained(BERT_MODEL_NAME)\n", "model = AutoModelForSequenceClassification.from_pretrained(\n", " BERT_MODEL_NAME, num_labels=2\n", ").to(device)\n", "print(\"Loaded.\")\n" ] }, { "cell_type": "code", "execution_count": null, "id": "03d73e16", "metadata": {}, "outputs": [], "source": [ "train_ds = SoftLabelDataset(\n", " train_split[\"text\"].tolist(), train_split[\"soft_label\"].values, tokenizer,\n", ")\n", "val_ds = SoftLabelDataset(\n", " val_split[\"text\"].tolist(), val_split[\"soft_label\"].values, tokenizer,\n", ")\n", "train_loader = DataLoader(train_ds, batch_size=BATCH_SIZE, shuffle=True, num_workers=2)\n", "val_loader = DataLoader(val_ds, batch_size=EVAL_BATCH_SIZE, shuffle=False, num_workers=2)\n", "\n", "optimizer = AdamW(model.parameters(), lr=LEARNING_RATE, weight_decay=WEIGHT_DECAY)\n", "total_steps = len(train_loader) * NUM_EPOCHS\n", "scheduler = get_linear_schedule_with_warmup(\n", " optimizer,\n", " num_warmup_steps=int(WARMUP_RATIO * total_steps),\n", " num_training_steps=total_steps,\n", ")\n", "\n", "\n", "@torch.no_grad()\n", "def evaluate_model(model, loader, device):\n", " model.eval()\n", " all_probs, all_targets, losses = [], [], []\n", " for batch in loader:\n", " input_ids = batch[\"input_ids\"].to(device)\n", " attn_mask = batch[\"attention_mask\"].to(device)\n", " soft = batch[\"soft_label\"].to(device)\n", " out = model(input_ids=input_ids, attention_mask=attn_mask)\n", " loss = soft_bce_loss(out.logits, soft)\n", " losses.append(loss.item())\n", " probs = torch.softmax(out.logits, dim=-1)[:, 1]\n", " all_probs.append(probs.cpu().numpy())\n", " all_targets.append(soft.cpu().numpy())\n", " probs = np.concatenate(all_probs)\n", " targets = np.concatenate(all_targets)\n", " hard_targets = (targets >= 0.5).astype(int)\n", " hard_preds = (probs >= 0.5).astype(int)\n", " acc = (hard_preds == hard_targets).mean()\n", " return {\"loss\": float(np.mean(losses)), \"acc_vs_hard_target\": float(acc)}\n", "\n", "\n", "best_val = float(\"inf\")\n", "MODEL_DIR.mkdir(parents=True, exist_ok=True)\n", "\n", "for epoch in range(1, NUM_EPOCHS + 1):\n", " model.train()\n", " losses = []\n", " pbar = tqdm(train_loader, desc=f\"epoch {epoch} train\")\n", " for batch in pbar:\n", " input_ids = batch[\"input_ids\"].to(device)\n", " attn_mask = batch[\"attention_mask\"].to(device)\n", " soft = batch[\"soft_label\"].to(device)\n", " optimizer.zero_grad()\n", " out = model(input_ids=input_ids, attention_mask=attn_mask)\n", " loss = soft_bce_loss(out.logits, soft)\n", " loss.backward()\n", " torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)\n", " optimizer.step()\n", " scheduler.step()\n", " losses.append(loss.item())\n", " pbar.set_postfix(loss=np.mean(losses[-50:]))\n", "\n", " metrics = evaluate_model(model, val_loader, device)\n", " print(\n", " f\"epoch {epoch} train_loss={np.mean(losses):.4f} \"\n", " f\"val_loss={metrics['loss']:.4f} \"\n", " f\"val_acc_vs_hard={metrics['acc_vs_hard_target']:.4f}\"\n", " )\n", " if metrics[\"loss\"] < best_val:\n", " best_val = metrics[\"loss\"]\n", " model.save_pretrained(MODEL_DIR)\n", " tokenizer.save_pretrained(MODEL_DIR)\n", " print(f\" ↳ saved checkpoint to {MODEL_DIR}\")\n", "\n", "print(f\"\\nDone. Best val loss: {best_val:.4f}. Model in {MODEL_DIR}\")\n" ] }, { "cell_type": "markdown", "id": "063feb95", "metadata": {}, "source": [ "## Section 7 — Generate Gradescope predictions\n", "\n", "Predicts on `test{01,02,03}_text_only.csv` and writes Gradescope-shaped CSVs to `outputs/test{NN}-pred.csv` (columns: `row_id`, `prediction`).\n" ] }, { "cell_type": "code", "execution_count": null, "id": "692c68cd", "metadata": {}, "outputs": [], "source": [ "@torch.no_grad()\n", "def predict_probs(model, tokenizer, texts, device):\n", " model.eval()\n", " probs = []\n", " for start in tqdm(range(0, len(texts), EVAL_BATCH_SIZE), desc=\"predict\"):\n", " batch_texts = texts[start : start + EVAL_BATCH_SIZE]\n", " enc = tokenizer(\n", " batch_texts,\n", " truncation=True,\n", " padding=True,\n", " max_length=MAX_SEQ_LEN,\n", " return_tensors=\"pt\",\n", " ).to(device)\n", " out = model(**enc)\n", " p1 = torch.softmax(out.logits, dim=-1)[:, 1].cpu().numpy()\n", " probs.append(p1)\n", " return np.concatenate(probs)\n", "\n", "\n", "def predict_test_file(test_path, out_path, model, tokenizer, device):\n", " df = pd.read_csv(test_path)\n", " if \"text\" not in df.columns or \"row_id\" not in df.columns:\n", " raise ValueError(f\"{test_path} missing required columns\")\n", " probs = predict_probs(model, tokenizer, df[\"text\"].astype(str).tolist(), device)\n", " preds = (probs >= DECISION_THRESHOLD).astype(int)\n", " out_df = pd.DataFrame({\"row_id\": df[\"row_id\"].astype(int), \"prediction\": preds})\n", " out_df.to_csv(out_path, index=False)\n", " print(f\" {out_path.name}: {preds.sum()}/{len(preds)} positive → {out_path}\")\n", " return out_df\n", "\n", "\n", "# Reload from disk to ensure we're using the saved best checkpoint\n", "print(f\"Loading model from {MODEL_DIR}...\")\n", "tokenizer = AutoTokenizer.from_pretrained(MODEL_DIR)\n", "model = AutoModelForSequenceClassification.from_pretrained(MODEL_DIR).to(device)\n", "\n", "for n in (\"01\", \"02\", \"03\"):\n", " in_path = PROJECT_FILES_DIR / f\"test{n}_text_only.csv\"\n", " out_path = OUTPUT_DIR / f\"test{n}-pred.csv\"\n", " if not in_path.exists():\n", " print(f\" skipped {in_path} (not found)\")\n", " continue\n", " predict_test_file(in_path, out_path, model, tokenizer, device)\n" ] }, { "cell_type": "markdown", "id": "475bdc40", "metadata": {}, "source": [ "## Section 8 — BERT diagnostics on the 20 seed examples\n", "\n", "Sanity check the trained BERT against the noisy seed labels. Disagreement is informative both ways:\n", "\n", "* Model wrong on a seed → maybe the LFs+aggregation steered it incorrectly\n", "* Model \"wrong\" but you agree with it on inspection → the seed label was wrong\n" ] }, { "cell_type": "code", "execution_count": null, "id": "21d35f6c", "metadata": {}, "outputs": [], "source": [ "seed_bert_probs = predict_probs(\n", " model, tokenizer, seed_df[\"text\"].astype(str).tolist(), device,\n", ")\n", "seed_bert_preds = (seed_bert_probs >= DECISION_THRESHOLD).astype(int)\n", "\n", "print(f\"BERT agreement with (noisy) seed labels: {(seed_bert_preds == y_seed).mean():.2%}\")\n", "print(f\"\\nConfusion (rows=seed, cols=pred):\")\n", "for s in (0, 1):\n", " row = [int(((y_seed == s) & (seed_bert_preds == p)).sum()) for p in (0, 1)]\n", " print(f\" seed={s}: pred=0:{row[0]:3d} pred=1:{row[1]:3d}\")\n", "\n", "print(\"\\nPer-row breakdown:\")\n", "for i in range(len(seed_df)):\n", " mark = \"✓\" if seed_bert_preds[i] == y_seed[i] else \"✗\"\n", " print(f\" row {i:2d}: seed={y_seed[i]} bert_p={seed_bert_probs[i]:.3f} pred={seed_bert_preds[i]} {mark}\")\n" ] }, { "cell_type": "markdown", "id": "ea5b48f7", "metadata": {}, "source": [ "## Section 9 — Approach 1 baseline: pure rule-based (LF majority vote)\n", "\n", "For the report's *negative results / iterative exploration* section. Quantifies how much of the test signal is captured by handwritten heuristics alone, before any ML. Writes separate `outputs/test{NN}-pred-rulebased.csv` files.\n" ] }, { "cell_type": "code", "execution_count": null, "id": "f8f2555c", "metadata": {}, "outputs": [], "source": [ "def majority_vote(L):\n", " \"\"\"Per row: count POS vs NEG votes; ties / all-abstain → predict 1.\"\"\"\n", " pos_votes = (L == 1).sum(axis=1)\n", " neg_votes = (L == 0).sum(axis=1)\n", " return np.where(pos_votes >= neg_votes, 1, 0).astype(int)\n", "\n", "\n", "for n in (\"01\", \"02\", \"03\"):\n", " in_path = PROJECT_FILES_DIR / f\"test{n}_text_only.csv\"\n", " out_path = OUTPUT_DIR / f\"test{n}-pred-rulebased.csv\"\n", " if not in_path.exists():\n", " print(f\" skipped {in_path}\")\n", " continue\n", " df = pd.read_csv(in_path)\n", " L_test = apply_lfs(df[\"text\"].astype(str).tolist())\n", " preds = majority_vote(L_test)\n", " out = pd.DataFrame({\"row_id\": df[\"row_id\"].astype(int), \"prediction\": preds})\n", " out.to_csv(out_path, index=False)\n", " print(f\" {out_path.name}: {preds.sum()}/{len(preds)} positive\")\n" ] }, { "cell_type": "markdown", "id": "df0adafd", "metadata": {}, "source": [ "## Section 10 — Compare rule baseline vs. trained BERT\n", "\n", "Cross-check how often the two disagree on the test sets. Big disagreement = BERT is doing something the rules can't capture (good — that's why we trained it). Tiny disagreement = the rules already capture most of the signal (also useful information for the report).\n" ] }, { "cell_type": "code", "execution_count": null, "id": "c11af3b4", "metadata": {}, "outputs": [], "source": [ "for n in (\"01\", \"02\", \"03\"):\n", " rule_path = OUTPUT_DIR / f\"test{n}-pred-rulebased.csv\"\n", " bert_path = OUTPUT_DIR / f\"test{n}-pred.csv\"\n", " if not rule_path.exists() or not bert_path.exists():\n", " continue\n", " r = pd.read_csv(rule_path)[\"prediction\"].values\n", " b = pd.read_csv(bert_path)[\"prediction\"].values\n", " agree = (r == b).mean()\n", " print(f\"test{n}: rule_pos={r.sum()}, bert_pos={b.sum()}, agreement={agree:.2%}\")\n" ] }, { "cell_type": "markdown", "id": "d95f57cb", "metadata": {}, "source": [ "## Notes for the report\n", "\n", "* **Soft-label BCE training** is the technically interesting bit — the model learns from LabelModel's calibrated uncertainty rather than thresholded hard labels. Mention this; it differentiates the work from a vanilla Snorkel pipeline.\n", "* **The 20 seed labels are noisy** (themselves BERT-generated). Frame any \"agreement with seed\" numbers as agreement, not accuracy.\n", "* **Negative results are explicitly rewarded** by the rubric. Include the rule-based baseline (Section 9), the BERT model (Section 7), and ideally one variant: e.g., BERT trained on the 20 seeds *directly* (no MIMIC, no Snorkel) — likely overfits and is much worse, which is informative. You can build that variant by skipping Sections 3-5 and replacing `train_df` in Section 6 with a dataframe of just the 20 seeds.\n", "* **Related work** to read for the report: CAML (Mullenbach et al. 2018) for ICD coding on MIMIC-III, Snorkel (Ratner et al.) for weak supervision theory, ClinicalBERT / Bio_ClinicalBERT for the encoder choice, SetFit for the few-shot baseline you could optionally add.\n" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "name": "python", "version": "3.10" } }, "nbformat": 4, "nbformat_minor": 5 }