Advanced Deep Learning Framework for WSN Intrusion Detection using TCN-MHA Architecture
Features β’ Installation β’ Usage β’ Results β’ Architecture
IntruTect is a state-of-the-art intrusion detection framework specifically designed for Wireless Sensor Networks (WSNs). It implements the IDFSWSN-DRL (Intrusion Detection Framework for WSN using Deep Reinforcement Learning) methodology, combining bio-inspired optimization algorithms with advanced deep learning architectures to achieve high-precision attack detection while maintaining computational efficiency.
The framework is trained on the WSN-DS dataset, which captures the behavior of the LEACH (Low-Energy Adaptive Clustering Hierarchy) protocol and detects five types of network attacks: Normal, Blackhole, Grayhole, Flooding, and TDMA Scheduling attacks.
- π― 99.09% Validation Accuracy achieved on WSN-DS dataset
- 𧬠Bio-Inspired Optimization: Gazelle Optimization Algorithm (GOA) for feature selection
- π Hyperparameter Tuning: Catch Fish Optimization Algorithm (CFA)
- π§ Deep Learning: Temporal Convolutional Network with Multi-Head Attention (TCN-MHA)
- π Comprehensive Evaluation: Detailed metrics and visualizations
- β‘ Optimized for GTX 1660 Ti: Memory-efficient training with mixed precision
-
Robust Preprocessing
- Median/IQR-based scaling (resilient to outliers)
- SMOTE for class balancing
- Label encoding and data splitting
-
Feature Selection (GOA)
- Nature-inspired metaheuristic algorithm
- Reduces feature dimensionality from 18 to 6 critical features
- Balances exploration and exploitation
-
Hyperparameter Optimization (CFA)
- Automatic tuning of learning rate, batch size, dropout, etc.
- Optimizes TCN-MHA architecture parameters
-
TCN-MHA Model
- Temporal Convolutional Network for sequence learning
- Multi-Head Attention for feature weighting
- Handles long-range temporal dependencies
-
Early Stopping & Monitoring
- Automatic early stopping to prevent overfitting
- Comprehensive training history tracking
- Real-time progress bars
Input Data β Robust Preprocessing β GOA Feature Selection β CFA Hyperparameter Tuning
β
TCN-MHA Model Training
β
Evaluation & Metrics
Sequence Input β TCN Layers (Dilated Convolutions)
β Multi-Head Attention
β Global Average Pooling
β Fully Connected Layers
β Softmax β Classification (5 Classes)
- Python 3.8 or higher
- CUDA-capable GPU (recommended) or CPU
- 8GB+ RAM
- 6GB+ VRAM (for GPU training)
git clone https://github.com/yourusername/intrutect.git
cd intrutectpip install -r requirements.txttorch>=2.0.0- Deep learning frameworkpandas>=2.0.0- Data manipulationnumpy>=1.24.0- Numerical computingscikit-learn>=1.3.0- Machine learning utilitiesimbalanced-learn>=0.11.0- SMOTE for balancingmatplotlib>=3.7.0- Visualizationseaborn>=0.12.0- Statistical visualizationtqdm>=4.65.0- Progress bars
Place the WSN-DS.csv file in the project root directory. The dataset will be automatically loaded and preprocessed.
Alternatively, the script can download the dataset from Kaggle using kagglehub:
pip install kagglehub[pandas-datasets]Run the complete training pipeline:
python train_idfswsn_drl.pyThis will:
- Load and preprocess the WSN-DS dataset
- Apply robust scaling and SMOTE balancing
- Perform feature selection using GOA (saves checkpoint for faster reruns)
- Optimize hyperparameters using CFA
- Train the TCN-MHA model with early stopping
- Generate comprehensive training visualizations
- Save the trained model checkpoint
After training, evaluate the model on the test set:
python evaluate_model.pyThis generates:
- Confusion matrix
- ROC curves
- Per-class performance metrics
- Detailed classification report
- JSON and pickle files with all metrics
To understand the dataset features:
python load_wsn_ds.py --explainThe model achieved excellent performance on the WSN-DS dataset:
- Validation Accuracy: 99.09%
- F1-Score (Weighted): 0.99+
- Best Epoch: 8 (with early stopping)
- Training Time: ~15-20 minutes (on GTX 1660 Ti)
The comprehensive training dashboard shows:
Key Observations:
- Model reached peak performance at epoch 8
- Early stopping prevented overfitting
- Learning rate schedule optimized convergence
- Minimal generalization gap at best epoch
The confusion matrix shows excellent per-class performance:
intrutect/
βββ train_idfswsn_drl.py # Main training script
βββ evaluate_model.py # Model evaluation script
βββ load_wsn_ds.py # Dataset loading and preprocessing
βββ idfswsn_drl_preprocessing.py # Robust preprocessing module
βββ idfswsn_drl_goa.py # Gazelle Optimization Algorithm
βββ idfswsn_drl_cfa.py # Catch Fish Optimization Algorithm
βββ idfswsn_drl_model.py # TCN-MHA model architecture
βββ requirements.txt # Python dependencies
βββ README.md # This file
β
βββ Data/
β βββ WSN-DS.csv # WSN-DS dataset (not included)
β
βββ Checkpoints/
β βββ idfswsn_drl_model.pth # Trained model checkpoint
β βββ goa_results.pkl # GOA feature selection results
β βββ training_history.pkl # Training history
β
βββ Results/
βββ training_history.png # Comprehensive training dashboard
βββ loss_curve.png # Loss visualization
βββ accuracy_curve.png # Accuracy visualization
βββ confusion_matrix.png # Confusion matrix
βββ evaluation_results.json # Evaluation metrics (JSON)
βββ evaluation_results_full.pkl # Full evaluation results
- Robust Scaling: Uses median and IQR instead of mean/std (resilient to outliers)
- SMOTE: Synthetic Minority Oversampling Technique for class balancing
- Train/Val/Test Split: 80/10/10 stratified split
The Gazelle Optimization Algorithm selects the most discriminative features:
- Selected Features: 6 out of 18 original features
- Best Feature:
ADV_S(Advertisement Sent) - strongest indicator of flooding attacks - Fitness-Based Selection: Optimizes classification performance
The Catch Fish Optimization Algorithm optimizes:
- Learning rate
- Batch size
- Dropout rate
- Kernel size
- Number of attention heads
- TCN channel configurations
TCN-MHA Components:
- Temporal Blocks: Dilated causal convolutions for temporal dependencies
- Multi-Head Attention: Parallel attention mechanisms for feature weighting
- Global Pooling: Aggregates temporal information
- Classification Head: Softmax output for 5-class prediction
The framework detects five distinct attack patterns:
- Normal: Standard legitimate network operation
- Blackhole: Malicious node drops ALL packets
- Grayhole: Malicious node drops packets SELECTIVELY (more sophisticated)
- Flooding: Exhausts energy by sending excessive control messages
- TDMA: Disrupts time-slotted communication schedule
Key features for attack detection:
ADV_S(Advertisement Sent) - Best indicator for flooding attacksExpaned Energy- Critical for energy-draining attack detectionIs_CH(Cluster Head status) - Role-based attack patternsData_Sent_To_BS- Forwarding behavior analysis
- CPU: Multi-core processor (AMD Ryzen 4000+ or equivalent)
- RAM: 8GB
- Storage: 2GB free space
- GPU: Optional (CPU training supported but slower)
- CPU: AMD Ryzen 4000 Series 7 or equivalent
- GPU: NVIDIA GTX 1660 Ti (6GB VRAM) or better
- RAM: 16GB
- Storage: 5GB free space
- Mixed precision training (FP16) for faster GPU training
- Batch size optimization for 6GB VRAM
- Memory-efficient data loading
- Progress bars for all long-running operations
| Metric | Value |
|---|---|
| Best Validation Accuracy | 99.09% |
| Best Epoch | 8 |
| Total Training Time | ~15-20 min |
| Early Stopping | Yes (patience=10) |
| Final F1-Score (Weighted) | 0.99+ |
- Feature Selection: ~7 minutes (with checkpoint saving)
- Hyperparameter Tuning: ~20-30 minutes
- Model Training: ~10-15 minutes (50 epochs max, early stopping at epoch 8)
- Evaluation: ~2-3 minutes
Edit train_idfswsn_drl.py to customize:
# Early stopping
early_stopping_patience = 10
early_stopping_min_delta = 0.001
# Training epochs
num_epochs = 50
# GOA parameters
n_gazelles = 30
max_iterations = 50
# CFA parameters
n_fish = 12
max_iterations = 15Modify idfswsn_drl_model.py to adjust:
- Number of TCN layers
- Attention heads
- Dropout rates
- Sequence length
If you use this code in your research, please cite:
@software{intrutect2025,
title={IntruTect: Intrusion Detection Framework for Wireless Sensor Networks},
author={Pranav, Harshit},
year={2025},
url={https://github.com/aharshit123456/intrutect}
}Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.
- 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
This project is licensed under the MIT License - see the LICENSE file for details.
- WSN-DS Dataset: Bassam Kasasbeh et al. for providing the WSN-DS dataset
- LEACH Protocol: Original LEACH protocol researchers
- PyTorch Community: For the excellent deep learning framework
- Open Source Libraries: All contributors to the open-source packages used
For questions, issues, or collaborations:
- GitHub Issues: Open an issue
- Email: aharshit123456@gmail.com
- Support for additional WSN datasets (WSN-BFSF, IDSAI)
- Real-time intrusion detection capabilities
- Model compression for edge deployment
- Integration with WSN simulators
- Web-based dashboard for monitoring
β Star this repo if you find it useful! β
Made with β€οΈ for the WSN Security Community





