Deep Learning · Cybersecurity

Transparent Intrusion Detection via Explainable LSTM–HMM Hybrid

SHAP and LIME-based interpretability for deep learning IDS — bridging the gap between detection accuracy and human-understandable reasoning.

DatasetCIC-Darknet2020
KeywordsXAI · IDS · LSTM · HMM · SHAP · LIME
0 % Accuracy
0 Macro F1-Score
0 Cross-Val Folds
0 Flow Records

The Black-Box
Transparency Crisis

Modern networks face increasingly sophisticated cyber threats. While deep learning-based IDS achieve impressive detection rates, their opaque nature creates a critical trust and compliance barrier in security operations.

$9.4T
Projected global cybercrime cost by 2025
43%
Of attacks target small/mid businesses unable to interpret IDS alerts
300K+
New malware variants detected daily, outpacing signature-based systems
<0.1%
False positive tolerance in finance & healthcare IDS deployments
🔒

Signature-Based Systems Fail

Traditional HIDS and NIDS rely on known attack signatures — rendering them blind to zero-day exploits and advanced persistent threats (APTs) that evolve faster than rules can be written.

🧠

Deep Learning = Black Box

CNNs and RNNs achieve 94–98% detection rates but offer no actionable reasoning. Security analysts cannot understand why a packet was flagged — eroding trust and creating compliance nightmares.

⚖️

Regulatory & Operational Pressure

Finance, defence, and healthcare sectors face legal accountability requirements. Non-interpretable models are unacceptable risks — decisions must be auditable and justifiable.

📊

Class Imbalance & Concept Drift

Real-world traffic data is highly imbalanced. Attack patterns evolve continuously (concept drift), causing models trained on historical data to degrade in performance over time without transparent diagnostics.

Threat Detection Gap — Signature vs. ML vs. Deep Learning

Signature-based IDS~60% known threats
Traditional ML (SVM/RF)~85% detection
Deep Learning (CNN/LSTM)~97% detection
LSTM-HMM + XAI (Ours)99.17% + interpretable

LSTM–HMM Hybrid with
Dual-Layer Explainability

A novel architecture fusing temporal sequence modeling with probabilistic state transitions — delivering both state-of-the-art detection and human-understandable reasoning through SHAP and LIME.

Our approach addresses the core tension in IDS design: performance vs. interpretability. Instead of choosing one, we engineer a system that excels at both.

The stacked LSTM encoder captures short-term temporal dependencies across consecutive network flows — learning subtle behavioral patterns within traffic sessions that signature-based rules cannot express.

The Hidden Markov Model operates on LSTM embeddings to model long-range sequential dynamics and probabilistic state transitions — providing an interpretable representation of how network behavior evolves, detecting multi-stage stealthy attacks invisible to frame-level models.

Finally, post-hoc SHAP + LIME explainers illuminate the model's reasoning — translating complex embeddings into feature-level attributions that security analysts can act on.

System Architecture Pipeline
🌐

Raw Network Flows (Darknet.csv)

158K+ flow records: Non-Tor, Non-VPN, Tor, VPN traffic — 79 statistical features per flow

⚙️

Preprocessing & Feature Engineering

Label encoding, Min-Max scaling, sliding window (size=8, stride=1) → shape (n, 8, 79)

🔄

Stacked LSTM Encoder

2 LSTM layers (64→32 units), Dropout ≈0.2, Adam optimizer, categorical cross-entropy, EarlyStopping @ epoch 9-10

📈

Hidden Markov Model Layer

Latent state transitions on LSTM embeddings; Viterbi paths; diagonal-dominant transition matrix (0.87–0.90)

🔍

XAI: SHAP + LIME Explainers

Global feature importance (SHAP) + local instance-level diagnosis (LIME) for every alert

🛡️

Analyst Dashboard & Alert

Actionable output with reasoning: which features drove detection, latent state, anomaly score

LSTM Encoder

Temporal Sequence Learning

A stacked two-layer LSTM architecture that processes sliding windows of network flows, learning temporal dependencies invisible to stateless classifiers.

64 units (layer 1) → 32 units (layer 2)
Sliding window size = 8 timesteps
Dropout 0.2 for regularization
EarlyStopping at epoch 9–10 (≈99% acc)
ReduceLROnPlateau for stable convergence
HMM Layer

Probabilistic State Modeling

A Hidden Markov Model fitted on LSTM embeddings, capturing latent behavioral states and their transition probabilities across network sessions.

K latent states (learned from data)
Diagonal-dominant matrix (0.87–0.90)
Viterbi algorithm for state path decoding
Anomaly scoring: top 5% flagged (7,928 flows)
Concept drift resistance via regime detection
XAI Layer

