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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
# Brain Tumor AI Pipeline
## Multi-Task Brain Tumor Analysis with DeepLabV3+ Segmentation and Explainable EfficientNetV2 Classification

<p align="center">

![Python](https://img.shields.io/badge/Python-3.x-3776AB?style=flat-square&logo=python&logoColor=white)
![TensorFlow](https://img.shields.io/badge/TensorFlow-2.x-FF6F00?style=flat-square&logo=tensorflow&logoColor=white)
![Keras](https://img.shields.io/badge/Keras-Deep%20Learning-D00000?style=flat-square)
![OpenCV](https://img.shields.io/badge/OpenCV-Image%20Processing-5C3EE8?style=flat-square&logo=opencv&logoColor=white)
![Medical Imaging](https://img.shields.io/badge/Domain-Brain%20Tumor%20MRI-0F766E?style=flat-square)

</p>

> 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:

```text
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:

```text
                    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

```text
┌────────────────────────────────────────────────────────────────────┐
│                         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**:

```text
Input = 256 × 256 × 1
```

Because ResNet101V2 is loaded with ImageNet weights, the input is replicated to three channels **inside the model**:

```text
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:

```python
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:

```text
                    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.

```text
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.

```text
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:

```text
Lseg = 0.50 LFT + 0.35 LGD + 0.10 LBoundary + 0.05 LFocal
```

where:

- `LFT` = Focal Tversky loss
- `LGD` = Generalized Dice loss
- `LBoundary` = Sobel boundary loss
- `LFocal` = Focal loss

### Focal Tversky

Uses:

```text
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:

```text
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:

```text
test_results_optimized.csv
```

and generates qualitative examples containing:

```text
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:

```text
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.

```text
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:

- `AttentionVisualizer`
- `MCDropout`
- `EvidentialLoss`
- `EvidentialLayer`
- `ExplainableSelfAttention`
- `MaxProbLayer`

The original feature representation is reused while a new classification / uncertainty head is attached.

This creates a transfer-learning pipeline:

```text
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.

```text
Backbone = Frozen
Head     = Trainable
LR       = 2e-5
Epochs   = 10
```

## Phase 2 — Full Fine-Tuning

The network is then unfrozen:

```text
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:

```text
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:

```text
H × W × C
```

it is flattened to spatial tokens:

```text
(H × W) × C
```

and transformed into query, key, and value representations.

The attention mechanism is:

```text
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:

```text
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:

```text
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:

```text
Lcls = 2.00 LCE + 0.05 LEvidential + 0.01 LConfidence
```

where:

- `LCE` is categorical cross-entropy with label smoothing `0.05`
- `LEvidential` is the custom evidential loss
- `LConfidence` is 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:

```text
Quadratic Weighted Kappa
Accuracy
Weighted F1
Per-class F1
Per-class Recall
```

The checkpoint criterion is:

```text
Best Validation QWK
```

Training uses:

```text
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

```text
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

```text
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:

```text
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:

```text
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:

```bash
pip install tensorflow numpy pandas scipy h5py opencv-python scikit-learn matplotlib seaborn albumentations
```

Expected CSV columns:

```text
slice_path
target
```

Expected HDF5 content for segmentation:

```text
image
mask
```

Expected HDF5 content for classification:

```text
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:

```text
┌──────────────────────────────────────────────┐
│                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

```bibtex
@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}
}
```

---

<p align="center">

**Brain Tumor AI Pipeline · 2026**  
*Segmentation · Classification · Uncertainty · Explainable AI*

</p>