Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions .devcontainer/devcontainer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
{
"name": "Python 3",
// Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile
"image": "mcr.microsoft.com/devcontainers/python:1-3.11-bookworm",
"customizations": {
"codespaces": {
"openFiles": [
"README.md",
"CBAM_ResNet50_Cervical_Classification/app.py"
]
},
"vscode": {
"settings": {},
"extensions": [
"ms-python.python",
"ms-python.vscode-pylance"
]
}
},
"updateContentCommand": "[ -f packages.txt ] && sudo apt update && sudo apt upgrade -y && sudo xargs apt install -y <packages.txt; [ -f requirements.txt ] && pip3 install --user -r requirements.txt; pip3 install --user streamlit; echo '✅ Packages installed and Requirements met'",
"postAttachCommand": {
"server": "streamlit run CBAM_ResNet50_Cervical_Classification/app.py --server.enableCORS false --server.enableXsrfProtection false"
},
"portsAttributes": {
"8501": {
"label": "Application",
"onAutoForward": "openPreview"
}
},
"forwardPorts": [
8501
]
}
1 change: 1 addition & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
CBAM_ResNet50_Cervical_Classification/cbam_resnet50_cervical/*.pth filter=lfs diff=lfs merge=lfs -text
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,9 @@ dmypy.json
*.pb
*.tflite

# Exception: Allow specific model file for deployment
!CBAM_ResNet50_Cervical_Classification/cbam_resnet50_cervical/best_model.pth

# IDE and Editor files
.vscode/
.idea/
Expand Down
1 change: 1 addition & 0 deletions .python-version
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
3.11
31 changes: 31 additions & 0 deletions CBAM_ResNet50_Cervical_Classification/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
env/
venv/
*.egg-info/

# Jupyter Notebook
.ipynb_checkpoints
*.ipynb

# IDE
.vscode/
.idea/

# OS
.DS_Store
Thumbs.db

# Model outputs (keep best_model.pth)
cbam_resnet50_cervical/*.csv
cbam+resnet_outputs/*
gradcam_outputs/*
gradcam_specific_class_outputs/*

# Temporary files
*.log
*.tmp
1 change: 1 addition & 0 deletions CBAM_ResNet50_Cervical_Classification/.python-version
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
3.11
14 changes: 14 additions & 0 deletions CBAM_ResNet50_Cervical_Classification/.streamlit/config.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
[theme]
primaryColor = "#1f77b4"
backgroundColor = "#FFFFFF"
secondaryBackgroundColor = "#F0F2F6"
textColor = "#262730"
font = "sans serif"

[server]
maxUploadSize = 200
enableCORS = false
enableXsrfProtection = true

[browser]
gatherUsageStats = false
166 changes: 78 additions & 88 deletions CBAM_ResNet50_Cervical_Classification/README.md
Original file line number Diff line number Diff line change
@@ -1,116 +1,106 @@
# CBAM-ResNet50 Cervical Classification
# CBAM-ResNet50 Cervical Cancer Cell Classifier

This folder contains the code and notebooks for training, evaluating and explaining a CBAM-ResNet50 model for cervical cell image classification. The language used here is intentionally simple so that both technical and non-technical readers can follow the workflow.
🔬 **Complete Pipeline**: Raw Image → Preprocessing → Classification → Explainability

## Folder Contents
## Features

- `CBAM_ResNet50_Cervical_Classification.ipynb` – main training and evaluation notebook
- `CBAM_ResNet50_Explainability_GradCAM.ipynb` – explainability and visualisation notebook
- `app.py` – script for running the trained model in an application/dashboard setting
- `cbam_resnet50_cervical/` – saved model weights and metric outputs
- `gradcam_outputs/`, `gradcam_specific_class_outputs/` – saved Grad-CAM heatmaps
- `sample_image/` – example image used for demos
- `requirements.txt` – Python dependencies for this module
- `README_DASHBOARD.md` – separate documentation for the dashboard application
- **Advanced Model Architecture**: CBAM-ResNet50 with Channel & Spatial Attention
- **Preprocessing Pipeline**: Resize → NLM Denoising → CLAHE Enhancement
- **Explainable AI**: GradCAM++ visualization
- **Interactive Dashboard**: Built with Streamlit
- **High Performance**: 94.32% accuracy on test set

---
## Cell Types Classified

## 1. CBAM_ResNet50_Cervical_Classification.ipynb
1. Dyskeratotic
2. Koilocytotic
3. Metaplastic
4. Parabasal
5. Superficial-Intermediate

This is the main notebook where the CBAM-ResNet50 model is built, trained and evaluated on cervical cell images.
## Quick Start

At a high level, the notebook walks through:
### Local Installation

1. **Project overview and motivation**
Explains why cervical cell classification is important and how attention mechanisms (CBAM) can help the model focus on the nucleus and other relevant regions.

2. **Dataset setup**
- Describes the folder structure of the dataset (one folder per cell type).
- Shows how image paths and labels are loaded.
- Applies standard image preprocessing and augmentation (resize, normalization, flips, etc.).

3. **CBAM-ResNet50 model definition**
- Starts from a ResNet50 model pretrained on ImageNet.
- Adds Convolutional Block Attention Modules (CBAM) that learn **what** features and **where** in the image to focus on.
- Modifies the final layer to predict the five cervical cell classes.

4. **Training pipeline**
- Defines loss function (for example cross-entropy) and optimizer.
- Sets training hyperparameters such as learning rate, batch size and number of epochs.
- Trains the model over multiple epochs, printing progress for training and validation.

5. **Evaluation and metrics**
- Computes overall accuracy and per-class accuracy.
- Saves detailed per-class metrics to `per_class_metrics.csv`.
- Plots and saves a confusion matrix (`confusion_matrix.png`) and training curves (`training_history.png`).

6. **Saving results**
- Saves the best-performing model weights to `cbam_resnet50_cervical/best_model.pth`.
- Exports predictions to `test_predictions.csv`.
- Stores training history in `training_history.csv` for later analysis.

If you want to reproduce the training, open this notebook, adjust the dataset paths to your environment, install the dependencies listed in `requirements.txt`, and run the cells from top to bottom.

---

## 2. CBAM_ResNet50_Explainability_GradCAM.ipynb

This notebook focuses on making the CBAM-ResNet50 model more interpretable using Grad-CAM based visual explanations.
```bash
# Clone the repository
git clone <your-repo-url>
cd CBAM_ResNet50_Cervical_Classification

The main steps are:
# Install dependencies
pip install -r requirements.txt

1. **Environment setup**
- Installs and imports the required libraries, including `pytorch-grad-cam`, `torch`, `torchvision`, `opencv-python` and `matplotlib`.
- Detects whether the notebook is running in Google Colab or locally.
# Run the app
streamlit run app.py
```

2. **Model reconstruction and weight loading**
- Re-creates the same CBAM-ResNet50 architecture used during training.
- Loads the trained weights from `cbam_resnet50_cervical/best_model.pth`.
- Moves the model to CPU or GPU depending on availability.
### Streamlit Cloud Deployment

3. **Image preprocessing**
- Defines transforms to resize, normalize and convert images to tensors in the same way as during training.
- Loads either a `sample_image` from this folder or user-specified test images.
1. Push your code to GitHub
2. Go to [share.streamlit.io](https://share.streamlit.io)
3. Click "New app"
4. Select your repository
5. Set main file path: `CBAM_ResNet50_Cervical_Classification/app.py`
6. Click "Deploy"

4. **Grad-CAM and Grad-CAM++ generation**
- Sets up Grad-CAM / Grad-CAM++ on the chosen model layers.
- Generates class-specific heatmaps that highlight which parts of the image influenced the model’s decision.
- Overlays these heatmaps on the original images for intuitive visualisation.
**Important**: Ensure these files are in your repository:
- `cbam_resnet50_cervical/best_model.pth` (trained model)
- `sample_image/original_images/` (sample images)
- `requirements.txt`
- `packages.txt`
- `.streamlit/config.toml`

5. **Saving and organising outputs**
- Saves attention and Grad-CAM maps into `gradcam_outputs/`.
- Optionally organises examples per class under `gradcam_specific_class_outputs/`.
- Helps you visually inspect how the model attends to different cervical cell types.
## Usage

You can use this notebook to understand and validate the behaviour of the trained model, especially whether it is focusing on the nucleus and other medically relevant regions.
### Upload Image
1. Use the sidebar to upload a cervical cell microscopy image
2. Supported formats: BMP, PNG, JPG, JPEG

---
### Use Sample Images
1. Select "Use Sample Images" in the sidebar
2. Choose from pre-loaded sample images
3. View instant results

## 3. app.py
### View Results
- **Step 1**: Image preprocessing visualization
- **Step 2**: Classification results with confidence scores
- **Step 3**: GradCAM++ explainability heatmaps

`app.py` is a Python script intended to expose the trained CBAM-ResNet50 model as an interactive application (for example, a web dashboard). While details are documented in `README_DASHBOARD.md`, at a high level it typically:
### Download Results
- Preprocessed image
- GradCAM++ visualization
- Complete results (JSON)

- Loads the trained model weights from `cbam_resnet50_cervical/best_model.pth`.
- Preprocesses uploaded cervical cell images to match the training pipeline.
- Runs inference and returns the predicted cell class and confidence scores.
- Optionally displays attention maps or Grad-CAM overlays to improve interpretability for end users.
## Model Performance

This script is useful if you want to present the model to clinicians or other stakeholders in a user-friendly way without requiring them to run the notebooks.
| Metric | Score |
|--------|-------|
| Accuracy | 94.32% |
| Precision | 94.40% |
| Recall | 94.32% |
| F1-Score | 94.34% |

---
## Technical Details

## 4. How to Get Started
- **Parameters**: 24,214,989
- **Training Dataset**: 4,049 images (3,239 train / 405 val / 405 test)
- **Preprocessing**: NLM (h=3), CLAHE (clipLimit=1.2)
- **Input Size**: 224×224
- **Framework**: PyTorch

1. **Install dependencies** using the provided `requirements.txt` (ideally inside a virtual environment):
## Dependencies

```bash
pip install -r requirements.txt
```
- Python >= 3.8
- PyTorch >= 2.0.0
- Streamlit >= 1.28.0
- OpenCV (headless for deployment)
- scikit-image
- plotly

2. **Run the training notebook** `CBAM_ResNet50_Cervical_Classification.ipynb` to train or fine-tune the model on your dataset, or load the already provided `best_model.pth` if you only want to run inference.
## Notes

3. **Use the explainability notebook** `CBAM_ResNet50_Explainability_GradCAM.ipynb` to generate visual explanations for model predictions.
⚠️ **Disclaimer**: This tool is for research purposes only. Always consult medical professionals for diagnosis.

4. **Launch the application** using `app.py` (see `README_DASHBOARD.md` for specific run instructions) to provide an interactive interface for predictions.
## License

This structure allows you to go from raw cervical cell images to a trained attention-based classifier, interpret its decisions, and deploy it in an application-oriented setting from within this single folder.
This project is for educational and research purposes.
Loading