Dual Explainability Engine

Post-hoc model-agnostic explainers (SHAP + LIME) that translate complex model decisions into human-understandable feature attributions.

SHAP: global + local feature importance
LIME: per-alert surrogate linear model
Top signals: packet burstiness, flow duration
Protocol handshake indicators as key features
Temporal heatmaps for time-window diagnosis
📊

SHAP

SHapley Additive exPlanations

SHAP computes Shapley values rooted in cooperative game theory — fairly distributing the "credit" of a prediction across all features. It provides both global model-level insight and per-instance attribution, making it possible to ask: "Across all alerts, which features matter most?"

Our SHAP analysis consistently surfaces packet size evolution, flow duration, and protocol handshake patterns as the dominant discriminators between malicious and benign traffic.

Top SHAP Feature Contributions
Packet Burstiness0.87
Flow Duration0.74
Protocol Handshake Indicators0.68
Packet Size Variation0.62
Inter-Arrival Time0.51
🔬

LIME

Local Interpretable Model-agnostic Explanations

LIME focuses on individual predictions — perturbing a single network flow's features and fitting a simple linear surrogate model to approximate the complex model locally. The result: a per-alert explanation that tells an analyst exactly why this specific packet was flagged.

LIME's temporal heatmaps confirm SHAP's global rankings — anomalies are frequently caused by temporary flow spurts or uneven handshaking intervals within specific time windows.

LIME Instance-Level Attribution (Sample Alert)
Burst at t=5 (Flow Feature 23)+0.92
Unusual IAT at t=3 (Feature 41)+0.78
SYN Flood Pattern (Feature 7)+0.65
Flow Duration (Feature 2)+0.54
Normal Traffic Indicator (Feature 19)−0.41
0
Accuracy
Avg. over 3 folds
0
Precision
±0.0008 SD
0
Recall
±0.0009 SD
0
F1-Score
Macro average
3-Fold Cross-Validation Results on Darknet.csv
Fold Accuracy Precision Recall F1-Score Training Time
Fold 1 0.9914 0.9816 0.9821 0.9818 10.42 min
Fold 2 0.9918 0.9822 0.9813 0.9818 10.53 min
Fold 3 0.9920 0.9835 0.9834 0.9835 10.83 min
Mean ± SD 0.9917 ± 0.0003 0.9824 ± 0.0008 0.9823 ± 0.0009 0.9824 ± 0.0009 31.78 min total
🛡 Live IDS Simulation
Model Active
00:00:01LSTM-HMM initialized. Loading model weights...
00:00:02Model loaded. HMM transition matrix verified (6 latent states).
00:00:03Monitoring network traffic on interface eth0...

State of the Art in
Deep Learning IDS

Prior work has demonstrated impressive detection rates but consistently falls short on interpretability, generalizability, or both — creating a fragmented landscape where accuracy and transparency are treated as competing goals.

CNN + LSTM

98.42% acc
CICIoT2023 + CICIDS2017

Combines CNN for spatial feature extraction with LSTM for temporal modeling. Achieves state-of-the-art detection through complementary spatial+temporal representations.

No XAI integration. Black-box decisions reduce analyst trust and compliance viability.

Attention-CNN + LSTM

94.8–97.5%
NSL-KDD + Bot-IoT

Adds an attention mechanism to CNN-LSTM, helping the model focus on relevant temporal segments. Shows improved generalization across diverse network environments.

Attention weights ≠ human-interpretable explanations. No instance-level reasoning for security analysts.

FedXAIIDS (ANN + SHAP)

88.2% acc
CICIoT2023

Federated learning with SHAP global explanations. Pioneering privacy-preserving IDS with model interpretability — suitable for distributed enterprise environments.

No temporal modeling (ANN only). Global SHAP lacks instance-level explanations. Lower accuracy trade-off.

LSTM + SPIP Pipeline

~96% acc
NSL-KDD + UNSW-NB15 + TON_IoT

LSTM with SHAP+PDP+ICE explainability pipeline (SPIP). Excellent interpretable temporal IDS for IoT environments with both local and global explanations.

IoT-specific. No generalization to encrypted traffic (VPN/Tor). No probabilistic state modeling.

Hybrid Adaptive Ensemble

~97% acc
CIC/IDS Datasets

Ensemble of ML models with SHAP/LIME interpretation. High detection with strong feature ranking for debugging and model improvement workflows.

Statistical ensemble — cannot capture temporal sequence dependencies. Inferior on evolving attack patterns and concept drift.

