Skip to content

Latest commit

Β 

History

1 Commit

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

IntruTect: Intrusion Detection Framework for Wireless Sensor Networks

Python PyTorch License

Advanced Deep Learning Framework for WSN Intrusion Detection using TCN-MHA Architecture

Features β€’ Installation β€’ Usage β€’ Results β€’ Architecture


πŸ“‹ Overview

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.

Key Highlights

  • 🎯 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

✨ Features

Core Components

  1. Robust Preprocessing

    • Median/IQR-based scaling (resilient to outliers)
    • SMOTE for class balancing
    • Label encoding and data splitting
  2. Feature Selection (GOA)

    • Nature-inspired metaheuristic algorithm
    • Reduces feature dimensionality from 18 to 6 critical features
    • Balances exploration and exploitation
  3. Hyperparameter Optimization (CFA)

    • Automatic tuning of learning rate, batch size, dropout, etc.
    • Optimizes TCN-MHA architecture parameters
  4. TCN-MHA Model

    • Temporal Convolutional Network for sequence learning
    • Multi-Head Attention for feature weighting
    • Handles long-range temporal dependencies
  5. Early Stopping & Monitoring

    • Automatic early stopping to prevent overfitting
    • Comprehensive training history tracking
    • Real-time progress bars

πŸ—οΈ Architecture

Input Data β†’ Robust Preprocessing β†’ GOA Feature Selection β†’ CFA Hyperparameter Tuning
                                                                    ↓
                                                          TCN-MHA Model Training
                                                                    ↓
                                                          Evaluation & Metrics

Model Architecture

Sequence Input β†’ TCN Layers (Dilated Convolutions) 
              β†’ Multi-Head Attention 
              β†’ Global Average Pooling 
              β†’ Fully Connected Layers 
              β†’ Softmax β†’ Classification (5 Classes)

πŸ“¦ Installation

Prerequisites

  • Python 3.8 or higher
  • CUDA-capable GPU (recommended) or CPU
  • 8GB+ RAM
  • 6GB+ VRAM (for GPU training)

Step 1: Clone the Repository

git clone https://github.com/yourusername/intrutect.git
cd intrutect

Step 2: Install Dependencies

pip install -r requirements.txt

Required Packages

  • torch>=2.0.0 - Deep learning framework
  • pandas>=2.0.0 - Data manipulation
  • numpy>=1.24.0 - Numerical computing
  • scikit-learn>=1.3.0 - Machine learning utilities
  • imbalanced-learn>=0.11.0 - SMOTE for balancing
  • matplotlib>=3.7.0 - Visualization
  • seaborn>=0.12.0 - Statistical visualization
  • tqdm>=4.65.0 - Progress bars

πŸš€ Usage

1. Dataset Preparation

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]

2. Training the Model

Run the complete training pipeline:

python train_idfswsn_drl.py

This will:

  1. Load and preprocess the WSN-DS dataset
  2. Apply robust scaling and SMOTE balancing
  3. Perform feature selection using GOA (saves checkpoint for faster reruns)
  4. Optimize hyperparameters using CFA
  5. Train the TCN-MHA model with early stopping
  6. Generate comprehensive training visualizations
  7. Save the trained model checkpoint

3. Evaluating the Model

After training, evaluate the model on the test set:

python evaluate_model.py

This generates:

  • Confusion matrix
  • ROC curves
  • Per-class performance metrics
  • Detailed classification report
  • JSON and pickle files with all metrics

4. Feature Explanations

To understand the dataset features:

python load_wsn_ds.py --explain

πŸ“Š Results

Training Performance

The model achieved excellent performance on the WSN-DS dataset:

Overall Metrics

  • Validation Accuracy: 99.09%
  • F1-Score (Weighted): 0.99+
  • Best Epoch: 8 (with early stopping)
  • Training Time: ~15-20 minutes (on GTX 1660 Ti)

Training History

The comprehensive training dashboard shows:

Training History

Key Observations:

  • Model reached peak performance at epoch 8
  • Early stopping prevented overfitting
  • Learning rate schedule optimized convergence
  • Minimal generalization gap at best epoch

Loss and Accuracy Curves

Loss Curve: Loss Curve

Accuracy Curve: Accuracy Curve

Class Distribution

Before Balancing: Class Distribution

After SMOTE Balancing: Balanced Distribution

Model Performance

The confusion matrix shows excellent per-class performance:

Confusion Matrix


πŸ“ Project Structure

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

πŸ”¬ Methodology

1. Data Preprocessing

  • 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

2. Feature Selection (GOA)

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

3. Hyperparameter Tuning (CFA)

The Catch Fish Optimization Algorithm optimizes:

  • Learning rate
  • Batch size
  • Dropout rate
  • Kernel size
  • Number of attention heads
  • TCN channel configurations

4. Model Architecture

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

🎯 Attack Types Detected

The framework detects five distinct attack patterns:

  1. Normal: Standard legitimate network operation
  2. Blackhole: Malicious node drops ALL packets
  3. Grayhole: Malicious node drops packets SELECTIVELY (more sophisticated)
  4. Flooding: Exhausts energy by sending excessive control messages
  5. TDMA: Disrupts time-slotted communication schedule

Feature Importance

Key features for attack detection:

  • ADV_S (Advertisement Sent) - Best indicator for flooding attacks
  • Expaned Energy - Critical for energy-draining attack detection
  • Is_CH (Cluster Head status) - Role-based attack patterns
  • Data_Sent_To_BS - Forwarding behavior analysis

πŸ’» System Requirements

Minimum Requirements

  • CPU: Multi-core processor (AMD Ryzen 4000+ or equivalent)
  • RAM: 8GB
  • Storage: 2GB free space
  • GPU: Optional (CPU training supported but slower)

Recommended (for Training)

  • CPU: AMD Ryzen 4000 Series 7 or equivalent
  • GPU: NVIDIA GTX 1660 Ti (6GB VRAM) or better
  • RAM: 16GB
  • Storage: 5GB free space

Optimizations

  • 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

πŸ“ˆ Performance Benchmarks

Training Metrics

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+

Computational Efficiency

  • 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

πŸ”§ Configuration

Training Parameters

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 = 15

Model Architecture

Modify idfswsn_drl_model.py to adjust:

  • Number of TCN layers
  • Attention heads
  • Dropout rates
  • Sequence length

πŸ“ Citation

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}
}

🀝 Contributing

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.

Contribution Guidelines

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.


πŸ™ Acknowledgments

  • 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

πŸ“§ Contact

For questions, issues, or collaborations:


πŸ—ΊοΈ Roadmap

  • 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

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages