bai-6 Epilepsy | EEG Seizure Detection Model π§ β‘
Advanced deep learning model for automatic epileptic seizure detection from EEG brain signals using hybrid neural network architecture.
Overview
This project enables automatic epileptic seizure detection from EEG (Electroencephalography) signals using a state-of-the-art hybrid deep learning architecture. The system combines Temporal Convolutional Networks (TCN), Multi-Head Self-Attention mechanisms, and Bidirectional LSTM to achieve high accuracy in binary classification (Non-Seizure vs. Seizure) tasks.
Key Innovation: Hybrid architecture that captures both temporal patterns and long-range dependencies in EEG signals for robust seizure detection.
Model Architecture
The AdvancedEpilepsyDetector employs a sophisticated multi-path architecture:
Input (178-dim EEG features)
β
Input Projection (256-dim)
β
ββββββββββββββββββ¬βββββββββββββββββ
β β β
TCN Path Transformer Path BiLSTM Path
β β β
Channel Attn Multi-Head Attn Sequential
β β Modeling
ββββββββββββββββββ΄βββββββββββββββββ
β
Feature Concatenation
β
Classification Head (2 classes)
β
Output: [Non-Seizure, Seizure]
Architecture Components
Temporal Convolutional Network (TCN)
- 4 stacked blocks with increasing dilation rates (1, 2, 4, 8)
- Captures multi-scale temporal patterns
- Residual connections for gradient flow
Multi-Head Self-Attention
- 2 stacked attention layers with 8 heads each
- Learns long-range dependencies in EEG signals
- Layer normalization and residual connections
Channel Attention Module
- Adaptive feature weighting
- Enhances important channels
Bidirectional LSTM
- 2 layers, 128 hidden units per direction
- Sequential pattern modeling
Classification Head
- 4-layer fully connected network
- Batch normalization and dropout for regularization
Model Statistics
| Metric | Value |
|---|---|
| Total Parameters | 2,958,274 |
| Trainable Parameters | 2,958,274 |
| Model Size | 34.90 MB |
| Input Dimension | 178 EEG features |
| Output Classes | 2 (Binary) |
| Inference Time (GPU) | ~46 ms/batch |
| Throughput | ~1,350 samples/sec |
Performance Metrics
Validation Results (on real EEG data)
| Metric | Score |
|---|---|
| Validation F1-Score | 0.9740 |
| Validation AUC-ROC | 0.9972 |
| Training Epochs | 24 (early stopped) |
Test Results
Note: Test results shown below are based on simulated random data for demonstration purposes. Real-world performance on actual EEG datasets should refer to the validation metrics above.
| Metric | Value |
|---|---|
| Accuracy | 49.70% |
| Precision (Weighted) | 0.2470 |
| Recall (Weighted) | 0.4970 |
| F1-Score (Weighted) | 0.3300 |
| ROC-AUC Score | 0.4825 |
| Average Precision | 0.4939 |
Per-Class Performance (Random Test Data):
| Class | Precision | Recall | F1-Score | Support |
|---|---|---|---|---|
| Non-Seizure (0) | 0.497 | 1.000 | 0.664 | 497 |
| Seizure (1) | 0.000 | 0.000 | 0.000 | 503 |
β οΈ Important: The model achieves 97.4% F1-score and 99.7% AUC on validation data with real EEG signals. The low test scores above are due to random test data generation and do not reflect actual model performance.
Quick Start
Installation
pip install torch>=2.0.0 numpy pandas scikit-learn matplotlib seaborn tqdm tabulate
Basic Usage
import torch
import numpy as np
from epilepsy_detection_model import AdvancedEpilepsyDetector
# Device setup
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# Load pre-trained model
model = AdvancedEpilepsyDetector(input_dim=178, num_classes=2).to(device)
checkpoint = torch.load('bai-6 Epilepsy.pth', map_location=device)
model.load_state_dict(checkpoint['model_state_dict'])
model.eval()
# Prepare EEG data (178-dimensional features)
eeg_features = np.random.randn(1, 178).astype(np.float32) # Replace with real EEG
input_tensor = torch.FloatTensor(eeg_features).to(device)
# Make prediction
with torch.no_grad():
output = model(input_tensor)
probabilities = torch.softmax(output, dim=1)
prediction = torch.argmax(output, dim=1)
print(f"Prediction: {'Seizure' if prediction == 1 else 'Non-Seizure'}")
print(f"Confidence: {probabilities[0][prediction].item():.4f}")
Real-Time Seizure Detection
import torch
from epilepsy_detection_model import AdvancedEpilepsyDetector
class SeizureDetector:
def __init__(self, model_path, device='cuda'):
self.device = torch.device(device if torch.cuda.is_available() else 'cpu')
self.model = AdvancedEpilepsyDetector(input_dim=178, num_classes=2).to(self.device)
checkpoint = torch.load(model_path, map_location=self.device)
self.model.load_state_dict(checkpoint['model_state_dict'])
self.model.eval()
def predict(self, eeg_features):
"""
Predict seizure from EEG features
Args:
eeg_features: numpy array of shape (178,) or (batch_size, 178)
Returns:
prediction: 0 (Non-Seizure) or 1 (Seizure)
confidence: float between 0 and 1
"""
if eeg_features.ndim == 1:
eeg_features = eeg_features.reshape(1, -1)
input_tensor = torch.FloatTensor(eeg_features).to(self.device)
with torch.no_grad():
output = self.model(input_tensor)
probabilities = torch.softmax(output, dim=1)
prediction = torch.argmax(output, dim=1)
return prediction.cpu().numpy(), probabilities.cpu().numpy()
# Usage
detector = SeizureDetector('bai-6 Epilepsy.pth')
# Real-time loop
while True:
eeg_data = capture_eeg_features() # Your EEG feature extraction
pred, conf = detector.predict(eeg_data)
if pred[0] == 1 and conf[0][1] > 0.8:
trigger_alert("Seizure detected!")
print(f"ALERT: Seizure detected with {conf[0][1]:.2%} confidence")
Hardware Requirements
EEG Device Specifications
- Input: 178-dimensional feature vectors extracted from raw EEG
- Preprocessing: Requires feature extraction pipeline
- Sampling: Compatible with standard clinical EEG systems
- Channels: Any multi-channel EEG system (features must be extracted)
Recommended EEG Systems
- Clinical EEG systems (16-64 channels)
- Research-grade EEG devices
- OpenBCI (with feature extraction)
- g.tec systems
- Biosemi ActiveTwo
Applications
- π₯ Clinical Monitoring: Real-time seizure detection in hospitals
- π¨ Emergency Response: Automatic alert systems for epilepsy patients
- π¬ Medical Research: EEG signal analysis and seizure prediction studies
- π± Wearable Devices: Integration with portable EEG monitors
- π Treatment Optimization: Monitoring medication effectiveness
- π§ Brain-Computer Interfaces: Seizure prediction and prevention
Data Format
Input Requirements
Your EEG data must be preprocessed into 178-dimensional feature vectors:
- Shape: (178,) per sample or (batch_size, 178)
- Type: Float32
- Normalization: Recommended (Z-score or min-max)
- Classes: 0 (Non-Seizure), 1 (Seizure)
Feature Extraction
The model expects preprocessed features. Typical EEG feature extraction pipeline includes:
- Time-domain features (mean, variance, skewness, kurtosis)
- Frequency-domain features (band powers, spectral entropy)
- Time-frequency features (wavelet coefficients)
- Statistical moments
- Hjorth parameters
Training Configuration
The model was trained with the following setup:
| Parameter | Value |
|---|---|
| Batch Size | 64 |
| Learning Rate | 0.001 (initial) |
| Optimizer | AdamW (weight decay: 0.01) |
| Loss Function | Focal Loss (Ξ±=0.25, Ξ³=2) |
| Scheduler | ReduceLROnPlateau |
| Max Epochs | 100 |
| Early Stopping | 15 epochs patience |
| Best Epoch | 24 |
| Gradient Clipping | Max norm 1.0 |
Features
β State-of-the-art Architecture: Hybrid TCN + Transformer + LSTM design β High Performance: 97.4% F1-score and 99.7% AUC on validation data β Real-time Capable: Fast inference (~46ms per batch) β Robust Training: Focal Loss for handling class imbalance β Early Stopping: Prevents overfitting β GPU Accelerated: CUDA support for faster processing β Production Ready: Easy-to-use inference API β Comprehensive Metrics: Detailed evaluation tools included
Dependencies
torch>=2.0.0
numpy>=1.21.0
pandas>=1.3.0
scikit-learn>=1.0.0
matplotlib>=3.5.0
seaborn>=0.11.0
tqdm>=4.62.0
tabulate>=0.9.0
Model Files
bai-6 Epilepsy.pth- Trained model checkpointrequirements.txt- Python dependencies
Testing
This generates:
- Confusion matrix
- ROC curve
- Precision-Recall curve
- Confidence distribution plots
- Detailed performance metrics
Visualizations
The test suite generates comprehensive visualizations:
- Confusion Matrix - True vs Predicted labels
- ROC Curve - TPR vs FPR with AUC score
- Precision-Recall Curve - PR curve with AP score
- Confidence Distribution - Prediction confidence histograms
- Metrics Summary - Combined overview of all metrics
All visualizations are saved as high-resolution PNG files.
Limitations & Considerations
β οΈ Important Notes:
- Medical Use: This model is for research purposes and should NOT replace professional medical diagnosis
- Feature Dependency: Requires specific 178-dimensional feature extraction pipeline
- Binary Classification: Detects seizure vs non-seizure only (not seizure types)
- Patient Variability: Performance may vary across different patients
- Beta Version: Model is in BETA phase, use with caution
- Data Privacy: EEG data must be handled with strict confidentiality
Support
- Website: Neurazum
- Email: [email protected]
Acknowledgments
This model uses proprietary datasets from Neurazum. The data is closed source and subject to privacy regulations.
Note
Use at your own risk. Due to the complexity of EEG signals and patient variability, accuracy rates may vary. The model should be used as a supportive tool, not as a replacement for professional medical judgment. Since the data belongs to , the function structure may change in future models.
License
CC-BY-NC-SA 4.0 - see LICENSE for details.
Advancing epilepsy care through AI-powered seizure detection! π§ β‘
Neurazum AI Department