L-XAIDS (LIME Framework)

~95% acc
UNSW-NB15 + Others

LIME-centered production-ready explainability framework. Demonstrates local interpretability at scale, with supplementary SHAP for global insight.

Single XAI method primary. No HMM for state transition modeling or detection of multi-stage attacks.

How Our System
Outperforms the Field

A head-to-head comparison across the dimensions that matter most for real-world IDS deployment: accuracy, interpretability, temporal modeling, generalizability, and deployment readiness.

Model Accuracy Temporal XAI Local XAI Global VPN/Tor State Model Our LSTM-HMM ✦
CNN + LSTM (no XAI) 98.42% ✓ ✗ ✗ ~ ✗ +XAI, +HMM state
FedXAIIDS (ANN + SHAP) 88.2% ✗ ✗ ✓ ~ ✗ +11% accuracy, +LIME local
Attention-CNN + LSTM 94.8–97.5% ✓ ✗ ✗ ~ ✗ +Interpretable feature attribution
LSTM + SPIP (IoT) ~96% ✓ ✓ ✓ ✗ ✗ +Encrypted traffic, +HMM
Ensemble + SHAP/LIME ~97% ✗ ✓ ✓ ~ ✗ +Temporal modeling, +HMM states
LSTM-HMM + SHAP+LIME (Ours) 99.17% ✓ ✓ ✓ ✓ ✓ Complete solution

🏆 Dual XAI Coverage

Only system providing both SHAP (global feature importance) and LIME (instance-level attribution) in combination with deep temporal modeling — enabling analysts to understand both model-wide behavior and individual alert reasoning.

🔒 Encrypted Traffic Generalization

Cross-traffic adaptability across Non-Tor, Non-VPN, Tor, and VPN flows — unlike IoT-specific or non-encrypted-only baselines. Critical for modern enterprise networks where encrypted channels dominate.

📊 Probabilistic State Awareness

The HMM layer models latent behavioral regime transitions with a strongly diagonal matrix (0.87–0.90) — detecting multi-stage attacks that span multiple temporal states, invisible to frame-level classifiers.

Known Challenges
& Deployment Constraints

Honest assessment of the system's current constraints — understanding these limitations is essential for responsible deployment and drives our future research agenda.

⚖️

Class Imbalance

Minority classes (Tor and VPN traffic) show lower recall despite stratified 70/15/15 splitting and class weighting. Rare attack categories may require targeted augmentation — GAN-based synthetic generation or SMOTE oversampling — to achieve robust minority-class detection.

⚡

Computational Overhead

The combined LSTM + HMM + SHAP/LIME pipeline is computationally intensive. Training totals ~31.78 minutes; inference plus explanation generation may not meet sub-second SLAs required for high-throughput network monitoring without hardware acceleration.

⏱️

Explainability Latency

SHAP and LIME add non-trivial inference latency per alert. Real-time deployment requires approximate explainers (FastSHAP, SHAP sampling), selective explanation policies (explain only high-confidence alerts), or pre-computed surrogate models to maintain throughput.

💾

HMM Memory Scalability

HMM fitting on high-dimensional LSTM embeddings scales poorly in memory for very large deployment contexts. Low-resource edge devices or embedded IDS systems cannot accommodate the current HMM footprint without model compression or quantization.

🔀

Explanation Instability

LIME's perturbation-based approach can produce inconsistent attributions across runs for borderline samples. SHAP kernel approximations also carry variance. Stability must be empirically verified across multiple explanation runs before analyst-facing deployment.

🌐

Single Dataset Validation

Evaluation is limited to CIC-Darknet2020 (Darknet.csv). Transferability to UNSW-NB15, NSL-KDD, CICIDS2017, or live enterprise traffic is assumed but unverified. Cross-dataset benchmarking is a critical next step for production readiness claims.

Where This Technology
Makes Impact

Explainable IDS has transformative potential across high-stakes industries where alert reasoning is as critical as detection rate — enabling trust, compliance, and human-AI collaboration at scale.

🏦

Financial Services

PCI-DSS and regulatory compliance demands auditable IDS decisions. Explainability enables forensic-grade incident reports that satisfy regulators and reduce liability.

🏥

Healthcare Networks

HIPAA-protected medical IoT demands both accuracy and transparency. Clinicians and compliance officers need to understand why patient data systems trigger alerts.

🏛️

Government & Defence

APT detection in critical infrastructure requires not just detection but attribution. XAI enables threat hunting teams to trace attack chains and build actionable intelligence.

☁️

Cloud & SaaS Platforms

