Leveraging Convolutional Neural Networks (CNNs) and Transfer Learning to classify brain MRI images into four categories: Glioma, Meningioma, Pituitary Tumor, and No Tumor. This project achieves up to 97% accuracy using ResNet50V2, supporting early diagnosis and clinical decision-making.
- Features
- Model Performance
- Dataset
- Project Structure
- Installation
- Usage
- Technical Details
- Results
- Environment Variables
- Resources
- Contributing
- License
-
Multi-Model Architecture: Implements and compares 5 different deep learning models
- Custom CNN
- VGG16 (Transfer Learning)
- VGG19 (Transfer Learning)
- ResNet50V2 (Transfer Learning)
- MobileNetV2 (Transfer Learning)
-
High Accuracy: Achieves up to 97% accuracy on test data with ResNet50V2
-
Comprehensive Evaluation:
- Accuracy, Precision, Recall, F1-Score metrics
- Confusion matrices for detailed performance analysis
- Training/validation loss and accuracy curves
-
Data Augmentation: Robust preprocessing pipeline for better generalization
-
Class Balancing: Automatic downsampling to handle class imbalance
-
Visualization Tools:
- Sample image visualization from training/testing sets
- Model comparison charts
- Training history plots
| Model | Test Accuracy | Precision | Recall | F1-Score | Loss |
|---|---|---|---|---|---|
| ResNet50V2 | 96.98% | 97.03% | 96.91% | 96.95% | 0.1647 |
| MobileNetV2 | 96.47% | 96.49% | 96.47% | 96.45% | 0.2659 |
| VGG19 | 94.76% | 94.85% | 94.76% | 94.67% | 0.3124 |
| VGG16 | 94.49% | 94.70% | 94.27% | 94.30% | 0.3187 |
| Custom CNN | 88.61% | 88.86% | 88.53% | 87.63% | 0.7931 |
Best Model: ResNet50V2 with 96.98% test accuracy π
The project uses two Kaggle datasets:
-
Brain Tumor Classification (MRI) by Sartaj Bhuvaji
-
Brain Tumor MRI Dataset by Masoud Nickparvar
Training/
βββ glioma_tumor/
βββ meningioma_tumor/
βββ no_tumor/
βββ pituitary_tumor/
Testing/
βββ glioma_tumor/
βββ meningioma_tumor/
βββ no_tumor/
βββ pituitary_tumor/
- Glioma Tumor: Malignant brain tumors arising from glial cells
- Meningioma Tumor: Tumors arising from meninges (brain coverings)
- Pituitary Tumor: Tumors in the pituitary gland
- No Tumor: Normal brain MRI scans
- Images resized to 224x224 pixels
- Normalization: pixel values scaled to [0, 1]
- Class balancing through downsampling
- Batch size: 32
BRAIN-TUMOR-CLASSIFICATION/
β
βββ src/
β βββ Models/
β βββ CNN.ipynb # Custom CNN implementation
β βββ MobileNet.ipynb # MobileNetV2 transfer learning
β βββ ResNet.ipynb # ResNet50V2 transfer learning
β βββ VGG_16.ipynb # VGG16 transfer learning
β βββ VGG_19.ipynb # VGG19 transfer learning
β
βββ results/
β βββ CNN_Result/
β β βββ CNN.png # CNN performance visualization
β βββ MobileNet_Result/
β β βββ MobileNet.png
β βββ ResNet_Result/
β β βββ ResNet.png
β βββ VGG_16_Result/
β β βββ VGG_16.png
β βββ VGG_19_Result/
β β βββ VGG_19.png
β βββ Comparison_Models/
β β βββ Comparison_1.png # Model accuracy comparison
β β βββ Comparison_2.png # Validation loss comparison
β β βββ Comparison_3.png # Training curves
β β βββ Comparison_4.png # Bar charts
β β βββ Comparison_5.png # Horizontal comparison
β β βββ Comparison_6.png # Final rankings
β β βββ Comparison_7.png # Detailed metrics
β βββ Data_Visualization/
β βββ Testing_data.png # Sample test images
β βββ Training_data.png # Sample training images
β βββ validtion_data.png # Merged dataset samples
β
βββ brain-tumor-classification-cnn-97-acc.py # Main training script
βββ models.txt # Links to trained models (.h5 files)
βββ dataset.txt # Dataset download links
βββ kaggle_notebook.txt # Link to Kaggle notebook
βββ requirements.txt # Python dependencies
βββ .env.example # Environment variables template
βββ .gitignore # Git ignore rules
βββ LICENSE # Project license
βββ README.md # This file
- Python 3.10 or higher
- CUDA-compatible GPU (recommended for faster training)
- 8GB+ RAM
- 10GB+ free disk space
Download and install MiniConda from here
Create a new environment:
conda create -n Brain_Tumor_Classification python=3.10Activate the environment:
conda activate Brain_Tumor_Classificationgit clone https://github.com/Abdelhady-22/brain_tumor_classification.git
cd brain-tumor-classificationpip install -r requirements.txtOption A: Using Kaggle API
pip install kagglehub
python -c "import kagglehub; kagglehub.dataset_download('sartajbhuvaji/brain-tumor-classification-mri')"
python -c "import kagglehub; kagglehub.dataset_download('masoudnickparvar/brain-tumor-mri-dataset')"Option B: Manual Download
- Download datasets from links in
dataset.txt - Extract to project directory
cp .env.example .envEdit .env file:
PROJECT_VERSION=1.0
IMAGE_SIZE=224
BATCH_SIZE=32
EPOCHS=20
LEARNING_RATE=0.0001Run the main training script:
python brain-tumor-classification-cnn-97-accuracy.ipynbOr train individual models using Jupyter notebooks:
jupyter notebook src/Models/CNN.ipynbfrom tensorflow.keras.models import load_model
import numpy as np
from PIL import Image
# Load trained model
model = load_model('ResNet_best_model.keras')
# Load and preprocess image
img = Image.open('path/to/mri_scan.jpg')
img = img.resize((224, 224))
img_array = np.array(img) / 255.0
img_array = np.expand_dims(img_array, axis=0)
# Make prediction
prediction = model.predict(img_array)
classes = ['glioma_tumor', 'meningioma_tumor', 'no_tumor', 'pituitary_tumor']
result = classes[np.argmax(prediction)]
print(f"Prediction: {result}")
print(f"Confidence: {np.max(prediction) * 100:.2f}%")# Load test data
from tensorflow.keras.preprocessing.image import ImageDataGenerator
test_datagen = ImageDataGenerator(preprocessing_function=lambda x: x/255.0)
test_generator = test_datagen.flow_from_directory(
'path/to/Testing',
target_size=(224, 224),
batch_size=32,
class_mode='categorical'
)
# Evaluate model
results = model.evaluate(test_generator)
print(f"Test Accuracy: {results[1]*100:.2f}%")Input (224x224x3)
β Conv2D(64) + MaxPool
β Conv2D(64) + MaxPool
β Conv2D(128) + MaxPool
β Flatten + Dropout(0.4)
β Dense(128) + Dense(64) + Dense(64)
β Output (4 classes, softmax)
- Base Models: Pre-trained on ImageNet
- Frozen Layers: All base layers non-trainable
- Custom Head:
- GlobalAveragePooling2D / Flatten
- Dense(256, relu)
- Output(4, softmax)
| Parameter | Value |
|---|---|
| Image Size | 224 Γ 224 |
| Batch Size | 32 |
| Epochs | 20 (with early stopping) |
| Optimizer | Adam |
| Learning Rate | 0.0001 |
| Loss Function | Categorical Crossentropy |
- EarlyStopping: Patience=5, monitors val_loss
- ModelCheckpoint: Saves best model based on val_loss
- ReduceLROnPlateau: Reduces LR by 0.5 when val_loss plateaus
- GPU: NVIDIA GPU with CUDA support (recommended)
- RAM: 8GB minimum, 16GB recommended
- Storage: 10GB for datasets and models
All models were trained for up to 20 epochs with early stopping:
- ResNet50V2: Best validation loss at epoch 12
- MobileNetV2: Best validation loss at epoch 15
- VGG19: Best validation loss at epoch 18
- VGG16: Best validation loss at epoch 16
- Custom CNN: Best validation loss at epoch 19
- Transfer Learning Superiority: Pre-trained models significantly outperform custom CNN
- ResNet50V2 Excellence: Achieved best overall performance with 97% accuracy
- Convergence Speed: Transfer learning models converge faster (fewer epochs)
- Generalization: All models show good generalization on merged dataset
Create a .env file with the following variables:
# Project Configuration
PROJECT_NAME=Brain_Tumor_Classification
PROJECT_VERSION=1.0
# Model Parameters
IMAGE_SIZE=224
BATCH_SIZE=32
EPOCHS=20
LEARNING_RATE=0.0001
# Paths
TRAIN_PATH=/kaggle/input/brain-tumor-mri-dataset/Training
TEST_PATH=/kaggle/input/brain-tumor-mri-dataset/Testing
MODEL_SAVE_PATH=/kaggle/working/
# Training Configuration
EARLY_STOPPING_PATIENCE=5
REDUCE_LR_PATIENCE=3
REDUCE_LR_FACTOR=0.5
MIN_LEARNING_RATE=1e-7
# Callbacks
MONITOR_METRIC=val_loss
SAVE_BEST_ONLY=TrueAll trained models (.h5 and .keras formats) are available in models.txt:
- Custom CNN Model
- VGG16 Model
- VGG19 Model
- ResNet50V2 Model
- MobileNetV2 Model
Complete interactive notebook: See kaggle_notebook.txt for link
Download links available in dataset.txt
Contributions are welcome! Please follow these steps:
- Fork the repository
- Create a 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
- Follow PEP 8 style guide for Python code
- Add docstrings to functions and classes
- Update README.md for significant changes
- Test code before submitting PR
This project is licensed under the MIT License - see the LICENSE file for details.
- Abdelhady Ali - Initial work - MYGitHub
- Datasets: Thanks to Sartaj Bhuvaji and Masoud Nickparvar for providing the datasets
- Kaggle: For providing the platform and computational resources
- TensorFlow/Keras: For the deep learning framework
- Medical Community: For inspiring this work to assist in early diagnosis
For questions, suggestions, or collaborations:
- Email: abdulhadi2322005@gmail.com
- LinkedIn: My LinkedIn
- GitHub: My GitHub
This project is for educational and research purposes only. The models should not be used as a substitute for professional medical diagnosis. Always consult qualified healthcare professionals for medical advice and diagnosis.
If you use this project in your research, please cite:
@misc{brain_tumor_classification_2025,
title={AI-Powered Brain Tumor Classification using Deep Learning},
author={abdelhady ali},
year={2025},
publisher={GitHub},
url={https://github.com/Abdelhady-22/brain_tumor_classification}
}Made with β€οΈ for advancing medical AI
β Star this repo if you find it helpful!
