File size: 6,751 Bytes
8cf978d |
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 |
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Sybil - Lung Cancer Risk Prediction\\n",
"\\n",
"This notebook demonstrates how to use the Sybil model from Hugging Face for lung cancer risk prediction."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 1. Install Requirements"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"!pip install huggingface-hub torch torchvision pydicom sybil requests"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 2. Load Model from Hugging Face"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from huggingface_hub import snapshot_download\\n",
"import sys\\n",
"\\n",
"# Download model\\n",
"print(\"Downloading Sybil model from Hugging Face...\")\\n",
"model_path = snapshot_download(repo_id=\"Lab-Rasool/sybil\")\\n",
"sys.path.append(model_path)\\n",
"\\n",
"# Import model\\n",
"from modeling_sybil_wrapper import SybilHFWrapper\\n",
"from configuration_sybil import SybilConfig\\n",
"\\n",
"# Initialize\\n",
"config = SybilConfig()\\n",
"model = SybilHFWrapper(config)\\n",
"print(\"✅ Model loaded successfully!\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 3. Download Demo Data"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import requests\\n",
"import zipfile\\n",
"from io import BytesIO\\n",
"import os\\n",
"\\n",
"def get_demo_data():\\n",
" cache_dir = os.path.expanduser(\"~/.sybil_demo\")\\n",
" demo_dir = os.path.join(cache_dir, \"sybil_demo_data\")\\n",
" \\n",
" if not os.path.exists(demo_dir):\\n",
" print(\"Downloading demo DICOM files...\")\\n",
" url = \"https://www.dropbox.com/scl/fi/covbvo6f547kak4em3cjd/sybil_example.zip?rlkey=7a13nhlc9uwga9x7pmtk1cf1c&dl=1\"\\n",
" response = requests.get(url)\\n",
" \\n",
" os.makedirs(cache_dir, exist_ok=True)\\n",
" with zipfile.ZipFile(BytesIO(response.content)) as zf:\\n",
" zf.extractall(cache_dir)\\n",
" \\n",
" # Find DICOM files\\n",
" dicom_files = []\\n",
" for root, dirs, files in os.walk(cache_dir):\\n",
" for file in files:\\n",
" if file.endswith('.dcm'):\\n",
" dicom_files.append(os.path.join(root, file))\\n",
" \\n",
" print(f\"Found {len(dicom_files)} DICOM files\")\\n",
" return sorted(dicom_files)\\n",
"\\n",
"# Get demo data\\n",
"dicom_files = get_demo_data()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 4. Run Prediction"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Run prediction\\n",
"print(\"Running lung cancer risk prediction...\")\\n",
"output = model(dicom_paths=dicom_files)\\n",
"risk_scores = output.risk_scores.numpy()\\n",
"\\n",
"# Display results\\n",
"print(\"\\n\" + \"=\"*40)\\n",
"print(\"Lung Cancer Risk Predictions\")\\n",
"print(\"=\"*40)\\n",
"\\n",
"for i, score in enumerate(risk_scores):\\n",
" risk_pct = score * 100\\n",
" bar_length = int(risk_pct * 2) # Scale for visualization\\n",
" bar = '█' * bar_length + '░' * (30 - bar_length)\\n",
" print(f\"Year {i+1}: {bar} {risk_pct:.1f}%\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 5. Visualize Risk Progression"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\\n",
"import numpy as np\\n",
"\\n",
"# Create visualization\\n",
"years = np.arange(1, 7)\\n",
"risk_percentages = risk_scores * 100\\n",
"\\n",
"plt.figure(figsize=(10, 6))\\n",
"plt.bar(years, risk_percentages, color=['green', 'green', 'yellow', 'yellow', 'orange', 'orange'])\\n",
"plt.xlabel('Years from Scan', fontsize=12)\\n",
"plt.ylabel('Lung Cancer Risk (%)', fontsize=12)\\n",
"plt.title('Predicted Lung Cancer Risk Over Time', fontsize=14, fontweight='bold')\\n",
"plt.grid(axis='y', alpha=0.3)\\n",
"\\n",
"# Add value labels on bars\\n",
"for i, (year, risk) in enumerate(zip(years, risk_percentages)):\\n",
" plt.text(year, risk + 0.5, f'{risk:.1f}%', ha='center', fontweight='bold')\\n",
"\\n",
"plt.tight_layout()\\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 6. Using Your Own Data\\n",
"\\n",
"To use your own CT scan data, replace the demo data with your DICOM file paths:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Example with your own data (uncomment and modify)\\n",
"# my_dicom_files = [\\n",
"# \"/path/to/your/scan/slice001.dcm\",\\n",
"# \"/path/to/your/scan/slice002.dcm\",\\n",
"# # ... add all slices\\n",
"# ]\\n",
"# \\n",
"# output = model(dicom_paths=my_dicom_files)\\n",
"# my_risk_scores = output.risk_scores.numpy()\\n",
"# \\n",
"# for i, score in enumerate(my_risk_scores):\\n",
"# print(f\"Year {i+1}: {score*100:.1f}% risk\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Important Notes\\n",
"\\n",
"⚠️ **Medical Disclaimer**: This model is for research and educational purposes. Always consult qualified healthcare professionals for medical decisions.\\n",
"\\n",
"📚 **Citation**: If you use this model in research, please cite:\\n",
"```\\n",
"Mikhael, P.G., Wohlwend, J., Yala, A. et al. (2023).\\n",
"Sybil: A validated deep learning model to predict future lung cancer risk\\n",
"from a single low-dose chest computed tomography.\\n",
"Journal of Clinical Oncology, 41(12), 2191-2200.\\n",
"```"
]
}
],
"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.8.0"
}
},
"nbformat": 4,
"nbformat_minor": 4
} |