An AI-powered deep learning system for automated brain tumor detection and classification from MRI scans
Features โข Tech Stack โข Installation โข Usage โข Deployment
This project harnesses the power of deep learning to tackle a critical medical challenge: accurately classifying brain tumors from MRI scans. Built using transfer learning with the renowned VGG16 architecture, it classifies tumors into four key categories: glioma, meningioma, pituitary, or no tumor.
Leveraging Python and TensorFlow, this system aims to deliver reliable, interpretable AI diagnostics that can support medical imaging workflows.
๐งฌ Transfer Learning with VGG16 Leveraging the pre-trained VGG16 convolutional base, freezing most layers to retain powerful learned features, while fine-tuning the top layers to specialize the model for brain tumor MRI classification.
๐ผ๏ธ Custom Image Augmentation To maximize model robustness despite a limited dataset, brightness and contrast adjustments are applied on-the-fly during training, improving the model's ability to generalize.
๐ข Dynamic Data Loading & Label Encoding Images are efficiently loaded from organized folder structures, shuffled, and labels encoded dynamically for seamless batch training.
โ๏ธ Tailored Model Architecture The core model stacks the VGG16 base (excluding its classification head) with flattening, dropout layers, and fully connected dense layers topped with softmax for multi-class tumor prediction.
๐ Thorough Training and Evaluation Training uses the Adam optimizer and sparse categorical cross-entropy loss. The system monitors accuracy and loss trends and validates model performance via detailed classification reports, confusion matrices, and ROC/AUC analyses.
๐พ Model Persistence & Practical Inference
After training, the model is saved (model.h5) and can predict tumor type and confidence on new MRI images through an easy-to-use inference function.
Input MRI Image (224x224x3)
โ
โโโโโโโโโโโโโโโโโโโโโโโโโโ
โ VGG16 Base Model โ
โ (Pre-trained on โ
โ ImageNet) โ
โ - Conv Layers โ
โ - MaxPooling โ
โ - (Most layers frozen)โ
โโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Flatten Layer โ
โโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Dropout (0.5) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Dense (256 units) โ
โ ReLU Activation โ
โโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Dropout (0.5) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Dense (4 units) โ
โ Softmax Activation โ
โโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
Output Classes:
- Glioma
- Meningioma
- Pituitary
- No Tumor
1๏ธโฃ Data Preparation
- Loaded MRI images from well-structured training and testing folders
- Shuffled datasets and encoded labels dynamically
- Applied brightness and contrast augmentations in real-time during training to boost robustness
2๏ธโฃ Model Setup
- Initialized VGG16 pretrained on ImageNet without its top layers
- Froze most layers to preserve pretrained features; unfroze several top layers for targeted fine-tuning
- Added custom classification layers with dropout and dense connections
3๏ธโฃ Training
- Used a custom data generator for efficient batch processing
- Trained the model over multiple epochs with the Adam optimizer
- Tracked and visualized accuracy and loss metrics throughout the training cycle
4๏ธโฃ Evaluation
- Assessed model performance with classification reports and confusion matrices on test data
- Visualized results through heatmaps and ROC/AUC curves for detailed understanding
5๏ธโฃ Inference
- Preprocessed new MRI images and ran predictions with confidence scoring
- Presented results alongside input images for interpretability
Prerequisites
- Python 3.8 or higher
- pip package manager
- Jupyter Notebook
- (Optional) Virtual environment
Setup
- Clone the repository
git clone https://github.com/PasinduSuraweera/MRI-Brain-Tumor-Diagnosis-System.git
cd MRI-Brain-Tumor-Diagnosis-System- Create a virtual environment (recommended)
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate- Install dependencies
pip install -r requirements.txt- Launch Jupyter Notebook
jupyter notebookCreate a requirements.txt file with the following packages:
tensorflow>=2.10.0
keras>=2.10.0
numpy>=1.21.0
pandas>=1.3.0
matplotlib>=3.4.0
seaborn>=0.11.0
pillow>=8.3.0
scikit-learn>=0.24.0
opencv-python>=4.5.0
flask>=2.0.0
gunicorn>=20.1.0Training the Model
- Open the training notebook in Jupyter
- Organize your dataset in the following structure:
data/
โโโ Training/
โ โโโ glioma/
โ โโโ meningioma/
โ โโโ pituitary/
โ โโโ notumor/
โโโ Testing/
โโโ glioma/
โโโ meningioma/
โโโ pituitary/
โโโ notumor/
- Run the cells sequentially to train the model
- Model checkpoints will be saved as
model.h5
Making Predictions
In Jupyter Notebook:
# Load the trained model
from tensorflow.keras.models import load_model
from PIL import Image
import numpy as np
model = load_model('model.h5')
# Preprocess and predict
def predict_tumor(image_path):
img = Image.open(image_path).resize((224, 224))
img_array = np.array(img) / 255.0
img_array = np.expand_dims(img_array, axis=0)
prediction = model.predict(img_array)
classes = ['Glioma', 'Meningioma', 'No Tumor', 'Pituitary']
predicted_class = classes[np.argmax(prediction)]
confidence = np.max(prediction) * 100
print(f"Prediction: {predicted_class}")
print(f"Confidence: {confidence:.2f}%")
return predicted_class, confidence
# Use the function
predict_tumor('path/to/mri_scan.jpg')The system is deployed on Render to provide seamless web access. The backend is built using Flask, serving the model and handling image uploads smoothly.
๐ Live Demo Explore the live application here:
Deploying Your Own Instance
- Create a Flask Application (
app.py) - Configure
requirements.txtwith all dependencies - Create
Procfilefor Render:
web: gunicorn app:app
- Deploy to Render:
- Connect your GitHub repository
- Configure build settings
- Deploy automatically on push
MRI-Brain-Tumor-Diagnosis-System/
โ
โโโ notebooks/ # Jupyter notebooks
โ โโโ training.ipynb # Model training pipeline
โ โโโ evaluation.ipynb # Model evaluation & metrics
โ โโโ inference.ipynb # Prediction demonstrations
โ
โโโ data/ # Dataset directory
โ โโโ Training/ # Training images
โ โ โโโ glioma/
โ โ โโโ meningioma/
โ โ โโโ pituitary/
โ โ โโโ notumor/
โ โโโ Testing/ # Testing images
โ โโโ glioma/
โ โโโ meningioma/
โ โโโ pituitary/
โ โโโ notumor/
โ
โโโ models/ # Saved models
โ โโโ model.h5 # Trained VGG16 model
โ
โโโ app.py # Flask web application
โโโ requirements.txt # Project dependencies
โโโ Procfile # Render deployment config
โโโ README.md # Project documentation
This project works with MRI brain scan datasets organized into four categories:
- Glioma - A type of tumor that occurs in the brain and spinal cord
- Meningioma - A tumor that arises from the meninges
- Pituitary - A tumor in the pituitary gland
- No Tumor - Healthy brain scans
Recommended Datasets:
Important: Ensure you have proper authorization and follow ethical guidelines when using medical data.
This model is not 100% accurate and is trained on a relatively small dataset, which may impact its performance on new, unseen cases.
This system should be viewed as a supportive diagnostic aid rather than a definitive medical tool. It is designed for research and educational purposes and should NOT be used as a substitute for professional medical diagnosis.
Always consult qualified healthcare professionals for medical decisions.
This MRI Brain Tumor Diagnosis System showcases how transfer learning with VGG16 can be effectively applied to challenging medical imaging tasks, even when working with limited data. By combining strategic data augmentation, fine-tuning, and comprehensive evaluation, the system achieves promising tumor classification accuracy.
This project lays a solid foundation for future AI-driven diagnostic applications and underscores deep learning's potential to empower healthcare professionals with faster, more informed decision-making.
๐ฎ Future Directions
- ๐ Expanding the dataset with more diverse MRI scans
- ๐ฅ Including additional tumor classes and subtypes
- ๐ฌ Implementing explainable AI techniques (Grad-CAM, attention maps)
- ๐๏ธ Progressing toward clinical deployment and validation
- โก Exploring more advanced architectures (ResNet, EfficientNet, Vision Transformers)
- ๐ Multi-center validation studies
Contributions are welcome! Whether it's bug fixes, feature additions, or documentation improvements, your help is appreciated.
How to Contribute:
- Fork the project
- Create your feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
Pasindu Suraweera
- ๐ GitHub: @PasinduSuraweera
- ๐ Live Demo: MRI Brain Tumor Diagnosis System
- ๐ฅ Medical imaging research community
- ๐ค TensorFlow and Keras development teams
- ๐ ImageNet and VGG16 researchers
- ๐ก Open-source contributors
- ๐จโโ๏ธ Healthcare professionals providing guidance and feedback
For questions, feedback, or collaboration opportunities, please open an issue in the repository or reach out through GitHub.