XPathology β€” Brain Tumor MRI Specialist (EfficientNetB0)

Part of the X-Pathology AI-Assisted Medical Screening Platform
Developed by Muhammad Hassan Β· AgenticEra Systems


Overview

XPathology Brain Tumor MRI Specialist is a fine-tuned EfficientNetB0 CNN trained to classify brain MRI scans into 4 diagnostic categories: glioma, meningioma, no tumor, and pituitary tumor. It is the second specialist model in the X-Pathology platform, which combines CNN classification with Grad-CAM explainability and Gemini-powered dual clinical/patient reporting.

This model was trained and evaluated entirely on the masoudnickparvar/brain-tumor-mri-dataset, using its pre-defined Training/ and Testing/ splits β€” the standard academic partition for this benchmark dataset.

You can see the whole Training Notebook of this model: https://github.com/Muhammad-Hassan12/xpathology-brain-specialist

Disclaimer: This model is intended for research and educational use only. It is not FDA-approved or CE-marked diagnostic software. All outputs must be verified by a licensed radiologist or neurosurgeon before any clinical decision-making.


Model Details

Property Value
Model name XPathology_BrainSpecialist_B0_v2
Architecture EfficientNetB0 (ImageNet pretrained)
Framework TensorFlow / Keras
Input size 224 Γ— 224 Γ— 3 (RGB, pixel values 0–255)
Output 4-class softmax
Training split masoudnickparvar Training/ (5,600 images, 80/20 internal split)
Holdout split masoudnickparvar Testing/ (1,600 images, pre-defined by dataset authors)
Temperature (T) 0.7867 (post-hoc calibration applied)
Mixed precision Yes (float16 compute, float32 weights)
Training hardware Kaggle T4 (single GPU)

Tumor Classes

Index Class Description
0 glioma Malignant tumor arising from glial cells β€” most aggressive class
1 meningioma Typically benign tumor of the meninges
2 notumor No tumor detected β€” healthy brain tissue
3 pituitary Benign adenoma of the pituitary gland

Performance

Internal Validation (20% split of Training/)

Metric Value
Accuracy 94.20%
AUC 0.9942
Top-2 Accuracy 98.93%
Val Loss 0.5124

Holdout Validation (Testing/ β€” 1,600 images, never seen during training)

Metric Value
Accuracy 90.06%
AUC 0.9786
Macro F1 0.8982
Domain shift gap 4.14%

Per-Class Performance (Holdout)

Class Precision Recall F1 Support
glioma 0.9228 0.7775 0.8440 400
meningioma 0.8942 0.8450 0.8689 400
notumor 0.8980 0.9900 0.9417 400
pituitary 0.8919 0.9900 0.9384 400

Note on glioma recall (77.75%): Glioma is the most morphologically heterogeneous class. The glioma↔meningioma confusion (39 cases) is consistent with published benchmarks on this dataset β€” both tumor types can present with overlapping MRI signal characteristics at 2D slice level. This was confirmed across four systematic training runs (varying architecture, unfreeze percentage, and loss function), all showing glioma recall in the 77–80% range, confirming a dataset-level ceiling rather than a training failure.


Training Configuration

Architecture

Input (224Γ—224Γ—3)
  └── EfficientNetB0 backbone (ImageNet weights)
        └── GlobalAveragePooling2D
              └── BatchNormalization
                    └── Dropout(0.5)
                          └── Dense(4, softmax, dtype=float32)

Two-Phase Training

Phase 1 β€” Warm-up (10 epochs)

  • Backbone fully frozen
  • Adam optimizer, LR = 1e-3
  • CategoricalCrossentropy, label smoothing = 0.1
  • EarlyStopping (patience=5)

Phase 2 β€” Fine-tuning (30 epochs, early stopping)

  • Top 20% of backbone layers unfrozen
  • All BatchNorm layers remain frozen throughout
  • Adam optimizer, LR = 1e-5, gradient clipping (clipnorm=1.0)
  • EarlyStopping (patience=5), ReduceLROnPlateau (factor=0.3, patience=3)
  • Best checkpoint saved on val_loss

MRI-Specific Augmentation (CPU-side via tf.data)

RandomFlip (horizontal only)      β€” brains are left-right symmetric
RandomRotation (Β±15Β°)             β€” small rotation, MRI has fixed orientation
RandomBrightness (Β±0.15)          β€” scanner intensity variation
RandomContrast (0.85–1.15)        β€” scanner contrast variation
RandomCrop (95–100%)              β€” simulates scan field-of-view variation
NO vertical flip                  β€” anatomically invalid for brain MRI
NO hue/saturation augmentation    β€” MRI is grayscale-to-RGB, colour is meaningless

Confidence Calibration

Post-training temperature scaling was applied on the holdout set to produce calibrated probabilities:

Optimal temperature T = 0.7867
NLL before calibration: 0.3479
NLL after  calibration: 0.3335

T < 1 indicates the raw softmax outputs were more diffuse than the ground truth distribution β€” consistent with label smoothing during training. Apply at inference: probs = softmax(logits / T).


