benedictpepper
Include HF config in README
f4b7328
|
Raw History Blame Contribute Delete
12.4 kB
---
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
<table>
<tr>
<td align="center"><b>Model Architecture β€” Concat Pooling</b></td>
<td align="center"><b>Training Strategy Comparison</b></td>
</tr>
<tr>
<td><img src="figures/01_architecture_concat_pooling.png" width="420"/></td>
<td><img src="figures/02_training_strategy_comparison.png" width="420"/></td>
</tr>
<tr>
<td align="center" colspan="2"><b>Data Pipeline &amp; Augmentation Strategy</b></td>
</tr>
<tr>
<td colspan="2" align="center"><img src="figures/03_data_pipeline.png" width="840"/></td>
</tr>
</table>
### Experimental Results (from Kaggle Execution)
<table>
<tr>
<td align="center"><b>ROC Curve β€” Both Models (N=390)</b></td>
<td align="center"><b>Confusion Matrix β€” Both Models (N=390, TTA)</b></td>
</tr>
<tr>
<td><img src="kaggle_output/roc_comparison.png" width="420"/></td>
<td><img src="kaggle_output/confusion_matrix_comparison.png" width="420"/></td>
</tr>
<tr>
<td align="center"><b>Training Curves β€” Fixed Size (32 epochs)</b></td>
<td align="center"><b>Training Curves β€” Progressive Resizing (41 epochs)</b></td>
</tr>
<tr>
<td><img src="kaggle_output/learning_curves_fixed.png" width="420"/></td>
<td><img src="kaggle_output/learning_curves_progressive.png" width="420"/></td>
</tr>
</table>
### Grad-CAM Interpretability: Fixed Size vs. Progressive Resizing
<table>
<tr>
<td align="center"><b>Grad-CAM Comparison (Both Models)</b></td>
</tr>
<tr>
<td align="center"><img src="figures/09_gradcam_comparison.png" width="840"/></td>
</tr>
</table>
> 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