File size: 70,405 Bytes
8d6f9a9 | 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 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 | {
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Mammography Breast Cancer Detection\n",
"This notebook uses the dataset from the kaggle challenge \"Mammography breast cancer detection\" \n",
"\n",
"The images are stored in dicom format and so you will be tasked to unload them when training the model\n",
"\n",
"| | RSNA (mammography) |\n",
"|---|---|\n",
"| Input format | DICOM |\n",
"| Image size | 2048Γ1024 |\n",
"| Backbone | ConvNeXt-small |\n",
"| Output | 2-class softmax |\n",
"| Metric | pF1 (probabilistic F1) |\n",
"| Imbalance | ~2% positive |"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---\n",
"## 0. Environment Setup\n",
"\n",
"Install dependencies"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"\n",
"!pip install timm albumentations torcheval scikit-learn opencv-python-headless tqdm pydicom pylibjpeg pylibjpeg-libjpeg"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import os, gc, time, copy, random\n",
"from pathlib import Path\n",
"from collections import defaultdict\n",
"\n",
"import numpy as np\n",
"import pandas as pd\n",
"import cv2\n",
"import matplotlib.pyplot as plt\n",
"\n",
"import pydicom\n",
"from pydicom.pixel_data_handlers.util import apply_voi_lut\n",
"\n",
"import torch\n",
"import torch.nn as nn\n",
"import torch.optim as optim\n",
"from torch.optim import lr_scheduler\n",
"from torch.utils.data import Dataset, DataLoader\n",
"\n",
"import timm\n",
"import albumentations as A\n",
"from albumentations.pytorch import ToTensorV2\n",
"\n",
"from sklearn.model_selection import StratifiedGroupKFold\n",
"from sklearn.metrics import roc_auc_score\n",
"from torcheval.metrics.functional import binary_auroc\n",
"from tqdm import tqdm\n",
"\n",
"print(\"PyTorch:\", torch.__version__)\n",
"print(\"CUDA available:\", torch.cuda.is_available())\n",
"if torch.cuda.is_available():\n",
" print(\"GPU:\", torch.cuda.get_device_name(0))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---\n",
"## 1. Configuration\n",
"\n",
"The winning solution used **2048Γ1024** images with **ConvNeXt-small**. \n",
"This is memory-intensive β if you have a smaller GPU, reduce `img_h` and `img_w` first, then scale up."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"CONFIG = {\n",
" 'data_dir': './data/rsna-breast-cancer-detection',\n",
" 'train_images_dir': './data/rsna-breast-cancer-detection/train_images',\n",
" 'csv_path': './data/rsna-breast-cancer-detection/train.csv',\n",
" 'processed_dir': './data/processed_pngs', # pre-converted 8-bit PNGs\n",
" 'models_folder': './saved_models',\n",
"\n",
" 'model_name': 'convnext_small.fb_in22k_ft_in1k',\n",
" 'img_h': 2048, # height (tall axis of mammogram)\n",
" 'img_w': 1024, # width\n",
" 'num_classes': 2, # softmax: 0=benign, 1=malignant\n",
" 'drop_rate': 0.0,\n",
" 'drop_path_rate': 0.0,\n",
"\n",
" 'seed': 42,\n",
" 'epochs': 15,\n",
" 'train_batch_size': 4, # large images require small batches\n",
" 'valid_batch_size': 8,\n",
" 'n_accumulate': 8, # effective batch = 4 Γ 8 = 32\n",
" 'device': 'cuda' if torch.cuda.is_available() else 'cpu',\n",
" 'n_folds': 4, # same as winning solution\n",
" 'group_col': 'patient_id',\n",
"\n",
" 'learning_rate': 2e-5,\n",
" 'weight_decay': 1e-6,\n",
"\n",
" 'scheduler': 'CosineAnnealingLR',\n",
" 'T_max': 500,\n",
" 'min_lr': 1e-7,\n",
"}\n",
"\n",
"def set_seed(seed):\n",
" random.seed(seed)\n",
" np.random.seed(seed)\n",
" torch.manual_seed(seed)\n",
" if torch.cuda.is_available():\n",
" torch.cuda.manual_seed_all(seed)\n",
" torch.backends.cudnn.deterministic = True\n",
" torch.backends.cudnn.benchmark = False\n",
"\n",
"set_seed(CONFIG['seed'])\n",
"os.makedirs(CONFIG['models_folder'], exist_ok=True)\n",
"os.makedirs(CONFIG['processed_dir'], exist_ok=True)\n",
"print(\"Device:\", CONFIG['device'])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---\n",
"## 2. Dataset Overview\n",
"\n",
"The RSNA dataset contains **~54,000 DICOM mammograms** from ~11,900 patients. \n",
"Each patient has up to 4 views (CC and MLO, left and right). The label is **per-patient** β if a patient has cancer, all their images are positive.\n",
"\n",
"**Key columns in `train.csv`:**\n",
"| Column | Description |\n",
"|---|---|\n",
"| `patient_id` | Unique patient identifier |\n",
"| `image_id` | Unique image identifier |\n",
"| `laterality` | L / R |\n",
"| `view` | CC / MLO |\n",
"| `cancer` | 0 / 1 (our target) |\n",
"| `biopsy` | Whether biopsy was performed |\n",
"| `age` | Patient age |\n",
"| `machine_id` | Acquisition machine |\n",
"\n",
"Download from: https://www.kaggle.com/competitions/rsna-breast-cancer-detection/data"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"df = pd.read_csv(CONFIG['csv_path'])\n",
"df = df.rename(columns={'cancer': 'target'})\n",
"\n",
"print(f\"Total images : {len(df)}\")\n",
"print(f\"Unique patients : {df.patient_id.nunique()}\")\n",
"print(f\"Malignant (1) : {df.target.sum()} ({100*df.target.mean():.2f}%)\")\n",
"print(f\"\\nViews: {df.view.value_counts().to_dict()}\")\n",
"print(f\"Laterality: {df.laterality.value_counts().to_dict()}\")\n",
"df.head()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# ββ TODO ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n",
"# Task A β Label granularity:\n",
"# The label 'cancer' is per-patient, but images are per-view. Does every\n",
"# view of a cancerous patient get label=1, even the healthy breast (R vs L)?\n",
"# Check using the 'laterality' column. This matters for training signal quality.\n",
"#\n",
"# Task B β Patient-level vs image-level leakage:\n",
"# Why is group_col='patient_id' critical for the CV split?\n",
"# What would happen if you split by image_id instead?\n",
"#\n",
"# Task C β Explore metadata:\n",
"# Plot cancer rate by (a) view (CC vs MLO), (b) laterality, (c) age group.\n",
"# Does machine_id correlate with cancer rate? (hint: site-level confounds)\n",
"# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n",
"\n",
"fig, axes = plt.subplots(1, 3, figsize=(15, 4))\n",
"\n",
"df.groupby('view')['target'].mean().plot(kind='bar', ax=axes[0], title='Cancer rate by view', color='steelblue')\n",
"df.groupby('laterality')['target'].mean().plot(kind='bar', ax=axes[1], title='Cancer rate by laterality', color='coral')\n",
"df['age_bin'] = pd.cut(df['age'], bins=[30, 40, 50, 60, 70, 80, 90])\n",
"df.groupby('age_bin')['target'].mean().plot(kind='bar', ax=axes[2], title='Cancer rate by age', color='mediumseagreen')\n",
"\n",
"for ax in axes: ax.set_ylabel('Cancer rate'); ax.tick_params(axis='x', rotation=45)\n",
"plt.tight_layout(); plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---\n",
"## 3. DICOM Preprocessing\n",
"\n",
"Mammograms are stored as **DICOM files** β a medical imaging format that carries both pixel data and metadata (patient info, acquisition parameters, photometric interpretation). \n",
"\n",
"**Critical preprocessing steps:**\n",
"1. **Decode DICOM** β read pixel array, apply Value Of Interest (VOI) LUT if present\n",
"2. **Handle photometric inversion** β some scanners store `MONOCHROME1` (white=air, dark=tissue) vs `MONOCHROME2` (dark=air). Must invert `MONOCHROME1`.\n",
"3. **Normalise to 8-bit [0, 255]** β scale by min/max of the image\n",
"4. **Crop breast ROI** β remove dark background (Part 1: threshold; Part 2: YOLOX)\n",
"5. **Save as PNG** β avoids re-decoding DICOM every epoch (huge speed gain)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def read_dicom(path: str, voi_lut: bool = True) -> np.ndarray:\n",
" \"\"\"Read a DICOM file and return a normalised uint8 numpy array.\"\"\"\n",
" dcm = pydicom.dcmread(path)\n",
" \n",
" if voi_lut:\n",
" # Apply the VOI LUT (window/level) embedded in the DICOM header.\n",
" # This maps the raw stored values to a display-meaningful range.\n",
" data = apply_voi_lut(dcm.pixel_array, dcm)\n",
" else:\n",
" data = dcm.pixel_array\n",
"\n",
" # MONOCHROME1: pixel value 0 = white (dense tissue), high = black (air)\n",
" # We want the standard radiological convention: bright tissue, dark background.\n",
" if dcm.PhotometricInterpretation == 'MONOCHROME1':\n",
" data = np.max(data) - data # invert\n",
"\n",
" # Normalise to uint8\n",
" data = data.astype(np.float32)\n",
" data -= data.min()\n",
" if data.max() > 0:\n",
" data /= data.max()\n",
" data = (data * 255).astype(np.uint8)\n",
" return data"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# ββ TODO ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n",
"# Task A β Inspect a raw DICOM:\n",
"# Load one DICOM and print dcm.PhotometricInterpretation, dcm.BitsStored,\n",
"# dcm.PixelRepresentation, and dcm.pixel_array.shape.\n",
"# What is the raw pixel value range before normalisation?\n",
"#\n",
"# Task B β VOI LUT effect:\n",
"# Read the same DICOM with voi_lut=True and voi_lut=False.\n",
"# Plot both histograms. When does the VOI LUT make a visible difference?\n",
"#\n",
"# Task C β MONOCHROME1 vs MONOCHROME2:\n",
"# Find one example of each in the dataset. Plot them side by side,\n",
"# before and after the photometric inversion step.\n",
"# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n",
"\n",
"# Example: Load and display one mammogram\n",
"# sample_path = f\"{CONFIG['train_images_dir']}/{df.patient_id[0]}/{df.image_id[0]}.dcm\"\n",
"# img = read_dicom(sample_path)\n",
"# plt.figure(figsize=(4, 8))\n",
"# plt.imshow(img, cmap='gray'); plt.axis('off'); plt.title('Raw mammogram'); plt.show()\n",
"# print(f\"Shape: {img.shape}, dtype: {img.dtype}, range: [{img.min()}, {img.max()}]\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 3.1 Breast ROI Cropping (Threshold-based)\n",
"\n",
"The original mr.robot pipeline uses **YOLOX-nano** to detect the breast bounding box. \n",
"In Part 1 we use a classical approach: threshold the image to find the breast region.\n",
"\n",
"**Why crop at all?** \n",
"Mammograms have large black corners (the scanner bed). These contain no diagnostic information and waste model capacity. Cropping the ROI also allows us to upsample the breast tissue to fill the full 2048Γ1024 resolution."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def crop_breast_roi_threshold(img: np.ndarray, threshold: int = 10) -> np.ndarray:\n",
" \"\"\"\n",
" Simple threshold-based breast ROI extraction.\n",
" Finds the bounding box of pixels brighter than `threshold` and crops.\n",
" Works well for clean backgrounds but can fail on noisy scanners.\n",
" \"\"\"\n",
" # Binarise: breast tissue is bright, background is ~0\n",
" mask = (img > threshold).astype(np.uint8)\n",
" \n",
" # Find the largest connected component (the breast)\n",
" num_labels, labels, stats, _ = cv2.connectedComponentsWithStats(mask, connectivity=8)\n",
" \n",
" if num_labels < 2:\n",
" return img # no component found, return original\n",
" \n",
" # Component 0 is background; find largest foreground component\n",
" largest_label = 1 + np.argmax(stats[1:, cv2.CC_STAT_AREA])\n",
" \n",
" x = stats[largest_label, cv2.CC_STAT_LEFT]\n",
" y = stats[largest_label, cv2.CC_STAT_TOP]\n",
" w = stats[largest_label, cv2.CC_STAT_WIDTH]\n",
" h = stats[largest_label, cv2.CC_STAT_HEIGHT]\n",
" \n",
" return img[y:y+h, x:x+w]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# ββ TODO ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n",
"# Task A β Visualise cropping quality:\n",
"# Apply crop_breast_roi_threshold to 6 different images.\n",
"# Show original vs cropped side by side.\n",
"# Cases to check: normal scan, noisy scanner, implant, dense breast.\n",
"#\n",
"# Task B β Morphological cleanup:\n",
"# Add a cv2.morphologyEx OPEN step before finding components to remove\n",
"# small bright artifacts (scanner labels, rulers). Does it help?\n",
"#\n",
"# Task C β Compare to YOLOX (preview for Part 2):\n",
"# Note any cases where threshold cropping produces a poor crop.\n",
"# These are exactly the failure cases YOLOX is trained to handle.\n",
"# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n",
"\n",
"# Quick test\n",
"# raw = read_dicom(sample_path)\n",
"# cropped = crop_breast_roi_threshold(raw)\n",
"# fig, axes = plt.subplots(1, 2, figsize=(10, 8))\n",
"# axes[0].imshow(raw, cmap='gray'); axes[0].set_title(f'Original {raw.shape}')\n",
"# axes[1].imshow(cropped, cmap='gray'); axes[1].set_title(f'Cropped {cropped.shape}')\n",
"# for ax in axes: ax.axis('off')\n",
"# plt.tight_layout(); plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 3.2 Convert the Full Dataset to PNG (One-Time)\n",
"\n",
"Reading DICOM at training time is ~10Γ slower than reading PNG. \n",
"Run this once to convert all DICOMs β cropped 8-bit PNGs."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def convert_dicom_to_png(row, src_dir: str, dst_dir: str, apply_crop: bool = True):\n",
" \"\"\"Convert a single DICOM to a normalised, optionally-cropped PNG.\"\"\"\n",
" src_path = os.path.join(src_dir, str(row.patient_id), f'{row.image_id}.dcm')\n",
" dst_path = os.path.join(dst_dir, f'{row.patient_id}_{row.image_id}.png')\n",
" \n",
" if os.path.exists(dst_path):\n",
" return dst_path # already converted\n",
" \n",
" img = read_dicom(src_path)\n",
" if apply_crop:\n",
" img = crop_breast_roi_threshold(img)\n",
" cv2.imwrite(dst_path, img)\n",
" return dst_path\n",
"\n",
"# ββ TODO ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n",
"# Task: Run this conversion on the full training set.\n",
"# Parallelise with concurrent.futures.ThreadPoolExecutor (I/O bound)\n",
"# or multiprocessing.Pool (CPU bound) for speed.\n",
"# Estimated time: ~2-4 hours for 54,000 images on a single CPU core.\n",
"# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n",
"\n",
"from concurrent.futures import ThreadPoolExecutor\n",
"from functools import partial\n",
"\n",
"def batch_convert(df, src_dir, dst_dir, n_workers=8):\n",
" convert_fn = partial(convert_dicom_to_png, src_dir=src_dir, dst_dir=dst_dir)\n",
" with ThreadPoolExecutor(max_workers=n_workers) as executor:\n",
" paths = list(tqdm(\n",
" executor.map(convert_fn, [row for _, row in df.iterrows()]),\n",
" total=len(df), desc='Converting DICOMs'\n",
" ))\n",
" return paths\n",
"\n",
"# Uncomment to run:\n",
"# paths = batch_convert(df, CONFIG['train_images_dir'], CONFIG['processed_dir'])\n",
"# df['path'] = paths\n",
"\n",
"# OR: point to pre-processed paths if conversion already done\n",
"df['path'] = df.apply(\n",
" lambda r: os.path.join(CONFIG['processed_dir'], f\"{r.patient_id}_{r.image_id}.png\"), axis=1\n",
")\n",
"print(\"Paths added to dataframe.\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---\n",
"## 4. Augmentations\n",
"\n",
"**Mammography-specific considerations vs dermoscopy:**\n",
"- **No transpose** β the tall/wide axis of a mammogram is anatomically meaningful\n",
"- **Horizontal flip is valid** β the breast can be mirrored for augmentation\n",
"- **No colour jitter** β mammograms are grayscale (converted to 3-channel by replication)\n",
"- **No hue/saturation** β irrelevant for grayscale\n",
"- **Larger CoarseDropout** β at 2048Γ1024 a 384px patch is only ~19% of height\n",
"- **Downscaling** β the winning solution applies random downscale to simulate low-res scans"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def get_mammography_augmentations(CONFIG):\n",
" img_h, img_w = CONFIG['img_h'], CONFIG['img_w']\n",
" \n",
" train_transform = A.Compose([\n",
" # Geometry\n",
" A.HorizontalFlip(p=0.5),\n",
" A.VerticalFlip(p=0.5),\n",
" A.ShiftScaleRotate(\n",
" shift_limit=0.05, scale_limit=0.05,\n",
" rotate_limit=10, border_mode=cv2.BORDER_CONSTANT,\n",
" value=0, p=0.5\n",
" ),\n",
" \n",
" # Pixel-level β grayscale-safe\n",
" A.RandomBrightnessContrast(brightness_limit=0.2, contrast_limit=0.2, p=0.5),\n",
" A.OneOf([\n",
" A.GaussianBlur(blur_limit=(3, 5)),\n",
" A.MotionBlur(blur_limit=5),\n",
" A.MedianBlur(blur_limit=5),\n",
" ], p=0.3),\n",
" A.GaussNoise(var_limit=(5.0, 20.0), p=0.3),\n",
" \n",
" # Distortions β subtle, preserve tissue structure\n",
" A.OneOf([\n",
" A.ElasticTransform(alpha=1, sigma=20, p=0.5),\n",
" A.GridDistortion(num_steps=5, distort_limit=0.3, p=0.5),\n",
" ], p=0.3),\n",
"\n",
" # Simulate lower-resolution acquisitions\n",
" A.Downscale(scale_range=(0.5, 0.9), p=0.3),\n",
"\n",
" # Resize to model input\n",
" A.Resize(img_h, img_w),\n",
"\n",
" # Regularisation\n",
" A.CoarseDropout(\n",
" max_holes=1,\n",
" max_height=int(img_h * 0.2),\n",
" max_width=int(img_w * 0.2),\n",
" num_holes_range=(1, 1),\n",
" p=0.5\n",
" ),\n",
"\n",
" # Normalise with ImageNet stats (ConvNeXt pretrained on ImageNet)\n",
" A.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225],\n",
" max_pixel_value=255.0, p=1.0),\n",
" ToTensorV2(),\n",
" ])\n",
"\n",
" valid_transform = A.Compose([\n",
" A.Resize(img_h, img_w),\n",
" A.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225],\n",
" max_pixel_value=255.0, p=1.0),\n",
" ToTensorV2(),\n",
" ])\n",
"\n",
" return {'train': train_transform, 'valid': valid_transform}\n",
"\n",
"data_transforms = get_mammography_augmentations(CONFIG)\n",
"print(\"Train transforms:\\n\", data_transforms['train'])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# ββ TODO ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n",
"# Task A β Grayscale β RGB conversion:\n",
"# PNGs saved above are grayscale. Albumentations and timm expect 3-channel\n",
"# input. Verify that the Dataset class below handles the cv2.COLOR_GRAY2RGB\n",
"# conversion. What would happen if you passed a single-channel tensor to\n",
"# a model expecting 3 channels?\n",
"#\n",
"# Task B β Anatomy-aware flipping:\n",
"# In mammography, left (L) and right (R) breasts are mirror images.\n",
"# A common strategy is to always flip R images to face left (normalise\n",
"# laterality) before augmentation. Implement this as a preprocessing step.\n",
"#\n",
"# Task C β CLAHE for mammography:\n",
"# CLAHE (Contrast Limited Adaptive Histogram Equalisation) is widely used\n",
"# in medical imaging. Add A.CLAHE(clip_limit=2.0, p=0.5) to the pipeline\n",
"# and compare training curves vs without.\n",
"# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---\n",
"## 5. Dataset Classes\n",
"\n",
"Same class-balanced sampler approach as the ISIC notebook, adapted for mammography.\n",
"\n",
"**Important difference:** Labels are **per-image** in the CSV but diagnostically **per-laterality**. \n",
"The sampler below treats each image independently (simpler, standard approach)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"class RSNADatasetSimple(Dataset):\n",
" \"\"\"Sequential dataset β used for validation and inference.\"\"\"\n",
" def __init__(self, meta_df, transforms=None, do_augmentations=True):\n",
" self.meta_df = meta_df.reset_index(drop=True)\n",
" self.transforms = transforms\n",
" self.do_augmentations = do_augmentations\n",
"\n",
" def __len__(self):\n",
" return len(self.meta_df)\n",
"\n",
" def __getitem__(self, idx):\n",
" row = self.meta_df.iloc[idx]\n",
" target = int(row.target)\n",
"\n",
" img = cv2.imread(row.path, cv2.IMREAD_GRAYSCALE)\n",
" if img is None:\n",
" raise FileNotFoundError(f\"Image not found: {row.path}\")\n",
" img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB) # HxWx3\n",
"\n",
" if self.transforms and self.do_augmentations:\n",
" img = self.transforms(image=img)['image']\n",
"\n",
" # One-hot encode for softmax training\n",
" label = torch.zeros(2, dtype=torch.float32)\n",
" label[target] = 1.0\n",
"\n",
" return {'image': img, 'target': label, 'target_int': target}\n",
"\n",
"\n",
"class RSNADatasetSampler(Dataset):\n",
" \"\"\"50/50 positive/negative oversampling β used for training.\"\"\"\n",
" def __init__(self, meta_df, transforms=None, do_augmentations=True):\n",
" self.df_pos = meta_df[meta_df.target == 1].reset_index(drop=True)\n",
" self.df_neg = meta_df[meta_df.target == 0].reset_index(drop=True)\n",
" self.transforms = transforms\n",
" self.do_augmentations = do_augmentations\n",
"\n",
" def __len__(self):\n",
" return len(self.df_pos) * 2\n",
"\n",
" def _load_img(self, path):\n",
" img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)\n",
" if img is None:\n",
" raise FileNotFoundError(f\"Image not found: {path}\")\n",
" return cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)\n",
"\n",
" def __getitem__(self, index):\n",
" # Alternate between positive and negative samples\n",
" if random.random() >= 0.5:\n",
" row = self.df_pos.iloc[index % len(self.df_pos)]\n",
" else:\n",
" row = self.df_neg.iloc[random.randint(0, len(self.df_neg) - 1)]\n",
"\n",
" img = self._load_img(row.path)\n",
" target = int(row.target)\n",
"\n",
" if self.transforms and self.do_augmentations:\n",
" img = self.transforms(image=img)['image']\n",
"\n",
" label = torch.zeros(2, dtype=torch.float32)\n",
" label[target] = 1.0\n",
"\n",
" return {'image': img, 'target': label, 'target_int': target}\n",
"\n",
"\n",
"def prepare_loaders(df_train, df_valid, CONFIG, data_transforms, num_workers=4):\n",
" train_ds = RSNADatasetSampler(df_train, transforms=data_transforms['train'])\n",
" valid_ds = RSNADatasetSimple(df_valid, transforms=data_transforms['valid'])\n",
"\n",
" train_loader = DataLoader(train_ds, batch_size=CONFIG['train_batch_size'],\n",
" shuffle=True, num_workers=num_workers,\n",
" pin_memory=True, drop_last=True)\n",
" valid_loader = DataLoader(valid_ds, batch_size=CONFIG['valid_batch_size'],\n",
" shuffle=False, num_workers=num_workers,\n",
" pin_memory=True)\n",
" return train_loader, valid_loader"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# ββ TODO ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n",
"# Task A β Verify grayscale β RGB:\n",
"# Load one batch and check image.shape == [B, 3, H, W].\n",
"# Are the three channels identical (since input is grayscale)?\n",
"# This is fine β ImageNet-pretrained models expect RGB, and repeated\n",
"# grayscale channels still carry the correct intensity information.\n",
"#\n",
"# Task B β Label distribution in sampler:\n",
"# Iterate 100 batches from train_loader. Compute the mean of target[:, 1]\n",
"# (fraction of positives). Does it converge to ~0.5 as expected?\n",
"#\n",
"# Task C β Laterality normalisation in the dataset:\n",
"# Add a 'flip' flag to the dataframe rows where laterality == 'R',\n",
"# and apply cv2.flip(img, 1) inside __getitem__ before augmentations.\n",
"# This normalises all breasts to face left, reducing the domain shift.\n",
"# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---\n",
"## 6. Model: ConvNeXt-Small \n",
"\n",
"ConvNext will be used for the start and you will try other models"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"class MammographyConvNeXt(nn.Module):\n",
" def __init__(self, model_name: str, num_classes: int = 2,\n",
" drop_rate: float = 0.0, drop_path_rate: float = 0.0,\n",
" pretrained: bool = True):\n",
" super().__init__()\n",
" self.model = timm.create_model(\n",
" model_name,\n",
" pretrained=pretrained,\n",
" drop_rate=drop_rate,\n",
" drop_path_rate=drop_path_rate,\n",
" )\n",
" # Replace classification head\n",
" in_features = self.model.head.fc.in_features\n",
" self.model.head.fc = nn.Linear(in_features, num_classes)\n",
" self.softmax = nn.Softmax(dim=1)\n",
"\n",
" def forward(self, images):\n",
" return self.softmax(self.model(images))\n",
"\n",
" def get_cancer_probability(self, images):\n",
" \"\"\"Convenience method: returns only the malignant class probability.\"\"\"\n",
" return self.forward(images)[:, 1]\n",
"\n",
"\n",
"def setup_model(CONFIG):\n",
" model = MammographyConvNeXt(\n",
" model_name=CONFIG['model_name'],\n",
" num_classes=CONFIG['num_classes'],\n",
" drop_rate=CONFIG['drop_rate'],\n",
" drop_path_rate=CONFIG['drop_path_rate'],\n",
" pretrained=True,\n",
" )\n",
" return model.to(CONFIG['device'])\n",
"\n",
"\n",
"def print_trainable_parameters(model):\n",
" total = sum(p.numel() for p in model.parameters())\n",
" trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
" print(f\"Trainable: {trainable:,} / Total: {total:,} ({100*trainable/total:.1f}%)\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"model = setup_model(CONFIG)\n",
"print_trainable_parameters(model)\n",
"\n",
"# Verify forward pass shape\n",
"dummy = torch.zeros(2, 3, CONFIG['img_h'], CONFIG['img_w']).to(CONFIG['device'])\n",
"with torch.no_grad():\n",
" out = model(dummy)\n",
"print(f\"Output shape: {out.shape}\") # [2, 2]\n",
"print(f\"Sum per sample (should be 1.0): {out.sum(dim=1)}\") # softmax sums to 1"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# ββ TODO ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n",
"# Task A β Explore timm ConvNeXt variants:\n",
"# Swap model_name to 'convnext_tiny.fb_in22k_ft_in1k' (smaller, faster)\n",
"# or 'convnext_base.fb_in22k_ft_in1k' (larger, potentially higher accuracy).\n",
"# Compare parameter counts and estimated GPU memory usage.\n",
"#\n",
"# Task B β Global pooling strategy:\n",
"# The winning team notes MaxPool worked better than AvgPool (\"AvgPool tends\n",
"# to wash away the signal\"). This makes clinical sense: cancer is a focal\n",
"# finding β the maximum activation in any region matters more than the average.\n",
"# Try modifying the head to use nn.AdaptiveMaxPool2d before the linear layer.\n",
"#\n",
"# Task C β Mixed precision:\n",
"# At 2048Γ1024, memory is tight. Enable AMP (Automatic Mixed Precision)\n",
"# using torch.cuda.amp.autocast() and GradScaler. This can 2Γ throughput.\n",
"# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---\n",
"## 7. Loss Function & Competition Metric\n",
"\n",
"**Loss:** Cross-Entropy Loss for softmax output (equivalent to `BCELoss` for the 2-class case but pairs naturally with softmax).\n",
"\n",
"**Competition metric: Probabilistic F1 (pF1)** \n",
"The RSNA competition used a *probabilistic* variant of F1 that operates on predicted probabilities rather than hard thresholds:\n",
"\n",
"$$pF1 = \\frac{2 \\cdot \\sum_i p_i \\cdot y_i}{\\sum_i p_i + \\sum_i y_i}$$\n",
"\n",
"This avoids arbitrary threshold selection and penalises both low recall (missed cancers) and low precision (unnecessary biopsies)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def criterion(outputs, targets):\n",
" \"\"\"Cross-entropy loss for softmax output with one-hot targets.\"\"\"\n",
" return nn.CrossEntropyLoss()(outputs, targets)\n",
"\n",
"\n",
"def probabilistic_f1(y_pred_proba: np.ndarray, y_true: np.ndarray) -> float:\n",
" \"\"\"\n",
" Probabilistic F1 score (RSNA competition metric).\n",
" \n",
" Args:\n",
" y_pred_proba: predicted probabilities for class 1, shape (N,)\n",
" y_true: binary ground truth labels, shape (N,)\n",
" \"\"\"\n",
" tp_sum = np.sum(y_pred_proba * y_true)\n",
" pred_sum = np.sum(y_pred_proba)\n",
" true_sum = np.sum(y_true)\n",
" if pred_sum + true_sum == 0:\n",
" return 0.0\n",
" return 2 * tp_sum / (pred_sum + true_sum)\n",
"\n",
"\n",
"# Demonstrate pF1 sensitivity\n",
"np.random.seed(42)\n",
"y_true_demo = np.random.binomial(1, 0.02, 1000)\n",
"y_good = np.clip(y_true_demo + np.random.normal(0, 0.1, 1000), 0, 1)\n",
"y_low_recall = np.clip(y_true_demo * np.random.uniform(0, 0.3, 1000), 0, 1)\n",
"\n",
"print(f\"Good model pF1: {probabilistic_f1(y_good, y_true_demo):.4f}\")\n",
"print(f\"Low recall pF1: {probabilistic_f1(y_low_recall, y_true_demo):.4f}\")\n",
"print(f\"All-zero pF1: {probabilistic_f1(np.zeros_like(y_true_demo), y_true_demo):.4f}\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# ββ TODO ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n",
"# Task A β pF1 vs threshold F1:\n",
"# For the same set of predictions, compute pF1 and hard-threshold F1\n",
"# at thresholds in [0.1, 0.3, 0.5, 0.7, 0.9]. Plot all values.\n",
"# Why does pF1 avoid the threshold selection problem?\n",
"#\n",
"# Task B β Clinical interpretation:\n",
"# A false negative (missed cancer) has far worse consequences than a\n",
"# false positive (unnecessary recall). How does pF1 account for this?\n",
"# Compare to pAUC from the ISIC notebook β which metric is more\n",
"# sensitive to the rare-positive problem?\n",
"#\n",
"# Task C β Class-weighted loss:\n",
"# With ~2% positives, the model can score well on CE loss by predicting\n",
"# all zeros. Add weight=torch.tensor([0.02, 0.98]) to CrossEntropyLoss\n",
"# to penalise false negatives more heavily. Does it improve pF1?\n",
"# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---\n",
"## 8. Training & Validation Loops"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def fetch_scheduler(optimizer, CONFIG):\n",
" if CONFIG['scheduler'] == 'CosineAnnealingLR':\n",
" return lr_scheduler.CosineAnnealingLR(\n",
" optimizer, T_max=CONFIG['T_max'], eta_min=CONFIG['min_lr'])\n",
" elif CONFIG['scheduler'] == 'CosineAnnealingWarmRestarts':\n",
" return lr_scheduler.CosineAnnealingWarmRestarts(\n",
" optimizer, T_0=25, eta_min=CONFIG['min_lr'])\n",
" return None\n",
"\n",
"\n",
"def train_one_epoch(model, optimizer, scheduler, dataloader, device, epoch, CONFIG):\n",
" model.train()\n",
" running_loss, dataset_size = 0.0, 0\n",
" scaler = torch.cuda.amp.GradScaler() # AMP for memory efficiency\n",
"\n",
" bar = tqdm(enumerate(dataloader), total=len(dataloader))\n",
" for step, data in bar:\n",
" images = data['image'].to(device, dtype=torch.float)\n",
" targets = data['target'].to(device, dtype=torch.float)\n",
" batch_size = images.size(0)\n",
"\n",
" with torch.cuda.amp.autocast():\n",
" outputs = model(images) # [B, 2]\n",
" loss = criterion(outputs, targets) / CONFIG['n_accumulate']\n",
"\n",
" scaler.scale(loss).backward()\n",
"\n",
" if (step + 1) % CONFIG['n_accumulate'] == 0:\n",
" scaler.step(optimizer)\n",
" scaler.update()\n",
" optimizer.zero_grad()\n",
" if scheduler is not None:\n",
" scheduler.step()\n",
"\n",
" running_loss += loss.item() * batch_size * CONFIG['n_accumulate']\n",
" dataset_size += batch_size\n",
" epoch_loss = running_loss / dataset_size\n",
"\n",
" bar.set_postfix(Epoch=epoch, Loss=f'{epoch_loss:.4f}',\n",
" LR=f'{optimizer.param_groups[0][\"lr\"]:.2e}')\n",
"\n",
" gc.collect()\n",
" return epoch_loss\n",
"\n",
"\n",
"@torch.inference_mode()\n",
"def valid_one_epoch(model, dataloader, device, epoch, optimizer, return_preds=False):\n",
" model.eval()\n",
" running_loss, dataset_size = 0.0, 0\n",
" all_preds, all_targets = [], []\n",
"\n",
" bar = tqdm(enumerate(dataloader), total=len(dataloader))\n",
" for step, data in bar:\n",
" images = data['image'].to(device, dtype=torch.float)\n",
" targets = data['target'].to(device, dtype=torch.float)\n",
" t_int = data['target_int'].numpy()\n",
" batch_size = images.size(0)\n",
"\n",
" outputs = model(images) # [B, 2]\n",
" loss = criterion(outputs, targets)\n",
"\n",
" cancer_prob = outputs[:, 1].cpu().numpy() # malignant probability\n",
" all_preds.append(cancer_prob)\n",
" all_targets.append(t_int)\n",
"\n",
" running_loss += loss.item() * batch_size\n",
" dataset_size += batch_size\n",
" epoch_loss = running_loss / dataset_size\n",
"\n",
" bar.set_postfix(Epoch=epoch, Val_Loss=f'{epoch_loss:.4f}',\n",
" LR=f'{optimizer.param_groups[0][\"lr\"]:.2e}')\n",
"\n",
" gc.collect()\n",
" all_preds = np.concatenate(all_preds)\n",
" all_targets = np.concatenate(all_targets)\n",
"\n",
" pf1 = probabilistic_f1(all_preds, all_targets)\n",
" auroc = roc_auc_score(all_targets, all_preds)\n",
"\n",
" if return_preds:\n",
" return epoch_loss, pf1, auroc, all_preds, all_targets\n",
" return epoch_loss, pf1, auroc"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def run_training(train_loader, valid_loader, model, optimizer, scheduler,\n",
" CONFIG, model_name='best_model.pth', tolerance_max=8, seed=42):\n",
" set_seed(seed)\n",
" best_pf1 = -np.inf\n",
" best_weights = copy.deepcopy(model.state_dict())\n",
" history = defaultdict(list)\n",
" tolerance = 0\n",
" start = time.time()\n",
"\n",
" for epoch in range(1, CONFIG['epochs'] + 1):\n",
" if tolerance > tolerance_max:\n",
" print(f\"Early stopping at epoch {epoch}\")\n",
" break\n",
"\n",
" train_loss = train_one_epoch(\n",
" model, optimizer, scheduler,\n",
" train_loader, CONFIG['device'], epoch, CONFIG)\n",
"\n",
" val_loss, val_pf1, val_auroc = valid_one_epoch(\n",
" model, valid_loader, CONFIG['device'], epoch, optimizer)\n",
"\n",
" history['train_loss'].append(train_loss)\n",
" history['val_loss'].append(val_loss)\n",
" history['val_pf1'].append(val_pf1)\n",
" history['val_auroc'].append(val_auroc)\n",
" history['lr'].append(scheduler.get_last_lr()[0] if scheduler else CONFIG['learning_rate'])\n",
"\n",
" print(f\"Epoch {epoch:02d} | \"\n",
" f\"Train Loss: {train_loss:.4f} | \"\n",
" f\"Val Loss: {val_loss:.4f} | \"\n",
" f\"Val pF1: {val_pf1:.4f} | \"\n",
" f\"Val AUC: {val_auroc:.4f}\")\n",
"\n",
" if val_pf1 > best_pf1:\n",
" tolerance = 0\n",
" best_pf1 = val_pf1\n",
" best_weights = copy.deepcopy(model.state_dict())\n",
" save_path = os.path.join(CONFIG['models_folder'], model_name)\n",
" torch.save(model.state_dict(), save_path)\n",
" print(f\" β New best pF1: {best_pf1:.4f} β saved to {save_path}\")\n",
" else:\n",
" tolerance += 1\n",
"\n",
" elapsed = time.time() - start\n",
" print(f\"\\nTraining complete in {elapsed//3600:.0f}h {(elapsed%3600)//60:.0f}m\")\n",
" print(f\"Best pF1: {best_pf1:.4f}\")\n",
" model.load_state_dict(best_weights)\n",
" return model, history"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---\n",
"## 9. Cross-Validation (4-Fold, Patient-Stratified)\n",
"\n",
"The winning solution used **4-fold stratified group CV** with `patient_id` as the group. \n",
"Final predictions are the **mean of all 4 fold models** (ensembling)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"sgkf = StratifiedGroupKFold(n_splits=CONFIG['n_folds'], shuffle=True, random_state=CONFIG['seed'])\n",
"\n",
"fold_results = []\n",
"oof_df_list = []\n",
"\n",
"for fold_n, (train_idx, val_idx) in enumerate(sgkf.split(df, y=df.target, groups=df[CONFIG['group_col']])):\n",
" print(f\"\\n{'='*60}\")\n",
" print(f\"FOLD {fold_n + 1} / {CONFIG['n_folds']}\")\n",
" print(f\"{'='*60}\")\n",
"\n",
" fold_train = df.iloc[train_idx].reset_index(drop=True)\n",
" fold_valid = df.iloc[val_idx].reset_index(drop=True)\n",
"\n",
" print(f\" Train: {len(fold_train)} images | Positive rate: {fold_train.target.mean():.3f}\")\n",
" print(f\" Valid: {len(fold_valid)} images | Positive rate: {fold_valid.target.mean():.3f}\")\n",
"\n",
" set_seed(CONFIG['seed'])\n",
" model = setup_model(CONFIG)\n",
" optimizer = optim.AdamW(model.parameters(),\n",
" lr=CONFIG['learning_rate'],\n",
" weight_decay=CONFIG['weight_decay'])\n",
" scheduler = fetch_scheduler(optimizer, CONFIG)\n",
"\n",
" train_loader, valid_loader = prepare_loaders(\n",
" fold_train, fold_valid, CONFIG, data_transforms, num_workers=4)\n",
"\n",
" model, history = run_training(\n",
" train_loader, valid_loader, model, optimizer, scheduler,\n",
" CONFIG=CONFIG,\n",
" model_name=f'convnext_fold{fold_n}.pth',\n",
" tolerance_max=5,\n",
" seed=CONFIG['seed'],\n",
" )\n",
"\n",
" # Get out-of-fold predictions\n",
" _, pf1, auroc, oof_preds, oof_targets = valid_one_epoch(\n",
" model, valid_loader, CONFIG['device'], epoch=0,\n",
" optimizer=optimizer, return_preds=True\n",
" )\n",
"\n",
" fold_valid['oof_pred'] = oof_preds\n",
" fold_valid['fold_n'] = fold_n\n",
" oof_df_list.append(fold_valid)\n",
" fold_results.append({'fold': fold_n, 'pf1': pf1, 'auroc': auroc})\n",
" print(f\" Fold {fold_n+1} β pF1: {pf1:.4f} | AUC: {auroc:.4f}\")\n",
"\n",
" torch.cuda.empty_cache(); gc.collect()\n",
"\n",
"print(\"\\n=== Cross-Validation Summary ===\")\n",
"results_df = pd.DataFrame(fold_results)\n",
"print(results_df)\n",
"print(f\"\\nMean pF1: {results_df.pf1.mean():.4f} Β± {results_df.pf1.std():.4f}\")\n",
"print(f\"Mean AUC: {results_df.auroc.mean():.4f} Β± {results_df.auroc.std():.4f}\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---\n",
"## 10. Out-of-Fold Analysis"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"oof_df = pd.concat(oof_df_list).reset_index(drop=True)\n",
"\n",
"oof_pf1 = probabilistic_f1(oof_df.oof_pred.values, oof_df.target.values)\n",
"oof_auroc = roc_auc_score(oof_df.target.values, oof_df.oof_pred.values)\n",
"print(f\"OOF pF1 (all folds combined): {oof_pf1:.4f}\")\n",
"print(f\"OOF AUC (all folds combined): {oof_auroc:.4f}\")\n",
"\n",
"# Score breakdown by fold\n",
"for fn, g in oof_df.groupby('fold_n'):\n",
" f = probabilistic_f1(g.oof_pred.values, g.target.values)\n",
" a = roc_auc_score(g.target.values, g.oof_pred.values)\n",
" print(f\" Fold {fn}: pF1={f:.4f} AUC={a:.4f}\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from sklearn.metrics import roc_curve, precision_recall_curve\n",
"\n",
"fig, axes = plt.subplots(1, 3, figsize=(16, 5))\n",
"\n",
"# ROC curve\n",
"fpr, tpr, _ = roc_curve(oof_df.target.values, oof_df.oof_pred.values)\n",
"axes[0].plot(fpr, tpr, label=f'AUC={oof_auroc:.3f}')\n",
"axes[0].plot([0,1],[0,1],'--', color='gray')\n",
"axes[0].set_xlabel('FPR'); axes[0].set_ylabel('TPR')\n",
"axes[0].set_title('ROC Curve'); axes[0].legend()\n",
"\n",
"# Precision-Recall curve\n",
"prec, rec, _ = precision_recall_curve(oof_df.target.values, oof_df.oof_pred.values)\n",
"axes[1].plot(rec, prec, color='coral')\n",
"axes[1].axhline(oof_df.target.mean(), linestyle='--', color='gray', label=f'Baseline ({oof_df.target.mean():.3f})')\n",
"axes[1].set_xlabel('Recall'); axes[1].set_ylabel('Precision')\n",
"axes[1].set_title('Precision-Recall Curve'); axes[1].legend()\n",
"\n",
"# Prediction distribution\n",
"axes[2].hist(oof_df[oof_df.target==0].oof_pred, bins=50, alpha=0.6, label='Benign', color='steelblue')\n",
"axes[2].hist(oof_df[oof_df.target==1].oof_pred, bins=50, alpha=0.6, label='Malignant', color='red')\n",
"axes[2].set_xlabel('Predicted cancer probability')\n",
"axes[2].set_title('Score Distribution'); axes[2].legend()\n",
"\n",
"plt.tight_layout(); plt.show()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# ββ TODO ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n",
"# Task A β Subgroup analysis:\n",
"# Compute pF1 and AUC separately for:\n",
"# (a) CC view vs MLO view\n",
"# (b) Left vs Right laterality \n",
"# (c) Age < 55 vs Age β₯ 55\n",
"# Are there systematic performance gaps across subgroups?\n",
"#\n",
"# Task B β Threshold optimisation:\n",
"# Find the threshold that maximises hard-threshold F1 on the OOF predictions.\n",
"# Is it close to 0.5 or significantly different?\n",
"#\n",
"# Task C β Ensemble the 4 folds:\n",
"# Load all 4 saved checkpoints, run inference on the validation set,\n",
"# and average the predictions. Does the ensemble improve over any single fold?\n",
"# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---\n",
"---\n",
"# π Part 2: Improving with YOLOX ROI Detection\n",
"\n",
"**What problem does YOLOX solve?**\n",
"\n",
"The threshold-based cropper from Part 1 fails on:\n",
"- Implants (bright background)\n",
"- Bright scanner markers/labels overlaid on the image\n",
"- Low-contrast images where the breast edge is poorly defined\n",
"- Cases where the background is not uniformly dark\n",
"\n",
"The winning solution trains **YOLOX-nano** (a fast anchor-free object detector, 416Γ416 input) to directly predict the **bounding box of the breast ROI**. The crop is then resized to 2048Γ1024 for ConvNeXt.\n",
"\n",
"```\n",
"DICOM (raw) β 8-bit normalise β YOLOX-nano (416Γ416) β breast bbox\n",
" β crop to bbox β resize to 2048Γ1024 β ConvNeXt-small\n",
"```\n",
"\n",
"**Result:** Cleaner, more consistent crops β improved ConvNeXt performance."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Part 2.1 β Why YOLOX for Medical ROI Detection?\n",
"\n",
"YOLOX is anchor-free and extremely fast at small sizes (nano = 0.91M params), making it ideal as a preprocessing step that must run on every image at inference time.\n",
"\n",
"| Aspect | Threshold cropper | YOLOX-nano |\n",
"|---|---|---|\n",
"| Speed | Very fast (CPU) | Fast (GPU, ~5ms) |\n",
"| Robustness | Fails on bright artefacts | Handles most cases |\n",
"| Training required | No | Yes (labelled boxes needed) |\n",
"| Generalisation | Scanner-dependent | Generalises across scanners |\n",
"\n",
"The winning team annotated **571 images** manually (in YOLOv5 format) for training the detector."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Part 2.2 β YOLOX Setup"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Install YOLOX from the winning team's repo\n",
"!git clone https://github.com/Megvii-BaseDetection/YOLOX.git\n",
"%cd YOLOX\n",
"!pip install -v -e . # install in editable mode\n",
"%cd .."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# ββ TODO ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n",
"# Task A β Understand the annotation format:\n",
"# YOLOX uses the YOLOv5 annotation format:\n",
"# <class_id> <x_center> <y_center> <width> <height> (all normalised 0-1)\n",
"# For breast ROI there is only one class (class_id = 0 = breast).\n",
"# Given a mammogram of shape (H=3000, W=1500), write a function that\n",
"# converts a pixel bounding box (x1, y1, x2, y2) to this format.\n",
"# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n",
"\n",
"def pixel_bbox_to_yolo(x1, y1, x2, y2, img_h, img_w):\n",
" \"\"\"\n",
" Convert pixel (x1,y1,x2,y2) bbox to YOLO normalised format.\n",
" Returns: class_id, x_center, y_center, width, height (all in [0,1])\n",
" \"\"\"\n",
" # TODO: implement this\n",
" raise NotImplementedError\n",
"\n",
"\n",
"def yolo_to_pixel_bbox(x_c, y_c, w, h, img_h, img_w):\n",
" \"\"\"\n",
" Convert YOLO normalised format back to pixel (x1,y1,x2,y2).\n",
" \"\"\"\n",
" # TODO: implement this\n",
" raise NotImplementedError"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Part 2.3 β Creating the ROI Detection Dataset\n",
"\n",
"To train YOLOX we need bounding box annotations for breast ROIs. \n",
"Two options:\n",
"1. **Use threshold cropper to generate pseudo-labels** (quick, imperfect)\n",
"2. **Download the winning team's 571 manual annotations** from the repo (better)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Option 1: Auto-generate pseudo-labels from threshold cropper\n",
"# These will be noisy but sufficient for a reasonable detector.\n",
"\n",
"import yaml\n",
"\n",
"ROI_DATASET_DIR = './data/roi_det'\n",
"os.makedirs(f'{ROI_DATASET_DIR}/images/train', exist_ok=True)\n",
"os.makedirs(f'{ROI_DATASET_DIR}/images/val', exist_ok=True)\n",
"os.makedirs(f'{ROI_DATASET_DIR}/labels/train', exist_ok=True)\n",
"os.makedirs(f'{ROI_DATASET_DIR}/labels/val', exist_ok=True)\n",
"\n",
"\n",
"def generate_pseudo_label(row, src_dir, dst_img_dir, dst_lbl_dir):\n",
" \"\"\"Threshold-crop a DICOM, save resized PNG + YOLO annotation.\"\"\"\n",
" src = os.path.join(src_dir, str(row.patient_id), f'{row.image_id}.dcm')\n",
" img = read_dicom(src)\n",
" H, W = img.shape\n",
"\n",
" # Get bbox from threshold cropper\n",
" mask = (img > 10).astype(np.uint8)\n",
" num_labels, labels, stats, _ = cv2.connectedComponentsWithStats(mask, connectivity=8)\n",
" if num_labels < 2:\n",
" return None\n",
" lbl = 1 + np.argmax(stats[1:, cv2.CC_STAT_AREA])\n",
" x1 = stats[lbl, cv2.CC_STAT_LEFT]\n",
" y1 = stats[lbl, cv2.CC_STAT_TOP]\n",
" bw = stats[lbl, cv2.CC_STAT_WIDTH]\n",
" bh = stats[lbl, cv2.CC_STAT_HEIGHT]\n",
" x2, y2 = x1 + bw, y1 + bh\n",
"\n",
" # Save 416Γ416 resized image for YOLOX\n",
" img_416 = cv2.resize(img, (416, 416))\n",
" img_path = os.path.join(dst_img_dir, f'{row.patient_id}_{row.image_id}.png')\n",
" cv2.imwrite(img_path, img_416)\n",
"\n",
" # Scale bbox to 416Γ416 and write YOLO label\n",
" x1_s = x1 * 416 / W; x2_s = x2 * 416 / W\n",
" y1_s = y1 * 416 / H; y2_s = y2 * 416 / H\n",
" xc = (x1_s + x2_s) / 2 / 416\n",
" yc = (y1_s + y2_s) / 2 / 416\n",
" bw_n = (x2_s - x1_s) / 416\n",
" bh_n = (y2_s - y1_s) / 416\n",
"\n",
" lbl_path = os.path.join(dst_lbl_dir, f'{row.patient_id}_{row.image_id}.txt')\n",
" with open(lbl_path, 'w') as f:\n",
" f.write(f'0 {xc:.6f} {yc:.6f} {bw_n:.6f} {bh_n:.6f}\\n')\n",
"\n",
" return img_path\n",
"\n",
"\n",
"# Write dataset YAML for YOLOX\n",
"roi_yaml = {\n",
" 'path': ROI_DATASET_DIR,\n",
" 'train': 'images/train',\n",
" 'val': 'images/val',\n",
" 'nc': 1,\n",
" 'names': ['breast']\n",
"}\n",
"with open(f'{ROI_DATASET_DIR}/dataset.yaml', 'w') as f:\n",
" yaml.dump(roi_yaml, f)\n",
"\n",
"print(\"Dataset directory structure created.\")\n",
"\n",
"# Uncomment to run (slow β one DICOM per image):\n",
"# for _, row in tqdm(df.iterrows(), total=len(df)):\n",
"# split = 'train' if random.random() > 0.1 else 'val'\n",
"# generate_pseudo_label(row, CONFIG['train_images_dir'],\n",
"# f'{ROI_DATASET_DIR}/images/{split}',\n",
"# f'{ROI_DATASET_DIR}/labels/{split}')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Part 2.4 β Training YOLOX-Nano"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# ββ TODO ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n",
"# Task A β Experiment file:\n",
"# YOLOX uses Python experiment files (exps/) to configure training.\n",
"# Create exps/rsna_yolox_nano.py based on the nano template,\n",
"# setting num_classes=1, input_size=(416,416), max_epoch=50.\n",
"#\n",
"# Task B β Run training:\n",
"# python YOLOX/tools/train.py -f exps/rsna_yolox_nano.py -d 1 -b 16 --fp16\n",
"# Monitor mAP@0.5 on the val split. The winning team reports ~95% AP@0.5.\n",
"#\n",
"# Task C β Why nano and not a larger YOLOX?\n",
"# The ROI detection task is simple (one large object per image, near-perfect\n",
"# contrast). A nano model (0.91M params) is sufficient and runs fast.\n",
"# Verify: does a larger YOLOX-s actually improve downstream ConvNeXt pF1?\n",
"# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n",
"\n",
"# Example training command (run in terminal):\n",
"YOLOX_TRAIN_CMD = \"\"\"\n",
"PYTHONPATH=$(pwd)/YOLOX:$PYTHONPATH python YOLOX/tools/train.py \\\\\n",
" -f exps/rsna_yolox_nano.py \\\\\n",
" -d 1 \\\\\n",
" -b 16 \\\\\n",
" --fp16 \\\\\n",
" -o \\\\\n",
" --cache\n",
"\"\"\"\n",
"print(\"Training command:\")\n",
"print(YOLOX_TRAIN_CMD)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Part 2.5 β YOLOX Inference for ROI Cropping"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import sys\n",
"sys.path.insert(0, 'YOLOX')\n",
"\n",
"from yolox.data.data_augment import ValTransform\n",
"from yolox.data.datasets import COCO_CLASSES\n",
"from yolox.exp import get_exp\n",
"from yolox.utils import fuse_model, get_model_info, postprocess\n",
"\n",
"\n",
"class YOLOXBreastDetector:\n",
" \"\"\"\n",
" Wrapper around a trained YOLOX-nano model for breast ROI detection.\n",
" Produces a (x1, y1, x2, y2) bounding box on the original image scale.\n",
" \"\"\"\n",
" def __init__(self, exp_file: str, ckpt_path: str, device: str = 'cuda',\n",
" input_size: tuple = (416, 416), score_thresh: float = 0.3):\n",
" self.input_size = input_size\n",
" self.score_thresh = score_thresh\n",
" self.device = device\n",
"\n",
" exp = get_exp(exp_file, None)\n",
" exp.test_size = input_size\n",
"\n",
" self.model = exp.get_model()\n",
" ckpt = torch.load(ckpt_path, map_location=device)\n",
" self.model.load_state_dict(ckpt.get('model', ckpt))\n",
" self.model = fuse_model(self.model).to(device).eval()\n",
"\n",
" self.preproc = ValTransform(legacy=False)\n",
"\n",
" @torch.inference_mode()\n",
" def detect(self, img_gray: np.ndarray):\n",
" \"\"\"\n",
" Args:\n",
" img_gray: uint8 grayscale mammogram array (H, W)\n",
" Returns:\n",
" bbox (x1, y1, x2, y2) in original image pixels, or None if no detection\n",
" \"\"\"\n",
" H, W = img_gray.shape\n",
" img_rgb = cv2.cvtColor(img_gray, cv2.COLOR_GRAY2RGB)\n",
"\n",
" # Preprocess to YOLOX input size\n",
" img_t, ratio = self.preproc(img_rgb, None, self.input_size)\n",
" img_t = torch.from_numpy(img_t).unsqueeze(0).float().to(self.device)\n",
"\n",
" # Run YOLOX\n",
" outputs = self.model(img_t)\n",
" outputs = postprocess(outputs, num_classes=1, conf_thre=self.score_thresh,\n",
" nms_thre=0.45, class_agnostic=True)\n",
"\n",
" if outputs[0] is None or len(outputs[0]) == 0:\n",
" return None # no detection β fall back to threshold crop\n",
"\n",
" # Take highest-confidence detection\n",
" boxes = outputs[0].cpu().numpy()\n",
" best = boxes[np.argmax(boxes[:, 4])]\n",
" x1, y1, x2, y2 = best[:4] / ratio\n",
"\n",
" # Clamp to image bounds\n",
" x1 = max(0, int(x1)); y1 = max(0, int(y1))\n",
" x2 = min(W, int(x2)); y2 = min(H, int(y2))\n",
" return x1, y1, x2, y2\n",
"\n",
"\n",
"print(\"YOLOXBreastDetector class defined.\")\n",
"print(\"Instantiate with:\")\n",
"print(\" detector = YOLOXBreastDetector(\")\n",
"print(\" exp_file='exps/rsna_yolox_nano.py',\")\n",
"print(\" ckpt_path='YOLOX/YOLOX_outputs/rsna_yolox_nano/best_ckpt.pth'\")\n",
"print(\" )\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def crop_with_yolox(img_gray: np.ndarray, detector: YOLOXBreastDetector,\n",
" fallback_threshold: bool = True) -> np.ndarray:\n",
" \"\"\"\n",
" Crop breast ROI using YOLOX. Falls back to threshold cropping if no\n",
" detection is found (robustness measure).\n",
" \"\"\"\n",
" bbox = detector.detect(img_gray)\n",
" if bbox is not None:\n",
" x1, y1, x2, y2 = bbox\n",
" return img_gray[y1:y2, x1:x2]\n",
" elif fallback_threshold:\n",
" return crop_breast_roi_threshold(img_gray)\n",
" else:\n",
" return img_gray"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# ββ TODO ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n",
"# Task A β Compare crop quality side by side:\n",
"# For 6 images (2 normal, 2 with artefacts, 2 implants):\n",
"# Show: original | threshold crop | YOLOX crop\n",
"# Mark the predicted bounding box on the original image.\n",
"#\n",
"# Task B β Measure coverage:\n",
"# Compute what fraction of images YOLOX successfully detects vs falls back\n",
"# to threshold cropping. What are the characteristics of failed detections?\n",
"#\n",
"# Task C β YOLOX confidence analysis:\n",
"# Plot the distribution of detection confidence scores.\n",
"# Do low-confidence detections produce worse crops?\n",
"# Consider using a higher score_thresh (e.g. 0.5) and more aggressive fallback.\n",
"# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Part 2.6 β Regenerate Processed PNGs with YOLOX Crops\n",
"\n",
"Now rerun the DICOMβPNG conversion pipeline from Section 3, but replace `crop_breast_roi_threshold` with `crop_with_yolox`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"PROCESSED_YOLOX_DIR = './data/processed_pngs_yolox'\n",
"os.makedirs(PROCESSED_YOLOX_DIR, exist_ok=True)\n",
"\n",
"\n",
"def convert_dicom_to_png_yolox(row, src_dir: str, dst_dir: str, detector):\n",
" \"\"\"DICOM β 8-bit normalise β YOLOX crop β PNG.\"\"\"\n",
" src = os.path.join(src_dir, str(row.patient_id), f'{row.image_id}.dcm')\n",
" dst = os.path.join(dst_dir, f'{row.patient_id}_{row.image_id}.png')\n",
"\n",
" if os.path.exists(dst):\n",
" return dst\n",
"\n",
" img = read_dicom(src)\n",
" img = crop_with_yolox(img, detector, fallback_threshold=True)\n",
" cv2.imwrite(dst, img)\n",
" return dst\n",
"\n",
"\n",
"# Uncomment after training YOLOX:\n",
"# detector = YOLOXBreastDetector(\n",
"# exp_file='exps/rsna_yolox_nano.py',\n",
"# ckpt_path='YOLOX/YOLOX_outputs/rsna_yolox_nano/best_ckpt.pth'\n",
"# )\n",
"# for _, row in tqdm(df.iterrows(), total=len(df)):\n",
"# convert_dicom_to_png_yolox(row, CONFIG['train_images_dir'], PROCESSED_YOLOX_DIR, detector)\n",
"\n",
"# Update paths in df\n",
"# df['path'] = df.apply(\n",
"# lambda r: os.path.join(PROCESSED_YOLOX_DIR, f\"{r.patient_id}_{r.image_id}.png\"), axis=1\n",
"# )\n",
"print(\"After regenerating PNGs, rerun Section 9 (CV training) with the updated df['path'].\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Part 2.7 β Retrain ConvNeXt with YOLOX-Cropped Images"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# ββ TODO ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n",
"# Task A β Retrain and compare:\n",
"# Run the full 4-fold CV from Section 9 again, but with\n",
"# YOLOX-cropped images (df['path'] pointing to PROCESSED_YOLOX_DIR).\n",
"# Fill in the table below:\n",
"#\n",
"# | Crop method | OOF pF1 | OOF AUC |\n",
"# |--- |--- |--- |\n",
"# | Threshold | ? | ? |\n",
"# | YOLOX-nano | ? | ? |\n",
"#\n",
"# Task B β Error analysis on improved crops:\n",
"# Identify images where YOLOX cropping changed the prediction significantly\n",
"# (|pred_yolox - pred_threshold| > 0.2). Are these the artefact/implant cases?\n",
"#\n",
"# Task C β Larger YOLOX vs YOLOX-nano:\n",
"# Try training YOLOX-s (small, 9M params). Does the better detection\n",
"# quality translate to better ConvNeXt pF1? Or is YOLOX-nano already\n",
"# good enough (the winning answer from the mr.robot team is: nano is sufficient).\n",
"# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---\n",
"## Summary: From Baseline to Winning Pipeline\n",
"\n",
"```\n",
"Part 1 β Baseline\n",
" DICOM β threshold crop β 2048Γ1024 ConvNeXt-small (softmax)\n",
" Expected OOF pF1: ~0.52-0.56\n",
"\n",
"Part 2 β Full winning pipeline\n",
" DICOM β YOLOX-nano crop β 2048Γ1024 ConvNeXt-small (softmax) Γ 4 folds\n",
" Expected OOF pF1: ~0.59-0.62 (LB: 0.65, AUC: 0.93 with ensemble)\n",
"```\n",
"\n",
"**Further improvements the winning team explored (but are out of scope here):**\n",
"- External data (VinDr, CMMD, CBIS-DDSM) for backbone pretraining\n",
"- TTA (horizontal flip ensemble at inference)\n",
"- All 4 views (CC+MLO, L+R) as a patient-level prediction\n",
"- `MONOCHROME1` inversion verified per-scanner\n",
"- MaxPool head instead of AvgPool (already implemented above)\n",
"\n",
"**Reference:** \n",
"mr.robot team writeup: https://www.kaggle.com/competitions/rsna-breast-cancer-detection/writeups/mr-robot-1st-place-solution \n",
"Code: https://github.com/dangnh0611/kaggle_rsna_breast_cancer"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"name": "python",
"version": "3.10.0"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
|