Instructions to use leminhhung0101/BrainModel with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Keras
How to use leminhhung0101/BrainModel with Keras:
# Available backend options are: "jax", "torch", "tensorflow". import os os.environ["KERAS_BACKEND"] = "jax" import keras model = keras.saving.load_model("hf://leminhhung0101/BrainModel") - Notebooks
- Google Colab
- Kaggle
YAML Metadata Warning:empty or missing yaml metadata in repo card
Check out the documentation for more information.
- Brain Tumor AI Pipeline
- 2. Research Motivation
- 3. Main Contributions
- 4. Overall Architecture
- 5. Segmentation Model
- 6. ASPP Multi-Scale Context
- 7. CBAM Attention
- 8. Decoder and Shape Alignment
- 9. Segmentation Objective
- 10. Segmentation Training Configuration
- 11. Segmentation Post-Processing
- 12. Segmentation Metrics
- 13. Classification Model
- 14. Transfer Learning and Fine-Tuning
- 15. Two-Phase Classification Training
- 16. Data Strategy for Classification
- 17. Explainable Self-Attention
- 18. Evidential Uncertainty
- 19. Confidence Branch
- 20. Multi-Task Classification Objective
- 21. QWK-Centered Model Selection
- 22. Classification Outputs
- 23. Outputs and Artifacts
- 24. Experimental Configuration Summary
- 25. Methodological Advantages
- 26. Important Limitations
- 27. Future Work
- 28. Reproducibility
- 29. Research Summary
Brain Tumor AI Pipeline
Multi-Task Brain Tumor Analysis with DeepLabV3+ Segmentation and Explainable EfficientNetV2 Classification
A research-oriented two-stage deep learning framework for brain MRI analysis, combining pixel-level tumor segmentation with tumor / non-tumor classification, uncertainty estimation, confidence modeling, and explainable attention.
1. Abstract
This project implements two complementary neural-network pipelines for brain tumor analysis from 2D MRI slices.
The first branch performs tumor segmentation using a customized DeepLabV3+ with ResNet101V2, augmented with Atrous Spatial Pyramid Pooling (ASPP), CBAM attention, a lightweight separable-convolution decoder, a hybrid loss, and morphological post-processing.
The second branch performs tumor classification using a pretrained EfficientNetV2-B3-derived backbone with two-phase fine-tuning, tumor-centric sampling, strong Albumentations augmentation, evidential uncertainty estimation, explainable self-attention, and a dedicated confidence head. Model selection is performed using Quadratic Weighted Kappa (QWK) rather than accuracy alone.
The overall design separates three complementary objectives:
Brain MRI Slice
│
├──────────────► Localization
│ DeepLabV3+
│ ResNet101V2
│ CBAM + ASPP
│
└──────────────► Recognition
EfficientNetV2
Self-Attention
Evidential Head
Confidence Head
The result is a research framework that combines localization, recognition, reliability estimation, and interpretability rather than treating brain tumor analysis as a single classification problem.
2. Research Motivation
Brain tumor analysis from MRI is challenging because tumor regions can show strong variation in size, shape, intensity, and visual appearance. In addition, the foreground tumor region is often much smaller than the background, creating substantial class imbalance for segmentation.
A single classification probability is also insufficient for a reliability-aware medical imaging system. For that reason, the project separates the problem into two questions:
Where is the tumor?
and
Does this slice contain a tumor, and how reliable is that prediction?
This leads to the following conceptual structure:
Brain MRI
│
┌─────────┴─────────┐
▼ ▼
Segmentation Classification
│ │
▼ ▼
Tumor Mask Class Probability
│
┌─────────────┼─────────────┐
▼ ▼ ▼
Uncertainty Confidence Attention
3. Main Contributions
3.1 Segmentation Branch
The segmentation model combines:
- DeepLabV3+
- ResNet101V2 ImageNet backbone
- ASPP with dilation rates 6, 12, and 18
- Image-level pooling branch
- CBAM attention on semantic and low-level features
- Separable convolution decoder
- Dynamic upsampling / resize alignment
- Hybrid Focal-Tversky + Generalized Dice + Boundary + Focal loss
- Morphological post-processing
- Region, boundary, and detection-oriented metrics
3.2 Classification Branch
The classification model combines:
- Pretrained EfficientNetV2-B3-derived representation
- Mixed-precision training
- Two-phase freeze / unfreeze fine-tuning
- Tumor-centric batch sampling
- Class-weighted learning
- Strong Albumentations augmentation
- Explainable spatial self-attention
- Evidential probability modeling
- Epistemic uncertainty
- Aleatoric uncertainty
- Confidence estimation
- QWK-based validation and checkpoint selection
4. Overall Architecture
┌────────────────────────────────────────────────────────────────────┐
│ BRAIN MRI SLICE │
└───────────────────────────────┬────────────────────────────────────┘
│
┌──────────────────┴──────────────────┐
│ │
▼ ▼
┌─────────────────────────┐ ┌──────────────────────────────┐
│ SEGMENTATION BRANCH │ │ CLASSIFICATION BRANCH │
│ │ │ │
│ 1ch → 3ch replication │ │ EfficientNetV2 representation│
│ │ │ │ │ │
│ ResNet101V2 │ │ ▼ │
│ │ │ │ Explainable Self-Attention │
│ ┌─────┴─────┐ │ │ │ │
│ ▼ ▼ │ │ Global Features │
│ Low-level High-level │ │ │ │
│ │ │ │ │ ┌──────┴──────┐ │
│ CBAM ASPP │ │ ▼ ▼ │
│ │ │ │ │ Classification Evidential │
│ │ CBAM │ │ │ │ │
│ └──────┬────┘ │ │ └──────┬──────┘ │
│ ▼ │ │ ▼ │
│ Feature Fusion │ │ Confidence Head │
│ │ │ │ │
│ Decoder │ └──────────────────────────────┘
│ │ │
│ ▼ │
│ Tumor Mask │
└─────────────────────────┘
5. Segmentation Model
5.1 Input Strategy
The segmentation pipeline keeps the dataset representation as one grayscale channel:
Input = 256 × 256 × 1
Because ResNet101V2 is loaded with ImageNet weights, the input is replicated to three channels inside the model:
Gray MRI
│
├─────┐
├─────┼──► Concatenate
└─────┘
│
▼
256 × 256 × 3
│
▼
ResNet101V2
This avoids changing the pretrained backbone while preserving a compact single-channel data representation at the input.
5.2 Encoder
The backbone is:
ResNet101V2(
include_top=False,
weights="imagenet"
)
Two feature levels are extracted:
| Feature | Layer | Role |
|---|---|---|
| Low-level | conv2_block3_out |
Spatial detail / boundaries |
| High-level | base_model.output |
Semantic context |
Batch Normalization layers in the backbone are kept non-trainable, while other backbone layers remain trainable.
6. ASPP Multi-Scale Context
The high-level representation enters an ASPP module containing parallel branches:
High-level Feature Map
│
┌────────────────────┼────────────────────┐
│ │ │ │ │
▼ ▼ ▼ ▼ ▼
1×1 d=6 d=12 d=18 Image Pool
│ │ │ │ │
└──────────┴─────────┴─────────┴──────────┘
│
▼
Concatenate
│
▼
1×1 Conv
│
▼
Dropout
The use of multiple dilation rates allows the network to capture tumor context at different effective receptive fields.
7. CBAM Attention
CBAM is applied to both the ASPP output and the low-level feature path.
Input Feature
│
▼
Channel Attention
│
▼
Spatial Attention
│
▼
Refined Feature
This provides two complementary forms of feature selection:
- Channel attention: which feature channels matter
- Spatial attention: where relevant structures are located
The intention is to improve feature selectivity before decoder fusion.
8. Decoder and Shape Alignment
A common engineering issue in encoder-decoder segmentation networks is spatial mismatch between high-level and low-level feature maps.
This implementation explicitly computes the upsampling factor from the actual tensor dimensions and, when necessary, performs a final resize before concatenation.
High-level / ASPP
│
▼
Dynamic Upsampling
│
▼
Shape Check
│
┌────┴────┐
│ │
Match Mismatch
│ │
│ ▼
│ tf.image.resize
│ │
└────┬────┘
▼
Concatenate with low-level features
This is a practical improvement that makes the architecture less brittle when tensor dimensions change.
9. Segmentation Objective
The main segmentation loss is a weighted hybrid:
Lseg = 0.50 LFT + 0.35 LGD + 0.10 LBoundary + 0.05 LFocal
where:
LFT= Focal Tversky lossLGD= Generalized Dice lossLBoundary= Sobel boundary lossLFocal= Focal loss
Focal Tversky
Uses:
alpha = 0.8
beta = 0.2
gamma = 0.75
to control the relative penalty for false negatives and false positives.
Generalized Dice
Improves robustness to foreground/background imbalance.
Boundary Loss
Compares Sobel-derived edge maps of the ground-truth and predicted masks.
Focal Loss
Adds additional emphasis to hard pixels.
The overall design therefore optimizes both region agreement and boundary fidelity.
10. Segmentation Training Configuration
| Parameter | Value |
|---|---|
| Resolution | 256 × 256 |
| Batch size | 16 |
| Epochs | 60 |
| Initial LR | 1e-4 |
| Weight decay | 5e-4 |
| Gradient clipping | clipnorm=1.0 |
| LR schedule | CosineDecayRestarts |
| Dropout | 0.7 / 0.6 / 0.5 |
| Training subset | 30% |
| Validation split | 25% temporary split, then half for validation/test |
The relatively small batch size is chosen to reduce memory pressure caused by the ResNet101V2-based architecture.
11. Segmentation Post-Processing
The raw probability map is post-processed as follows:
Sigmoid Probability Map
│
▼
Threshold = 0.25
│
▼
Morphological Closing
│
▼
Connected Components
│
▼
Remove components < 100 px
│
▼
Light Dilation
│
▼
Final Mask
This stage is designed to remove isolated noise and improve mask continuity.
12. Segmentation Metrics
The evaluation includes:
| Metric | Interpretation |
|---|---|
| Dice | Overlap between prediction and ground truth |
| Generalized Dice | Imbalance-aware overlap |
| Weighted Dice | Foreground-prioritized overlap |
| IoU | Jaccard similarity |
| Boundary IoU | Boundary agreement |
| Sensitivity | Tumor recall |
| Specificity | Background rejection |
| Precision | False-positive control |
| F1 | Precision-recall balance |
The pipeline stores per-slice results in:
test_results_optimized.csv
and generates qualitative examples containing:
Input | Ground Truth | Prediction | Overlay
13. Classification Model
The classifier uses a previously trained EfficientNetV2-based model as a feature extractor and builds a new multi-output prediction head.
The pipeline receives:
299 × 299 × 3
The three channels are currently constructed by repeating the same MRI slice because true adjacent-slice information is not available in the generator.
Central slice
│
├──────── Channel 1
├──────── Channel 2
└──────── Channel 3
Therefore, this is a 2D / pseudo-3-channel representation, not true 3D context.
14. Transfer Learning and Fine-Tuning
The pretrained model is loaded with custom objects including:
AttentionVisualizerMCDropoutEvidentialLossEvidentialLayerExplainableSelfAttentionMaxProbLayer
The original feature representation is reused while a new classification / uncertainty head is attached.
This creates a transfer-learning pipeline:
Pretrained EfficientNetV2
│
▼
Feature Extraction
│
▼
New Task-Specific Head
│
┌──────┼─────────┐
▼ ▼ ▼
Class Evidence Confidence
15. Two-Phase Classification Training
Phase 1 — Head Adaptation
The pretrained backbone is frozen and only the new head is optimized.
Backbone = Frozen
Head = Trainable
LR = 2e-5
Epochs = 10
Phase 2 — Full Fine-Tuning
The network is then unfrozen:
Backbone = Trainable
Head = Trainable
LR = 5e-6
The lower learning rate reduces the risk of destroying useful pretrained representations.
16. Data Strategy for Classification
The classification data pipeline includes several improvements.
Volume-aware sampling
Each volume contributes at least one slice before the remaining samples are selected.
Stratified sampling
Additional data are sampled according to the target class.
Tumor-centric batches
Training batches target:
60% tumor
40% non-tumor
Class weighting
The generator additionally computes class weights from the selected training set.
Augmentation
Albumentations introduces geometric, intensity, blur, noise, and elastic variations.
17. Explainable Self-Attention
The classification model includes a custom spatial self-attention layer.
Given a feature map:
H × W × C
it is flattened to spatial tokens:
(H × W) × C
and transformed into query, key, and value representations.
The attention mechanism is:
Q = Wq X
K = Wk X
V = Wv X
A = softmax(QKᵀ / √d)
Y = AV
The output is reshaped back into image space, and the attention layer can return a normalized spatial attention map.
This provides an explicit mechanism for visualizing where the representation is attending.
18. Evidential Uncertainty
The classifier does not stop at softmax probabilities.
The evidential head computes positive evidence using a softplus activation:
Feature Vector
│
▼
Dense Layer
│
▼
Softplus
│
▼
Evidence
│
▼
alpha = evidence + 1
│
▼
Normalized Probability
Two uncertainty signals are exposed:
Epistemic Uncertainty
A signal related to the model's lack of knowledge.
Aleatoric Uncertainty
A signal related to uncertainty inherent in the observation.
These signals are then used together with maximum class probability to construct the confidence branch.
19. Confidence Branch
The confidence head uses:
max(class probability)
│
├──────────────┐
▼ ▼
epistemic uncertainty aleatoric uncertainty
│ │
└──────┬───────┘
▼
Dense Network
│
▼
Confidence ∈ [0,1]
This is intended to provide a dedicated model confidence signal rather than interpreting softmax probability alone as certainty.
20. Multi-Task Classification Objective
The compiled model optimizes three supervised outputs:
Lcls = 2.00 LCE + 0.05 LEvidential + 0.01 LConfidence
where:
LCEis categorical cross-entropy with label smoothing0.05LEvidentialis the custom evidential lossLConfidenceis mean-squared error
The classification objective remains dominant, while the evidential and confidence branches act as auxiliary learning signals.
21. QWK-Centered Model Selection
The custom ImprovedQWKEvaluation callback evaluates validation predictions after every epoch.
It computes:
Quadratic Weighted Kappa
Accuracy
Weighted F1
Per-class F1
Per-class Recall
The checkpoint criterion is:
Best Validation QWK
Training uses:
EarlyStopping(patience=10)
ReduceLROnPlateau(patience=5)
This makes the optimization process more aligned with the selected validation objective than monitoring accuracy alone.
22. Classification Outputs
The final model exposes multiple outputs:
| Output | Meaning |
|---|---|
classification |
Standard 2-class softmax probabilities |
evidential_prob |
Evidential class probabilities |
epistemic_uncertainty |
Epistemic uncertainty estimate |
aleatoric_uncertainty |
Aleatoric uncertainty estimate |
confidence_score |
Dedicated confidence prediction |
attention_map |
Spatial explanation map |
conv_features |
Intermediate feature representation |
This makes the model suitable for both prediction and downstream analysis.
23. Outputs and Artifacts
Segmentation
brain_tumor_models/
├── best_deeplabv3plus_resnet101v2_model.keras
├── final_optimized_model.keras
├── training_log.csv
├── test_results_optimized.csv
├── training_history_optimized.png
└── visualizations/
├── test_sample_0.png
├── test_sample_1.png
└── ...
Classification
brain_tumor_models/
├── phase1_finetuned_best.keras
├── phase2_finetuned_best.keras
├── final_finetuned_model.keras
├── phase1_finetuned_training.csv
├── phase2_finetuned_training.csv
├── test_confusion_matrix.png
├── test_classification_report.csv
├── confidence_analysis.png
└── training_history.png
24. Experimental Configuration Summary
Segmentation
| Component | Configuration |
|---|---|
| Resolution | 256 × 256 |
| Input channels | 1 |
| Backbone | ResNet101V2 |
| Architecture | DeepLabV3+ |
| Attention | CBAM |
| ASPP dilation | 6 / 12 / 18 |
| Batch size | 16 |
| Epochs | 60 |
| Initial LR | 1e-4 |
| Weight decay | 5e-4 |
| LR scheduler | CosineDecayRestarts |
| Dataset sample | 30% |
| Output | Binary tumor mask |
Classification
| Component | Configuration |
|---|---|
| Resolution | 299 × 299 |
| Input channels | 3 (repeated slice) |
| Backbone | EfficientNetV2-B3-derived pretrained model |
| Classes | 2 |
| Batch size | 10 |
| Dataset sample | 10% |
| Tumor-centric ratio | 60% |
| Precision | Mixed FP16 |
| Phase 1 LR | 2e-5 |
| Phase 2 LR | 5e-6 |
| Total epochs | 30 |
| Model selection | QWK |
25. Methodological Advantages
The combined design has several strengths.
Multi-scale segmentation
ASPP captures spatial context at multiple dilation rates, while the decoder restores fine details through low-level feature fusion.
Attention-guided representation
CBAM helps refine both semantic and spatial feature representations.
Imbalance-aware optimization
The segmentation loss explicitly considers overlap, boundary quality, and hard examples; the classifier uses balanced sampling and class weighting.
Transfer learning
The classifier reuses a pretrained EfficientNetV2 representation rather than learning all features from scratch.
Reliability-aware classification
The evidential branch, uncertainty signals, and confidence head provide information beyond the class label itself.
Explainability
The self-attention component exposes a spatial attention representation suitable for visualization and qualitative analysis.
26. Important Limitations
This repository should be considered a research and experimental framework, not a clinically validated diagnostic system.
Slice-level processing
Both pipelines primarily operate on 2D slices.
Pseudo-3-channel classification input
The classifier currently repeats the same slice three times:
Channel 1 = central slice
Channel 2 = central slice
Channel 3 = central slice
Therefore, it does not yet model true inter-slice anatomical context.
Sampling subset
The training scripts use sampled portions of the dataset (30% for segmentation and 10% for classification). Performance should therefore be re-evaluated when using the complete dataset.
Leakage considerations
For research-grade evaluation, splitting should ideally be performed at the patient / volume level, not only at the slice level, to avoid highly correlated slices from the same volume appearing across train, validation, and test sets.
Clinical validation
No clinical diagnostic claim should be inferred without external validation, calibration analysis, multi-center evaluation, and appropriate clinical study design.
27. Future Work
A natural extension is to move from slice-level to volume-aware analysis:
2D Slice
│
▼
2.5D Adjacent Slices
│
▼
3D Volume Modeling
│
▼
Volume-level Classification
│
▼
Integrated Segmentation + Classification
Potential research directions include:
- True adjacent-slice 2.5D input
- 3D segmentation architectures
- Patient / volume-level splitting
- External-dataset validation
- Probability calibration
- Uncertainty calibration
- Attention faithfulness evaluation
- Joint segmentation-classification learning
- Volume-level aggregation
- Ensemble-based uncertainty estimation
28. Reproducibility
Install the main dependencies:
pip install tensorflow numpy pandas scipy h5py opencv-python scikit-learn matplotlib seaborn albumentations
Expected CSV columns:
slice_path
target
Expected HDF5 content for segmentation:
image
mask
Expected HDF5 content for classification:
image
Configure the dataset and pretrained-model paths in the scripts before execution.
29. Research Summary
The project can be summarized as a four-layer analytical framework:
┌──────────────────────────────────────────────┐
│ Brain MRI Input │
└──────────────────────┬───────────────────────┘
│
┌────────────┴────────────┐
▼ ▼
┌────────────────────┐ ┌──────────────────────┐
│ Tumor Localization │ │ Tumor Classification │
│ DeepLabV3+ │ │ EfficientNetV2 │
│ ResNet101V2 │ │ Self-Attention │
│ ASPP + CBAM │ │ Evidential Learning │
└──────────┬─────────┘ └───────────┬──────────┘
│ │
▼ ▼
Tumor Mask Class + Uncertainty
+
Confidence
+
Attention
The central research idea is therefore:
Localization + Recognition + Uncertainty + Explainability
rather than a single black-box classification output.
Citation
@software{brain_tumor_ai_pipeline_2026,
title = {Brain Tumor AI Pipeline: DeepLabV3+ Segmentation and Explainable EfficientNetV2 Classification},
year = {2026},
note = {Research-oriented brain MRI analysis framework}
}
Brain Tumor AI Pipeline · 2026
Segmentation · Classification · Uncertainty · Explainable AI
- Downloads last month
- 32