Showing posts with label CNN. Show all posts
Showing posts with label CNN. 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.

Saturday, August 01, 2026

Building a Sign Language Classifier using CNN & Keras.

Building a Sign Language Classifier using CNN & Keras

Computer vision plays a critical role in developing assistive technologies. In this post, we build a Convolutional Neural Network (CNN) model trained on the Sign Language MNIST dataset to recognize American Sign Language (ASL) gestures from pixel data.


1. Environment Setup & Data Loading

We begin by downloading the datamunge/sign-language-mnist dataset using KaggleHub and loading the training set via Pandas.

import os
import pandas as pd
import kagglehub

# Download dataset
path = kagglehub.dataset_download("datamunge/sign-language-mnist")

# Load training data
train_df = pd.read_csv(os.path.join(path, 'sign_mnist_train.csv'))
print(f"Dataset shape: {train_df.shape}")

The dataset contains 27,455 samples with 785 columns (1 label column + 784 pixel columns representing a 28x28 grayscale image).

2. Data Preprocessing & Visualization

Before passing our images into a deep learning model, we perform three essential preprocessing steps:

  • Separate target labels from feature vectors.
  • Normalize pixel intensity values from [0, 255] to [0.0, 1.0].
  • Reshape pixel arrays into standard image dimensions (28, 28, 1).
from sklearn.model_selection import train_test_split
from tensorflow.keras.utils import to_categorical

# Feature / Label split & Normalization
X = train_df.drop('label', axis=1) / 255.0
y = train_df['label']

# Train / Test split
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42
)

# Reshape for CNN input
X_train_reshaped = X_train.values.reshape(-1, 28, 28, 1)
X_test_reshaped = X_test.values.reshape(-1, 28, 28, 1)

# One-hot encode targets
num_classes = y_train.max() + 1
y_train_encoded = to_categorical(y_train, num_classes=num_classes)
y_test_encoded = to_categorical(y_test, num_classes=num_classes)

Sample Preview

Each gesture maps to an alphabet character (excluding motion-based letters J and Z):

Sample ASL Gesture
Figure 1: Visualization of a single 28x28 grayscale ASL letter sample.

3. CNN Architecture Definition

We implement a multi-layer Convolutional Neural Network with Max-Pooling and Dropout layers to prevent overfitting:

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout

model = Sequential([
    Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),
    MaxPooling2D((2, 2)),
    Conv2D(64, (3, 3), activation='relu'),
    MaxPooling2D((2, 2)),
    Flatten(),
    Dense(128, activation='relu'),
    Dropout(0.5),
    Dense(num_classes, activation='softmax')
])

model.compile(
    optimizer='adam',
    loss='categorical_crossentropy',
    metrics=['accuracy']
)

4. Training and Evaluation

The network is trained over 10 epochs using a batch size of 32:

history = model.fit(
    X_train_reshaped, y_train_encoded,
    epochs=10,
    batch_size=32,
    validation_data=(X_test_reshaped, y_test_encoded)
)

Final Model Evaluation Metrics

Test Loss: 0.0014
Test Accuracy: 99.96%

5. Model Inference Verification

Testing the model on unseen test samples demonstrates strong prediction capability with high probability confidence scores.

import numpy as np

# Select test sample
sample_image = X_test_reshaped[0]
processed_image = np.expand_dims(sample_image, axis=0)

# Prediction
predictions = model.predict(processed_image)
predicted_label = np.argmax(predictions[0])

print(f"Predicted Class Index: {predicted_label}")
Prediction Result Preview
Figure 2: Successful model inference comparing ground truth vs. model prediction.

Conclusion: Convolutional architectures provide exceptional performance for static sign language character classification tasks. Next steps include expanding to video stream processing for real-time gesture recognition.

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