{"id":51170730,"url":"https://github.com/code-with-zeeshan/skin-lesion-classification","last_synced_at":"2026-06-27T00:04:06.891Z","repository":{"id":346217872,"uuid":"1184740361","full_name":"code-with-zeeshan/skin-lesion-classification","owner":"code-with-zeeshan","description":"🏥 AI-powered skin lesion classifier (Benign vs Malignant) using EfficientNetB3 + Grad-CAM. AUC: 0.935 | Recall: 94.7%","archived":false,"fork":false,"pushed_at":"2026-03-23T12:15:31.000Z","size":29755,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-03-23T12:32:07.271Z","etag":null,"topics":["deep-learning","efficientnet","grad-cam","gradio","image-classification","medical-ai","python","skin-cancer","tensorflow","transfer-learning"],"latest_commit_sha":null,"homepage":"https://huggingface.co/spaces/code-with-zeeshan/skin-lesion-classifier","language":"Jupyter Notebook","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/code-with-zeeshan.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2026-03-17T22:19:00.000Z","updated_at":"2026-03-23T12:15:39.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/code-with-zeeshan/skin-lesion-classification","commit_stats":null,"previous_names":["code-with-zeeshan/skin-lesion-classification"],"tags_count":null,"template":false,"template_full_name":null,"purl":"pkg:github/code-with-zeeshan/skin-lesion-classification","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/code-with-zeeshan%2Fskin-lesion-classification","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/code-with-zeeshan%2Fskin-lesion-classification/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/code-with-zeeshan%2Fskin-lesion-classification/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/code-with-zeeshan%2Fskin-lesion-classification/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/code-with-zeeshan","download_url":"https://codeload.github.com/code-with-zeeshan/skin-lesion-classification/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/code-with-zeeshan%2Fskin-lesion-classification/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":34835793,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-26T02:00:06.560Z","response_time":106,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["deep-learning","efficientnet","grad-cam","gradio","image-classification","medical-ai","python","skin-cancer","tensorflow","transfer-learning"],"created_at":"2026-06-27T00:04:03.048Z","updated_at":"2026-06-27T00:04:06.886Z","avatar_url":"https://github.com/code-with-zeeshan.png","language":"Jupyter Notebook","funding_links":[],"categories":[],"sub_categories":[],"readme":"# 🏥 Skin Lesion Classification: Benign vs Malignant\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"assets/banner.png\" alt=\"Project Banner\" width=\"800\"/\u003e\n\u003c/p\u003e\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"https://img.shields.io/badge/TensorFlow-2.x-orange?logo=tensorflow\" /\u003e\n  \u003cimg src=\"https://img.shields.io/badge/Python-3.10+-blue?logo=python\" /\u003e\n  \u003cimg src=\"https://img.shields.io/badge/AUC-0.935-green\" /\u003e\n  \u003cimg src=\"https://img.shields.io/badge/Recall-94.7%25-brightgreen\" /\u003e\n  \u003cimg src=\"https://img.shields.io/badge/Deployed-Gradio-yellow?logo=gradio\" /\u003e\n\u003c/p\u003e\n\n## 📋 Overview\n\nA deep learning-based screening tool that classifies skin lesion images\nas **benign** or **malignant** using EfficientNetB3 with transfer learning,\nthreshold optimization, test-time augmentation (TTA), and Grad-CAM explainability.\n\n| Metric | Score |\n|---|---|\n| **AUC-ROC** | 0.935 |\n| **Cancer Detection (Recall)** | 94.7% |\n| **Accuracy** | 83.8% |\n| **F1 Score** | 0.842 |\n| **MCC** | 0.698 |\n| **Missed Cancers** | Only 16/300 (5.3%) |\n\n\u003e ⚕️ **Disclaimer:** For educational/screening purposes only.\n\u003e Not a substitute for professional medical diagnosis.\n\n---\n\n## 🏗️ Architecture\n\n```\nInput Image (300×300×3)\n    │\n    ▼\nEfficientNetB3 (Pre-trained ImageNet)\n    │  Phase 1: Frozen base\n    │  Phase 2: Fine-tuned last 50 layers\n    ▼\nGlobalAveragePooling2D\n    │\nBatchNormalization\n    │\nDense(512, ReLU) → Dropout(0.5)\nDense(256, ReLU) → Dropout(0.4)\nDense(128, ReLU) → Dropout(0.3)\n    │\nDense(1, Sigmoid) → Benign (0) / Malignant (1)\n    │\n    ▼\nThreshold Optimization (0.38) + Test-Time Augmentation (10 rounds)\n```\n\n---\n\n## 📁 Project Structure\n\n```\nskin-lesion-classification/\n├── README.md                                  ← Project documentation\n├── requirements.txt                           ← Dependencies\n├── final_config.json                          ← Model config\n├── .gitignore                                 ← Excludes .keras files\n├── notebooks/\n│   └── skin_lesion_classification_v2.ipynb    ← Clean Colab notebook\n├── app/\n│   └── gradio_app.py                          ← Standalone Gradio app\n├── assets/\n│   ├── banner.png                             ← Project banner\n│   ├── training_history.png                   ← Training curves\n│   ├── confusion_matrix.png                   ← CM plot\n│   ├── roc_curve.png                          ← ROC curve\n│   ├── score_distribution.png                 ← Score distribution\n│   ├── complete_evaluation.png                ← All metrics visual\n│   ├── gradcam_samples.png                    ← Grad-CAM examples\n│   ├── error_analysis.png                     ← Wrong predictions\n│   ├── class_distribution.png                 ← Dataset EDA\n│   ├── final_evaluation.png                   ← final metrics\n│   └── sample_images.png                      ← Sample images\n├── docs/\n│   ├── model_evaluation_report.md             ← Full eval report\n│   └── deployment_guide.md                    ← Deployment instructions\n└── samples/\n    ├── benign/\n    │   ├── image1.jpg\n    │   └── image2.jpg\n    └── malignant/\n        ├── image1.jpg\n        └── image2.jpg\n```\n\n---\n\n## 📥 Model Downloads\n\nModels are hosted on **HuggingFace** (too large for GitHub):\n\n| File | Size | Link |\n|---|---|---|\n| `model_b3.keras` | ~96.4 MB | [HuggingFace Space](https://huggingface.co/spaces/code-with-zeeshan/skin-lesion-classifier/blob/main/model_b3.keras) |\n| `model_b0.keras` | ~33.4 MB | [HuggingFace Space](https://huggingface.co/spaces/code-with-zeeshan/skin-lesion-classifier/blob/main/model_b0.keras) |\n| `final_config.json` | 1 KB | Included in this repo |\n\n### Automatic Download\nThe Gradio app **automatically downloads** models from HuggingFace on first run:\n```bash\npython app/gradio_app.py\n```\n\n### Manual Download\n```python\nfrom huggingface_hub import hf_hub_download\n\nmodel_path = hf_hub_download(\n    repo_id=\"code-with-zeeshan/skin-lesion-classifier\",\n    filename=\"model_b3.keras\",\n    repo_type=\"space\"\n)\n```\n\n---\n\n## ⚙️ Two Prediction Modes\n\n| Mode | AUC | Recall | Accuracy | Speed |\n|---|---|---|---|---|\n| ⚡ **Fast Mode** | 0.911 | 90.0% | 81.7% | ~2 sec |\n| 🎯 **Best Mode (TTA)** | 0.935 | 94.7% | 83.8% | ~20 sec |\n\n---\n\n## 🔧 Key Technical Decisions\n\n### 1. Why EfficientNetB3?\n- **Compound scaling** optimizes depth, width, and resolution simultaneously\n- 81.6% ImageNet accuracy with only 12.3M parameters\n- Superior accuracy-per-parameter vs ResNet50 (25.6M params, 76.1% accuracy)\n- Built-in preprocessing eliminates manual rescaling errors\n\n### 2. Why NO `rescale=1./255`?\nEfficientNet has **internal preprocessing layers** expecting [0, 255] input.\nAdding `rescale=1./255` causes double preprocessing → model receives garbage\nvalues → learns nothing (predicts all one class). This was our first major\nbug fix.\n\n### 3. Why Two-Phase Training?\n- **Phase 1 (Frozen):** Trains only the custom head while preserving ImageNet features\n- **Phase 2 (Fine-tune):** Unfreezes last 50 layers with 10× smaller learning rate\n  to adapt base features to skin lesion domain without catastrophic forgetting\n\n### 4. Why Threshold Optimization?\nDefault 0.5 threshold gave 82% recall. In medical screening, missing cancers\n(false negatives) is more dangerous than false alarms. Optimized threshold\n(0.38) targets ≥90% recall, accepting slightly more false alarms for safety.\n\n### 5. Why Test-Time Augmentation?\nTTA averages predictions over 10 augmented versions of each image.\nFree +2.4% AUC improvement with zero retraining. Single biggest\nno-cost accuracy boost.\n\n---\n\n## 📊 Results\n\n### Evolution of the Model\n\n| Stage | AUC | Recall | Missed Cancers | Key Change |\n|---|---|---|---|---|\n| Broken V1 | 0.349 | 0.0% | 300/300 | Bug: double preprocessing |\n| Fixed V1 (B0) | 0.908 | 85.7% | 43/300 | Removed rescale, optimized threshold |\n| V2 (B3) | 0.911 | 90.0% | 30/300 | Upgraded to EfficientNetB3 |\n| **V2 (B3+TTA)** | **0.935** | **94.7%** | **16/300** | Added test-time augmentation |\n\n### Final Metrics (B3 + TTA on Unseen Test Data)\n\n| Metric | Score | Grade |\n|---|---|---|\n| AUC-ROC | 0.935 | 🟢 Good |\n| Accuracy | 83.8% | 🟡 Okay |\n| Balanced Accuracy | 84.7% | 🟡 Okay |\n| Sensitivity (Recall) | 94.7% | 🏆 Excellent |\n| Specificity | 74.7% | 🟡 Okay |\n| Precision (Malignant) | 75.7% | 🟡 Okay |\n| F1 Score (Malignant) | 0.842 | 🟡 Okay |\n| MCC | 0.698 | 🟢 Good |\n| NPV | 94.4% | 🏆 Excellent |\n| **Overall Verdict** | | **🟢 Good — Reliable for Screening** |\n\n### Confusion Matrix\n\n```\n                    Predicted Benign    Predicted Malignant\nActual Benign            269                 91\nActual Malignant          16                284\n```\n\n---\n\n## 🔥 Features\n\n- 📷 **Image Upload:** Upload any skin lesion image\n- 👤 **Patient Info:** Name, age, gender for personalized report\n- 🔬 **Prediction:** Benign vs Malignant with confidence score\n- 🔥 **Grad-CAM:** Visual explanation of model focus areas\n- 🛡️ **Precautions:** Automated medical precaution report\n- ⚡ **Two Modes:** Fast (single prediction) or Best (TTA)\n\n---\n\n## 🔥 Grad-CAM Visualization\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"assets/gradcam_samples.png\" alt=\"Grad-CAM\" width=\"700\"/\u003e\n\u003c/p\u003e\n\nGrad-CAM shows the model focuses on lesion borders, color variations,\nand texture irregularities — consistent with dermatological diagnostic criteria.\n\n---\n\n## 🚀 Quick Start\n\n### Prerequisites\n```bash\npip install -r requirements.txt\n```\n\n### Run Gradio App (Downloads model automatically)\n```bash\npython app/gradio_app.py\n```\n\n### Run Inference (Code)\n```python\nfrom tensorflow.keras.models import load_model\nimport numpy as np, json\nfrom tensorflow.keras.preprocessing import image\n\nmodel = load_model('model_b3.keras')\nconfig = json.load(open('final_config.json'))\n\nimg = image.load_img('path/to/lesion.jpg', target_size=(300, 300))\nimg_array = np.expand_dims(image.img_to_array(img), axis=0)  # No /255!\npred = model.predict(img_array)[0][0]\n\nlabel = \"MALIGNANT\" if pred \u003e= config['threshold'] else \"BENIGN\"\nprint(f\"{label} (score: {pred:.4f})\")\n```\n\n---\n\n## 🔄 How to Reproduce\n\n1. **Clone the repository:**\n   ```bash\n   git clone https://github.com/code-with-zeeshan/skin-lesion-classification.git\n   cd skin-lesion-classification\n   ```\n\n2. **Install dependencies:**\n   ```bash\n   pip install -r requirements.txt\n   ```\n\n3. **Option A — Run Gradio App (uses pre-trained model):**\n   ```bash\n   python app/gradio_app.py\n   ```\n\n4. **Option B — Retrain from scratch:**\n   - Open `notebooks/skin_lesion_classification_v2.ipynb` in Google Colab\n   - Upload the Skin Lesions Classification dataset to Google Drive\n   - Run all cells in order\n   - Training takes ~30-45 minutes on Colab GPU\n\n5. **Option C — Open in Colab directly:**\n\n   [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/code-with-zeeshan/skin-lesion-classification/blob/main/notebooks/skin_lesion_classification_v2.ipynb)\n\n---\n\n## 📈 Lessons Learned\n\n### Bugs Encountered \u0026 Fixed\n| Bug | Impact | Fix |\n|---|---|---|\n| `rescale=1./255` with EfficientNet | Model predicted all benign (AUC: 0.35) | Removed rescaling — EfficientNet has built-in preprocessing |\n| `layer.output_shape` in Grad-CAM | AttributeError in TF 2.16+ | Hardcoded `top_activation` layer name |\n| Default threshold (0.5) | 82% recall → missed many cancers | Threshold optimization → 94.7% recall |\n| Gradio 6.0 breaking changes | `theme` and `show_copy_button` errors | Removed deprecated parameters |\n\n### What Worked Best\n1. **Transfer learning** \u003e training from scratch (small dataset)\n2. **Threshold optimization** gave the biggest practical improvement\n3. **TTA** provided free +2.4% AUC boost\n4. **Class weights** helped with mild imbalance\n\n### What Didn't Help Much\n1. **EfficientNetB3 vs B0:** Only marginal AUC improvement\n2. **Ensemble (B0+B3):** Didn't beat B3+TTA alone\n3. Both hit the same ~0.93 AUC ceiling → **dataset size is the bottleneck**\n\n---\n\n## 🛠️ Tools \u0026 Acknowledgments\n\n- **AI Assistance:** [Claude AI](https://claude.ai) (Anthropic) was used as\n  a productivity tool for:\n  - Code generation and debugging\n  - Model architecture suggestions\n  - Performance analysis and optimization recommendations\n  - Documentation structure guidance\n\n  All experimental decisions, hyperparameter choices, result interpretation,\n  and project direction were made by the author. Claude served as an\n  accelerator — similar to using Stack Overflow or documentation — not as\n  the decision maker.\n\n- **Framework:** TensorFlow 2.x / Keras\n- **Pre-trained Model:** EfficientNetB3 (ImageNet weights)\n- **Deployment:** Gradio\n- **Environment:** Google Colab (GPU runtime)\n\n---\n\n## Docs\n- [Deployment](docs/deployment_guide.md)\n- [Evaluation](docs/model_evaluation_report.md)\n\n---\n\n## Demo Video\n- [Demo](assets/Skin_Lesion_Classification_demo.gif)\n\n## 🔮 Future Improvements\n\n- [ ] Add more training data (ISIC Archive: 25,000+ images)\n- [ ] Try advanced augmentation (albumentations: CLAHE, elastic transform)\n- [ ] Implement 5-fold cross-validation for more robust evaluation\n- [ ] Deploy permanently on HuggingFace Spaces [DEPLOYED](https://huggingface.co/spaces/code-with-zeeshan/skin-lesion-classifier)\n- [ ] Add multi-class classification (melanoma, BCC, SCC, etc.)\n\n---\n\n## 📄 License\n\nThis project is for educational purposes only. Not intended for clinical use.\n\n---\n\n## 📬 Contact\n\nMOHAMMAD ZEESHAN — [LinkedIn](https://www.linkedin.com/in/mohammad-zeeshan-37637a1a5)\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcode-with-zeeshan%2Fskin-lesion-classification","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcode-with-zeeshan%2Fskin-lesion-classification","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcode-with-zeeshan%2Fskin-lesion-classification/lists"}