{ "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", "# (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 }