Usage

Installation

pip install tensorflow>=2.12 numpy opencv-python

Load and Infer

import numpy as np
import tensorflow as tf
import json
import cv2

model   = tf.keras.models.load_model('xpathology_brain_specialist_b0.keras')
T       = np.load('brain_temperature_value.npy')[0]
classes = json.load(open('brain_class_names.json'))

logit_model = tf.keras.Model(
    inputs  = model.input,
    outputs = model.get_layer('uncertainty_dropout').output
)
final_dense   = model.get_layer('brain_specialist_output')
weights, bias = final_dense.get_weights()

def predict(image_array):
    """
    Args:
        image_array: np.ndarray shape (224, 224, 3), float32, range [0, 255]
    Returns:
        predicted_class (str), confidence (float), all_probs (dict)
    """
    img      = tf.expand_dims(image_array, axis=0)
    features = logit_model(img, training=False).numpy()
    logits   = features @ weights + bias
    scaled   = logits / T
    exp_l    = np.exp(scaled - scaled.max())
    probs    = (exp_l / exp_l.sum()).flatten()
    idx      = int(np.argmax(probs))
    return classes[idx], float(probs[idx]), dict(zip(classes, probs.tolist()))


# Example
img = cv2.imread('brain_mri.jpg')
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img = cv2.resize(img, (224, 224)).astype(np.float32)

label, conf, probs = predict(img)
print(f"Prediction : {label}")
print(f"Confidence : {conf:.4f}")
print(f"All probs  : {probs}")

Input Requirements

Property Requirement
Modality T1 or T2-weighted brain MRI
Orientation Axial plane preferred
Resolution Any (resized to 224Γ—224)
Color space RGB (convert grayscale to 3-channel first)
Pixel range 0–255 β€” do NOT normalize to [0,1]
File formats JPEG, PNG

Important: EfficientNetB0 performs its own internal normalization. Do not apply rescale=1./255 before passing the image to the model.


Repository Structure

xpathology-brain-specialist/
β”œβ”€β”€ xpathology_brain_specialist_b0.keras   # Trained model weights
β”œβ”€β”€ brain_temperature_value.npy            # Calibration temperature T = 0.7867
β”œβ”€β”€ brain_class_names.json                 # Ordered class labels
β”œβ”€β”€ brain_training_summary.json            # Full training metadata
β”œβ”€β”€ brain_training_log.csv                 # Epoch-by-epoch metrics (40 epochs)
└── README.md

Limitations

  • 2D single-slice only: This model classifies individual 2D MRI images. Clinical diagnosis uses full 3D volumetric context across multiple slices and modalities (T1, T2, FLAIR, T1ce). Slice-level classification is a known simplification.
  • Glioma recall ceiling ~78%: Documented across four systematic training runs. The glioma↔meningioma overlap is inherent to 2D T1-weighted MRI without multi-modal or 3D context.
  • Single dataset source: Training and Testing splits originate from the same dataset. Cross-institutional validation has not been performed.
  • Axial plane orientation: Trained on axial-plane images. Coronal or sagittal slices may produce unreliable predictions.
  • Not for clinical use: This model has not undergone regulatory review and must not be used as the sole basis for any diagnostic or treatment decision.

X-Pathology Platform

This is the second specialist in X-Pathology, a multi-modal AI medical screening research platform.

Deployed specialists:

Specialist Architecture Val accuracy Holdout accuracy
Colon Histopathology EfficientNetB1, 9 classes 99.1% 92.7% (external dataset)
Brain MRI (this model) EfficientNetB0, 4 classes 94.2% 90.1%

Pipeline:

  1. User uploads brain MRI scan
  2. EfficientNetB0 classifies tumor type
  3. Grad-CAM generates attention heatmap
  4. Gemini 2.5 Flash writes dual report β€” clinical + plain-English patient summary

Live demo: x-pathology.vercel.app GitHub: github.com/Muhammad-Hassan12


Training Reproducibility

Python          3.12
TensorFlow      2.x
Keras           3.x
Hardware        Kaggle T4 (single GPU β€” no MirroredStrategy)
Mixed precision float16
Batch size      32

License

Released under the Apache 2.0 License. The training dataset is provided by Masoud Nickparvar on Kaggle. Please credit the dataset source in published work.


Citation

@misc{hassan2026xpathologybrain,
  author    = {Muhammad Hassan},
  title     = {XPathology Brain Tumor MRI Specialist: EfficientNetB0 for 4-Class Brain MRI Classification},
  year      = {2026},
  publisher = {Hugging Face},
  url       = {https://huggingface.co/rarfileexe/xpathology-brain-specialist}
}

Built by Muhammad Hassan Β· AgenticEra Systems
BSCS Student Β· Certified GenAI Developer Β· Computational Pathology & Radiology Research

Downloads last month
13
Inference Providers NEW
This model isn't deployed by any Inference Provider. πŸ™‹ Ask for provider support

Space using rarfileexe/xpathology-brain-specialist 1