File size: 47,447 Bytes
f419704
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
{
 "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
}