File size: 11,776 Bytes
508216c 8840efe 508216c 8944117 508216c 8944117 508216c 8944117 508216c 8944117 508216c 8944117 508216c 8944117 508216c |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 |
---
license: cc-by-nc-sa-4.0
language:
- en
- tr
tags:
- ai
- brain
- eeg
- neuroscience
- deeplearning
- mind
- bci
- epilepsy
- seizure-detection
- medical-ai
- healthcare
- dl
- artificial-intelligence
- eeg-classification
- temporal-analysis
- attention-mechanism
- epilepsy
- seizure-detection
pipeline_tag: time-series-forecasting
library_name: keras
---
# 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
1. **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
2. **Multi-Head Self-Attention**
- 2 stacked attention layers with 8 heads each
- Learns long-range dependencies in EEG signals
- Layer normalization and residual connections
3. **Channel Attention Module**
- Adaptive feature weighting
- Enhances important channels
4. **Bidirectional LSTM**
- 2 layers, 128 hidden units per direction
- Sequential pattern modeling
5. **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
```bash
pip install torch>=2.0.0 numpy pandas scikit-learn matplotlib seaborn tqdm tabulate
```
### Basic Usage
```python
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
```python
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 checkpoint
- `requirements.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:
1. **Confusion Matrix** - True vs Predicted labels
2. **ROC Curve** - TPR vs FPR with AUC score
3. **Precision-Recall Curve** - PR curve with AP score
4. **Confidence Distribution** - Prediction confidence histograms
5. **Metrics Summary** - Combined overview of all metrics
All visualizations are saved as high-resolution PNG files.
## Limitations & Considerations
β οΈ **Important Notes:**
1. **Medical Use**: This model is for research purposes and should NOT replace professional medical diagnosis
2. **Feature Dependency**: Requires specific 178-dimensional feature extraction pipeline
3. **Binary Classification**: Detects seizure vs non-seizure only (not seizure types)
4. **Patient Variability**: Performance may vary across different patients
5. **Beta Version**: Model is in BETA phase, use with caution
6. **Data Privacy**: EEG data must be handled with strict confidentiality
## Support
- **Website**: [Neurazum](https://neurazum.com)
- **Email**: [[email protected]](mailto:[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](https://creativecommons.org/licenses/by-nc-sa/4.0/) for details.
---
*Advancing epilepsy care through AI-powered seizure detection! π§ β‘*
<span style="color: #ff8d26;"><b>Neurazum</b> AI Department</span> |