{ "cells": [ { "cell_type": "markdown", "id": "3d7f60a0", "metadata": {}, "source": [ "---\n", "## Stage 1 — Data Exploration\n", "\n", "### What & Why\n", "\n", "Before writing any model code, we need to understand the raw data deeply. \n", "BraTS2020 gives us 369 training cases, each with 4 MRI modalities and a segmentation mask.\n", "\n", "**Key questions this stage answers:**\n", "- What shape and dtype are the volumes?\n", "- Are intensity ranges consistent across modalities and patients?\n", "- What is the class distribution in the segmentation masks?\n", "- What label remapping is required before training?" ] }, { "cell_type": "code", "execution_count": 9, "id": "9cb7973b", "metadata": {}, "outputs": [], "source": [ "import nibabel as nib\n", "import numpy as np\n", "from pathlib import Path\n", "\n", "# ── Point this at your BraTS2020 training data root ──────────────────────────\n", "DATA_ROOT = Path(r\"D:\\personal projects\\Brain-Tumor-Segmentation-with-BraTS\\BraTS2020_TrainingData\\MICCAI_BraTS2020_TrainingData\")\n", "CASE_001 = DATA_ROOT / \"BraTS20_Training_001\"\n", "MODALITIES = [\"flair\", \"t1\", \"t1ce\", \"t2\"]" ] }, { "cell_type": "markdown", "id": "4de818c4", "metadata": {}, "source": [ "### 1.1 Modality Exploration\n", "\n", "We load each modality and inspect:\n", "- **Shape** — should be `(240, 240, 155)` for all BraTS2020 volumes\n", "- **Intensity range** — will differ across modalities (MRI values are not standardized)\n", "- **Non-zero fraction** — tells us how much of the volume is actual brain vs background air" ] }, { "cell_type": "code", "execution_count": 11, "id": "5328263a", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "============================================================\n", "MODALITY EXPLORATION — Case 001\n", "============================================================\n", "\n", "── FLAIR ──────────────────────────\n", " Shape: (240, 240, 155)\n", " Dtype: float64\n", " Global min/max: 0.0 / 625.0\n", " Brain mean: 173.0\n", " Brain std: 64.9\n", " Non-zero voxels: 1,342,885 / 8,928,000 (15.0%)\n", "\n", "── T1 ──────────────────────────\n", " Shape: (240, 240, 155)\n", " Dtype: float64\n", " Global min/max: 0.0 / 678.0\n", " Brain mean: 354.3\n", " Brain std: 84.2\n", " Non-zero voxels: 1,342,885 / 8,928,000 (15.0%)\n", "\n", "── T1CE ──────────────────────────\n", " Shape: (240, 240, 155)\n", " Dtype: float64\n", " Global min/max: 0.0 / 1845.0\n", " Brain mean: 417.3\n", " Brain std: 109.2\n", " Non-zero voxels: 1,342,885 / 8,928,000 (15.0%)\n", "\n", "── T2 ──────────────────────────\n", " Shape: (240, 240, 155)\n", " Dtype: float64\n", " Global min/max: 0.0 / 376.0\n", " Brain mean: 114.7\n", " Brain std: 47.7\n", " Non-zero voxels: 1,342,885 / 8,928,000 (15.0%)\n" ] } ], "source": [ "print(\"=\" * 60)\n", "print(\"MODALITY EXPLORATION — Case 001\")\n", "print(\"=\" * 60)\n", "\n", "for mod in MODALITIES:\n", " path = CASE_001 / f\"BraTS20_Training_001_{mod}.nii\"\n", " img = nib.load(str(path))\n", " vol = img.get_fdata()\n", "\n", " brain_mask = vol > 0\n", " brain_voxels = vol[brain_mask]\n", "\n", " print(f\"\\n── {mod.upper()} ──────────────────────────\")\n", " print(f\" Shape: {vol.shape}\")\n", " print(f\" Dtype: {vol.dtype}\")\n", " print(f\" Global min/max: {vol.min():.1f} / {vol.max():.1f}\")\n", " print(f\" Brain mean: {brain_voxels.mean():.1f}\")\n", " print(f\" Brain std: {brain_voxels.std():.1f}\")\n", " print(f\" Non-zero voxels: {brain_mask.sum():,} / {vol.size:,} ({100*brain_mask.mean():.1f}%)\")" ] }, { "cell_type": "markdown", "id": "6f39f11f", "metadata": {}, "source": [ "**What this tells us:**\n", "\n", "| Observation | Implication |\n", "|---|---|\n", "| All modalities: shape `(240, 240, 155)` | Pre-registered — voxel [x,y,z] is the same tissue in all 4 |\n", "| All modalities: same non-zero fraction | Shared brain mask — background zeroed identically |\n", "| Intensity ranges differ wildly (T2 max=376 vs T1ce max=1845) | Cannot normalize globally — must normalize **per modality** |\n", "| Only 15% of voxels are non-zero | 85% is background air — wasteful for model input, crop it |" ] }, { "cell_type": "markdown", "id": "0ba37626", "metadata": {}, "source": [ "### 1.2 Segmentation Mask Exploration\n", "\n", "The segmentation mask is the ground truth we train against. \n", "BraTS2020 uses label set `{0, 1, 2, 4}` — note the jump from 2 to 4. \n", "This is a historical artifact. Our model uses output indices `{0,1,2,3}`, so we must remap `4 → 3`." ] }, { "cell_type": "code", "execution_count": 12, "id": "ab2d226c", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "============================================================\n", "SEGMENTATION MASK — Case 001\n", "============================================================\n", "\n", " Shape: (240, 240, 155)\n", " Unique labels: [0 1 2 4]\n", "\n", " Label 0: 8,716,021 voxels (97.63%) ← Background\n", " Label 1: 15,443 voxels (0.17%) ← Necrotic Core (NCR)\n", " Label 2: 168,794 voxels (1.89%) ← Peritumoral Edema (ED)\n", " Label 4: 27,742 voxels (0.31%) ← Enhancing Tumor (ET)\n", "\n", "⚠ Label 4 will be remapped to 3 before training\n", " Tumor burden: 2.37% of all voxels\n" ] } ], "source": [ "print(\"=\" * 60)\n", "print(\"SEGMENTATION MASK — Case 001\")\n", "print(\"=\" * 60)\n", "\n", "seg_path = CASE_001 / \"BraTS20_Training_001_seg.nii\"\n", "seg = nib.load(str(seg_path)).get_fdata().astype(np.uint8)\n", "\n", "CLASS_NAMES = {0: \"Background\", 1: \"Necrotic Core (NCR)\", 2: \"Peritumoral Edema (ED)\", 4: \"Enhancing Tumor (ET)\"}\n", "\n", "print(f\"\\n Shape: {seg.shape}\")\n", "print(f\" Unique labels: {np.unique(seg)}\")\n", "print()\n", "\n", "for label in np.unique(seg):\n", " count = int((seg == label).sum())\n", " pct = 100 * count / seg.size\n", " name = CLASS_NAMES.get(label, \"Unknown\")\n", " print(f\" Label {label}: {count:>10,} voxels ({pct:.2f}%) ← {name}\")\n", "\n", "print()\n", "print(\"⚠ Label 4 will be remapped to 3 before training\")\n", "print(f\" Tumor burden: {100*(seg>0).mean():.2f}% of all voxels\")" ] }, { "cell_type": "markdown", "id": "982c8657", "metadata": {}, "source": [ "**Why class imbalance matters:**\n", "\n", "Background = **97.63%** of all voxels. If a model predicts background everywhere, \n", "it achieves 97.63% voxel accuracy — and is clinically worthless.\n", "\n", "This is why we use **Dice loss** instead of cross-entropy alone. \n", "Dice is computed per class independently, so a 0.17% class gets the same gradient weight as a 50% class.\n", "\n", "**BraTS Evaluation Regions** (derived from the 4 labels):\n", "\n", "| Region | Labels | Clinical meaning |\n", "|---|---|---|\n", "| Whole Tumor (WT) | {1, 2, 3} | Total tumor extent |\n", "| Tumor Core (TC) | {1, 3} | Surgically targetable core |\n", "| Enhancing Tumor (ET) | {3} | Active, contrast-enhancing tumor |" ] }, { "cell_type": "markdown", "id": "240e9ec0", "metadata": {}, "source": [ "### 1.3 Affine and Voxel Size" ] }, { "cell_type": "code", "execution_count": 13, "id": "4cf35669", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Affine matrix (voxel → world space in mm):\n", "[[ -1. -0. -0. 0.]\n", " [ -0. -1. -0. 239.]\n", " [ 0. 0. 1. 0.]\n", " [ 0. 0. 0. 1.]]\n", "\n", "Voxel size: [1. 1. 1.] mm\n", "→ Isotropic 1mm³ — each voxel represents 1mm × 1mm × 1mm of brain tissue\n" ] } ], "source": [ "img = nib.load(str(CASE_001 / \"BraTS20_Training_001_t1.nii\"))\n", "print(\"Affine matrix (voxel → world space in mm):\")\n", "print(img.affine)\n", "print()\n", "voxel_size = np.sqrt((img.affine[:3, :3] ** 2).sum(axis=0))\n", "print(f\"Voxel size: {voxel_size} mm\")\n", "print(\"→ Isotropic 1mm³ — each voxel represents 1mm × 1mm × 1mm of brain tissue\")" ] }, { "cell_type": "markdown", "id": "043bd59d", "metadata": {}, "source": [ "---\n", "## Stage 2 — Z-Score Normalization\n", "\n", "### What & Why\n", "\n", "MRI intensity values are **scanner-dependent** — they have no universal physical meaning. \n", "A voxel value of 400 in one patient's T1 is not comparable to 400 in another patient's T1, \n", "even on the same scanner.\n", "\n", "**Why not min-max normalization?** \n", "MRI volumes often contain bright artifact voxels (motion, metal implants) that would \n", "compress the entire meaningful intensity range into a tiny interval.\n", "\n", "**The solution: Z-score normalization restricted to brain voxels**\n", "\n", "$$z = \\frac{x - \\mu_{brain}}{\\sigma_{brain}}$$\n", "\n", "Where $\\mu_{brain}$ and $\\sigma_{brain}$ are computed only over non-zero (brain) voxels. \n", "Background voxels are left at exactly 0.\n", "\n", "**Applied independently per modality** — never across modalities, never globally." ] }, { "cell_type": "markdown", "id": "db65548c", "metadata": {}, "source": [ "### 2.1 Implementation\n", "\n", "```\n", "CODE │ EXPLANATION\n", "────────────────────────────────────────│─────────────────────────────────────────\n", "def normalize_modality(vol): │ Takes one 3D modality volume.\n", " │\n", " brain_mask = vol > 0 │ Boolean mask: True = brain tissue.\n", " │ Background air is exactly 0 in BraTS.\n", " │\n", " if brain_mask.sum() == 0: │ Edge case: completely empty volume\n", " return vol │ (e.g. a corrupted scan). Return as-is,\n", " │ do not divide by zero.\n", " │\n", " mu = vol[brain_mask].mean() │ Mean of brain voxels ONLY.\n", " std = vol[brain_mask].std() + 1e-8 │ Std of brain voxels + epsilon.\n", " │ Epsilon (1e-8) prevents div-by-zero\n", " │ if a region has constant intensity.\n", " │\n", " normalized = np.zeros_like(vol) │ Start with all zeros — background\n", " │ stays 0 without any extra masking step.\n", " │\n", " normalized[brain_mask] = ( │ Apply z-score to brain voxels only.\n", " vol[brain_mask] - mu) / std │ Background is untouched (stays 0).\n", " │\n", " return normalized │ Returns float32 array, same shape.\n", "```" ] }, { "cell_type": "code", "execution_count": 14, "id": "99c728a6", "metadata": {}, "outputs": [], "source": [ "def normalize_modality(vol: np.ndarray) -> np.ndarray:\n", " \"\"\"\n", " Z-score normalization restricted to brain (non-zero) voxels.\n", " Background voxels remain exactly 0.\n", " Returns float32 array of same shape as input.\n", " \"\"\"\n", " brain_mask = vol > 0\n", "\n", " if brain_mask.sum() == 0:\n", " return vol\n", "\n", " mu = vol[brain_mask].mean()\n", " std = vol[brain_mask].std() + 1e-8\n", "\n", " normalized = np.zeros_like(vol)\n", " normalized[brain_mask] = (vol[brain_mask] - mu) / std\n", " return normalized.astype(np.float32)" ] }, { "cell_type": "markdown", "id": "7c0de8b9", "metadata": {}, "source": [ "### 2.2 Verification" ] }, { "cell_type": "code", "execution_count": 15, "id": "0b472c6c", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "=== BEFORE ===\n", " mean (brain): 417.33\n", " std (brain): 109.19\n", " background: 0.0000\n", "\n", "=== AFTER ===\n", " mean (brain): 0.0000 ← should be ≈ 0.0\n", " std (brain): 1.0000 ← should be ≈ 1.0\n", " background: 0.0000 ← should be exactly 0.0\n", " dtype: float32 ← should be float32\n", "\n", "=== EDGE CASES ===\n", " Empty volume — all zeros: True\n", " Empty volume — no NaN: True\n", " Background unchanged: True\n", "\n", "=== ALL MODALITIES ===\n", " flair → mean: +0.0000 std: 1.0000\n", " t1 → mean: -0.0000 std: 1.0000\n", " t1ce → mean: +0.0000 std: 1.0000\n", " t2 → mean: +0.0000 std: 1.0000\n" ] } ], "source": [ "vol = nib.load(str(CASE_001 / \"BraTS20_Training_001_t1ce.nii\")).get_fdata().astype(np.float32)\n", "norm = normalize_modality(vol)\n", "brain_mask = vol > 0\n", "\n", "print(\"=== BEFORE ===\")\n", "print(f\" mean (brain): {vol[brain_mask].mean():.2f}\")\n", "print(f\" std (brain): {vol[brain_mask].std():.2f}\")\n", "print(f\" background: {vol[0,0,0]:.4f}\")\n", "\n", "print(\"\\n=== AFTER ===\")\n", "print(f\" mean (brain): {norm[brain_mask].mean():.4f} ← should be ≈ 0.0\")\n", "print(f\" std (brain): {norm[brain_mask].std():.4f} ← should be ≈ 1.0\")\n", "print(f\" background: {norm[0,0,0]:.4f} ← should be exactly 0.0\")\n", "print(f\" dtype: {norm.dtype} ← should be float32\")\n", "\n", "print(\"\\n=== EDGE CASES ===\")\n", "empty = np.zeros((240,240,155), dtype=np.float32)\n", "result = normalize_modality(empty)\n", "print(f\" Empty volume — all zeros: {(result == 0).all()}\")\n", "print(f\" Empty volume — no NaN: {np.isfinite(result).all()}\")\n", "print(f\" Background unchanged: {((vol==0) == (norm==0)).all()}\")\n", "\n", "print(\"\\n=== ALL MODALITIES ===\")\n", "for mod in MODALITIES:\n", " v = nib.load(str(CASE_001 / f\"BraTS20_Training_001_{mod}.nii\")).get_fdata().astype(np.float32)\n", " n = normalize_modality(v)\n", " b = v > 0\n", " print(f\" {mod:6s} → mean: {n[b].mean():+.4f} std: {n[b].std():.4f}\")" ] }, { "cell_type": "markdown", "id": "aa3d4a27", "metadata": {}, "source": [ "---\n", "## Stage 3 — Bounding Box Crop + Resize\n", "\n", "### What & Why\n", "\n", "After normalization the volume is still `(240, 240, 155)` — but 85% is background zeros. \n", "Feeding this to a 3D U-Net wastes GPU memory on empty space.\n", "\n", "**Two-step spatial reduction:**\n", "1. **Crop** — find the smallest box enclosing all non-zero voxels, discard the rest\n", "2. **Resize** — interpolate the cropped volume to a fixed `(128, 128, 128)` shape\n", "\n", "Why `128³`? It is the largest cube that fits in ~10GB VRAM with batch size 1 \n", "using a standard 3D U-Net with 32 base filters. It is the de facto BraTS standard." ] }, { "cell_type": "markdown", "id": "43ed8cf3", "metadata": {}, "source": [ "### 3.1 Crop to Brain Bounding Box\n", "\n", "```\n", "CODE │ EXPLANATION\n", "────────────────────────────────────────│─────────────────────────────────────────\n", "def crop_to_brain(vol): │ Takes a 3D numpy array.\n", " │\n", " coords = np.array( │ np.where(vol > 0) returns a tuple of\n", " np.where(vol > 0)) │ 3 arrays: (x_idxs, y_idxs, z_idxs)\n", " │ for every non-zero voxel.\n", " │ np.array(...) stacks them → shape (3, N)\n", " │\n", " if coords.shape[1] == 0: │ Edge case: empty volume.\n", " return vol │\n", " │\n", " mins = coords.min(axis=1) │ Minimum index along each axis.\n", " │ shape (3,) → [x_min, y_min, z_min]\n", " │\n", " maxs = coords.max(axis=1) + 1 │ Maximum index + 1.\n", " │ +1 because Python slicing is exclusive\n", " │ at the end: vol[0:228] gives indices\n", " │ 0..227, so last brain voxel at 227\n", " │ requires stop index 228.\n", " │\n", " return vol[mins[0]:maxs[0], │ Slice all three axes simultaneously.\n", " mins[1]:maxs[1], │ Returns a VIEW — no data is copied\n", " mins[2]:maxs[2]] │ until you modify it.\n", "```" ] }, { "cell_type": "code", "execution_count": 16, "id": "e678433b", "metadata": {}, "outputs": [], "source": [ "def crop_to_brain(vol: np.ndarray) -> np.ndarray:\n", " \"\"\"\n", " Crop vol to the tight bounding box of non-zero voxels.\n", " If the volume is entirely zero, return it unchanged.\n", " \"\"\"\n", " coords = np.array(np.where(vol > 0))\n", "\n", " if coords.shape[1] == 0:\n", " return vol\n", "\n", " mins = coords.min(axis=1)\n", " maxs = coords.max(axis=1) + 1\n", "\n", " return vol[mins[0]:maxs[0],\n", " mins[1]:maxs[1],\n", " mins[2]:maxs[2]]" ] }, { "cell_type": "markdown", "id": "effdef0f", "metadata": {}, "source": [ "### 3.2 Resize to Target Shape\n", "\n", "```\n", "CODE │ EXPLANATION\n", "────────────────────────────────────────│─────────────────────────────────────────\n", "def resize_volume(vol, target= │ Default target is 128³.\n", " (128,128,128)): │\n", " │\n", " tensor = torch.from_numpy(vol) │ numpy → torch tensor\n", " .float() │ Ensure float32\n", " .unsqueeze(0) │ Add batch dim: (H,W,D) → (1,H,W,D)\n", " .unsqueeze(0) │ Add channel dim: (1,H,W,D) → (1,1,H,W,D)\n", " │ F.interpolate requires (B,C,H,W,D)\n", " │\n", " resized = F.interpolate( │\n", " tensor, │\n", " size=target, │ Target spatial shape (128,128,128)\n", " mode=\"trilinear\", │ 3D equivalent of bilinear for images.\n", " │ Smoothly interpolates between voxels.\n", " │ (nearest-neighbor creates blocky edges)\n", " align_corners=True │ Corner voxels of input map exactly to\n", " ) │ corner voxels of output.\n", " │ Use True for medical data — ensures\n", " │ image and mask stay aligned when resized\n", " │ separately.\n", " │\n", " return resized.squeeze().numpy() │ Remove batch+channel dims, back to numpy\n", " │ (1,1,128,128,128) → (128,128,128)\n", "```" ] }, { "cell_type": "code", "execution_count": 17, "id": "9eecc011", "metadata": {}, "outputs": [], "source": [ "import torch\n", "import torch.nn.functional as F\n", "\n", "def resize_volume(vol: np.ndarray, target=(128, 128, 128)) -> np.ndarray:\n", " \"\"\"\n", " Resize a 3D volume to target shape using trilinear interpolation.\n", " align_corners=True ensures image and mask stay aligned when resized separately.\n", " \"\"\"\n", " tensor = torch.from_numpy(vol).float().unsqueeze(0).unsqueeze(0)\n", "\n", " resized = F.interpolate(\n", " tensor,\n", " size=target,\n", " mode=\"trilinear\",\n", " align_corners=True\n", " )\n", "\n", " return resized.squeeze().numpy()" ] }, { "cell_type": "markdown", "id": "46e24f22", "metadata": {}, "source": [ "### 3.3 Verification" ] }, { "cell_type": "code", "execution_count": 18, "id": "c1c0211d", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "=== CROP ===\n", " Before: (240, 240, 155)\n", " After: (136, 171, 132) ← smaller than (240,240,155)\n", " Brain signal preserved: True\n", "\n", "=== RESIZE ===\n", " Shape: (128, 128, 128) ← should be (128, 128, 128)\n", " dtype: float32 ← should be float32\n", "\n", "=== FULL PIPELINE — ALL 4 MODALITIES ===\n", " (normalize → crop → resize)\n", " flair → (128, 128, 128) mean=+0.932\n", " t1 → (128, 128, 128) mean=+0.747\n", " t1ce → (128, 128, 128) mean=+0.659\n", " t2 → (128, 128, 128) mean=+0.993\n", "\n", " ✅ All modalities: (128, 128, 128) — ready for model input\n" ] } ], "source": [ "vol = nib.load(str(CASE_001 / \"BraTS20_Training_001_t1ce.nii\")).get_fdata().astype(np.float32)\n", "norm = normalize_modality(vol)\n", "\n", "print(\"=== CROP ===\")\n", "cropped = crop_to_brain(norm)\n", "print(f\" Before: {norm.shape}\")\n", "print(f\" After: {cropped.shape} ← smaller than (240,240,155)\")\n", "print(f\" Brain signal preserved: {(cropped > 0).any()}\")\n", "\n", "print(\"\\n=== RESIZE ===\")\n", "resized = resize_volume(cropped, target=(128, 128, 128))\n", "print(f\" Shape: {resized.shape} ← should be (128, 128, 128)\")\n", "print(f\" dtype: {resized.dtype} ← should be float32\")\n", "\n", "print(\"\\n=== FULL PIPELINE — ALL 4 MODALITIES ===\")\n", "print(\" (normalize → crop → resize)\")\n", "for mod in MODALITIES:\n", " v = nib.load(str(CASE_001 / f\"BraTS20_Training_001_{mod}.nii\")).get_fdata().astype(np.float32)\n", " processed = resize_volume(crop_to_brain(normalize_modality(v)))\n", " print(f\" {mod:6s} → {processed.shape} mean={processed[processed>0].mean():+.3f}\")\n", "print(\"\\n ✅ All modalities: (128, 128, 128) — ready for model input\")" ] }, { "cell_type": "markdown", "id": "0787a97b", "metadata": {}, "source": [ "### 3.4 What the Pipeline Does to One Voxel\n", "\n", "```\n", "Raw T1ce voxel at brain center: 417.3 (scanner units, meaningless across patients)\n", "After normalize_modality: 0.0 (mean of brain = 0, std = 1)\n", "After crop_to_brain: 0.0 (same value, just in smaller array)\n", "After resize_volume: ~0.0 (trilinear blend of neighbors, close to 0)\n", "```\n", "\n", "```\n", "Raw T1ce bright tumor voxel: 1845.0\n", "After normalize_modality: 12.9 (13 standard deviations above brain mean)\n", "After crop_to_brain: 12.9\n", "After resize_volume: ~12.0 (slightly smoothed by interpolation)\n", "```\n", "\n", "The tumor voxel remains a strong outlier even after normalization. \n", "That outlier signal is exactly what the model learns to detect." ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.0" } }, "nbformat": 4, "nbformat_minor": 5 }