ClearScan is a medical machine learning framework designed to detect Pneumonia vs. Normal cases from chest X-ray images using the Kaggle Chest X-Ray Pneumonia dataset.
The project evaluates and compares two distinct machine learning paradigms:
-
Classical Computer Vision & Ensemble Learning: SIFT (Scale-Invariant Feature Transform) feature extraction
$\rightarrow$ K-Means visual vocabulary (Bag of Visual Words)$\rightarrow$ Random Forest classification. - Deep Learning & Transfer Learning: Custom Convolutional Neural Network (CNN) with Batch Normalization and Dropout vs. Fine-tuned EfficientNetB0.
flowchart TD
A[Raw Chest X-Rays] --> B[Preprocessing & Normalization]
B --> C[Dataset Balancing & Augmentation]
C --> D[Stratified Train / Test / Verify Splits]
D --> E1[Classical CV Pipeline]
E1 --> F1[SIFT Feature Extraction]
F1 --> G1[K-Means Visual Vocabulary Creation]
G1 --> H1[Histogram Vector Encoding]
H1 --> I1[Random Forest / SVM Grid Search]
D --> E2[Deep Learning Pipeline]
E2 --> F2[Custom 3-Layer CNN]
E2 --> F3[EfficientNetB0 Transfer Learning]
I1 --> J[Evaluation & Benchmark Metrics]
F2 --> J
F3 --> J
- SIFT Feature Extraction: Identifies scale- and rotation-invariant keypoints across X-ray images in parallel using multi-threaded OpenCV.
-
Visual Vocabulary (Bag of Visual Words): Clusters SIFT descriptors into
$K$ visual words using K-Means clustering. - Histogram Encoding: Transforms each image into a normalized histogram counting visual word frequencies.
-
Classification & Tuning: Trains a Random Forest classifier optimized via 5-fold
GridSearchCVhyperparameter tuning and Stratified$K$ -Fold Cross-Validation.
-
Custom CNN: Built with TensorFlow/Keras featuring 3 convolutional blocks (
Conv2D$\rightarrow$ BatchNormalization$\rightarrow$ MaxPooling2D$\rightarrow$ Dropout) to extract hierarchical features directly from raw image pixels. - Transfer Learning: Utilizes an EfficientNetB0 backbone pre-trained on ImageNet, freezing base feature extractors and fine-tuning dense classification heads.
| Model Architecture | Feature Representation | Test Accuracy | Precision | Recall | F1-Score |
|---|---|---|---|---|---|
| SIFT + Random Forest | Bag of Visual Words ( |
87.0% | 87.0% | 87.0% | 87.0% |
| Custom CNN (3-Block) | Learned End-to-End Convolutions | 95.1% | 95.0% | 95.0% | 95.0% |
| EfficientNetB0 (Frozen) | Pre-trained ImageNet Embeddings | 50.0% | 25.0% | 50.0% | 33.0% |
Key Takeaway: The Custom CNN achieves the highest classification performance (95.1% test accuracy), learning spatial lung opacity patterns directly from raw X-ray pixels. The classical SIFT + Random Forest pipeline achieves a strong baseline (87.0% accuracy) using visual word histograms without deep features. Frozen EfficientNetB0 requires unfreezing top layers for domain-specific fine-tuning on single-channel chest X-rays.
- Python 3.9+
- Virtual Environment setup (
venv)
# Clone the repository
git clone https://github.com/your-username/ClearScan.git
cd ClearScan
# Create and activate virtual environment
python3 -m venv .venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate
# Install dependencies
pip install -r requirements.txtClearScan features an automated YAML-configured pipeline runner (pipeline.yml):
python run.pyThe pipeline driver run.py parses the configuration file pipeline.yml to automate stage execution:
- Configuration Modes:
mode: sequential: Iterates through all declared steps in order and executes those whereenabled: true.mode: single: Runs only the specific module designated by thestepkey (e.g.step: cnn).
- Argument Construction:
- Translates YAML key-value pairs (e.g.
epochs: 10,batch_size: 32,target_size: (128,128)) into CLI arguments (--epochs 10 --batch_size 32) passed directly to target module entrypoints.
- Translates YAML key-value pairs (e.g.
- Cross-Platform Execution:
- Spawns non-blocking subprocesses using the active Python interpreter (
sys.executable), ensuring native execution across macOS, Linux, and Windows.
- Spawns non-blocking subprocesses using the active Python interpreter (
When running python run.py, ClearScan streams structured, human-readable logging directly to standard stdout:
- Stage Headers: Displays active step indicators (
[Step Name] Running...or[Step Name] Step is disabled. Skipping....). - Command Transparency: Prints the exact CLI command invoked for full auditability.
- Preprocessing Output: Logs normalization status, original vs. balanced dataset pie chart export locations, and image count distributions.
- SIFT & Clustering Progress: Logs parallel multi-threading CPU allocation, SIFT descriptor count extraction, and K-Means visual word cluster convergence.
- Model Training Progress: Streams Keras epoch progress bars (
loss,accuracy,val_loss,val_accuracy) for CNN models, andGridSearchCVhyperparameter iteration logs for Random Forest training. - Evaluation Summaries: Prints final classification metrics (Precision, Recall, F1-Score) and 2x2 confusion matrices directly to the console upon stage completion.
[Preprocess] Running...
Executing command: python -m src.preprocessing.run_preprocessing --target_size (128,128) --visualize True
Loading data...
Normalizing data...
Saving normalized data...
Saved pie chart: /Users/user/Projects/ClearScan/results/balanced/original_distribution.png
Balancing dataset...
Saved pie chart: /Users/user/Projects/ClearScan/results/balanced/balanced_distribution.png
Balanced dataset saved.
[Preprocess] Finished successfully.
[Train CNN] Running...
Executing command: python -m src.cnn.run_train_cnn --validate True --epochs 5 --batch_size 32 --use_custom_model True
Loading balanced dataset...
Preparing data...
Training model...
Epoch 1/5 - loss: 0.3842 - accuracy: 0.8351 - val_loss: 0.2910 - val_accuracy: 0.8850
...
Epoch 5/5 - loss: 0.1104 - accuracy: 0.9635 - val_loss: 0.1164 - val_accuracy: 0.9511
Saving model...
Evaluating model...
Validation Loss: 0.1164, Validation Accuracy: 0.9511
Classification Report:
precision recall f1-score support
0 0.93 0.98 0.95 470
1 0.98 0.92 0.95 470
accuracy 0.95 940
macro avg 0.95 0.95 0.95 940
weighted avg 0.95 0.95 0.95 940
Confusion Matrix:
[[460 10]
[ 36 434]]
Plotting results...
Saved training and validation plots.
[Train CNN] Finished successfully.
[Train Random Forest] Running...
Executing command: python -m src.ensemble.run_train_random_forest --kmeans_k 20 --perform_k_fold False
Loading histogram features and labels...
Starting grid search...
Best Parameters: {'max_depth': 20, 'min_samples_leaf': 2, 'min_samples_split': 5, 'n_estimators': 50}
Evaluating best model...
Classification Report:
precision recall f1-score support
0 0.88 0.85 0.87 470
1 0.86 0.89 0.87 470
accuracy 0.87 940
macro avg 0.87 0.87 0.87 940
weighted avg 0.87 0.87 0.87 940
Accuracy: 0.87
Saving model...
Model saved.
[Train Random Forest] Finished successfully.
If you prefer to run individual modules manually without the YAML orchestrator:
# Download dataset via kagglehub
python -m src.preprocessing.run_download_dataset
# Normalize, balance, and split dataset
python -m src.preprocessing.run_preprocessing
python -m src.preprocessing.run_create_subsetspython -m src.cnn.run_train_cnn --validate True --epochs 10 --batch_size 32 --use_custom_model True# Extract SIFT features & build visual vocabulary (K=20)
python -m src.ensemble.run_feature_extraction --k 20
# Train & evaluate Random Forest classifier
python -m src.ensemble.run_train_random_forest --kmeans_k 20 --perform_k_fold TrueClearScan/
βββ pipeline.yml # Pipeline step configuration
βββ run.py # Automated cross-platform pipeline runner
βββ custom_procedure.py # Hyperparameter exploration script
βββ requirements.txt # Dependency manifest
βββ README.md # Project documentation
βββ src/
βββ common/
β βββ path_utils.py # Cross-platform relative path resolver
βββ preprocessing/
β βββ preprocess.py # Normalization, data augmentation & balancing
β βββ create_subsets.py # Stratified train/val/test splitter
β βββ run_download_dataset.py # Kaggle dataset downloader
β βββ run_preprocessing.py # Data preprocessing script
β βββ run_create_subsets.py # Subset generation script
βββ ensemble/
β βββ feature_extraction.py # Parallel SIFT & Bag of Visual Words (K-Means)
β βββ train_random_forest.py # Random Forest & Stratified K-Fold CV
β βββ run_feature_extraction.py # Feature extraction entry point
β βββ run_train_random_forest.py # Random forest GridSearch entry point
βββ cnn/
βββ train_cnn.py # Custom CNN & EfficientNetB0 architectures
βββ run_train_cnn.py # CNN training & evaluation entry point
This project is open source and available under the MIT License.