--- title: Pneumonia Classifier emoji: ๐Ÿซ colorFrom: blue colorTo: indigo sdk: docker pinned: false --- # EfficientNetB4 Pneumonia Classification: Fixed Size vs. Progressive Resizing [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE) [![Python 3.9+](https://img.shields.io/badge/Python-3.9%2B-blue.svg)](https://www.python.org/) [![TensorFlow 2.19](https://img.shields.io/badge/TensorFlow-2.19-orange.svg)](https://www.tensorflow.org/) [![Platform: Kaggle](https://img.shields.io/badge/Platform-Kaggle-20BEFF.svg)](https://www.kaggle.com/) > **Paper:** *Perbandingan Strategi Pelatihan EfficientNetB4 dengan dan tanpa Progressive Resizing untuk Klasifikasi Pneumonia Bakterial dan Viral pada Citra X-Ray Dada* > Presented at SEMNAS (National Seminar on Technology and Applied Science), 2025. --- ## Overview This repository accompanies a comparative study evaluating two training strategies for EfficientNetB4 on the task of distinguishing **bacterial** from **viral pneumonia** in chest X-ray images: 1. **Fixed Size** โ€” trains exclusively at the target resolution (384 ร— 384 px) using a two-phase head-training + global fine-tuning schedule. 2. **Progressive Resizing** โ€” a curriculum learning approach that trains through progressively higher resolutions (224 โ†’ 256 โ†’ 384 px) with continuous weight transfer between stages. Both models share an identical architecture, loss function, optimizer, and augmentation pipeline. The only variable is the training resolution schedule. **Key finding:** Fixed-size training at 384 ร— 384 px achieves **86.92% accuracy and 0.9198 AUC**, outperforming Progressive Resizing (78.46%, AUC 0.8011) by 8.46 percentage points, despite using fewer total epochs (32 vs 41). The result suggests that sustained high-resolution exposure during fine-tuning is more critical than curriculum-based resolution scaling for this task. --- ## Results ### Main Experiments โ€” Test Set (N=390, 242 bacterial : 148 viral, with 2-step TTA) | Model | Strategy | Epochs | Accuracy | ROC AUC | Macro F1 | Viral Recall | |-------|----------|--------|----------|---------|----------|--------------| | EfficientNetB4 | **Fixed Size** (384ร—384) | **32** | **86.92%** | **0.9198** | **85.02%** | **67.57%** | | EfficientNetB4 | Progressive Resizing (224โ†’256โ†’384) | 41 | 78.46% | 0.8011 | 74.72% | 52.70% | ### Per-Class Metrics | Class | Precision (Fixed) | Recall (Fixed) | F1 (Fixed) | Precision (Prog) | Recall (Prog) | F1 (Prog) | |-------|-------------------|----------------|------------|------------------|---------------|-----------| | Bacterial | 83.28% | 98.76% | 90.36% | 76.51% | 94.21% | 84.44% | | Viral | 97.09% | 67.57% | 79.68% | 84.78% | 52.70% | 65.00% | > **Note:** The test set uses the original Kaggle `test/PNEUMONIA` distribution (unbalanced: > 242 bacterial, 148 viral). Both models show higher false-negative rates for the viral class, > reflecting the intrinsic difficulty of this clinically important sub-task. ### Legacy Architecture Comparison (v1 pipeline, `archive/legacy_experiments/`) | Model | Accuracy | |-------|----------| | VGG16 v2 | 55.47% | | EfficientNetB4 v1 | 52.34% | | EfficientNetB0 v2 | 40.62% | | ResNet50 v1 | 37.50% | --- ## Architecture ``` EfficientNetB4 (ImageNet pretrained, include_top=False) โ†’ top_activation feature maps [None, H, W, 1792] โ”œโ”€โ”€ GlobalAveragePooling2D โ†’ [None, 1792] โ””โ”€โ”€ GlobalMaxPooling2D โ†’ [None, 1792] โ†’ Concatenate โ†’ [None, 3584] โ† Concat Pooling โ†’ Dense(512, activation='swish') โ†’ BatchNormalization โ†’ Dropout(0.5) โ†’ Dense(2, activation='softmax', dtype='float32') Total parameters: 18,594,913 Head parameters: 921,090 Fine-tuned (block6a+): 9,556,294 ``` | Component | Detail | |-----------|--------| | Loss | `CategoricalFocalCrossentropy` (ฮฑ=0.25, ฮณ=2.0, label_smoothing=0.1) | | Optimizer | AdamW + `LossScaleOptimizer` (fp16) | | LR โ€” head | 1ร—10โปยณ | | LR โ€” Fixed Size FT | 1ร—10โปโด โ†’ 6.25ร—10โปโถ (ReduceLROnPlateau ร—0.5) | | LR โ€” Progressive FT | CosineDecayRestarts (initial 1ร—10โปโต, t_mul=2.0, m_mul=0.9) | | Augmentation | CLAHE ยท ShiftScaleRotate ยท RandomBrightnessContrast ยท HorizontalFlip ยท MixUp | | TTA | 2-step deterministic (original + H-flip) | | Platform | Kaggle Notebooks โ€” Tesla P100-PCIE-16GB | | Framework | TensorFlow 2.19.0, Keras, mixed precision fp16 | --- ## Dataset All experiments use the **Kermany et al. Chest X-Ray** dataset (bacterial vs. viral pneumonia subset). - **Source:** [Kaggle โ€” Chest X-Ray Images (Pneumonia)](https://www.kaggle.com/datasets/paultimothymooney/chest-xray-pneumonia) - **Classes used:** Bacterial Pneumonia (label 0), Viral Pneumonia (label 1). Normal class excluded. - **Labeling:** Derived from filename prefix (`bacteria_*` โ†’ 0, `virus_*` โ†’ 1) **Split protocol (v2 pipeline):** | Subset | Bacterial | Viral | Total | |--------|-----------|-------|-------| | Training (80% of pool) | ~2,030 | ~1,076 | 3,106 | | Validation (20% of pool) | ~508 | ~269 | 777 | | Test (Kaggle original, isolated) | 242 | 148 | **390** | | Pool (train + val combined) | 2,538 | 1,345 | 3,883 | > **Class imbalance handling:** Computed via `sklearn.compute_class_weight('balanced')`. > Bacterial weight = 0.765 ยท Viral weight = 1.444. No physical oversampling was performed. --- ## Visualizations ### Architecture & Pipeline
Model Architecture โ€” Concat Pooling Training Strategy Comparison
Data Pipeline & Augmentation Strategy
### Experimental Results (from Kaggle Execution)
ROC Curve โ€” Both Models (N=390) Confusion Matrix โ€” Both Models (N=390, TTA)
Training Curves โ€” Fixed Size (32 epochs) Training Curves โ€” Progressive Resizing (41 epochs)
### Grad-CAM Interpretability: Fixed Size vs. Progressive Resizing
Grad-CAM Comparison (Both Models)
> Grad-CAM activations computed on the `top_activation` layer (12ร—12ร—1,792 feature maps). > **Fixed Size (left column)** shows precise, focused activation on the pathological lung parenchyma. > **Progressive Resizing (right column)** shows slightly more diffuse activation patterns. > Both models misclassify the viral samples (bottom two rows), reacting to the bilateral interstitial infiltrates but failing to find sufficient discriminative features for a correct viral prediction. --- ## Repository Structure ``` . โ”œโ”€โ”€ kaggle_pipeline/ # 8-cell Kaggle notebook, broken into scripts โ”‚ โ”œโ”€โ”€ 01_setup_and_imports.py โ”‚ โ”œโ”€โ”€ 02_data_pipeline.py # tf.data + Albumentations + MixUp โ”‚ โ”œโ”€โ”€ 03_model_architecture.py # Concat Pooling + Focal Loss โ”‚ โ”œโ”€โ”€ 04_experiment_1_fixed_size.py โ”‚ โ”œโ”€โ”€ 05_experiment_1_evaluation.py โ”‚ โ”œโ”€โ”€ 06_experiment_2_progressive.py โ”‚ โ”œโ”€โ”€ 07_experiment_2_evaluation.py โ”‚ โ”œโ”€โ”€ 08_final_comparison_and_gradcam.py โ”‚ โ””โ”€โ”€ README.md โ”‚ โ”œโ”€โ”€ kaggle_output/ # Figures and execution log from Kaggle run โ”‚ โ”œโ”€โ”€ *.png # Training curves, ROC, confusion matrices โ”‚ โ”œโ”€โ”€ gradcam_images/ # Grad-CAM sample visualizations โ”‚ โ””โ”€โ”€ pneumonia-fix-vs-progressive-resizing-v2.md # Full execution log โ”‚ โ”œโ”€โ”€ figures/ # Generated diagrams (architecture, pipeline, strategy) โ”‚ โ”œโ”€โ”€ 01_architecture_concat_pooling.png โ”‚ โ”œโ”€โ”€ 02_training_strategy_comparison.png โ”‚ โ””โ”€โ”€ 03_data_pipeline.png โ”œโ”€โ”€ paper/ # Conference paper (manuskrip_deep_learning.md) โ”œโ”€โ”€ demo/ # Flask demo โ€” Fixed Size vs Progressive comparison โ”‚ โ”œโ”€โ”€ app.py โ”‚ โ”œโ”€โ”€ model.py # .keras loader + Concat Pooling Grad-CAM โ”‚ โ”œโ”€โ”€ templates/index.html โ”‚ โ””โ”€โ”€ static/ โ”‚ โ”œโ”€โ”€ style.css โ”‚ โ””โ”€โ”€ script.js โ”‚ โ”œโ”€โ”€ models/ # Model weights โ€” NOT tracked in git โ”‚ โ”œโ”€โ”€ .gitkeep โ”‚ โ”œโ”€โ”€ README.md # Download instructions โ”‚ โ”œโ”€โ”€ fixed_size_model.keras โ† download from GitHub Releases โ”‚ โ””โ”€โ”€ progressive_model.keras โ† download from GitHub Releases โ”‚ โ”œโ”€โ”€ test_dataset/ # Small sample subset for local Grad-CAM testing โ”œโ”€โ”€ scripts/ # Utility scripts โ”œโ”€โ”€ archive/ โ”‚ โ””โ”€โ”€ legacy_experiments/ # v1 pipeline results (old architecture, H5 weights) โ”‚ โ”œโ”€โ”€ requirements.txt โ”œโ”€โ”€ CITATION.cff โ””โ”€โ”€ LICENSE ``` --- ## Local Demo A Flask-based web demo is included in `demo/`. It supports: - **Single model inference** โ€” select Fixed Size or Progressive Resizing - **Compare mode** โ€” run both models on the same image side-by-side with Grad-CAM ```bash # 1. Download the pre-trained weights (see models/README.md) # Place both .keras files in models/ # 2. Install dependencies pip install -r requirements.txt # 3. Run the demo server cd demo python app.py # โ†’ open http://localhost:5000 ``` Upload any chest X-ray (JPEG/PNG). The interface returns: - Predicted class with confidence scores - Per-class probability bars - Grad-CAM activation heatmap highlighting diagnostically relevant lung regions --- ## Model Weights Trained weights are tracked via **GitHub Releases** (not in the repository โ€” each ~332 MB). | Model | File | Download | |-------|------|----------| | Fixed Size (384ร—384) | `fixed_size_model.keras` | [GitHub Releases โ†’](https://github.com/bennypepper/pneumonia-efficientnetb4/releases) | | Progressive Resizing | `progressive_model.keras` | [GitHub Releases โ†’](https://github.com/bennypepper/pneumonia-efficientnetb4/releases) | Place both files in the `models/` directory at the repository root. --- ## Reproducing the Experiments The full pipeline is available as 8 modular Python scripts in `kaggle_pipeline/`. See [`kaggle_pipeline/README.md`](kaggle_pipeline/README.md) for execution instructions. The original Kaggle notebook is available on Kaggle at: > *(link to be added upon public Kaggle release)* --- ## Update History | Version | Date | Summary | |---------|------|---------| | **v2.0** | May 2025 | Complete pipeline overhaul: native `tf.data`, Concat Pooling, AdamW, CLAHE+MixUp augmentation, `.keras` format, strict data isolation, dynamic class weights. | | v1.0 | Apr 2025 | Initial release: legacy H5 models, GAP-only pooling, manual oversampling. See `archive/legacy_experiments/`. | --- ## Citation ```bibtex @inproceedings{pepper2025efficientnetb4pneumonia, title = {Perbandingan Strategi Pelatihan EfficientNetB4 dengan dan tanpa Progressive Resizing untuk Klasifikasi Pneumonia Bakterial dan Viral pada Citra X-Ray Dada}, author = {Pepper, Benedict}, booktitle = {Prosiding Seminar Nasional Teknologi dan Sains Terapan}, year = {2025} } ``` --- ## License Released under the [MIT License](LICENSE). The Kermany chest X-ray dataset is made available under [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) โ€” please cite the original paper when using it: > Kermany, D. S., et al. (2018). *Identifying Medical Diagnoses and Treatable Diseases > by Image-Based Deep Learning.* Cell, 172(5), 1122โ€“1131. > https://doi.org/10.1016/j.cell.2018.02.010