Multi-tenant cloud environments with diverse encrypted traffic (VPN/Tor) benefit directly from our cross-traffic generalization — detecting lateral movement across service boundaries.

🏭

Industrial IoT (IIoT)

OT/IT convergence in smart factories creates novel attack surfaces. HMM-based state modeling excels at detecting multi-stage process manipulation invisible to stateless classifiers.

🎓

Security Training & SOC

SHAP/LIME explanations serve as real-time pedagogical tools in Security Operations Centers — helping junior analysts understand attack patterns through concrete feature attributions.

🔬

Cyber Threat Research

SHAP's consistent identification of discriminative features (burstiness, handshake timing) provides hypothesis generation for malware researchers and threat intelligence teams.

🌐

Darknet & Tor Monitoring

Validated directly on CIC-Darknet2020 — effective discrimination between Tor, VPN, Non-Tor, Non-VPN traffic enables ISP-level and law enforcement darknet activity monitoring.

The Road Ahead —
Research Frontiers

Five high-impact research directions that will extend the current system toward production-ready, federated, and privacy-preserving explainable intrusion detection.

01

Runtime-Efficient XAI

Replace full SHAP/LIME with FastSHAP approximations, surrogate tree models, or learned explanation networks. Implement selective explanation policies — explain only high-confidence anomalies or novel alert categories — to achieve real-time throughput without sacrificing interpretability quality.

02

Cross-Dataset External Validation

Benchmark on UNSW-NB15, NSL-KDD, CICIDS2017/2018, and live enterprise traffic captures. Stress-test transferability across different network environments, attack taxonomies, and traffic distributions to validate generalizability claims beyond Darknet.csv.

03

Federated & Privacy-Preserving XAI-IDS

Adapt the architecture for federated learning — training across distributed organizational nodes without sharing raw network flows. Implement differentially private SHAP summaries that provide global insight without exposing sensitive enterprise traffic patterns to central coordinators.

04

Advanced Sequence Models

Experiment with Transformer architectures (self-attention over flow sequences) and Graph Neural Networks (relational modeling of network topology) as LSTM replacements or complements. Evaluate interpretability-accuracy trade-offs and develop GNN-compatible explanation methods for graph-structured network data.

05

Human-in-the-Loop SOC Integration

Conduct formal analyst user studies measuring triage speed, decision quality, and trust calibration with vs. without SHAP/LIME explanations. Develop HITL feedback loops where analyst corrections refine the explanation model and inform active learning for continuous model improvement in production.

Bridging Detection Power
& Human Trust

This work demonstrates that the long-standing tension between detection performance and model interpretability in IDS design is not a fundamental trade-off — it is an engineering challenge with a solution.

Our LSTM-HMM hybrid achieves 99.17% accuracy and macro F1 ≈ 0.985 across three stratified folds on the CIC-Darknet2020 dataset — matching or exceeding state-of-the-art deep learning IDS while simultaneously providing two layers of explainability.

SHAP reveals that packet burstiness, flow duration, and protocol handshake patterns are the dominant discriminators between malicious and benign traffic — insights that enable security analysts to build mental models of attack behavior and improve their threat hunting intuition.

LIME's temporal heatmaps provide instance-level diagnosis — each alert comes with a reasoning trace that explains exactly which network features, at which timestep, drove the classification decision.

The HMM layer adds a dimension of behavioral regime modeling that makes the system robust to multi-stage attacks and concept drift — a capability absent from all comparable single-model approaches.

Deep sequence learning with dual explainability provides a viable and robust IDS — one that maintains a principled balance between the efficacy of detection and the transparency required for human trust and regulatory compliance.

— Jhawar, Grover et al., XAI-IDS Research, KIIT University 2025

✦ State-of-the-art accuracy

99.17% accuracy across all traffic types — Non-Tor, Non-VPN, Tor, VPN — on the Darknet benchmark with stable cross-validation performance (SD ±0.0003).

✦ Dual-layer interpretability

SHAP provides global model transparency. LIME provides per-alert reasoning. Together they address both compliance and operational trust requirements.

✦ Temporal regime modeling

HMM's diagonal-dominant transition matrix (0.87–0.90) captures stable behavioral states — enabling detection of multi-stage attacks that span multiple flow windows.

✦ Cross-traffic generalization

Validated on encrypted (Tor/VPN) and non-encrypted traffic simultaneously — the first XAI-IDS to demonstrate this breadth on the Darknet dataset.

✦ Actionable analyst output

Feature-level attributions give security teams concrete evidence for each alert — reducing mean time to triage and enabling evidence-based incident response.