Skip to content
Stoyan-ZlatevPublic

About

Chest X-Ray pneumonia classification pipeline using TensorFlow/Keras CNNs (95.1% acc) and SIFT feature extraction with Random Forest.

Topics

Resources

Stars

1 star

Watchers

1 watching

Forks

Latest commit

Β 

History

13 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

ClearScan: Chest X-Ray Pneumonia Detection Pipeline

Python 3.9+ TensorFlow Scikit-Learn OpenCV License: MIT

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:

  1. 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.
  2. Deep Learning & Transfer Learning: Custom Convolutional Neural Network (CNN) with Batch Normalization and Dropout vs. Fine-tuned EfficientNetB0.

πŸ“ Pipeline Architecture

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
Loading

πŸ”¬ Comparative Methodology

1. Classical Feature Engineering (SIFT + BoVW + Random Forest)

  • 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 GridSearchCV hyperparameter tuning and Stratified $K$-Fold Cross-Validation.

2. End-to-End Deep Learning (CNN & EfficientNetB0)

  • 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.

πŸ“Š Comparative Benchmark Summary

Model Architecture Feature Representation Test Accuracy Precision Recall F1-Score
SIFT + Random Forest Bag of Visual Words ($K=20$) 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.


⚑ Quickstart & Local Execution

Prerequisites

  • Python 3.9+
  • Virtual Environment setup (venv)

1. Clone & Setup Environment

# 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.txt

2. Running via Pipeline Orchestrator (run.py)

ClearScan features an automated YAML-configured pipeline runner (pipeline.yml):

python run.py

βš™οΈ Pipeline Execution & Live Console Monitoring

How the Pipeline Orchestrator Operates

The pipeline driver run.py parses the configuration file pipeline.yml to automate stage execution:

  1. Configuration Modes:
    • mode: sequential: Iterates through all declared steps in order and executes those where enabled: true.
    • mode: single: Runs only the specific module designated by the step key (e.g. step: cnn).
  2. 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.
  3. Cross-Platform Execution:
    • Spawns non-blocking subprocesses using the active Python interpreter (sys.executable), ensuring native execution across macOS, Linux, and Windows.

Real-Time Console Output & Progress Streaming

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, and GridSearchCV hyperparameter 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.

Sample Console Output Stream

[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.

Step-by-Step Manual Execution

If you prefer to run individual modules manually without the YAML orchestrator:

Step A: Download & Preprocess Data

# 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_subsets

Step B: Train CNN Model

python -m src.cnn.run_train_cnn --validate True --epochs 10 --batch_size 32 --use_custom_model True

Step C: Train SIFT + Random Forest Classifier

# 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 True

πŸ“ Repository Structure

ClearScan/
β”œβ”€β”€ 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

πŸ“œ License

This project is open source and available under the MIT License.

About

Chest X-Ray pneumonia classification pipeline using TensorFlow/Keras CNNs (95.1% acc) and SIFT feature extraction with Random Forest.

Topics

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages