Showing posts with label Tensorflow. Show all posts
Showing posts with label Tensorflow. Show all posts

Friday, August 14, 2026

Brain Tumor Detection Using CNN and TensorFlow

Brain MRI Overview
Sample Batch Predictions

Brain Tumor Detection Using CNN and TensorFlow

A practical deep learning project using TensorFlow and a brain MRI image dataset to demonstrate end-to-end image classification with a Convolutional Neural Network (CNN).

#Python #TensorFlow #CNN #Kaggle #MedicalImaging

Introduction

Medical image classification is an important application of machine learning and computer vision. In this project, we build a Convolutional Neural Network (CNN) using TensorFlow to classify brain MRI images into specified dataset categories.

Workflow Overview: Download Dataset → Directory Inspection → Train/Val Split → Input Pipeline Optimization → Rescaling → CNN Architecture → Model Training & Learning Curve Plots.
Important: This project is strictly for educational and research purposes. Any deep learning workflow applied to health datasets requires rigorous clinical validation, multi-center testing, regulatory approvals, and qualified medical oversight before any diagnostic use.

1. Environment Setup & Data Acquisition

We retrieve the dataset directly from Kaggle using the kagglehub library.

import kagglehub # Download dataset path path = kagglehub.dataset_download( "navoneel/brain-mri-images-for-brain-tumor-detection" )

2. Inspecting the Dataset Directory

Understanding folder hierarchies helps confirm how directory-based dataset utilities infer target labels.

import os for root, dirs, files in os.walk(path): level = root.replace(path, '').count(os.sep) indent = ' ' * 4 * level print(f"{indent}{os.path.basename(root)}/") subindent = ' ' * 4 * (level + 1) for f in files[:3]: # Sample display print(f"{subindent}{f}")

3. Input Data Pipeline Configuration

We configure spatial resolution, batch sizing, and partitioned data loading splits (80% training / 20% validation) with random seed controls.

import tensorflow as tf image_size = (180, 180) batch_size = 32 data_dir = os.path.join(path, "brain_tumor_dataset") # Training split train_ds = tf.keras.preprocessing.image_dataset_from_directory( data_dir, validation_split=0.2, subset="training", seed=123, image_size=image_size, batch_size=batch_size ) # Validation split val_ds = tf.keras.preprocessing.image_dataset_from_directory( data_dir, validation_split=0.2, subset="validation", seed=123, image_size=image_size, batch_size=batch_size ) class_names_list = train_ds.class_names print("Detected Classes:", class_names_list)

4. Pipeline Optimization & Normalization

We leverage memory caching, prefetching via AUTOTUNE, and rescale standard integer pixel intensity values ($[0, 255]$) down to floating-point ranges ($[0.0, 1.0]$).

AUTOTUNE = tf.data.AUTOTUNE train_ds = train_ds.cache().prefetch(buffer_size=AUTOTUNE) val_ds = val_ds.cache().prefetch(buffer_size=AUTOTUNE) # Pixel Scaling normalization_layer = tf.keras.layers.Rescaling(1./255) train_ds = train_ds.map(lambda x, y: (normalization_layer(x), y)) val_ds = val_ds.map(lambda x, y: (normalization_layer(x), y))

5. CNN Model Architecture

We build a Sequential model with alternating Convolutional and Max Pooling stages followed by Dense representation layers.

num_classes = len(class_names_list) model = tf.keras.Sequential([ tf.keras.layers.Conv2D(32, 3, activation='relu', input_shape=(180, 180, 3)), tf.keras.layers.MaxPooling2D(), tf.keras.layers.Conv2D(32, 3, activation='relu'), tf.keras.layers.MaxPooling2D(), tf.keras.layers.Conv2D(32, 3, activation='relu'), tf.keras.layers.MaxPooling2D(), tf.keras.layers.Flatten(), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dense(num_classes) ]) model.compile( optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy'] )

Model Architectural Summary

Layer Type Kernel / Pool Specs Activation Output Function
Conv2D (x3) 3 × 3 Filters (32) ReLU Spatial Feature Extraction
MaxPooling2D (x3) 2 × 2 Pooling - Dimensional Downsampling
Flatten 1D Vector Mapping - Pre-Dense Unrolling
Dense 128 Units ReLU Representation Learning
Output Dense num_classes Units Linear (Logits) Raw Class Score Generation

6. Execution & Performance Evaluation

Model optimization runs across 10 epochs while logging training accuracy, validation metrics, and categorical cross-entropy loss curves.

epochs = 10 history = model.fit( train_ds, validation_data=val_ds, epochs=epochs )
import matplotlib.pyplot as plt acc = history.history['accuracy'] val_acc = history.history['val_accuracy'] loss = history.history['loss'] val_loss = history.history['val_loss'] epochs_range = range(epochs) plt.figure(figsize=(12, 5)) plt.subplot(1, 2, 1) plt.plot(epochs_range, acc, label='Training Accuracy') plt.plot(epochs_range, val_acc, label='Validation Accuracy') plt.legend(loc='lower right') plt.title('Accuracy Evaluation') plt.subplot(1, 2, 2) plt.plot(epochs_range, loss, label='Training Loss') plt.plot(epochs_range, val_loss, label='Validation Loss') plt.legend(loc='upper right') plt.title('Loss Curves') plt.show()

7. Advanced Production & Validation Enhancements

To upgrade this exploratory pipeline into a production-grade machine learning model, consider incorporating the following procedures:

  • Data Augmentation: Apply geometric shifts, random rotation, and contrast modifications to prevent overfitting.
  • Transfer Learning: Fine-tune pre-trained weights from architectures like EfficientNet or ResNet.
  • Explainable AI (XAI): Integrate Grad-CAM heatmaps to verify anatomical regions driving predictions.
  • Comprehensive Metrics: Evaluate performance using Sensitivity, Specificity, Confusion Matrices, and ROC-AUC metrics instead of accuracy alone.

Featured Post

3rd Place at the BAKE Blogger Awards: Thank You for the Support!

3rd Place at the BAKE Blogger Awards: Thank You for the Support! ...

Meet the Authors
Zacharia Nyambu’s blog features multiple contributors with clear activity status.
Active ✔
πŸ§‘‍πŸ’»
Zacharia Nyambu
Lead Author
Inactive ✖
πŸ‘©‍πŸ’»
Linda Bahati
Co‑Author
Inactive ✖
πŸ‘¨‍πŸ’»
Jefferson Mwangolo
Co‑Author
Inactive ✖
πŸ‘©‍πŸŽ“
Florence Wavinya
Guest Author
Inactive ✖
πŸ‘©‍πŸŽ“
Esther Njeri
Guest Author
Inactive ✖
πŸ‘©‍πŸŽ“
Clemence Mwangolo
Guest Author

Followers