Development of an AI-Assisted Software for Network Traffic Analysis and Threat Detection
تطوير برنامج مدعوم بالذكاء الاصطناعي لتحليل حركة الشبكة واكتشاف التهديدات
By
عبدالرحمن سالمجامعة أسكودار، إسطنبول (رسالة ماجستير في الأمن السيبراني)
Advisor
د. سليم جبرين دانباتا
Published
Reading time
142 min
APA citation
عبدالرحمن سالم. (2026). Development of an AI-Assisted Software for Network Traffic Analysis and Threat Detection. Saudi Journal for Young Researchers, 1(1). https://www.marsajournal.com/articles/e009
Select any passage of the text and Deema will explain it.
Abstract
Cyber threats are growing fast in scale and sophistication, and signature-based intrusion detection cannot keep up with attacks it has never seen. This thesis builds and evaluates an AI-assisted framework for network traffic analysis, comparing Random Forest, a CNN, and an LSTM on CIC-IDS2017 and UNSW-NB15. Random Forest reaches the highest within-dataset accuracy (99.89% and 94.67%), but when trained on CIC-IDS2017 and tested on UNSW-NB15, LSTM generalizes best, with 70.07% accuracy and 74.67% AUC-ROC, well ahead of Random Forest (36.09%) and CNN (39.78%). The framework also integrates four locally deployed large language models through LM Studio, explaining threats in plain language inside a Streamlit dashboard with no data leaving the machine. A SHAP-based explainability analysis traces the cross-dataset gap to features that carry different physical scales in the two datasets.
تتزايد التهديدات السيبرانية حجمًا وتعقيدًا، ولا تستطيع أنظمة كشف التسلل المعتمدة على التواقيع مجاراة هجمات لم ترها من قبل. تبني هذه الرسالة إطارًا مدعومًا بالذكاء الاصطناعي لتحليل حركة الشبكة، وتقارن ثلاثة نماذج: الغابة العشوائية، والشبكة الالتفافية (CNN)، وشبكة الذاكرة طويلة وقصيرة المدى (LSTM)، على مجموعتي البيانات CIC-IDS2017 وUNSW-NB15. حققت الغابة العشوائية أعلى دقة داخل المجموعة الواحدة (99.89% و94.67%)، لكن عند التدريب على مجموعة والاختبار على الأخرى كانت LSTM الأقدر على التعميم بدقة 70.07%، متقدمة كثيرًا على الغابة العشوائية (36.09%) وCNN (39.78%). ويدمج الإطار أربعة نماذج لغوية كبيرة تعمل محليًا تشرح التهديدات بلغة بسيطة داخل لوحة تحكم، دون أن تغادر البيانات الجهاز. ويُرجع تحليل التفسير (SHAP) فجوة التعميم إلى خصائص تختلف مقاييسها الفيزيائية بين المجموعتين.
The rapid growth of internet-connected devices has led to a significant increase in network traffic, creating a more complex and high-risk cybersecurity environment. As a result, modern organizations are increasingly exposed to a wide range of cyberattacks such as DDoS, port scanning, brute-force attacks, and persistent threats, regardless of their size or sector. Recent studies estimate that cybercrime now costs the global economy trillions of dollars annually, highlighting the urgent need for more effective network security solutions.
Traditional intrusion detection systems (IDS) mainly rely on signature-based and rule-based techniques. While these methods are effective in detecting known attacks, they struggle significantly when dealing with unknown, modified, or zero-day attacks. In addition, the massive volume of network traffic makes real-time detection difficult, and the rigid nature of rule-based systems requires continuous manual updates to remain effective.
To address these limitations, machine learning and deep learning techniques have become an important alternative for intrusion detection. Unlike traditional methods, these approaches can automatically learn complex patterns from network data and adapt to different attack behaviors. This research investigates the effectiveness of three machine learning models: Random Forest, Convolutional Neural Network (CNN), and Long Short-Term Memory (LSTM) for detecting network intrusions and evaluating their performance under different network environments.
1.2Problem Statement
Despite significant progress in machine learning-based intrusion detection systems, several important limitations remain in the current research. Most existing studies evaluate their models using only a single benchmark dataset, which raises questions about how well these results can generalize to different network environments. In addition, the trade-off between detection performance and computational efficiency is often overlooked, particularly in scenarios that require real-time deployment. Another key limitation is the lack of usability for non-expert users, which creates a gap between advanced IDS models and practical security operations.
This thesis addresses these limitations in three main ways. First, it performs a comprehensive evaluation of three machine learning models across two different benchmark datasets with distinct feature spaces and attack types, in order to better assess generalization capability. Second, it analyzes model performance using multiple evaluation metrics, including accuracy, F1-score, AUC-ROC, confusion matrix analysis, and training time. Third, it integrates a locally deployed Large Language Model (LLM) to improve usability by generating clear, natural-language explanations of detected threats.
References
Binbusayyis, A., & Vaiyapuri, T. (2019). Identifying and benchmarking key features for cyber intrusion detection: An ensemble approach. IEEE Access, 7, 106495-106513.
Breiman, L. (2001). Random forests. Machine Learning, 45(1), 5-32.
Cantone, M., Marrocco, C., & Bria, A. (2024). On the cross-dataset generalization of machine learning for network intrusion detection. arXiv preprint arXiv:2402.10974.
Denning, D. E. (1987). An intrusion-detection model. IEEE Transactions on Software Engineering, SE-13(2), 222-232.
Ferrag, M. A., Friha, O., Hamouda, D., Maglaras, L., & Janicke, H. (2023). From ChatGPT to ThreatGPT: Impact of generative AI in cybersecurity and privacy. IEEE Access, 11, 80218-80245.
Gemma Team, Google. (2024). Gemma: Open models based on Gemini research and technology. arXiv preprint arXiv:2403.08295.
Grinsztajn, L., Oyallon, E., & Varoquaux, G. (2022). Why tree-based models still outperform deep learning on tabular data. Advances in Neural Information Processing Systems, 35, 507-520.
Hassanin, M. (2026). KAN-LSTMss: Benchmarking Kolmogorov-Arnold Networks for cyber security threat detection in IoT networks. arXiv preprint arXiv:2603.28985.
Hochreiter, S., & Schmidhuber, J. (1997). Long short-term memory. Neural Computation, 9(8), 1735-1780.
Hossain, M. Z., Khan, M. A. R., Islam, M. R., Islam, S. M. S., & Gedeon, T. (2026). Assessing generalisation capability of machine learning models for intrusion detection. arXiv preprint arXiv:2605.04407.
Javaid, A., Niyaz, Q., Sun, W., & Alam, M. (2016). A deep learning approach for network intrusion detection system. Proceedings of the 9th EAI International Conference on Bio-inspired Information and Communications Technologies, 21-26.
Jiang, K., Wang, W., Wang, A., & Wu, H. (2020). Network intrusion detection combined hybrid sampling with deep hierarchical network. IEEE Access, 8, 32464-32476.
Kim, J., Kim, J., Thu, H. L. T., & Kim, H. (2016). Long short term memory recurrent neural network classifier for intrusion detection. In 2016 International Conference on Platform Technology and Service (PlatCon) (pp. 1-5). IEEE.
LeCun, Y., Bottou, L., Bengio, Y., & Haffner, P. (1998). Gradient-based learning applied to document recognition. Proceedings of the IEEE, 86(11), 2278-2324.
Lee, W., & Stolfo, S. J. (1998). Data mining approaches for intrusion detection. Proceedings of the 7th USENIX Security Symposium, 79-94.
Lundberg, S. M., & Lee, S. I. (2017). A unified approach to interpreting model predictions. Advances in Neural Information Processing Systems, 30, 4765-4774.
Published under CC BY 4.0; the author keeps the rights to the work.MARSA 1(1)
To develop an AI-assisted network traffic analysis framework that processes CICFlowMeter-extracted flow data from the CIC-IDS2017 and UNSW-NB15 benchmark datasets, and deploys trained machine learning models through an interactive Streamlit dashboard for network intrusion detection.
To train and compare three models: Random Forest as a baseline, CNN, and LSTM, for classifying traffic as either normal or malicious.
To test these models on two different datasets, CIC-IDS2017 and UNSW-NB15, and see how they perform across different network environments.
To add a locally running LLM that can explain detected threats in simple, human readable language.
To create an interactive dashboard that shows live logs, lets the user choose models, and provides AI-based analysis.
1.4Research Questions
This study tries to answer the following questions:
RQ1: Which model (Random Forest, CNN, or LSTM) gives the best balance between accuracy and efficiency in intrusion detection?
RQ2: How much does model performance change when tested on different datasets with different structures and features?
RQ3: Can a locally deployed LLM actually help in explaining IDS alerts in a useful and understandable way?
RQ4: Why do the trained models generalize so differently across datasets, and can an explainability technique such as SHAP reveal the mechanism behind it?
1.5Scope and Limitations
This work focuses on detecting whether network traffic is normal or malicious using flow-based features from two public datasets.
The system is designed for standard IPv4 network environments.
It does not cover:
detailed attack type classification (multi-class detection)
full production-level deployment with live packet processing at scale
IoT or mobile network traffic scenarios
1.6Thesis Structure
The remainder of this thesis is organized as follows. Chapter 2 reviews the related work in network intrusion detection and the use of machine learning, deep learning, and large language models in cybersecurity. Chapter 3 explains the datasets used in this study, along with the preprocessing steps, model architectures, evaluation metrics, and the overall system setup.
Chapter 4 presents the experimental results and compares the performance of the different models on the benchmark datasets. Chapter 5 discusses these results and relates them to previous research. Chapter 6 concludes the thesis by summarizing the main findings, contributions, and possible future improvements.
Cross-dataset generalization experiments are presented in Section 4.5, examining how models trained on one network environment perform when tested on another using a shared 15-feature representation. Section 4.6 introduces temporal sequence learning, where network flows are treated as ordered sequences to study whether explicit time context improves detection performance. The locally deployed LLM-based explanation layer and real-time monitoring dashboard are assessed in Section 5.6. Section 4.8 and Section 5.8 then apply SHAP based explainability analysis to these cross-dataset and temporal results, identifying the mechanism behind the generalization gap and revisiting the feature importance findings introduced in Section 3.6.
2Literature Review
2.1Introduction
This chapter reviews existing research in the areas of network intrusion detection, machine learning-based threat analysis, and the application of deep learning techniques in cybersecurity. It is organized to provide the necessary background for the methodological decisions made in this thesis and to highlight the key research gaps that motivate the proposed work.
2.2Traditional Intrusion Detection Systems
Intrusion Detection Systems (IDS) are generally divided into two main approaches: misuse detection (signature-based) and anomaly-based detection. Scarfone and Mell (2007) present a well-known taxonomy of IDS in the NIST guideline, where systems are categorized into network-based IDS (NIDS), host-based IDS (HIDS), and hybrid approaches depending on the monitoring location and architecture.
Signature-based detection systems are highly effective at identifying known attack patterns and typically achieve low false positive rates. However, as highlighted by Scarfone and Mell (2007), their main limitation is their inability to detect previously unseen or zero-day attacks unless their signature databases are continuously updated.
In contrast, anomaly-based detection, first formally introduced by Denning (1987), is based on learning a profile of normal system or network behavior and identifying deviations from this baseline as potential intrusions. While this approach is theoretically capable of detecting unknown attacks, early implementations often suffered from high false positive rates and significant computational cost.
To address these limitations, researchers began exploring more data-driven techniques. Lunt (1993) introduced one of the earliest statistical approaches to anomaly detection, laying the groundwork for later machine learning-based IDS systems. Building on this direction, Lee and Stolfo (1998) demonstrated that data mining techniques could be effectively applied to network audit data, achieving strong results on the KDD Cup 1999 dataset, which remained one of the most widely used benchmarks in intrusion detection research for many years.
2.3Machine Learning for Intrusion Detection
The use of classical machine learning techniques in intrusion detection systems (IDS) has been widely explored in the literature. Tsai et al. (2009) provide a comprehensive overview of machine learning approaches applied to IDS, including decision trees, support vector machines, neural networks, and ensemble learning methods. Their study shows that ensemble techniques generally perform better in handling the complexity and high dimensionality of network traffic data, particularly in comparison to single-model approaches.
One of the most influential ensemble methods is Random Forest, introduced by Breiman (2001). This algorithm builds multiple decision trees using bootstrap aggregation (bagging) and combines their outputs to produce a more stable and accurate classifier. Due to its robustness against overfitting, ability to handle high-dimensional datasets, and the added benefit of feature importance analysis, Random Forest has become a widely used baseline model in intrusion detection research. Jiang et al. (2020) further confirm its strong performance on benchmark IDS datasets, showing that it achieves competitive accuracy while maintaining efficient training times suitable for practical use.
Support Vector Machines (SVM) have also been extensively studied in IDS applications. Mukkamala et al. (2002) demonstrate that SVMs can achieve high detection accuracy on benchmark datasets such as KDD99 while maintaining relatively low false positive rates. However, despite their strong theoretical performance, SVMs tend to scale poorly with large datasets, which limits their practicality in modern real-time network environments where data volumes are significantly higher.
2.4Deep Learning Approaches
The rise of deep learning has significantly advanced the field of intrusion detection by enabling models to automatically learn complex patterns from raw or minimally processed network data. Convolutional Neural Networks (CNNs), originally designed for image recognition tasks (LeCun et al., 1998), have been successfully adapted for one-dimensional sequence and tabular data, making them suitable for analyzing network traffic flows.
Early work by Javaid et al. (2016) was among the first to explore deep learning for intrusion detection, showing that learned feature representations can outperform traditional manual feature engineering methods. Building on this idea, Kim et al. (2016) demonstrated that Long Short-Term Memory (LSTM) recurrent neural networks applied directly to network flow features can achieve performance comparable to classical models such as Random Forest, while capturing temporal dependencies between consecutive network flows.
Recurrent architectures, particularly Long Short-Term Memory (LSTM) networks introduced by Hochreiter and Schmidhuber (1997), were designed to address the vanishing gradient problem in standard RNNs through gated memory mechanisms. This makes them especially suitable for sequential data, where dependencies may exist across multiple time steps or network flows.
Yin et al. (2017) provided one of the earliest systematic evaluations of LSTM models for intrusion detection, reporting improved performance over traditional machine learning approaches on the KDD Cup 1999 dataset. More recently, Binbusayyis and Vaiyapuri (2019) extended this line of work by systematically identifying and benchmarking key features for intrusion detection on the CIC-IDS2017 dataset using an ensemble approach, demonstrating that careful feature selection significantly improves detection performance across multiple attack classes.
2.5Benchmark Datasets
The quality and realism of benchmark datasets play a critical role in determining the validity of intrusion detection research. For many years, the KDD Cup 1999 dataset, which originated from the 1998 DARPA evaluation, was the most widely used benchmark in this field. However, later analysis by Tavallaee et al. (2009) revealed several important limitations, including redundant features and a distribution that does not accurately reflect real-world network traffic. These issues often led to overly optimistic detection results that do not generalize well to modern environments.
To overcome these shortcomings, the Canadian Institute for Cybersecurity introduced the CIC-IDS2017 dataset (Sharafaldin et al., 2018). This dataset was generated using a realistic network setup and includes a wide range of contemporary attack scenarios such as DDoS, PortScan, and various web-based attacks. Due to its realism and diversity, CIC-IDS2017 has become one of the most commonly used datasets in recent IDS research. It contains 78 flow-level features extracted using the CICFlowMeter tool, making it well-suited for machine learning-based intrusion detection.
Similarly, the UNSW-NB15 dataset was developed by Moustafa and Slay (2015) at the Australian Centre for Cyber Security. It was created using the IXIA PerfectStorm tool to simulate realistic network traffic and includes nine different attack categories such as Fuzzing, Backdoor, and Shellcode. Unlike CIC-IDS2017, it consists of 42 features and represents a different network environment and traffic distribution. This difference makes UNSW-NB15 particularly useful for evaluating how well intrusion detection models generalize across different datasets and network conditions.
2.6Comparative Studies on CIC-IDS2017 and UNSW-NB15
While Sections 2.3 and 2.4 reviewed machine learning and deep learning approaches to intrusion detection individually, comparatively few published studies evaluate Random Forest, CNN, and LSTM models side by side on the same benchmark datasets used in this thesis. Table 2.1 and Table 2.2 summarize recent literature reporting the performance of these three model families on CIC-IDS2017 and UNSW-NB15 respectively, alongside the corresponding results obtained in this thesis (Chapter 4).
Table 1: Comparison of Random Forest, CNN, and LSTM Performance on CIC-IDS2017
Study
Model
Accuracy
Precision
Recall
F1-Score
Soumik (2024)
Random Forest
99.90%
97.78%
97.08%
97.41%
Hassanin (2026)
CNN
82.75%
82.75%
40.50%
43.89%
Hassanin (2026)
LSTM
86.05%
86.32%
85.68%
85.47%
This thesis
Random Forest
99.89%
99.53%
99.91%
99.72%
This thesis
CNN
98.50%
94.51%
98.05%
96.24%
This thesis
LSTM
99.59%
99.01%
98.94%
98.98%
On CIC-IDS2017, the Random Forest baseline reported by Soumik (2024) achieves accuracy comparable to the Random Forest model trained in this thesis, confirming that ensemble tree-based methods remain highly competitive on this dataset. In contrast, the CNN and LSTM baselines reported by Hassanin (2026) achieve substantially lower recall and F1-scores than the deep learning models trained in this thesis, particularly for CNN, suggesting that architecture design and preprocessing choices strongly influence deep learning performance on flow-based intrusion detection data.
Table 2: Comparison of Random Forest, CNN, and LSTM Performance on UNSW-NB15
Study
Model
Accuracy
Precision
Recall
F1-Score
More et al. (2024)
Random Forest
99.42%
99.71%
99.63%
99.67%
Hossain et al. (2026)
Random Forest
95.08%
96.21%
96.08%
96.15%
Hassanin (2026)
CNN
93.10%
64.70%
66.10%
65.43%
Hassanin (2026)
LSTM
93.97%
68.83%
70.28%
69.55%
This thesis
Random Forest
94.67%
97.50%
94.07%
95.75%
This thesis
CNN
93.54%
95.62%
94.21%
94.91%
This thesis
LSTM
93.46%
94.81%
94.97%
94.90%
Two independent studies report considerably different Random Forest performance on UNSW-NB15 (More et al., 2024; Hossain et al., 2026), illustrating the sensitivity of reported results to preprocessing pipelines, feature selection, and train/test splitting strategy. The Random Forest, CNN, and LSTM results obtained in this thesis fall within the range reported in the literature, while providing directly comparable metrics across all three architectures under an identical experimental protocol, a condition rarely satisfied when comparing results drawn from separate publications.
Beyond within-dataset performance, an emerging body of literature has begun to examine whether models trained on one intrusion detection dataset generalize to another. Cantone et al. (2024) trained Linear Discriminant Analysis, Decision Tree, Random Forest, and XGBoost classifiers on CIC-IDS2017 and evaluated them on CSE-CIC-IDS2018 (and vice versa), finding that Random Forest's within-dataset Matthews Correlation Coefficient (MCC) of 99.74% collapsed to 25.96% under cross-dataset testing. Similarly, Hossain et al. (2026) trained Random Forest, Logistic Regression, and Naive Bayes on UNSW-NB15 and TON_IoT, reporting that Random Forest's within-dataset accuracy of 95.08% on UNSW-NB15 dropped to 38.07% when tested on TON_IoT, and to 39.54% in the reverse direction. Table 2.3 summarizes these cross-dataset generalization findings.
Table 3: Cross-Dataset Generalization Studies Reported in the Literature
Study
Train → Test
Model(s)
Within-Dataset
Cross-Dataset
Cantone et al. (2024)
CIC-IDS2017 → CSE-CIC-IDS2018
Random Forest
MCC 99.74%
MCC 25.96%
Hossain et al. (2026)
UNSW-NB15 → TON_IoT
Random Forest
Accuracy 95.08%
Accuracy 38.07%
Hossain et al. (2026)
TON_IoT → UNSW-NB15
Random Forest
Accuracy 99.79%
Accuracy 39.54%
This thesis
CIC-IDS2017 → UNSW-NB15
RF / CNN / LSTM
Acc 98.62% / 90.33% / 97.50%
Acc 36.09% / 39.78% / 70.07%
This thesis
UNSW-NB15 → CIC-IDS2017
RF / CNN / LSTM
Acc 90.21% / 89.00% / 87.52%
Acc 63.46% / 49.61% / 60.92%
Notably, neither of these generalization studies evaluates the specific CIC-IDS2017/UNSW-NB15 dataset pair used in this thesis, nor do they extend cross-dataset evaluation to CNN and LSTM architectures alongside Random Forest. This absence is a central motivation for the bidirectional cross-dataset experiments reported in Section 4.5 of this thesis, and is discussed further below.
2.7Large Language Models in Cybersecurity
The integration of Large Language Models (LLMs) into cybersecurity workflows is an emerging area of research that has recently gained significant attention. Ferrag et al. (2023) provide a comprehensive survey of LLM applications in cybersecurity, highlighting key use cases such as threat intelligence analysis, vulnerability assessment, and incident response. Their study shows that LLMs have the potential to bridge the gap between complex security data and human understanding by translating technical outputs into clear, actionable natural language explanations.
One important aspect of this development is the shift toward local deployment of LLMs, especially in environments where data privacy and confidentiality are critical. In this context, Touvron et al. (2023a) demonstrate that open-source models such as LLaMA can achieve competitive performance compared to proprietary systems, making them suitable for deployment in sensitive or restricted environments.
In this thesis, the integration of a locally deployed LLM with traditional IDS outputs is used to enhance interpretability. Rather than replacing detection systems, the LLM acts as an explanation layer that converts model predictions into human-readable insights, improving accessibility for normal users and supporting faster security decision-making.
The rapid proliferation of capable open-weight LLMs in 2023–2024 has substantially lowered the technical barrier to local deployment. Touvron et al. (2023b) demonstrated with Llama 2 that open-source models at the 7–70 billion parameter scale can achieve performance competitive with proprietary alternatives, making privacy-preserving local inference viable for sensitive enterprise environments. The Gemma model family (Gemma Team, 2024) extended this trend with compact, responsibly designed open models, while the Qwen3 series (Qwen Team, 2025) introduced strong multilingual, instruction-tuned capabilities with hybrid thinking modes. These developments directly underpin the local LLM integration demonstrated in this thesis: all four evaluated models are deployed via LM Studio with no network traffic data transmitted to external services, satisfying the privacy requirements of operational security environments.
2.8Research Gap
Despite the extensive body of research on machine learning-based intrusion detection systems, several important gaps still remain. Most existing studies evaluate their models using a single dataset, which limits the ability to draw strong conclusions about generalization across different network environments. As a result, the real-world robustness of many proposed approaches remains uncertain.
In addition, there is a lack of comprehensive comparative studies that evaluate both classical machine learning and deep learning models across multiple datasets under the same experimental conditions, particularly when considering not only detection performance but also computational efficiency and training cost. This makes it difficult to understand the practical trade-offs between different model types.
Furthermore, the integration of Large Language Models for generating explanations within IDS pipelines has not been systematically explored in the literature. Most existing work focuses on detection accuracy, with limited attention given to usability and interpretability for non-expert users.
This thesis addresses these gaps by conducting a rigorous evaluation of multiple machine learning and deep learning models across two distinct benchmark datasets, alongside an analysis of computational efficiency and a novel integration of a locally deployed LLM for natural language threat explanation.
3Materials and Methodology
3.1System Architecture Overview
The proposed system follows a modular pipeline architecture comprising five stages: network traffic capture, data preprocessing, model training and evaluation, LLM-based threat analysis, and dashboard visualization. This separation of concerns enables independent optimization of each component and facilitates future extension with additional detection models or data sources.
The workflow begins with converting raw PCAP files into CSV flow records because the detection models in this thesis operate on tabular flow-level features rather than packet payloads. Using CICFlowMeter as the first preprocessing step standardizes the traffic into the same feature format expected by the trained models and the dashboard, making the raw capture usable for downstream analysis, compatibility filtering, and model inference.
The implementation is based on Python 3.12.10, leveraging the PyTorch framework for deep learning model development and the scikit-learn library for the Random Forest baseline. GPU acceleration is utilized for CNN and LSTM training via CUDA-enabled PyTorch on an NVIDIA GeForce RTX 5060 Laptop GPU.
3.2Datasets
3.3CIC-IDS2017
The CIC-IDS2017 dataset was generated by the Canadian Institute for Cybersecurity using a B-Profile system to simulate realistic network behavior. The dataset spans five days of traffic capture (Monday through Friday) and includes eight traffic categories: BENIGN, DDoS, PortScan, DoS Hulk, DoS GoldenEye, FTP-Patator, SSH-Patator, and Web Attacks. The dataset provides 78 flow-level features extracted by CICFlowMeter, including packet length statistics, inter-arrival times, flow duration, and flag counts.
For this study, all eight CSV files are concatenated to form a unified dataset comprising 2,830,743 records. Following preprocessing, the final dataset contains 2,827,876 records with 78 features, partitioned into a training set of 2,262,300 samples and a test set of 565,576 samples using stratified random splitting at a 80:20 ratio.
3.4UNSW-NB15
The UNSW-NB15 dataset was created at the Australian Centre for Cyber Security (ACCS) using the IXIA PerfectStorm network traffic generation tool. The dataset encompasses nine attack categories: Fuzzers, Analysis, Backdoors, DoS, Exploits, Generic, Reconnaissance, Shellcode, and Worms, alongside normal traffic records.
The dataset is distributed as training and testing CSV files; however, consistent with best practices in machine learning evaluation, these files are concatenated and re-partitioned using stratified random splitting to ensure unbiased evaluation. The combined dataset contains 257,673 records with 42 network flow features, partitioned into 206,138 training samples and 51,535 test samples.
3.5Data Preprocessing
3.6Feature Selection and Encoding
For UNSW-NB15, non-informative identifier columns (id, attack_cat) are removed, yielding 42 numerical and categorical features. Categorical features (proto, service, state) are encoded using Label Encoding. For CIC-IDS2017, string-type columns (Flow ID, Source IP, Destination IP, Timestamp) are removed, and all remaining 78 features are numerical. Column names are stripped of leading and trailing whitespace to ensure consistent referencing.
3.7Label Encoding
Both datasets are converted to binary classification targets. For UNSW-NB15, the original label column (0 for normal, 1 for attack) is preserved directly. For CIC-IDS2017, the Label column is binarized such that BENIGN records receive label 0 and all attack categories receive label 1.
3.8Handling Missing and Infinite Values
Network flow features frequently contain infinite values resulting from division by zero in rate calculations (e.g., packets per second with zero duration). All infinite values (positive and negative) are replaced with NaN, followed by row-wise removal of records containing missing values. This conservative approach avoids introducing bias through imputation while maintaining dataset integrity.
3.9Feature Normalization
All features are normalized using StandardScaler (zero mean, unit variance). The scaler is fitted exclusively on training data and applied to test data to prevent data leakage. Normalized feature arrays are saved as NumPy binary files for efficient loading during model training.
3.10Model Architectures
3.11Random Forest (Baseline)
Random Forest serves as the classical machine learning baseline. The implementation uses scikit-learn's RandomForestClassifier with 100 estimators, a maximum depth of 20, and balanced class weights to address class imbalance. All available CPU cores are utilized through the n_jobs=-1 parameter. No cross-validation is performed; instead, the 80:20 train-test split provides the evaluation framework, consistent with deep learning model evaluation.
3.12Convolutional Neural Network (CNN)
A 1D Convolutional Neural Network is designed to extract local feature patterns from the input feature vectors. The architecture treats the feature vector as a 1D sequence of length equal to the feature count, with a single input channel. Two convolutional blocks are applied sequentially, each comprising a Conv1D layer, Batch Normalization, ReLU activation, MaxPooling (kernel size 2), and Dropout (rate 0.3). The first block uses 64 filters and the second uses 128 filters, both with kernel size 3 and same padding. The convolutional output is flattened and passed through a fully connected classifier with a 64-unit hidden layer, ReLU activation, Dropout (rate 0.3), and a sigmoid output unit for binary classification.
The model is trained using the Adam optimizer (learning rate 1e-3) and Binary Cross-Entropy loss. Training proceeds for a maximum of 20 epochs with a batch size of 512. Early stopping with patience 3 is applied based on training loss to prevent overfitting.
3.13Long Short-Term Memory (LSTM)
A bidirectional LSTM network is designed to capture sequential dependencies in the feature representation. The input feature vector is treated as a sequence of length 1 with dimensionality equal to the feature count, allowing the LSTM to process the complete feature set as a temporal unit. The architecture consists of a 2-layer LSTM with 128 hidden units per layer and inter-layer dropout of 0.3. The final hidden state is passed through a fully connected classifier with a 64-unit hidden layer, ReLU activation, Dropout (rate 0.3), and a sigmoid output unit.
Training configuration mirrors the CNN: Adam optimizer (lr=1e-3), Binary Cross-Entropy loss, maximum 20 epochs, batch size 512, and early stopping with patience 3.
In Section 3.4.4, an extended temporal variant of the LSTM is further evaluated. Unlike the baseline configuration, which processes each flow as an independent observation (sequence length = 1), this variant constructs input samples using sliding windows of consecutive flow records with sequence lengths of 5, 10, and 20. This reformulation enables the model to learn short- and medium-range temporal dependencies between network flows, rather than relying solely on static feature representations.
3.14Temporal Sequence LSTM (Extended)
3.15Motivation
The experiments in Chapter 4 and Section 4.5 treat each flow record as an independent tabular observation. This design is appropriate for classical machine learning baselines, but it does not allow the LSTM to exploit the temporal structure that recurrent networks are meant to model. As a result, the earlier LSTM implementation functions more like a gated classifier over a single feature vector than a true sequence learner.
This Section introduces a temporal redesign in which ordered flow records are grouped into sliding windows. The goal is to test whether explicit sequence modeling improves within-dataset detection and, more importantly, whether it strengthens or weakens transfer across CIC-IDS2017 and UNSW-NB15.
3.16Why the Single-Timestep LSTM Is Insufficient
A single-timestep LSTM cannot observe transitions between adjacent flows, nor can it capture the short-range temporal context that may precede an attack burst, scanning pattern, or sustained denial-of-service behavior. In that setting, the recurrent cell receives one vector per example and therefore has no meaningful temporal horizon over which to accumulate state.
The revised design instead forms windows of 5, 10, and 20 consecutive flows. Each window is treated as a sequence, allowing the network to learn from the ordering of observations rather than from a static snapshot alone. This does not reconstruct packet-level causality, but it is a substantially stronger temporal formulation than the single-step version used previously.
3.17Temporal Sequence Construction
Sequences are constructed by first ordering the raw records using an explicit time column when one exists. If a dataset does not expose a reliable timestamp column, the original dataset order is preserved as a conservative fallback. Where possible, flows are also grouped by session-like identifiers such as source and destination addresses or related endpoint fields, so that windows do not cross unrelated communication contexts.
The resulting input tensor has shape [batch, sequence length, 15 features]. For example, a sequence length of 10 produces a tensor of shape [N, 10, 15], where N is the number of windows extracted from the training split. The label is taken from the final flow in each window, which keeps the formulation causal: the model sees only earlier context when predicting the last observed event in the sequence.
Table: 1 summarizes the rules governing temporal sequence construction, including their implementation and scientific rationale.
Table 4: Temporal Sequence Construction Rules
Rule
Implementation
Scientific Purpose
Temporal ordering
Sort by timestamp when available; otherwise preserve record order
Preserve the most defensible local chronology
Session grouping
Prefer source/destination endpoint groups when available
Reduce leakage across unrelated communication contexts
Sliding window
Use sequence lengths 5, 10, and 20
Test short- and medium-range temporal context
Window label
Assign the final flow label to the window
Keep the prediction causal
Split discipline
Split train/test before sequence extraction
Avoid overlapping windows across evaluation boundaries
3.18Sequence Preprocessing
After window construction, the 15 shared features are standardized using statistics computed only on the training split. The scaler is applied to flattened windows and the transformed arrays are then reshaped back into sequence form. This procedure preserves the temporal structure while preventing leakage from the test set into normalization statistics.
Mini-batch training uses a batch format compatible with PyTorch's batch_first LSTM interface. The batching strategy keeps sequences intact inside each batch, so the model processes complete windows rather than fragmented fragments of neighboring windows.
3.19Sliding Window Methodology
The sliding window protocol is intended to test whether repeated local temporal context improves the ranking of attack traffic. For each sequence length L, the model receives L consecutive flow records and predicts the label of the final record. Overlapping windows are allowed inside a split because the overlap is part of the temporal signal; however, windows never cross train/test boundaries (see Section 5.5.8 for a discussion of the resulting sample-independence limitation).
This protocol is deliberately more conservative than random shuffling. Randomly mixing adjacent flows would create leakage because overlapping windows could place nearly identical contexts into both the training and testing partitions. By using ordered splits first and windows second, the experiment preserves temporal integrity.
3.20Experimental Setup
The temporal study should be run for sequence lengths 5, 10, and 20 on both CIC-IDS2017 and UNSW-NB15. Three evaluation settings are required: within-dataset temporal evaluation on CIC, within-dataset temporal evaluation on UNSW, and bidirectional cross-dataset transfer using the same 15-feature representation. The same metrics defined in Section 3.5 (Accuracy, F1-Score, AUC-ROC, and training time) remain the primary evaluation criteria.
Table: 2 outlines the temporal study design across sequence lengths, specifying what each configuration tests and how results should be interpreted.
Table 5: Temporal Study Design
Sequence Length
What It Tests
Interpretation
5
Very short local context
Useful if attacks are visible in immediate flow neighborhoods
10
Moderate temporal context
Balanced between context and over-smoothing
20
Longer temporal context
Tests whether broader context improves or harms transfer
3.21Evaluation Metrics
Model performance is evaluated using four metrics:
Accuracy: The proportion of correctly classified samples, providing an overall performance measure.
F1-Score (Weighted): The harmonic mean of precision and recall, weighted by class support. Preferred over accuracy for imbalanced datasets.
AUC-ROC: The area under the Receiver Operating Characteristic curve, measuring the model's discriminative ability across all classification thresholds.
Training Time: Wall-clock time for model training, providing a practical measure of computational efficiency relevant to deployment scenarios.
3.22Cross-Dataset Experimental Setup and Challenges
3.23Motivation
The experiment trains all three models (Random Forest, CNN, and LSTM) exclusively on CIC-IDS2017 data and evaluates them on UNSW-NB15 data, representing a realistic scenario where a deployed IDS encounters network traffic from an environment different from its training domain.
A fundamental limitation of many IDS studies is the evaluation of models exclusively on the same dataset used for training. While this approach yields high performance metrics, it does not address a critical practical question: can a model trained on traffic from one network environment generalize to a different environment with a different feature space and attack taxonomy? This Section presents a novel cross-dataset generalization experiment designed to answer this question.
3.24Challenge: Feature Space Incompatibility
A naive concatenation or direct transfer is therefore impossible. To address this, a systematic feature mapping procedure is developed to identify conceptually equivalent features across both datasets and construct a shared 15-dimensional feature space suitable for cross-dataset evaluation.
The primary technical challenge in cross-dataset evaluation is the fundamental incompatibility of feature spaces between CIC-IDS2017 (78 features) and UNSW-NB15 (42 features). These datasets were generated by different research groups using different traffic generation tools and feature extraction methodologies, resulting in entirely different column names and feature definitions despite representing similar underlying network phenomena.
3.25Feature Mapping and Namespace Standardization
Table: 3 presents the resulting 15-feature mapping between CIC-IDS2017 and UNSW-NB15, along with the semantic meaning of each shared feature.
Table 6: Feature Mapping Between CIC-IDS2017 and UNSW-NB15
CIC-IDS2017 Feature
UNSW-NB15 Feature
Semantic Meaning
Flow Duration
dur
Total flow duration
Total Fwd Packets
spkts
Source-to-destination packet count
Total Backward Packets
dpkts
Destination-to-source packet count
Total Length of Fwd Packets
sbytes
Source-to-destination byte count
Total Length of Bwd Packets
dbytes
Destination-to-source byte count
Fwd Packet Length Max
smean
Mean source packet size
Bwd Packet Length Max
dmean
Mean destination packet size
Flow Bytes/s
rate
Flow transfer rate
Flow Packets/s
sload
Source load (bits/sec)
Fwd IAT Mean
sinpkt
Mean inter-packet arrival (src)
Bwd IAT Mean
dinpkt
Mean inter-packet arrival (dst)
Fwd Header Length
swin
Source TCP window size
Bwd Header Length
dwin
Destination TCP window size
Fwd Packets/s
ct_srv_src
Connections to same service (src)
Bwd Packets/s
ct_srv_dst
Connections to same service (dst)
Note: Rows 6–7 represent approximate mappings: CIC-IDS2017 records the maximum packet length (Fwd/Bwd Packet Length Max) while UNSW-NB15 records the mean packet size (smean/dmean). These are the closest available equivalents between the two dataset schemas.
Feature mapping is performed through domain knowledge-guided manual alignment of conceptually equivalent network flow measurements across both datasets. Each mapped feature pair represents the same underlying network measurement captured through different feature extraction pipelines. The mapping prioritizes features with clear semantic equivalence. Thirteen of the fifteen mapped features represent direct semantic equivalents. Two pairs constitute approximate mappings: Fwd Packet Length Max and Bwd Packet Length Max (CIC-IDS2017) are mapped to smean and dmean (UNSW-NB15) respectively, as these are the closest available equivalents in the UNSW-NB15 schema despite measuring the maximum rather than mean packet size. This approximation is a known constraint of cross-dataset alignment and is acknowledged as a contributing factor to the domain shift observed in cross-dataset transfer (Section 5.7).
3.26Cross-Dataset Preprocessing and Normalization Pipeline
The resulting cross-dataset split comprises 2,827,876 CIC-IDS2017 training samples and 257,673 UNSW-NB15 test samples, both represented in the shared 15-dimensional feature space. Unlike the within-dataset evaluation, which reserves 20% of CIC-IDS2017 for testing (565,576 samples), the cross-dataset experiment uses the entire CIC-IDS2017 dataset for training, since the test set is drawn from a completely independent source domain (UNSW-NB15) and there is no risk of data leakage between the two datasets. This maximises the model's exposure to the source-domain distribution prior to cross-domain transfer.
Infinite values resulting from division-by-zero in rate calculations are replaced with NaN, followed by row-wise removal of records containing missing values. A StandardScaler is fitted exclusively on the CIC-IDS2017 training data and applied to both the CIC training set and the UNSW test set. This procedure ensures that the UNSW data is normalized using statistics derived entirely from CIC data, faithfully simulating a real-world deployment scenario where the model encounters previously unseen data.
Following feature mapping, a unified preprocessing pipeline is applied. The CIC-IDS2017 dataset is loaded in full (all 8 CSV files) and filtered to the 15 mapped features. The UNSW-NB15 dataset is similarly filtered and column names are renamed to match the CIC-IDS2017 conventions, establishing a common feature namespace.
3.27Validation of the Shared Feature Mapping
Table: 4 lists the validation criteria used to assess the shared feature mapping, along with guidance for interpreting each criterion.
Table 7: Suggested Validation Criteria for the Shared 15-Feature Mapping
Validation Criterion
What It Tests
How to Interpret It
Correlation analysis
Whether paired features move together
High correlation supports semantic similarity but does not guarantee equivalence
Mutual information
How strongly each feature relates to the label
A large gap may indicate that one side of the mapping is more informative
SHAP / permutation importance
Whether the model relies on the feature pair similarly
Inconsistent attributions suggest mapping risk
Distribution comparison
Whether feature values occupy comparable ranges
Strong divergence suggests domain shift remains large
PCA / t-SNE visualization
Whether the reduced feature space overlaps across datasets
Separation by dataset indicates limited transferability
A fitted baseline model can further be used to compute permutation importance or SHAP-style attribution scores for the mapped features within each dataset. If a feature pair is semantically aligned yet shows radically different attribution patterns or unstable importance rankings, the mapping should be treated cautiously and reported as approximate. Additional visualization through PCA or t-SNE on the reduced 15-feature space can help reveal whether the mapped feature distributions overlap meaningfully or remain strongly dataset-specific.
The 15-feature semantic mapping should be interpreted as a carefully constructed hypothesis rather than a guaranteed one-to-one equivalence. To improve methodological rigor, each mapped pair can be validated through complementary evidence from correlation analysis, mutual information with the target label, and distribution comparison across the two datasets. These checks do not prove that two features are identical, but they can indicate whether the mapping is plausible, stable, and sufficiently informative for transfer learning.
This validation step was carried out later in the thesis rather than at the mapping stage. Section 4.8 and Section 5.8 apply SHAP attribution to the trained models on both datasets and in both transfer directions, and the results confirm that the mapping is informative while also exposing a units and scale mismatch in several of the mapped features that the correlation and impurity checks proposed here would not have caught on their own.
3.28Feature Importance and Dimensionality Reduction Justification
Overall, the feature importance analysis validates the 15-feature shared representation as a principled reduction rather than an arbitrary one. The selected features capture the most architecturally consistent and semantically transferable aspects of network flow behavior, which explains both their predictive power within CIC-IDS2017 and their partial preservation of discriminative signal in cross-dataset settings.
Crucially, these 15 features are not just important in isolation; they are also the features used in the cross-dataset transfer experiments of Section 4.5, where LSTM achieves 70.07% accuracy and 74.67% AUC-ROC in the forward experiment (Table 4.6) despite never having seen UNSW-NB15 traffic during training. This connection between feature importance and cross-dataset generalization is not coincidental: features that encode fundamental network behavior (how much data flows, how fast, and in what rhythm) tend to remain meaningful across different network environments, even when the specific attack types and traffic distributions differ. Header-based and connection-counting features, which rank lowest in Table 3.5, are more likely to be environment-specific and therefore less transferable.
A notable difference emerges when comparing how each architecture weighs timing-related features. LSTM assigns comparatively higher importance to Flow Bytes/s, Fwd IAT Mean, and Bwd IAT Mean than either Random Forest or CNN. This is architecturally expected: recurrent networks process input sequentially and are inherently sensitive to temporal patterns, so it follows that LSTM would place greater weight on inter-arrival timing and transfer rate features that encode the rhythm of network communication. Random Forest, by contrast, relies more heavily on static volume features like byte and packet counts, which is consistent with its tree-based decision logic that splits on individual feature thresholds rather than sequential dependencies.
This comparison rests on mean decrease in impurity for Random Forest and an activation magnitude heuristic for CNN and LSTM. Section 5.8.2 revisits it using SHAP attribution, a rigorous, model agnostic method applied consistently across all three architectures, and finds that the activation magnitude heuristic did not capture what CNN and LSTM actually rely on. Both models turn out to concentrate most of their attribution on packet length features rather than timing features, so the apparent LSTM sensitivity to inter-arrival timing described above does not hold up under a proper attribution method. The Random Forest description remains largely accurate, since impurity decrease and SHAP attribution agree moderately well for tree based models.
Table: 5 shows a consistent pattern across all three models: payload-related features dominate, with Total Fwd Bytes and Total Bwd Bytes ranking first and second regardless of architecture, followed closely by packet count features. This consistency is itself a meaningful finding: it suggests that attack traffic is primarily distinguishable through the volume and size of data exchanged, not through packet header structure or connection metadata.
The selection of 15 features for cross-dataset evaluation represents a carefully reduced feature space derived from the union of CIC-IDS2017 (78 features) and UNSW-NB15 (42 features) feature sets. To justify this reduction and validate that the selected features capture the most predictive signal, Table 3.5 presents feature importance rankings for each model trained on CIC-IDS2017. Features are ranked by their mean decreasing impurity (for Random Forest) or activation magnitude (for CNN/LSTM), normalized to sum to 100% for interpretability.
The rankings in Table 3.5 reveal a consistent pattern across all three models: flow-duration and packet-length statistics (mean, maximum, and standard deviation) dominate the top positions, followed by inter-arrival time features and forward/backward packet counts. This convergence across Random Forest, CNN, and LSTM confirms that the 15 shared features capture the most discriminative signal available in both datasets, justifying their selection as the cross-dataset feature set.
Table 8: Feature Importance Rankings Across Models (CIC-IDS2017 Full Dataset)
Feature
RF Importance
CNN Importance
LSTM Importance
Semantic Role
Flow Duration
8.2%
7.1%
6.8%
Temporal context of connection
Total Fwd Packets
12.4%
11.3%
10.9%
Request volume indicator
Total Backward Packets
11.1%
10.2%
9.7%
Response volume indicator
Total Fwd Bytes
14.3%
13.8%
13.2%
Payload size in request direction
Total Bwd Bytes
13.7%
12.9%
12.1%
Payload size in response direction
Fwd Packet Length Max
6.9%
7.4%
7.6%
Avg packet structure in request
Bwd Packet Length Max
6.8%
7.2%
7.5%
Avg packet structure in response
Flow Bytes/s
5.2%
6.1%
6.8%
Transfer rate magnitude
Flow Packets/s
4.1%
4.8%
5.2%
Transfer rate frequency
Fwd IAT Mean
3.4%
3.9%
4.3%
Inter-arrival timing (request)
Bwd IAT Mean
3.3%
3.7%
4.1%
Inter-arrival timing (response)
Fwd Header Length
2.1%
2.6%
2.9%
Header overhead (request)
Bwd Header Length
2.0%
2.4%
2.7%
Header overhead (response)
Connections to Same Service (Src)
2.8%
3.2%
3.5%
Horizontal scanning indicator
Connections to Same Service (Dst)
2.7%
3.1%
3.4%
Service exploitation pattern
"Note: Values are rounded to one decimal place and may not sum to exactly 100% due to rounding."
3.29Interactive Dashboard System
A locally-deployed Large Language Model is integrated via LM Studio's OpenAI-compatible REST API endpoint (http://localhost:1234/v1/chat/completions). The integration constructs structured prompts from IDS detection outputs, including source and destination IPs, protocol, packet count, byte volume, flow duration, detected model, prediction label, attack type, and confidence score. The LLM generates concise threat assessments comprising a threat description, likely attack vector, recommended response action, and risk level classification.
Local deployment is chosen over cloud-based APIs to preserve data privacy and ensure applicability in air-gapped or security-sensitive network environments. The system is model-agnostic and compatible with any LLM accessible through the LM Studio interface.
3.30Interactive Dashboard System Overview
The operational interface of the proposed IDS framework is implemented as a multi-module Streamlit web application comprising two coordinated processes: the main analysis dashboard (streamlit_dashboard.py, port 8501) and a dedicated AI security chat interface (chat.py, port 8502). The complete pipeline spans six functional stages: (1) initialization and configuration, (2) feature mapping and asset loading, (3) traffic data ingestion and preprocessing, (4) machine learning inference execution, (5) advanced visualizations and simulation tools, and (6) mitigation advice and LLM handoff. This modular design allows each stage to operate independently while maintaining a unified data flow from raw CSV network capture input to actionable threat intelligence output. Figure 3.1 shows the complete dashboard architecture.
The dashboard sidebar provides a three-step workflow: data upload, model selection, and AI integration configuration. Users upload one or more CIC-IDS2017-format or UNSW-NB15-format CSV files via a file uploader widget supporting multi-file batch submission. The system accepts files up to 500 MB per upload (configurable via config.yaml) and automatically detects the column schema to route data to the appropriate preprocessing pipeline: CIC full (78 features), UNSW full (42 features), or Shared-15 (15 cross-dataset features). A model selection dropdown lists all available trained model files discovered from the models/ directory, displaying the inference mode (tabular or sequence) and feature schema. The LM Studio API endpoint URL is configured directly in the sidebar, and the active LLM model name with live connectivity status (green pulsing indicator) is displayed. Figures 3.2 and 3.3 show the sidebar interface and the main canvas after data upload.
Figure 2: Dashboard Sidebar – Data Upload, Model Selection, and LLM Status
Figure 3: Main Dashboard Canvas After CSV File Upload with Data Preview
3.32Machine Learning Inference Engine
The inference engine supports three model types loaded from the models/ directory: scikit-learn Random Forest classifiers (.pkl files loaded via joblib), PyTorch 1D Convolutional Neural Networks (CNN architecture: two Conv1d–BatchNorm1d–ReLU–MaxPool1d blocks followed by a fully-connected classifier with sigmoid output), and PyTorch bidirectional LSTM models (two-layer LSTM with hidden size 128, followed by a linear classifier). All neural network models are loaded from .pt state-dict files and transferred to the available compute device (CUDA GPU preferred, CPU fallback). Preprocessing applies the appropriate StandardScaler loaded from a corresponding .pkl scaler file. Inference is performed in configurable mini-batches (default: 4,096 samples) to handle large captures without exhausting GPU memory. Performance metrics reported include total inference time, throughput (packets per second), and per-packet latency. When ground-truth labels are present in the uploaded CSV, the system computes accuracy, F1-score (binary and weighted), ROC-AUC, precision, recall, false positive rate (FPR), and false negative rate (FNR), and renders a confusion matrix with a confidence distribution bar chart.
3.33LLM Integration and Threat Report Generation
Following model inference, the dashboard automatically constructs a structured Network Intrusion Detection Analysis Report. This report summarizes the file analysed, model used, preprocessing mode, total flow count, benign/malicious split, and average confidence. It then lists up to 50 critical-confidence attacks (confidence ≥ 90%) and 10 warning-level attacks (confidence 75–90%), each annotated with destination port, flow duration, forward/backward packet counts and byte totals, bytes-per-second rate, and automatically derived pattern annotations (e.g., 'High packet rate (possible DDoS/flood)' when packets-per-second exceeds 500, or 'Asymmetric traffic' when forward-to-backward packet ratio exceeds 10:1). A statistical summary appended at the report tail covers average, peak, and minimum attack confidence, top five target ports by attack count, top attacker IP addresses, and average/peak packet rates. All IP addresses and email addresses in the report are automatically sanitized via regex substitution before the data is made available for LLM processing. Clicking the 'Open AI Chat Interface' button serializes the log to a temporary JSON file and launches the chat subsystem on port 8502, as shown in Figure 3.4.
Figure 4: AI Analysis Interface Launch – Notification Messages After Clicking 'Open AI Chat Interface'
3.34AI Security Chat Interface
The AI Security Chat module (chat.py) provides a conversational threat analysis environment powered by a locally-deployed LLM served via LM Studio's OpenAI-compatible REST API. On startup, the interface reads the analysis log from the temporary JSON file and automatically injects it as the initial user message, pre-filled with the structured cybersecurity analyst prompt template. The prompt instructs the LLM to produce a structured analysis report with sections covering executive summary, attack patterns identified, network intelligence, technical details, and recommended actions using Markdown formatting including bullet points, code blocks, and alert boxes. The interface supports streaming token output for real-time display, maintains multi-turn conversation history (up to 15 context turns configurable), and allows the user to ask follow-up questions. The sidebar displays the active LLM model identifier, system resource utilization (CPU, RAM, GPU percentage), response metrics after each LLM response (total response time, time-to-first-token, tokens-per-second generation speed, input token count, output token count, and total token usage), and a log status indicator confirming the size of the loaded analysis data. Figures 3.5 and 3.6 show the AI chat canvas and sidebar respectively.
Figure 5: AI chat main page after forwarding to 8502
Figure 6: AI Chat Sidebar with LLM Status, System Resources, and Response Metrics Panel
3.35Advanced Visualizations and Auto-Remediation
The dashboard provides two advanced visualization panels accessible via expandable sections. The Attack Timeline chart renders detected malicious flows as a scatter plot with confidence level on the Y-axis and flow sequence number on the X-axis, color-coded by severity (red for critical ≥ 90%, orange for warning ≥ 75%, yellow for low confidence). This chart reveals temporal distribution and intensity patterns in the detected attack traffic. The Feature Correlation Heatmap computes the pairwise Pearson correlation matrix of all numeric columns in the result frame and renders it as an interactive heatmap with a red-yellow-green diverging color scale, enabling identification of co-varying traffic attributes. The Confidence Distribution histogram stratifies all classified flows into four confidence bands (Low <0.2, Medium 0.2–0.5, High 0.5–0.8, Critical >0.8). Figure 3.7 shows both advanced visualization panels.
The auto-remediation subsystem analyses detection results to identify attack categories based on heuristic rules: flows exceeding 50 total attacks trigger the DDoS/distributed attack pattern; any flow confidence ≥ 90% triggers the high-confidence attack pattern. For each identified pattern, actionable mitigation steps are retrieved from config.yaml and displayed. DDoS/distributed patterns recommend: enabling rate limiting, activating CDN protection, blocking source IP addresses, and enabling cloud scrubbing. An Attack Simulation Mode, accessible via an expandable panel, allows synthetic traffic generation for four attack profiles (DDoS, Port Scan, SQL Injection, Normal Traffic) with configurable duration and intensity for testing and validation purposes.
Figure 7: Advanced Charts Panel – Confidence Distribution Histogram and Feature Correlation Heatmap
3.36Dashboard Configuration and Deployment
System behavior is governed by two configuration files. The YAML configuration (config.yaml) defines: LLM endpoint parameters (API URL: http://localhost:1234/v1/chat/completions, max retries: 5, timeout: 180s, streaming: enabled, max context turns: 15, temperature: 0.7, request timeout: 900s); analysis thresholds (critical threshold: 90%, warning threshold: 75%, confidence cutoff: 75%, max critical attacks in log: 50, max warning attacks: 10); data processing settings (max file size: 500 MB, chunk size: 10,000 rows, cache enabled with 1-hour TTL); security settings (IP and email sanitization enabled, audit logging to logs/audit.log with automatic rotation at 100 MB, debug logging disabled); visualization preferences (dark theme, timeline enabled, heatmap enabled, max timeline points: 1,000); and attack-category remediation action lists for DDoS, port scan, SQL injection, and DoS patterns. The Streamlit server configuration (.streamlit/config.toml) sets maximum upload size to 2,048 MB, enables headless operation, and applies a dark UI theme (primary color: #1f77b4, background: #0e1117, text: #fafafa). The application is launched via 'streamlit run streamlit_dashboard.py' and the chat interface via 'streamlit run chat.py --server.port 8502'.
3.37Implementation Environment
Table: 6 summarises the hardware and software environment used to develop, train, and evaluate all system components presented in this study.
Although the evaluation framework in this study uses CSV file upload to ensure benchmark reproducibility and controlled experimental conditions, the underlying software architecture is designed with a microservice pipeline that can support real-time operation with minimal modification. This section documents the architectural properties that enable live streaming deployment; it does not constitute an empirical evaluation of real-time performance.
Mini-Batch Inference Engine. The ML inference engine processes network flow records in mini-batches of 4,096 rows. At this batch size, inference across millions of packets completes in milliseconds per batch, achieving latency characteristics well within the operational requirements of a production Security Operations Centre (SOC). The batch size is a configurable parameter and can be reduced to single-row (online) inference for scenarios requiring the lowest possible per-alert latency, or increased further for bulk offline analysis.
Microservice Architecture. The system separates concerns into four independently deployable layers: (1) a Data Ingestion Layer that receives flow-level records via file upload or a streaming adapter; (2) an ML Inference Engine that applies the trained RF, CNN, and LSTM models to incoming batches; (3) an LLM Threat Explanation Service that generates structured natural-language threat reports via LM Studio; and (4) a Dashboard Visualization Layer that renders classification results and threat narratives to the analyst. Each layer communicates through a defined API contract, OpenAI-compatible REST for the LLM service and a standard HTTP interface for inference, meaning the ingestion layer can be switched from CSV-file-based to streaming without any modification to the inference or explanation layers.
Live Streaming Integration. In a production SOC deployment, the CSV upload interface is replaced by a streaming adapter that consumes live outputs from network monitoring daemons. Two industry-standard tools are directly compatible:
CICFlowMeter: extracts the same 78 flow-level features used in this study from a live network interface and emits them as CSV at configurable intervals. At 1 Gbps line rate it typically emits 2,000–8,000 flow records per second, so each 4,096-row mini-batch represents approximately 0.5–2 seconds of live traffic, confirming sub-second classification latency before LLM analysis begins.
Zeek (formerly Bro): an enterprise-grade network analysis daemon that can be configured to emit conn.log and http.log entries in a schema matching the required 15-feature alignment used in the cross-dataset experiments (Section 3.6.3). Zeek's scripting engine allows custom log formats to be written directly compatible with the dashboard ingestion layer.
Important: the streaming integration described above constitutes an architectural design rather than an empirically validated production deployment. The CSV benchmark approach was a deliberate methodological choice to guarantee reproducibility using the publicly available CIC-IDS2017 and UNSW-NB15 datasets, and it was not evaluated against live network traffic. Real-time deployment would require additional validation, including latency testing under sustained load, memory profiling, and failover testing; these are left as future work.
4Findings
4.1Overview
This chapter presents the experimental results of the three evaluated models (Random Forest, CNN, and LSTM) on both the CIC-IDS2017 and UNSW-NB15 datasets. Results are reported in terms of False Positive Rate (FPR) and False Negative Rate (FNR), which are prioritized as the primary operational metrics, alongside Accuracy, F1-Score, AUC-ROC, and Training Time. FPR and FNR are placed first because, as argued throughout Chapter 5, they more directly determine operational usability in a security context than accuracy alone. Detailed classification reports and comparative analyses are provided for each dataset.
4.2Results on CIC-IDS2017
4.3Summary Table
Table: 1 summarizes the accuracy, F1-score, AUC-ROC, and training time achieved by each model on CIC-IDS2017.
Table 10: Model Performance on CIC-IDS2017
Model
FPR
FNR
Accuracy
F1-Score
AUC-ROC
Train Time
Random Forest
0.12%
0.09%
99.89%
99.72%
99.99%
53.4s
CNN
1.39%
1.95%
98.50%
96.24%
99.87%
416.6s
LSTM
0.24%
1.06%
99.59%
98.98%
99.98%
389.9s
4.4Confusion Matrices (Within-Dataset)
Table: 2 presents the within-dataset confusion matrices for CIC-IDS2017, reporting the true/false positive and negative counts and rates for each model.
Table 11: Confusion Matrices for CIC-IDS2017 (within-dataset)
Model
TN
FP
FN
TP
False Positive Rate
False Negative Rate
Random Forest
453,742
523
96
111,215
0.12%
0.09%
CNN
447,931
6,334
2,168
109,143
1.39%
1.95%
LSTM
453,163
1,102
1,183
110,128
0.24%
1.06%
4.5Results on UNSW-NB15
4.6Summary Table
Table: 3 summarizes the accuracy, F1-score, AUC-ROC, and training time achieved by each model on UNSW-NB15.
Table 12: Model Performance on UNSW-NB15
Model
FPR
FNR
Accuracy
F1-Score
AUC-ROC
Train Time
Random Forest
4.27%
5.93%
94.67%
95.75%
99.18%
1.7s
CNN
7.63%
5.79%
93.54%
94.91%
98.75%
35.2s
LSTM
9.2%
5.03%
93.46%
94.90%
98.75%
34.6s
4.7Confusion Matrices (Within-Dataset)
Table: 4 presents the corresponding within-dataset confusion matrices for UNSW-NB15.
Table 13: Confusion Matrices for UNSW-NB15 (within-dataset)
Model
TN
FP
FN
TP
False Positive Rate
False Negative Rate
Random Forest
17,806
794
1,954
30,981
4.27%
5.93%
CNN
17,180
1,420
1,907
31,028
7.63%
5.79%
LSTM
16,888
1,712
1,656
31,279
9.2%
5.03%
4.8Within-Dataset Comparative Summary
Table: 5 consolidates these results into a single comparative view across both datasets and all three models.
Table 14: Complete Comparative Results, All Models and Datasets
Model
Dataset
FPR
FNR
Accuracy
F1-Score
AUC-ROC
Train Time
Random Forest
CIC-IDS2017
0.12%
0.09%
99.89%
99.72%
99.99%
53.4s
CNN
CIC-IDS2017
1.39%
1.95%
98.50%
96.24%
99.87%
416.6s
LSTM
CIC-IDS2017
0.24%
1.06%
99.59%
98.98%
99.98%
389.9s
Random Forest
UNSW-NB15
4.27%
5.93%
94.67%
95.75%
99.18%
1.7s
CNN
UNSW-NB15
7.63%
5.79%
93.54%
94.91%
98.75%
35.2s
LSTM
UNSW-NB15
9.2%
5.03%
93.46%
94.90%
98.75%
34.6s
Figure 8: Accuracy Comparison of Random Forest, CNN, and LSTM on CIC-IDS2017 and UNSW-NB15
Figure 9: AUC-ROC Comparison of Models Across Both Datasets
Figure 10: Training Time Comparison (in seconds) for Each Model on CIC-IDS2017 and UNSW-NB15
4.9Cross-Dataset Transfer Experiments
4.10Forward Cross-Dataset Transfer Results (CIC→UNSW)
Table: 6 reports the forward cross-dataset transfer results, with models trained on CIC-IDS2017 and evaluated on UNSW-NB15.
To further test the robustness of the shared 15-feature mapping, the direction of the experiment was reversed: the models were trained on UNSW-NB15 and evaluated on CIC-IDS2017. This reverse setup keeps the same mapped feature space but swaps the training and testing domains, allowing a direct comparison of how each architecture behaves under a different distribution shift.
4.11Within-Dataset vs. Cross-Dataset Comparison
Table: 8 compares the CIC-IDS2017 and UNSW-NB15 within-dataset baselines, using the shared 15-feature representation, against the forward cross-dataset transfer results, isolating the accuracy drop attributable to domain shift.
Table 17: Within-Dataset vs. Cross-Dataset Performance Comparison
Model
CIC (15-feature within)
UNSW (15-feature within)
Cross-Dataset (CIC→UNSW)
Drop vs CIC Baseline
Random Forest
98.62%
90.21%
36.09%
−62.53%
CNN
90.33%
89.00%
39.78%
−50.55%
LSTM
97.50%
87.52%
70.07%
−27.43%
4.12Confusion Matrix Breakdown
Table: 9 and Table 4.10 break down the cross-dataset results into true negatives, false positives, false negatives, and true positives. This view is necessary because accuracy alone can hide whether a model is missing attacks or over-alerting on benign traffic.
Table 18: Confusion Matrix for Forward Transfer (Train: CIC-IDS2017 → Test: UNSW-NB15)
Model
TN (% Neg)
FP (% Neg)
FN (% Pos)
TP (% Pos)
Random Forest
93,000 (100%)
0 (0%)
164,673 (100%)
0 (0%)
CNN
89,028 (95.73%)
3,972 (4.27%)
151,537 (92.02%)
13,136 (7.98%)
LSTM
77,687 (83.53%)
15,313 (16.47%)
61,824 (37.54%)
102,849 (62.46%)
Table 19: Confusion Matrix for Reverse Transfer (Train: UNSW-NB15 → Test: CIC-IDS2017)
Model
TN (% Neg)
FP (% Neg)
FN (% Pos)
TP (% Pos)
Random Forest
1,610,291 (70.91%)
661,029 (29.09%)
372,220 (66.88%)
184,336 (33.12%)
CNN
1,238,480 (54.53%)
1,032,840 (45.47%)
391,988 (70.43%)
164,568 (29.57%)
LSTM
1,446,525 (63.69%)
824,795 (36.31%)
281,014 (50.49%)
275,542 (49.51%)
4.13Forward vs. Reverse Cross-Dataset Performance Comparison
The two directional cross-dataset experiments expose critical asymmetries in network intrusion detection generalization. A structured comparison reveals that performance is not symmetric and that the choice of training and test domains substantially influences model behavior and ranking quality.
Table: 11 presents this structured comparison, contrasting forward and reverse cross-dataset metrics and their differences.
Table 20: Comparative Analysis of Bidirectional Cross-Dataset Experiments
Metric
Forward (CIC→UNSW)
Reverse (UNSW→CIC)
Difference
RF Accuracy
36.09%
63.46%
+27.37%
RF AUC-ROC
37.26%
51.21%
+13.95%
CNN Accuracy
39.78%
49.61%
+9.83%
CNN AUC-ROC
68.90%
37.85%
-31.05%
LSTM Accuracy
70.07%
60.92%
-9.15%
LSTM AUC-ROC
74.67%
63.66%
-11.01%
4.14Temporal Sequence LSTM Results
4.15Within-Dataset Sequence Results
Table: 12 reports the within-dataset temporal LSTM performance across sequence lengths 5, 10, and 20 for both datasets.
Table 21: Within-Dataset Temporal LSTM Performance by Sequence Length
Dataset
Seq. Length
Accuracy
F1-Score
AUC-ROC
CIC-IDS2017
5
96.28%
0.9619
0.9717
CIC-IDS2017
10
95.69%
0.9557
0.9619
CIC-IDS2017
20
94.85%
0.9463
0.9493
UNSW-NB15
5
98.13%
0.9812
0.9988
UNSW-NB15
10
97.51%
0.9749
0.9974
UNSW-NB15
20
99.26%
0.9926
0.9973
4.16Cross-Dataset Sequence Results: Temporal Impact on Error Rates
Table: 13 reports the forward cross-dataset transfer results for the temporal LSTM across sequence lengths.
Table 22: CIC-IDS2017 → UNSW-NB15 Cross-Dataset Transfer (Temporal LSTM)
Sequence Length
Accuracy
F1-Score
AUC-ROC
Interpretation
5
48.69%
0.4405
0.6377
Weak transfer with short context
10
48.74%
0.4451
0.6519
Modest improvement with moderate context
20
48.95%
0.4390
0.8159
Strong AUC ranking despite low accuracy
Table 23: UNSW-NB15 → CIC-IDS2017 Cross-Dataset Transfer (Temporal LSTM)
Sequence Length
Accuracy
F1-Score
AUC-ROC
Interpretation
5
80.20%
0.7157
0.5807
High accuracy but poor ranking
10
80.39%
0.7210
0.5945
Maintained accuracy with marginal AUC gain
20
41.65%
0.4572
0.6576
Accuracy collapse; AUC slightly stronger
4.17Confusion Matrix Breakdown: Revealing Temporal Impact on False Alarms and Missed Attacks
Table: 15 breaks these results down into confusion-matrix form at sequence length 20 across all four experimental settings.
Table 24: Confusion Matrix for Temporal LSTM at Sequence Length 20
Experiment
TN (% Neg)
FP (% Neg)
FN (% Pos)
TP (% Pos)
CIC within
450,541 (99.18%)
3,704 (0.82%)
25,432 (22.85%)
85,880 (77.15%)
UNSW within
18,210 (97.98%)
371 (2.00%)
8 (0.02%)
32,927 (99.98%)
CIC→UNSW
88,742 (95.44%)
4,239 (4.56%)
127,274 (77.29%)
37,399 (22.71%)
UNSW→CIC
800,173 (35.23%)
1,471,128 (64.77%)
178,829 (32.13%)
377,727 (67.87%)
4.18LLM Performance Analysis
4.19LLM Model Specifications
Table: 16 lists the technical specifications of the four locally deployed LLMs evaluated in this study.
Table 25: Locally Deployed LLM Model Technical Specifications
Model Name
Architecture
Quantization
File Size (GB)
Developer
Gemma 4 E4B
Dense
Q4_K_M GGUF
5.89
Google
Gemma 4 26B-A4B QAT
MoE (26B total / 4B active)
Q4_0 GGUF (QAT)
14.56
Google
Qwen3.5 9B
Dense
Q6_K GGUF
7.71
Alibaba / Qwen Team
Qwen3.6 35B-A3B
MoE (35B total / 3B active)
Q4_K_M GGUF
20.55
Alibaba / Qwen Team
4.20LLM Response Performance Metrics
Table: 17 reports the corresponding response performance metrics for each model under a uniform input load.
Figure 22: Temporal Sequence LSTM AUC-ROC versus Accuracy by Sequence Length (Forward and Reverse)
5Results and Discussion
5.1Performance Metrics
This chapter reports model performance using a full binary-classification view rather than accuracy alone. The confusion matrix decomposes predictions into true negatives (TN), false positives (FP), false negatives (FN), and true positives (TP). In the security context, a false positive means that benign traffic is incorrectly blocked or flagged as malicious, which can disrupt legitimate users and increase analyst workload. A false negative is the opposite and is more critical operationally because a malicious flow is missed and allowed to proceed.
For the positive attack class, precision measures how many predicted attacks are truly attacks: Precision = TP / (TP + FP). Recall measures how many real attacks are recovered: Recall = TP / (TP + FN). F1-Score is the harmonic mean of precision and recall, so it penalizes models that perform well on only one of the two. False Positive Rate is computed as FP / (FP + TN) and is especially important in intrusion detection because it captures the rate at which benign traffic is mistakenly escalated or blocked.
Table: 1 summarizes these metrics, their formulas, and their security interpretation.
Table 45: Binary Classification Metrics Used in This Chapter
Metric
Formula
Security Interpretation
Confusion Matrix
[[TN, FP], [FN, TP]]
Shows correct vs. incorrect decisions for benign and attack traffic
Precision
TP / (TP + FP)
How many flagged attacks are truly malicious
Recall
TP / (TP + FN)
How many real attacks are detected
F1-Score
2PR / (P + R)
Balanced summary of precision and recall
False Positive Rate
FP / (FP + TN)
Rate at which benign traffic is incorrectly flagged
5.2Experimental Results
Table: 2 reports the detailed classification results for CIC-IDS2017.
Tables 5.4 and 5.5 decompose the within-dataset results into confusion matrix form. This view is essential for security operations because it reveals the absolute numbers of missed attacks (false negatives) and false alarms on benign traffic (false positives), which directly impact operational workload and detection effectiveness.
Table 48: Confusion Matrix with Percentages for Models on CIC-IDS2017 (within-dataset)
Model
TN (% of Neg)
FP (% of Neg)
FN (% of Pos)
TP (% of Pos)
Random Forest
453,742 (99.88%)
523 (0.12%)
96 (0.09%)
111,215 (99.91%)
CNN
447,931 (98.62%)
6,334 (1.39%)
2,168 (1.95%)
109,143 (98.05%)
LSTM
453,163 (99.76%)
1,102 (0.24%)
1,183 (1.06%)
110,128 (98.94%)
Table 49: Confusion Matrix with Percentages for Models on UNSW-NB15 (within-dataset)
Model
TN (% of Neg)
FP (% of Neg)
FN (% of Pos)
TP (% of Pos)
Random Forest
17,806 (95.73%)
794 (4.27%)
1,954 (5.93%)
30,981 (94.07%)
CNN
17,180 (92.37%)
1,420 (7.63%)
1,907 (5.79%)
31,028 (94.21%)
LSTM
16,888 (90.80%)
1,712 (9.20%)
1,656 (5.03%)
31,279 (94.99%)
On CIC-IDS2017, the confusion matrices reveal the superiority of Random Forest in controlling false alarms. With only 523 false positives on 454,265 benign flows, Random Forest achieves a false positive rate of just 0.12%, meaning that legitimate network traffic is almost never incorrectly flagged. This is critically important operationally: analysts are not overwhelmed with false alarms, and trust in the IDS remains high. LSTM follows closely at 0.24% false positive rate, while CNN's 1.39% false positive rate indicates that for every 100 benign flows, roughly 1–2 are incorrectly escalated. In intrusion detection, where alert fatigue directly reduces analyst effectiveness, this difference is substantial.
On UNSW-NB15, the picture is more complex. Random Forest again achieves the lowest false positive rate at 4.27%, compared to CNN's 7.63% and LSTM's 9.20%. However, UNSW's smaller benign class size (18,600 benign flows total) means the absolute number of false positives remains modest even for LSTM (1,712). The false negative rates on UNSW are also more problematic than on CIC: Random Forest misses 1,954 attacks (5.93%), while CNN misses approximately 1,907 (5.79%) and LSTM misses 1,656 (5.03%). These missed attacks represent a concrete security gap. The trade-off is clear: Random Forest minimizes false alarms but still lets some attacks through; LSTM accepts more false positives but retrieves slightly more total attacks. In a production environment, this trade-off should be driven by the cost of each error type, not by accuracy alone.
The key insight from Tables 5.4 and 5.5 is that the models exhibit remarkably different error profiles between the two datasets. On CIC, all three models control false positives effectively (0.12–1.39%), while on UNSW, false positive rates are substantially higher (4.27–9.20%). This dataset-level difference in false positive behavior foreshadows the cross-dataset experiments in Section 4.5, where the same models trained on one dataset and tested on another will experience dramatic increases in false positives and missed attacks. The 'clean' confusion matrices in this chapter demonstrate what good within-dataset detection looks like; Section 4.5 contrast this with the 'frustrated' matrices resulting from domain shift.
All three models demonstrate excellent performance on the CIC-IDS2017 dataset, reflecting the well-structured and representative nature of this benchmark. The Random Forest model achieves the highest accuracy of 99.89% and an AUC-ROC of 99.99%, establishing a strong baseline. The LSTM model closely follows with 99.59% accuracy and 99.98% AUC-ROC, demonstrating the effectiveness of sequential feature learning. The CNN model achieves 98.50% accuracy, slightly lower than the other two models on this dataset.
A notable finding is the significant difference in training time between Random Forest (53.4 seconds) and the deep learning models (CNN: 416.6s, LSTM: 389.9s). This difference, approximately 7-8x, has important implications for practical deployment scenarios where rapid model retraining on updated traffic data may be required.
5.5Classification Analysis
The CIC-IDS2017 dataset exhibits a class imbalance of approximately 80:20 (benign:attack). The Random Forest model's balanced class weight configuration effectively handles this imbalance, achieving near-perfect precision and recall across both classes. The CNN model shows slightly lower recall for the attack class (0.98), suggesting minor underfitting relative to the other models. The LSTM model achieves uniform 0.99 precision and recall across both classes.
5.6Within-Dataset Performance Analysis: UNSW-NB15
Performance on UNSW-NB15 is uniformly lower across all models compared to CIC-IDS2017, consistent with findings in the broader literature attributing this difference to the greater feature complexity and diverse attack taxonomy of UNSW-NB15. The Random Forest model again achieves the highest accuracy (94.67%) and F1-Score (95.75%), with a remarkably short training time of 1.7 seconds.
The CNN and LSTM models achieve nearly identical performance (93.54% vs 93.46% accuracy), suggesting that for tabular network flow features with a single temporal step, the architectural differences between convolutional and recurrent processing produce marginal effects. Both models achieve AUC-ROC of 98.75%, indicating strong discriminative capability despite lower accuracy.
5.7Comparative Overview
The cross-dataset analysis reveals consistent ranking across both environments: Random Forest outperforms deep learning models on both datasets in terms of accuracy and F1-score, while deep learning models demonstrate competitive AUC-ROC values. The performance gap between datasets (approximately 5% accuracy reduction on UNSW-NB15) is consistent across all three models, suggesting dataset-level characteristics rather than model-specific limitations as the primary driver.
The fundamental incompatibility of feature spaces between CIC-IDS2017 (78 features) and UNSW-NB15 (42 features) is addressed through the systematic 15-feature semantic mapping developed in Section 3.6, enabling the cross-dataset transfer evaluation reported in Section 4.5. This outcome underscores the practical importance of feature standardization in network intrusion detection research and demonstrates that domain-invariant representations are achievable through careful domain-knowledge-guided alignment.
5.8Discussion
The experimental results yield several important insights. The consistent superiority of Random Forest across both datasets challenges the assumption that deep learning architectures necessarily outperform classical methods for network intrusion detection. This finding aligns with recent meta-analyses (e.g., Grinsztajn et al., 2022) demonstrating that tree-based ensemble methods remain competitive with deep learning on tabular data, which constitutes the predominant format of network flow features.
The relatively modest performance advantage of Random Forest over deep learning models must be contextualized against the false-positive behavior reported above. In scenarios where model interpretability, training efficiency, and low false-alarm rates are prioritized, Random Forest is the most practical baseline. Deep learning models remain competitive, however, when the goal is to maximize recall or when the input representation is richer than tabular flow statistics.
The near-identical performance of CNN and LSTM on UNSW-NB15 warrants additional interpretation. The design choice to treat the feature vector as a single-timestep sequence for LSTM training fundamentally limits the model's ability to exploit temporal dependencies, which represents its main theoretical advantage over CNN. Because the current datasets provide flow-level aggregates rather than packet-level sequences, both deep models are effectively learning from static feature vectors, which reduces the practical distinction between them.
On CIC-IDS2017, LSTM slightly outperforms CNN, suggesting that the recurrent processing path extracts more informative structure from the higher-dimensional feature space. However, the difference is still modest compared with the advantage of Random Forest in false-positive control. This reinforces the broader message that IDS model selection should be driven by the operational cost of errors, not only by aggregate accuracy.
The observed performance gap between CIC-IDS2017 and UNSW-NB15 reflects fundamental differences in dataset characteristics. CIC-IDS2017, with its larger sample size and cleaner feature engineering through CICFlowMeter, provides a more favorable learning environment. UNSW-NB15's greater attack diversity and different class distribution naturally produce lower performance for all models. The results therefore reflect both architecture choice and dataset structure.
The near-perfect accuracy and AUC-ROC values obtained on CIC-IDS2017 (Random Forest: 99.89% accuracy, 99.99% AUC-ROC) warrant explicit discussion. CIC-IDS2017 is a highly structured benchmark in which attack flows are generated in controlled laboratory conditions, producing clearly separable traffic signatures across a small number of flow-level features. Published work on this dataset consistently reports accuracy in the 97–99% range, and near-perfect separation is achievable because the benign and attack distributions overlap very little. The substantially lower performance on UNSW-NB15 (94.67% for Random Forest) confirms that these high values are dataset-specific: UNSW-NB15 contains a more realistic traffic mix, greater class diversity, and different feature distributions that present a harder generalisation challenge. The cross-dataset experiments in Section 4.5, where accuracy falls to 36–70%, further confirm that in-distribution performance on CIC-IDS2017 should not be interpreted as a guarantee of real-world deployability.
5.9Training Efficiency
5.10Training Efficiency Analysis
Training time exhibits the most dramatic variation across models and datasets. On the smaller UNSW-NB15 dataset, Random Forest completes training in 1.7 seconds compared to approximately 35.2 seconds for CNN and 34.6 seconds for LSTM. On the larger CIC-IDS2017 dataset, this advantage narrows proportionally: Random Forest trains in 53.4 seconds while deep learning models require 390-417 seconds (approximately 7x longer).
GPU acceleration (NVIDIA RTX 5060, CUDA 12.8) is employed for CNN and LSTM training. Without GPU acceleration, deep learning training times would be substantially higher, further widening the efficiency gap relative to Random Forest. For deployment scenarios requiring frequent model retraining, Random Forest presents a significant practical advantage.
5.11Cross-Dataset Generalization Discussion
The cross-dataset results reveal a dramatic performance degradation across all three models compared to their within-dataset baselines, confirming the hypothesis that feature space differences between network environments constitute a significant generalization barrier. However, the magnitude and nature of this degradation differs substantially across models, yielding critical insights for operational security. From a cybersecurity perspective, the most important metrics are False Positive Rate (FPR) and False Negative Rate (FNR), not accuracy. An IDS that achieves 90% accuracy but produces alert fatigue (high FPR) is less useful operationally than one that achieves 70% accuracy but maintains analyst trust through low false alarms.
The Random Forest model exhibits catastrophic cross-dataset behavior, achieving only 36.09% accuracy and 37.26% AUC-ROC. More critically, when examining Table 4.9, it achieves a FPR of 0.00% because it defaults entirely to predicting benign, missing all 164,673 attacks (FNR = 100%). The model's decision boundaries learned on CIC-IDS2017 do not transfer to UNSW-NB15. From an operational standpoint, this model is useless: it never raises an alarm, so analysts face zero alert burden but receive zero detection, an operational failure that raw accuracy completely obscures.
The CNN model also struggles with cross-dataset transfer, achieving 39.78% accuracy and 68.90% AUC-ROC. More critically, Table 4.9 reveals that CNN recovers 13,136 attacks while producing 3,972 false positives on 93,000 benign flows, yielding FPR = 4.27% and FNR = 92.02%. This FPR is substantially higher than CNN's within-dataset FPR of 1.39% on CIC. The model faces a fundamental trade-off: to capture more attacks (reduce FNR), it must flag more benign traffic (increase FPR). The security question is whether 3,972 false alarms is tolerable when 151,537 attacks are still missed.
The LSTM model shows comparatively stronger cross-dataset behavior, achieving 70.07% accuracy, 70.60% F1-score, and 74.67% AUC-ROC. More importantly, Table 4.9 reveals a more balanced error profile: FPR = 16.47% and FNR = 37.54%. This means LSTM catches 102,849 attacks while flagging 15,313 benign flows as attacks, and misses 61,824 attacks. From an operational security perspective, LSTM is the only model that provides meaningful cross-domain detection while maintaining some semblance of manageable analyst workload. This balance (captured in FPR/FNR, not accuracy) is what matters for production deployment.
The values in Table 4.8 are now based on fair within-dataset baselines computed on the same reduced 15-feature representation used in the cross-dataset experiment. This removes the confounding effect of full-feature vs reduced-feature evaluation and makes the comparison directly interpretable.
For the forward experiment, the drop is computed against the CIC 15-feature baseline, because CIC is the source domain used to train the cross-dataset models. Under this fair setup, the strongest degradation is observed for Random Forest (from 98.62% to 36.09%), while LSTM retains the smallest drop (from 97.50% to 70.07%), confirming that recurrent modeling is the most robust to domain shift in the shared 15-feature space.
5.12Training Data Asymmetry in Cross-Dataset Experiments
A limitation of the cross-dataset experimental design is the substantial training data asymmetry: models are trained on 2.8M CIC samples and tested on 257K UNSW samples (11:1 ratio). This asymmetry means the models have vastly more exposure to CIC traffic patterns than to UNSW traffic patterns. While this is a realistic scenario for some deployment contexts (where a large labeled dataset exists for one network environment but not another), it limits the interpretability of the results: the 70.07% LSTM accuracy in the forward direction may be partially attributable to the larger training set rather than architectural superiority. To address this, future work should conduct cross-dataset experiments with balanced training set sizes (e.g., subsampling CIC to match UNSW's sample count) to isolate the effect of architecture from the effect of training data volume. The reverse transfer experiment (UNSW→CIC) partially addresses this by training on the smaller dataset and testing on the larger dataset, representing a more challenging scenario where training data is limited.
5.13Cross-Dataset Transfer Discussion
5.14Discussion and Implications: Prioritizing FPR and FNR Over Accuracy
The cross-dataset experiment yields three principal findings with direct implications for IDS research and deployment. First, high within-dataset accuracy does not imply cross-dataset generalizability, and more importantly, accuracy is the wrong metric for cross-dataset evaluation in security contexts. Models achieving near-perfect within-dataset accuracy (96–99%) may exhibit FPR/FNR profiles that make them operationally useless across domains. Random Forest's 0% FPR in cross-dataset transfer (Table 4.9) appears to be an advantage until revealed as a failure to detect any attacks (FNR = 100%). This finding underscores the importance of multi-dataset evaluation using false-alarm and missed-detection metrics as the primary success criteria, not accuracy.
Second, the LSTM architecture demonstrates superior cross-dataset generalization despite the accuracy metric appearing less favorable. More precisely, LSTM achieves a balanced trade-off between FPR (16.47%) and FNR (37.54%) across datasets, whereas Random Forest optimizes for zero false positives by detecting nothing (FNR = 100%) and CNN shows poor ranking quality. This suggests that recurrent architectures may learn more abstract, environment-independent representations of network behavior. From an operational deployment perspective, LSTM is preferable because it accepts a non-zero false positive rate in exchange for meaningful detection capability, a trade-off that makes security sense.
Third, the 15-feature shared space, while enabling cross-dataset evaluation, necessarily discards 63 CIC-IDS2017 features and 27 UNSW-NB15 features. The performance ceiling of models trained in this reduced feature space is unknown, as within-dataset results in the full feature spaces provide the only reference. Future work on standardized network flow feature extraction could eliminate this limitation by ensuring feature compatibility across datasets at the collection stage.
5.15Reverse Cross-Dataset Transfer Discussion
A critical factor in the reverse experiment is the severe training data asymmetry: models train on only 257,673 UNSW samples but evaluate on 2,827,876 CIC samples. This imbalance has profound operational implications. Random Forest achieves the highest accuracy at 63.46%, but its FPR = 29.10% (661,029 false positives) creates overwhelming alert fatigue: an analyst faces nearly 660K false alarms while still missing 372,220 attacks (FNR = 66.88%). The accuracy metric obscures operational failure. CNN performs even worse with FPR = 45.47% (1,032,840 false positives) and FNR = 70.43%. LSTM's FPR = 36.31% and FNR = 50.49% represent more balanced errors, though still operationally problematic. From a security standpoint, reverse transfer is fundamentally limited by the small UNSW training set, which cannot learn generalizable patterns.
The key insight from reverse transfer is that False Positive Rate is the dominant failure mode. When training data is limited, all models default to flagging many benign flows as malicious rather than learning accurate boundaries. Random Forest's 29.10% FPR means legitimate network traffic is disrupted and analyst trust collapses. This FPR pattern, not accuracy, determines whether the model is usable operationally. LSTM's marginally lower FPR (36.31% vs 29.10% for RF) comes at the cost of higher FNR, but it still represents a more defensible trade-off.
The LSTM again provides the most balanced behavior, with 60.92% accuracy, 64.67% F1-score, and 63.66% AUC-ROC. Although these values are lower than the within-dataset baselines, they are materially stronger than the CNN results and more stable than Random Forest in terms of ranking quality. Interestingly, the LSTM's superior performance despite the reduced training set size suggests that recurrent architectures are more efficient learners: they require fewer training samples to extract transferable temporal and sequential patterns from network flow features.
The asymmetry between the two cross-dataset directions confirms that generalization is not symmetric and is heavily influenced by data quantity. Training on UNSW and testing on CIC produces better accuracy for Random Forest than the opposite direction, but the ranking quality remains weak. By contrast, LSTM consistently shows the most robust transfer behavior in both directions, which supports the interpretation that sequential feature processing captures more abstract traffic patterns than tree-based splitting or local convolutional kernels, and that LSTM achieves better sample efficiency in learning these abstractions.
Overall, the reverse experiment reinforces the main conclusion of Section 4.5: cross-dataset intrusion detection is highly sensitive to dataset shift, class balance, feature distribution mismatch, and training data quantity. Even when the semantic feature mapping is preserved, performance can change sharply depending on the training domain and the size of the training set. The LSTM's ability to maintain reasonable performance with only ~9% of the CIC training data demonstrates that model architecture choice interacts strongly with data efficiency, a critical consideration for practical IDS deployment where labeled traffic data may be limited.
5.16Confusion Matrix Interpretation
Forward transfer is the harder setting because UNSW contains a large number of attack flows. Random Forest collapses into a benign-only rule, which explains the zero true positives and the weak ranking quality. CNN improves slightly but still misses most attacks. LSTM is the only model that retrieves a substantial fraction of attacks, which is consistent with its superior AUC-ROC in Section 4.5.
It is worth noting that RF's complete failure in the forward direction is not simply a consequence of data volume. In fact, the reverse experiment shows that RF achieves better accuracy when trained on far fewer samples (257K UNSW vs. 2.8M CIC), which might seem counterintuitive. The real driver is feature distribution shift: the decision boundaries RF learned from CIC-IDS2017 traffic simply do not map onto UNSW-NB15's different network environment, causing the model to default entirely to predicting benign. CNN faces the same underlying problem: despite detecting a small fraction of attacks (8%), it still misses 92% of them, suggesting that its convolutional filters captured CIC-specific patterns rather than generalizable attack signatures. Both RF and CNN reflect a fundamental limitation of models that memorize precise feature patterns rather than learning abstract traffic behavior, making them highly sensitive to any shift in the underlying data distribution. LSTM, by contrast, demonstrates that sequential processing offers a degree of natural resilience to this shift.
Reverse transfer shows a different error profile. Random Forest has the highest accuracy, but it also produces many false positives and still misses a large number of attacks. CNN yields the weakest overall balance. LSTM again offers the most stable compromise between false alarms and missed attacks, which matches the broader pattern that it is the most robust model under domain shift.
5.17Comparative Analysis: Forward vs. Reverse Cross-Dataset Performance
The most striking observation is the divergent accuracy trends across models. Random Forest exhibits a dramatic 27.37 percentage point improvement when trained on the smaller UNSW dataset and tested on the larger CIC dataset. However, this improvement in accuracy is accompanied by a corresponding improvement in ranking quality: the AUC-ROC increases by 13.95 points, from 37.26% to 51.21%. While this gain might seem positive at first glance, an AUC-ROC of 51.21% is barely above random chance (50%), meaning the model cannot reliably distinguish malicious from benign traffic despite its higher accuracy. The accuracy gain therefore masks a fundamental failure in decision boundary robustness: the model achieves better accuracy simply by defaulting to the dominant class in the CIC test set, not by learning transferable attack signatures.
In contrast, CNN's accuracy improves slightly in the reverse direction (39.78% to 49.61%, a 9.83 point gain), but its AUC-ROC collapses dramatically: from 68.90% forward to 37.85% reverse, a drop of 31.05 points. This is the sharpest ranking quality degradation observed across all models and both directions. A 37.85% AUC-ROC is actually below random chance, indicating that the CNN's predictions are systematically inverted when the training domain is reversed. This pattern suggests that convolutional filters, particularly when trained on limited UNSW data (257K samples), fail to extract abstractions that generalize across network flow distributions, and that the filters learned on UNSW may actively mislead classification on CIC traffic.
The LSTM exhibits the most consistent behavior across directions. Forward accuracy is 70.07% with 74.67% AUC-ROC; reverse accuracy is 60.92% with 63.66% AUC-ROC. Both metrics decline in the reverse direction, but the declines are moderate, 9.15 points in accuracy and 11.01 points in AUC-ROC, and the absolute performance remains superior to RF and CNN in ranking quality across both settings. Critically, LSTM maintains AUC-ROC values well above random (50%) in both directions, indicating that the model reliably ranks attack traffic above benign traffic regardless of which domain it was trained on. This consistency suggests that LSTM's sequential processing architecture captures more abstract, direction-invariant traffic patterns compared to tree-based splitting or local convolutional kernels.
The asymmetry between forward and reverse directions reveals the true operational constraints of cross-dataset transfer: False Positive Rates become unmanageable. In forward transfer (CIC→UNSW), LSTM achieves FPR = 16.47% (Table 4.9), meaning roughly 1 in 6 benign flows are flagged. In reverse transfer (UNSW→CIC), LSTM achieves FPR = 36.31% (Table 4.10), meaning roughly 1 in 3 benign flows are flagged. Random Forest performs even worse: forward FPR = 0%, which sounds ideal until you realize it achieves this by detecting nothing at all (FNR = 100%), and reverse FPR = 29.10%, generating over 661K false alarms. These FPR differences drive operational decisions far more than accuracy metrics. From a security standpoint, reverse transfer with 36% FPR would overwhelm any SOC with false alarms, whereas forward transfer with 16.5% FPR is more defensible when attack detection is the priority.
Ultimately, the bidirectional comparison reinforces a core finding: no single metric tells the full story. Random Forest (forward FNR = 100%, reverse FNR = 66.88%), CNN (forward FNR = 92.02%, reverse FNR = 70.43%), and LSTM (forward FNR = 37.54%, reverse FNR = 50.49%) each present different trade-off profiles. LSTM is the only model that achieves a balanced FPR/FNR trade-off in both directions: 16.47%/37.54% forward and 36.31%/50.49% reverse. Neither profile is operationally ideal, but LSTM is the only model that provides meaningful cross-domain detection capability. For practical IDS deployment, model selection should be driven by acceptable FPR/FNR operating points relative to the cost of missed attacks versus analyst alert fatigue, not by accuracy rankings alone.
5.18Temporal Sequence Analysis
5.19Within-Dataset Sequence Results Analysis
Table: 12 presents the within-dataset temporal LSTM performance across CIC-IDS2017 and UNSW-NB15 for sequence lengths 5, 10, and 20. A clear trend emerges: as sequence length increases, CIC accuracy decreases consistently (96.28% → 95.69% → 94.85%), while UNSW accuracy shows a non-monotonic pattern: dipping at sequence length 10 (97.51%) before recovering to peak performance at sequence length 20 (99.26%). This asymmetry reflects differences in the underlying flow structure and temporal organization between the two datasets. UNSW benefits from longer context windows, achieving near-perfect performance at sequence length 20 (99.26% accuracy, 0.9973 AUC). In contrast, CIC exhibits a modest decline, suggesting that longer windows may incorporate increasingly noisy flow relationships in this dataset. Both datasets maintain high AUC-ROC across all sequence lengths (CIC: 0.9493–0.9717, UNSW: 0.9973–0.9988), indicating that the temporal LSTM reliably ranks attack traffic despite occasional accuracy fluctuations.
5.20Cross-Dataset Sequence Results: Temporal Impact on Error Rates
Table: 13 and Table 4.14 present the cross-dataset transfer results for CIC→UNSW and UNSW→CIC. The most significant finding for security operations is not the accuracy metric, but the improvement in False Negative Rate (FNR) at sequence length 20 for CIC→UNSW: accuracy remains modest (48.95%) but more critically, Table 4.15 reveals that FNR improves substantially compared to non-temporal baselines. Temporal context allows the model to recover more attack instances despite maintaining similar false positive rates, achieving a better FPR/FNR trade-off. This improvement in operational error balance, not raw accuracy, is what matters for practical intrusion detection.
In contrast, UNSW→CIC transfer exhibits problematic error rate behavior: sequence length 5 achieves 80.20% accuracy with FPR = 11.01% and FNR = 29.45%, but increasing to sequence length 20 causes dramatic changes: accuracy drops to 41.65%, FPR increases to 64.77%, and FNR increases to 32.13%. The accuracy collapse is operationally catastrophic: an analyst deployed this model would see nearly 2 in 3 benign flows flagged as attacks (overwhelming alert fatigue) while still missing 1 in 3 actual attacks. This counterintuitive finding reveals that UNSW's temporal structure, when extended to longer sequence windows, encodes dataset-specific patterns that amplify domain shift rather than generalizing. From a security perspective, the operator must choose: either accept 64.77% FPR and 32.13% FNR at sequence length 20, or use sequence length 5 with more manageable 11.01% FPR and 29.45% FNR. Neither is operationally acceptable, but length 5 is clearly preferable despite lower accuracy.
5.21Confusion Matrix Breakdown: Revealing Temporal Impact on False Alarms and Missed Attacks
Table: 15 translates the best temporal setting (sequence length 20) into confusion-matrix form with explicit FPR and FNR calculations. This is the most useful view for security operations because it reveals the operational costs: how many attacks are missed (FNR) and how many benign flows trigger false alarms (FPR). From a cybersecurity standpoint, these error rates determine whether a model is deployable.
The confusion-matrix view (Table 4.15) clarifies the operational meaning and reveals critical differences driven by FPR and FNR. On UNSW within-dataset, FNR = 0.02% means the temporal model almost never misses attacks, a tremendous operational advantage. On CIC within-dataset, FPR = 0.82% and FNR = 22.85% represent excellent performance: very few false alarms and most attacks detected. In the forward cross-dataset setting (CIC→UNSW), FPR = 4.56% and FNR = 77.29%: the model catches many fewer attacks (misses 77% of them) but maintains reasonable false-alarm rates. In the reverse setting (UNSW→CIC), FPR explodes to 64.77% and FNR = 32.13%, creating catastrophic alert fatigue: nearly 2 in 3 benign flows are flagged as malicious. From an operator's perspective, forward transfer is marginally acceptable if attacks are critical; reverse transfer is operationally unusable.
5.22Bidirectional Transfer Analysis: FPR/FNR Asymmetries
The cross-dataset results reveal striking asymmetries in False Positive and False Negative rates between CIC→UNSW and UNSW→CIC transfer. Forward transfer (CIC→UNSW) achieves FPR = 4.56% and FNR = 77.29% at sequence length 20: moderate false alarms but poor attack recovery. This represents a practical compromise: analyst trust is preserved (only 1 in 20 alerts are false) despite poor attack detection. Backward transfer (UNSW→CIC) achieves FPR = 64.77% and FNR = 32.13%: catastrophic false positives that would overwhelm any SOC while still missing 1 in 3 attacks. This asymmetry is not explained by model architecture alone; it reflects the directional nature of temporal domain shift. CIC→UNSW transfer benefits from CIC's temporal structure, which generalizes; UNSW→CIC transfer suffers because UNSW's temporal patterns do not align with CIC's attack dynamics.
The operational implication is critical: from a security perspective, forward transfer at sequence length 20 is defensible despite low accuracy (48.95%), because the FPR/FNR trade-off is reasonable. Reverse transfer is indefensible at length 20 due to 64.77% FPR, and even at length 5 with FPR = 11.01% and FNR = 29.45%, it remains suboptimal compared to forward transfer's 4.56% FPR. This finding emphasizes that temporal context has directional effects on error rates: it reduces FNR in forward transfer but dramatically increases FPR in reverse transfer. Model selection should be driven by which FPR/FNR operating point is acceptable, not by accuracy rankings.
5.23Comparison Against Previous Non-Temporal Models: FPR/FNR Improvements
Comparing temporal LSTM results to the non-temporal LSTM baselines from Section 4.5 reveals that temporal modeling produces directional effects on error rates. Within-dataset: UNSW temporal LSTM achieves FNR = 0.02% at sequence length 20, dramatically better than within-dataset baselines, meaning the temporal model catches almost all attacks. CIC temporal LSTM maintains reasonable FPR/FNR balance across sequence lengths. Cross-dataset (CIC→UNSW): the key improvement is not accuracy, but FPR/FNR balance. Table 4.15 shows that temporal modeling at sequence length 20 achieves FPR = 4.56% and FNR = 77.29%, compared to the non-temporal LSTM’s FPR = 16.47% and FNR = 37.54% in the same forward cross-dataset setting (Table 4.9), temporal context substantially reduces false positives (FPR: 16.47%→4.56%) at the cost of higher missed attacks (FNR: 37.54%→77.29%). This represents a directional shift in the FPR/FNR trade-off rather than a uniform improvement: temporal modeling benefits analyst false-alarm experience while sacrificing attack detection coverage in the cross-domain setting.
5.24Discussion: Temporal Context as an FPR/FNR Management Tool
The temporal sequence learning experiments reveal that flow-level temporal context has asymmetric effects on False Positive and False Negative rates across domains. Forward transfer (CIC→UNSW) achieves improved FPR/FNR balance at sequence length 20: FPR = 4.56% and FNR = 77.29%, representing managed false alarms with substantial attack recovery. This operational improvement has practical significance: in production intrusion detection, the ability to maintain low false positive rates while recovering 22–23% of attacks (1 - FNR) is valuable despite low absolute accuracy. Reverse transfer exhibits opposite behavior: FPR explodes to 64.77% at sequence length 20, making this setting operationally unusable. This directional asymmetry suggests that temporal context amplifies or reduces domain shift depending on the training domain.
The key operational insight is that model selection in temporal transfer scenarios should be driven by FPR/FNR operating points, not accuracy. A 48.95% accuracy model (CIC→UNSW, length 20) is deployable if it achieves 4.56% FPR, because analysts can tolerate roughly 1 false alarm per 22 alerts while capturing legitimate threats. Conversely, a 41.65% accuracy model (UNSW→CIC, length 20) is not deployable with 64.77% FPR, because overwhelming alert fatigue would cause operators to disable the system. The accuracy metric completely fails to distinguish between these two cases; FPR/FNR metrics reveal the critical operational difference.
The temporal framework also illuminates the asymmetric nature of domain shift in intrusion detection. If domain shift were purely a feature-level mismatch, temporal context should help equally in both transfer directions, or hurt equally. Instead, the directional effects on error rates suggest that dataset-specific temporal structures either facilitate (CIC→UNSW) or impede (UNSW→CIC) generalization. CIC, generated in controlled laboratory conditions, may encode temporal patterns that generalize well; UNSW, collected from a real network, may encode environment-specific temporal patterns that conflict with CIC's attack dynamics. This hypothesis warrants further investigation in future work.
5.25Temporal Sequence Caveats
This temporal design depends critically on the quality and reliability of flow-level ordering information. CIC-IDS2017 contains explicit timestamps and is generated in controlled laboratory conditions, resulting in cleaner temporal structure. UNSW-NB15 may have less reliable or less informative temporal ordering because it is drawn from a production network where flow granularity may obscure true packet dynamics. The resulting sequences are operationally useful but represent an aggregation level between individual packets (too fine) and traffic flows (already extracted). Temporal conclusions derived from this flow-level window representation should therefore be treated as indicators of short-range behavioral patterns rather than definitive reconstruction of packet-level causality or true temporal dynamics.
Additionally, the class imbalance inherent in intrusion detection datasets means that accuracy improvements can be misleading. The dramatic accuracy drop in UNSW→CIC at sequence length 20 (80.20% → 41.65%) is partially due to this issue: the model may be predicting all sequences as benign at longer windows, achieving misleadingly low accuracy while maintaining moderate AUC through ranking. The use of AUC-ROC as the primary metric mitigates this issue but does not entirely resolve it. Future work should employ cost-sensitive loss functions and per-class analysis to better understand whether temporal context genuinely improves detection or merely redistributes prediction confidence.
5.26Overlapping Window Methodology and Its Limitations
The sliding window construction used in this study allows overlapping windows within each split (Section 3.4.4): for sequence length L, consecutive windows share L−1 flow records, since the window is advanced by a single record (stride = 1) rather than by a full window length. This is a deliberate design choice consistent with common practice in time series classification, where overlapping windows increase the number of training samples and capture patterns that may span multiple window boundaries. However, overlapping windows reduce sample independence: because consecutive windows share nearly all of their input records, the model may effectively see highly correlated data multiple times, which can inflate reported performance relative to a strictly independent-sample evaluation.
This thesis did not conduct a non-overlapping (stride = sequence length) ablation to quantify this effect, and the reported temporal sequence results (Section 4.6, Tables 4.12–4.14) should therefore be interpreted with this caveat in mind: some portion of the observed improvement from temporal context may be attributable to the overlapping window construction rather than to genuine temporal signal alone. Disentangling these two effects requires re-running the sliding-window experiments with a non-overlapping stride, which is left as future work.
5.27Summary of Temporal Findings
Section 5.5 demonstrates that true temporal sequence learning (with properly ordered, class-aware train/test splitting and configurable window sizes) fundamentally changes the transfer behavior of LSTM models in network intrusion detection. The key findings are: (1) within-dataset performance is dataset-dependent, with UNSW benefiting significantly from longer sequences while CIC shows modest gains; (2) cross-dataset AUC-ROC can be substantially improved through temporal context, with CIC→UNSW transfer achieving 0.8159 AUC at sequence length 20, a 28% improvement over sequence length 5; (3) transfer is asymmetric, with UNSW→CIC transfer degrading at longer sequence lengths, indicating that temporal patterns are more dataset-specific than feature patterns; and (4) the optimal sequence length varies by source–target domain pair, suggesting that temporal horizon selection should be part of transfer learning hyperparameter tuning.
The temporal framework advances the thesis in three ways. First, it provides a rigorous methodology for temporal sequence construction that respects both causality and the underlying temporal assumptions of recurrent networks. Second, it demonstrates that temporal context can improve cross-domain transfer when properly exploited (CIC→UNSW), validating the hypothesis that temporal information contains transferable signal. Third, it reveals the limits of temporal transfer by showing that dataset-specific temporal structure can amplify domain shift (UNSW→CIC), highlighting a previously underexamined dimension of the domain adaptation problem. Together, these results establish temporal sequence learning as a valuable but dataset-dependent tool for improving intrusion detection transfer learning, and provide evidence that the effectiveness of transfer depends not only on feature alignment but also on structural similarity between source and target datasets.
5.28LLM Integration Assessment
The integration of a locally-deployed LLM for threat explanation generation addresses a critical usability gap in traditional IDS systems. Security operations centers frequently employ analysts with varying levels of technical expertise; the ability to receive natural language explanations of detected threats, including attack vector analysis and recommended response actions, significantly reduces the expertise barrier for IDS adoption.
The LM Studio integration demonstrates that locally-deployed LLMs can provide contextually relevant threat analyses based on structured IDS outputs. The privacy-preserving nature of local deployment is particularly relevant for security environments where network traffic data is sensitive and cannot be transmitted to external cloud services.
5.29Dashboard-Integrated Model Performance Results
The Streamlit dashboard was used to perform live inference on the CIC-IDS2017 DDoS traffic capture (Friday-WorkingHours-Afternoon-DDos.pcap_ISCX.csv) containing 225,711 network flows. Three trained models were evaluated through the dashboard interface, demonstrating the system's capability to analyse large-scale network captures with high detection accuracy and throughput suitable for operational network monitoring.
5.30Random Forest Classifier Results
The Random Forest model (rf_cic.pkl) achieved the highest throughput of the three models at 1,739,715 packets per second with a total inference time of 129.7 ms, demonstrating its suitability for high-speed network monitoring. Over the 225,711-flow dataset, the model classified 127,973 flows as threats (confidence ≥ 0.8), 733 flows as suspected (confidence 0.2–0.8), and 97,005 flows as normal traffic. Evaluation against ground-truth labels yielded: Accuracy = 0.9992, F1 (binary) = 0.9993, F1 (weighted) = 0.9992, ROC-AUC = 1.0000, Precision = 0.9988, Recall = 0.9998, FPR = 0.0016, and FNR = 0.0002. The confusion matrix recorded 97,532 true negatives, 154 false positives, 23 false negatives, and 128,002 true positives. The auto-remediation panel automatically detected the DDoS pattern and presented four mitigation actions. Figures 5.1 and 5.2 show the evaluation metrics and suspicious flow table respectively. Figure 5.3 shows the auto-remediation panel output.
Figure 23: Random Forest Analysis Status, Inference Performance, and Evaluation Metrics on CIC-IDS2017 DDoS Dataset
Figure 24: Random Forest – Top Suspicious Flows Table and Attack Confidence Timeline
The 1D Convolutional Neural Network model (cnn_cic_best.pt) processed the same 225,711-flow dataset in 1,261.1 ms achieving a throughput of 178,973 packets per second. The model classified 125,854 flows as threats, 3,012 as suspected, and 96,845 as normal. Evaluation metrics: Accuracy = 0.9911, F1 (binary) = 0.9921, F1 (weighted) = 0.9911, ROC-AUC = 0.9995, Precision = 0.9965, Recall = 0.9877, FPR = 0.0045, FNR = 0.0123. The confusion matrix showed 97,247 true negatives, 439 false positives, 1,581 false negatives, and 126,444 true positives. The CNN model showed a higher FNR (1.23%) compared to the Random Forest and LSTM models, indicating that some DDoS flows were misclassified as benign at this confidence threshold. Figures 5.4 and 5.5 show the CNN evaluation dashboard output.
Figure 26: CNN Model Analysis Status, Inference Performance, and Evaluation Metrics on CIC-IDS2017 DDoS Dataset
Figure 27: CNN Model – Top Suspicious Flows Table and Attack Confidence Timeline
5.32LSTM Model Results
The bidirectional LSTM model (lstm_cic_best.pt) achieved a throughput of 213,892 packets per second with an inference time of 1,055.3 ms. It classified 127,883 flows as threats, 601 as suspected, and 97,227 as normal. Evaluation metrics: Accuracy = 0.9990, F1 (binary) = 0.9992, F1 (weighted) = 0.9990, ROC-AUC = 1.0000, Precision = 0.9992, Recall = 0.9991, FPR = 0.0011, FNR = 0.0009. The confusion matrix showed 97,580 true negatives, 106 false positives, 110 false negatives, and 127,915 true positives. The LSTM achieved the lowest FNR (0.09%) and FPR (0.11%) among the three models evaluated on this dataset, closely matching the Random Forest performance while offering GPU-accelerated inference. Figures 5.6 and 5.7 show the LSTM evaluation dashboard output.
Figure 28: LSTM Model Analysis Status, Inference Performance, and Evaluation Metrics on CIC-IDS2017 DDoS Dataset
Figure 29: LSTM Model – Top Suspicious Flows Table and Attack Confidence Timeline
5.33Threat Report Log Viewing
After inference, the dashboard generates and displays a structured Network Intrusion Detection Analysis Report within an expandable log panel. The report provides the LLM with a complete, human-readable summary of the analysis run. It includes file metadata, model details, aggregate statistics (total flows, benign/malicious counts, average confidence), followed by detailed per-attack entries categorized as critical or warning severity. Each entry records the attack confidence, destination port, flow duration, packet counts, byte totals, flow rate, and any automatically identified behavioral patterns. The report concludes with a statistical summary covering top target ports and peak packet rates. Figures 5.8 and 5.9 show the log panel with the complete threat report generated from the CNN model analysis of the DDoS dataset.
Figure 30: System Log Panel – Network Intrusion Detection Analysis Report (Header and Critical Attacks Section)
Figure 31: System Log Panel – Warning Attacks Section and Statistical Summary
5.34Advanced Visualization Results
The advanced charts panel provides two complementary visualizations. The confidence distribution histogram stratifies all classified flows into four bands: Low (<0.2), Medium (0.2–0.5), High (0.5–0.8), and Critical (>0.8). For the DDoS dataset, the distribution is strongly bimodal, with the overwhelming majority of flows in the Critical band (attack traffic detected with near-certainty) and a secondary cluster in the Low band (benign traffic with very low attack probability). This bimodal separation is characteristic of high-quality DDoS detection and reflects the models' confidence. The Feature Correlation Heatmap visualizes pairwise Pearson correlations among all numeric result columns. In the DDoS dataset, strong positive correlations are observed among packet-count features and byte-count features, while flow duration shows negative correlation with packet rates, consistent with the short high-intensity bursts characteristic of DDoS attacks. Figure 5.10 shows both visualizations.
Figure 32: Advanced Charts Panel – Confidence Distribution and Feature Correlation Heatmap from DDoS Analysis
5.35LLM Threat Analysis Sessions
Four locally-deployed large language models were evaluated for cybersecurity threat explanation quality using the AI Security Chat interface. Each model received an identical structured threat log generated from CNN inference on the DDoS dataset (125,854 attacks from 225,711 flows; 50 critical entries with 100% confidence targeting port 80; 10 warning entries with 89–90% confidence). The prompt template instructs each model to act as a senior cybersecurity analyst and produce a structured Markdown report covering: executive summary, attack patterns identified, network intelligence, technical details, and recommended actions. The models were deployed locally via LM Studio with the OpenAI-compatible API endpoint at http://localhost:1234/v1/chat/completions.
5.36Gemma 4 E4B Analysis
The Gemma 4 E4B (Google Gemma 4, 4-billion parameter efficiency model, 4-bit quantized) produced a structured threat analysis report identifying a DDoS/SYN flood attack targeting web services on port 80 with high-volume TCP connection requests. The model characterized the attack as originating from multiple distinct connection patterns, noting both high-bandwidth sustained flows and short-burst connection attempts. Response performance metrics: Total Response Time = 42.46s, Time to First Token = 5.57s, Generation Speed = 47.6 tokens/s, Input Tokens = 4,347, Output Tokens = 1,997, Total Tokens = 6,344. Figures 5.11 and 5.12 show the analysis output; Figure 5.13 shows the response metrics panel.
The Gemma-4-26b-a4b-qat (26-billion parameter, 4-bit quantized) produced a more detailed threat characterization. The model identified the attack as a large-scale distributed denial-of-service campaign, noting consistently asymmetric traffic flows with very few forward packets but multiple backward packets, characteristic of SYN-ACK reflection patterns. It recommended implementing TCP SYN rate limiting, enabling connection tracking, and isolating the target service. Response performance metrics: Total Response Time = 88.37s, Time to First Token = 16.05s, Generation Speed = 13.7 tokens/s, Input Tokens = 4,347, Output Tokens = 1,209, Total Tokens = 5,556. The higher parameter count produced richer technical context at the cost of reduced token generation speed compared to Gemma 4 E4B. Figures 5.14 through 5.16 show the analysis output; Figure 5.17 shows metrics.
Figure 36: Gemma-4-26b-a4b-qat Analysis – Executive Summary and Attack Overview
Figure 37: Gemma-4-26b-a4b-qat Analysis – Attack Patterns and Network Intelligence
Figure 38: Gemma-4-26b-a4b-qat Analysis – Technical Details and Recommendations
The Qwen3.5 9B model (9-billion parameter, Qwen3.5 series by Alibaba (Qwen Team, 2025)) generated the most detailed executive summary among the evaluated models, identifying three distinct attack sub-patterns within the DDoS traffic: (1) High-Rate Packet Count flood (SYN/Connection Flood), characterized by extremely high packet rates of up to 20,202 packets/s with very short flow durations; (2) Connection Exhaustion (Slowloris Variant), exploiting long-lived connections with minimal data transfer to exhaust server connection tables; and (3) Specific Port Targeting: all attacks directed at ports 80 and 22, suggesting a coordinated campaign. The model also noted anomalous flow behaviour consistent with port mirroring or measurement artifacts in the dataset. Response performance metrics: Total Response Time = 99.01s, Time to First Token = 12.40s, Generation Speed = 19.4 tokens/s, Input Tokens = 4,347, Output Tokens = 1,923, Total Tokens = 6,270. The lower generation speed reflects the larger model size. Figures 5.18 through 5.21 show the analysis output; Figure 5.22 shows metrics.
The Qwen3.6-35b-a3b (35-billion parameter, 4-bit quantized mixture-of-experts, active 3 billion parameters; Qwen Team, 2025) produced the most comprehensive threat intelligence report. The model characterised the attack as a large-scale, sustained distributed denial-of-service campaign targeting web services on port 80 with over 10,000 connections per source IP observed, noting specifically: high-volume packet count with flow rates ranging from 1,500 to 20,202 packets/s; long-lived connection staleness consistent with session hijacking or resource exhaustion; and specific port targeting with distinct signatures present on both port 80 (HTTP) and port 22 (SSH). Forensic observations included that the consistent attack signature across multiple source patterns is distinct and consistent with the CIC-IDS2017 DDoS dataset's known ground truth. The model recommended immediate containment actions including blocking traffic at the network perimeter, enabling traffic scrubbing, and implementing multi-layer defence. Figures 5.23 through 5.26 show the analysis output; Figure 5.27 shows the response metrics.
5.40LLM Analysis Quality and Comparative Assessment
All four LLM models successfully generated structured cybersecurity threat reports from the IDS analysis logs without transmitting any sensitive data to cloud services. The comparative evaluation reveals a clear quality-speed trade-off: response times were Gemma 4 E4B (42.46s at 47.6 tok/s), Gemma 4 26B-A4B QAT (88.37s at 13.7 tok/s), Qwen3.5 9B (99.01s at 19.4 tok/s), and Qwen3.6-35b-a3b (141.79s at 13.2 tok/s), with larger models delivering substantially richer threat characterizations with multi-level attack pattern decomposition. The Qwen3.5 9B model offered the best balance between analytical depth and response time, identifying three distinct attack sub-categories within the DDoS traffic where smaller models produced only a single-category classification. The 35B parameter model provided the most forensically detailed report but at the highest computational cost. These results confirm that locally-deployed LLMs provide meaningful security analysis capability comparable to cloud-based approaches, with the significant advantage of preserving network traffic data confidentiality. Figures 5.28 and 5.29 show the AI chat interface after a completed analysis session and the last response metrics panel.
To ensure an objective quality assessment, a two-tier evaluation methodology was employed. Five graduate students in a cybersecurity course independently rated the four LLM threat reports on a 1–5 Likert scale across five analytical criteria (Table 5.6). In addition, two commercial large language models (GPT-4o and Claude 3.5 Sonnet) were used as independent evaluators: each was presented with the four reports and asked to assess comprehensiveness, technical accuracy, and actionability without prior knowledge of which model produced which report. Table 5.7 consolidates the findings into a deployment recommendation matrix
Qwen3.6 35B-A3B received the highest combined score (5.0/5) from both student and expert evaluators, followed by Qwen3.5 9B (4.8/5). Graduate students specifically noted that Qwen3.6 35B-A3B produced the most operationally useful output, characterising the DDoS campaign with connection-staleness patterns, forensic artefacts, and layered mitigation recommendations that a SOC analyst could act on without further interpretation. Gemma 4 E4B scored lowest (3.4/5) due to limited pattern analysis depth; however, its generation speed advantage (47.6 tok/s, 42.46 s total) represents a practical benefit in high-volume alert environments where rapid initial triage outweighs analytical completeness.
Table 51: LLM Model Deployment Recommendation Matrix
Model
Quality Score
Speed Rank
Recommended Deployment Context
Student Rank
Expert Rank
Gemma 4 E4B (Q4_K_M)
3.4 / 5
1st (fastest)
High-volume rapid triage
4th
4th
Gemma 4 26B-A4B QAT (Q4_0)
4.0 / 5
2nd
Balanced analysis
3rd
3rd
Qwen3.5 9B (Q6_K)
4.8 / 5
3rd
Detailed multi-pattern analysis
2nd
2nd
Qwen3.6 35B-A3B (Q4_K_M)
5.0 / 5
4th (slowest)
In-depth forensic investigation
1st
1st
Figure 50: AI Security Chat Interface After Completed Analysis Session – Structured Threat Report in Markdown
Figure 51: Last Response Metrics Panel Showing Token Usage and Generation Performance
5.7 Limitations
This study acknowledges several limitations. The binary classification formulation, while appropriate for the primary research objective, does not evaluate multi-class attack categorization, which is relevant for incident response prioritization. The temporal constraints of the thesis preclude live packet capture integration with the trained models, limiting evaluation to offline dataset analysis. Additionally, the current deep learning formulations operate on flow-level vectors rather than true packet sequences, which may underutilize their temporal modeling capacity. Furthermore, two of the fifteen cross-dataset feature mappings constitute approximations rather than exact semantic equivalents: the CIC-IDS2017 maximum packet length features (Fwd/Bwd Packet Length Max) are mapped to the UNSW-NB15 mean packet size features (smean/dmean), as no exact equivalent exists in the UNSW-NB15 schema. This feature-level approximation contributes to the domain shift observed in cross-dataset transfer and partially explains the elevated false positive rates in the UNSW→CIC direction. Additionally, hyperparameters for all models were selected without a dedicated validation split held out from CIC-IDS2017; the large scale of the training data (millions of samples) reduces the risk of in-domain overfitting, but does not guarantee that hyperparameters selected on CIC-IDS2017 are optimal for the UNSW-NB15 distribution encountered during cross-dataset evaluation, and computational and GPU resource constraints made a full nested train/validation/test protocol infeasible at this scale.
5.41Explainability Analysis: Why Models Generalize Differently Across Datasets
Chapters 4.5 and 5.4 established that all three models degrade sharply when trained on one dataset and evaluated on the other, and that the degradation is asymmetric across architectures. That analysis, however, relied on aggregate performance metrics (accuracy, F1, AUC-ROC, FPR, FNR) without examining which specific input features drive each model's predictions, or why the same shared 15-feature representation supports strong within-dataset detection but collapses under domain shift. This section applies SHapley Additive exPlanations (SHAP) (Lundberg & Lee, 2017) to the trained Random Forest, CNN, and LSTM models (Section 4.8) to answer this question directly, complementing the impurity- and activation-magnitude-based importance reported in Table 3.5 with a rigorous, model-agnostic attribution method applied consistently across all three architectures and all four experimental settings (within-CIC, within-UNSW, forward transfer, reverse transfer).
5.42Method
SHAP values were computed using shap.TreeExplainer for Random Forest (exact, path-dependent feature perturbation) and shap.GradientExplainer for CNN and LSTM. All reported models are the same already-trained artifacts used to produce Tables 4.1-4.15; no model was retrained for this analysis, with one disclosed exception: the Random Forest models used in the forward and reverse cross-dataset SHAP analysis were retrained using the identical hyperparameters, random seed, and data pipeline as the original training scripts, because the original run never persisted these two models to disk. Table 4.31 confirms this retraining reproduces the thesis-reported accuracy and AUC-ROC for all four scenarios to four decimal places, so the SHAP attributions computed from them are attributions of the same decision boundaries already reported in Tables 4.6, 4.7, 4.9, and 4.10, not attributions of a different model. Feature attribution is reported as mean absolute SHAP value, normalized to a percentage of the total across the 15 shared features, so that values are directly comparable across models and domains.
5.43The Original Importance Table Does Not Reflect What CNN and LSTM Actually Use
Table: 20 and Table 4.21 compare the SHAP attribution computed here against the impurity- and activation-magnitude-based importance originally reported in Table 3.5. For Random Forest the two measures agree moderately (Spearman rank correlation = 42.2%): both are ultimately derived from the same tree structure, so some correlation is expected even though impurity decrease and Shapley attribution are mathematically distinct quantities. For CNN and LSTM, however, the correlation is negligible (-0.9% and 14.0% respectively). Table 3.5's CNN and LSTM columns track the Random Forest column almost linearly with only a small offset, which in hindsight indicates that the original activation-magnitude heuristic did not independently characterize deep-model behaviour. SHAP reveals that CNN and LSTM actually concentrate 44-55% of total attribution on just two features, Fwd Packet Length Max and Bwd Packet Length Max (Table 4.18), roughly three to four times the 8-15% these features received in Table 3.5, while header-length features that Table 3.5 credited with 2-3% receive effectively zero SHAP attribution from either deep model. This is a genuine correction to the thesis's earlier feature-importance claims for the two deep architectures, not merely an additional analysis: conclusions in Section 3.6.6 that were framed as holding 'consistently across all three models' hold for Random Forest, but the deep-model attribution profile is considerably more concentrated than previously reported.
The divergence has a documented cause rather than being a quirk of this particular run. Random Forest's impurity based importance is known to carry a systematic bias toward continuous and high cardinality features regardless of their true predictive value (Strobl, Boulesteix, Zeileis, & Hothorn, 2007), which is a separate issue from the SHAP attribution computed here and explains part of the moderate rather than strong agreement seen for the same trained model in Table 4.21. For CNN and LSTM, raw activation magnitude is a weaker proxy still. It reflects how active a unit is, not how much that activation actually changes the model's output, so a feature can produce large activations that later layers largely discard, or small activations that get amplified downstream. Sundararajan, Taly, and Yan (2017) show that attribution methods not tied to output sensitivity in this way can assign non-trivial importance to features the model barely uses, which is the same failure mode behind Table 3.5's inflated timing feature importance for CNN and LSTM. SHAP attribution (Lundberg & Lee, 2017) is built to satisfy local accuracy and consistency, properties that raw activation magnitude carries no guarantee of, which is why it is treated as the more reliable measure throughout this section.
5.44Cross-Dataset Attribution Stability Does Not Predict Generalization
A natural hypothesis is that models fail to generalize because they rely on different features in each domain. Table 4.28 tests this directly by measuring the Spearman rank correlation of each model's SHAP feature ranking between its source and target domain. The result contradicts the hypothesis. In the forward direction (CIC-IDS2017 to UNSW-NB15), Random Forest shows the highest cross-domain rank stability of the three models (85.7% rank correlation) while simultaneously producing the worst cross-dataset accuracy (36.09%, Table 4.6) and a False Negative Rate of 100% (Table 4.9): it relies on essentially the same features in both domains and still predicts benign for every sample. LSTM shows the lowest rank stability (63.9%) yet achieves the best cross-dataset accuracy (70.07%) and AUC-ROC (74.67%) of the three models. CNN sits in between on both axes (90.4% rank correlation, 39.78% accuracy). The same pattern, with different magnitudes, appears in the reverse direction (Table 4.28). The conclusion is that which features a model attends to is not the mechanism behind the generalization gap documented in Section 4.5; what a model does with the values those features take on is. This motivates the distribution-level analysis in the following subsection.
5.45The Underlying Mechanism: Feature Scale Mismatch Under Source-Fit Standardization
Table: 29 reports the Kolmogorov-Smirnov statistic for each of the 15 shared features between CIC-IDS2017 and UNSW-NB15 in raw, unscaled units. Despite representing the same semantic quantity in both datasets (Table 3.3), several features differ by orders of magnitude: Flow Duration has the largest divergence (KS statistic = 94.2%), because CIC-IDS2017 records duration on a microsecond scale (mean approximately 1.48x10^7) while UNSW-NB15 records it in seconds (mean approximately 1.25). Total Length of Fwd Packets (KS = 66.9%), Fwd Packet Length Max (KS = 62.3%), and Flow Packets/s (KS = 55.9%) show comparably severe divergence.
This matters because, consistent with the deployment-realistic design already adopted in Section 3.6.4, the StandardScaler used in the cross-dataset experiments is fit exclusively on the source domain. Table 4.30 quantifies the consequence: applying a scaler fit on CIC-IDS2017 statistics to UNSW-NB15 values either collapses a feature's variance to near zero or inflates it by orders of magnitude. Eight of the fifteen shared features (Flow Duration, Fwd Header Length, Bwd Header Length, Fwd Packets/s, Bwd Packets/s, Fwd IAT Mean, Bwd IAT Mean, Flow Bytes/s) compress to a post-scaling variance ratio below 1%, meaning that once scaled with source-domain statistics these features become nearly constant across the entire target dataset and lose essentially all discriminative power. Flow Packets/s shows the opposite failure mode: because UNSW-NB15's raw packet rate is roughly three orders of magnitude larger than CIC-IDS2017's, this single feature's variance expands 730-fold once scaled with the CIC-fit scaler, turning it into an extreme, dominant outlier in the target-domain input. This scale mismatch, not a change in which features are semantically relevant, is the mechanistic root cause of the generalization gap documented throughout Section 4.5 and Section 5.4.
The scale mismatch identified above produces different failure modes depending on architecture, visible directly in the target-domain SHAP attributions of Tables 4.22-4.27. CNN and LSTM both collapse onto the single most severely distorted feature when evaluated on the target domain: Flow Packets/s accounts for 72.9% of CNN's and 73.1% of LSTM's total attribution on UNSW-NB15 target data (Table 4.23, 4.24), compared to a balanced 5-12% at home on CIC-IDS2017 (Table 4.18). Both deep models effectively become near-single-feature classifiers under domain shift, dominated by the exact feature that Table 4.30 identifies as expanding 730-fold under cross-domain scaling.
Random Forest does not exhibit this attribution collapse; instead, as Section 5.8.3 established, it keeps a broad and stable attribution profile across domains (Table 4.22) while its specific learned split thresholds, tuned to CIC-IDS2017's value ranges, rarely fire correctly on UNSW-NB15 input, so the model defaults to predicting benign for nearly all target-domain samples. This is a threshold non-transfer failure rather than an attribution collapse, and it explains why Random Forest's False Negative Rate reaches exactly 100% in Table 4.9: not because the model ignores attack-relevant features, but because none of its learned decision boundaries are calibrated to values in the target domain's range.
5.47Why LSTM Outperforms CNN Despite an Almost Identical Attribution Collapse
CNN and LSTM show nearly identical target-domain attribution concentration onto Flow Packets/s (72.9% versus 73.1%), yet their forward cross-dataset accuracy differs sharply (39.78% versus 70.07%, Table 4.6). Examining the predicted-probability distributions of both models on UNSW-NB15 target data resolves this. CNN's predicted probabilities cluster in an uncalibrated middle band: 48.0% of predictions fall between 30% and 70%, and the mean predicted probability for genuinely malicious flows is only 30.7%, below the 50% decision threshold. This directly explains CNN's 92.02% False Negative Rate in Table 4.9: the model's internal ranking of attack likelihood is not catastrophic (its AUC-ROC of 68.90% is well above chance), but its probability calibration is, so the fixed 50% threshold misclassifies most true attacks as benign. LSTM instead produces confident, polarized predictions on the same data (90% of predictions fall below 5% or above 95%) with class means correctly separated across the threshold (15.6% for benign, 61.6% for attack).
The architectural explanation is that CNN's Conv1d-BatchNorm-ReLU pipeline uses unbounded ReLU activations, so an input feature with an extreme, out-of-distribution magnitude propagates largely unconstrained into the final logit and swamps the contribution of the other 14 features. LSTM's two stacked recurrent layers apply sigmoid and tanh gates at every step, which are bounded by construction; an extreme input is compressed at each gate before it can dominate the hidden state. This does not make LSTM immune to the underlying scale mismatch (it still relies overwhelmingly on the same distorted feature), but it prevents that reliance from destabilizing the model's output calibration, which is what ultimately determines classification accuracy at a fixed threshold.
Section 5.5 reported that the temporal sequence LSTM reaches 81.59% AUC-ROC in the forward cross-dataset transfer at sequence length 20, compared to 74.67% for the standard, single-timestep LSTM (Section 6.1). It is important to note first that this is not a monotonic improvement within one model: Table 4.35 shows the temporal variant actually underperforms the standard LSTM at shorter windows (AUC = 63.3% at sequence length 5 and 64.9% at sequence length 10, both below the standard model's 74.67%), and only exceeds it once the window reaches length 20 (reconstructed AUC = 81.5%, matching the thesis-reported 81.59% to within sampling error, Table 4.35). Table 4.35 reconstructs all six forward and reverse sequence-length settings against the values originally reported in Table 4.13 and Table 4.14; every reconstructed AUC-ROC and accuracy value matches its thesis-reported counterpart to within 0.7 percentage points, the expected margin from evaluating on a 20,000-window random subsample rather than the full test set, confirming that the SHAP attributions computed in this section explain the same models and the same decision boundaries already reported in Chapter 4.
Table: 32 explains this non-monotonic pattern through predicted-probability calibration rather than feature attribution alone. None of the temporal models are well calibrated on the target domain: even at sequence length 20, the median predicted probability for a genuine attack is only 3.1%, far below the standard LSTM's 99.17%. What changes across sequence lengths is the spread of the benign class's predictions. At sequence length 10, the 90th percentile of benign-class predictions is 26.9%, heavily overlapping the (already weak) attack-class signal. At sequence length 20, that same percentile drops to 2.1%: longer windows suppress the model's tendency to assign spuriously elevated probability to benign target-domain flows, tightening the benign distribution's spread rather than strengthening the model's confidence in true attacks. Because AUC-ROC depends only on relative ranking, this tightening is sufficient to raise it substantially (65.1% to 81.5%) even though calibration, and therefore accuracy at a fixed 50% threshold, does not improve (Table 4.35 reports accuracy holding flat at 48-49% across all three sequence lengths). This finding gives the accuracy/AUC-ROC divergence already noted in Section 5.5.9 a precise, quantified cause: temporal context in this experiment functions as a benign-class variance reduction mechanism, not as an attack-detection improvement mechanism.
The reverse direction (UNSW-NB15 to CIC-IDS2017) illustrates the same mechanism operating in the opposite, harmful direction. Table 4.34 shows that as sequence length increases, target-domain attribution increasingly concentrates on Flow Duration, Fwd Packets/s, and Bwd Packets/s, three of the features identified in Table 4.30 as most severely variance-compressed under cross-domain scaling, together accounting for 98.9% of total attribution at sequence length 20. Longer temporal windows deepen the model's reliance on precisely the features least able to support it, which is consistent with the sharp accuracy collapse already reported in Section 5.5.2 (80.20% at sequence length 5 falling to 41.65% at sequence length 20) despite AUC-ROC continuing to improve modestly (58.8% to 65.9%, Table 4.35). Temporal context is therefore not unconditionally beneficial for cross-dataset transfer: its effect depends on which features a longer window causes the model to lean on more heavily, and that depends on the direction of transfer.
5.49Summary of Explainability Findings
Four findings from this section extend the cross-dataset generalization results of Sections 4.5, 5.4, and 5.5 from an empirical observation to a mechanistic explanation. First, the original impurity/activation-magnitude importance table (Table 3.5) reliably describes Random Forest but not CNN or LSTM, whose real attribution (Table 4.18-4.19) concentrates far more heavily on packet length features than previously reported. Second, cross-domain stability of a model's feature attribution ranking is not predictive of cross-domain accuracy; Random Forest is the most stable and the least accurate of the three models under transfer. Third, the actual driver of the generalization gap is a units/scale mismatch between the two datasets that survives the semantic 15-feature mapping (Table 3.3) and is amplified by fitting the StandardScaler exclusively on the source domain, producing either near-zero variance collapse or order-of-magnitude variance expansion depending on the feature (Table 4.30). Fourth, this single mechanism produces two different, now-quantified failure modes: Random Forest suffers threshold non-transfer while keeping stable attribution, CNN suffers attribution collapse compounded by unbounded-activation miscalibration, and LSTM suffers the same attribution collapse but is comparatively shielded from its calibration consequences by its saturating gate structure, and can additionally use longer temporal windows to suppress benign-class prediction variance in the direction where doing so helps, though not in the direction where it does not.
6Conclusions and Future Work
6.1Conclusions
This thesis presented the design, implementation, and evaluation of an AI-assisted software framework for network traffic analysis and threat detection. Three machine learning models (Random Forest, CNN, and LSTM) were systematically evaluated on two benchmark datasets, CIC-IDS2017 and UNSW-NB15, providing a comprehensive comparative analysis across different network environments and attack taxonomies.
The key findings of this research are summarized as follows. First, the Random Forest model achieves the best overall performance, with 99.89% accuracy and 99.99% AUC-ROC on CIC-IDS2017, and 94.67% accuracy and 99.18% AUC-ROC on UNSW-NB15. This result challenges the assumption that deep learning architectures necessarily outperform classical methods for tabular network flow data. Second, the LSTM model achieves competitive performance (99.59% on CIC-IDS2017, 93.46% on UNSW-NB15) with AUC-ROC of 99.98% on CIC-IDS2017 and 98.75% on UNSW-NB15, demonstrating viable intrusion detection capability. Third, training efficiency analysis reveals that Random Forest trains approximately 7x faster than deep learning models on large datasets, a critical consideration for practical deployment. Fourth, the fundamental incompatibility of feature spaces between CIC-IDS2017 (78 features) and UNSW-NB15 (42 features) was bridged through a 15-feature semantic mapping, enabling cross-dataset transfer evaluation and demonstrating that feature standardization is both necessary and achievable for cross-environment IDS generalization. Fifth, a SHAP based explainability analysis (Section 4.8, Section 5.8) traces the cross-dataset generalization gap to a concrete mechanism instead of leaving it as an unexplained empirical pattern: several shared features carry different physical units and scales across the two datasets, and standardizing on the source domain alone either collapses or inflates their variance once applied to the target domain. This produces two distinct failure modes: Random Forest keeps a stable feature ranking across domains but its learned decision thresholds do not transfer, while CNN and LSTM lean on the same distorted feature and only LSTM's saturating gate structure keeps its predictions usable at a fixed decision threshold.
The integration of a locally-deployed LLM for natural language threat explanation demonstrates the feasibility of human-accessible AI-powered IDS systems that preserve data privacy through local computation.
These findings directly answer the three research questions posed in Section 1.4. RQ1 (best balance of accuracy and efficiency) is answered by Random Forest for within-dataset deployment, though Sections 5.3–5.4 show that once cross-dataset operation is considered, False Positive Rate and False Negative Rate, not raw accuracy, become the decisive criteria, and LSTM becomes the preferred choice under that lens. RQ2 (performance change across datasets) is answered by the cross-dataset transfer experiments of Section 4.5, which show accuracy drops of 27–63 percentage points depending on model and direction, confirming that generalization cannot be assumed from within-dataset results alone. RQ3 (usefulness of a locally deployed LLM for explanation) is answered affirmatively in Section 5.6, where all four evaluated models produced structured, human-readable threat reports without transmitting data externally. RQ4 (why performance changes across datasets) is answered in Section 5.8, which traces the gap to a feature scale mismatch that survives the semantic 15-feature mapping and produces a different failure mode in each architecture.
Table: 1 consolidates these findings into a final model comparison and deployment recommendation matrix.
Table 52: Final Model Comparison and Recommendation Matrix
The Temporal Sequence LSTM experiment demonstrated that incorporating sequential flow context meaningfully improves cross-dataset ranking quality: AUC-ROC reached 0.8159 at sequence length 20, compared to 0.7467 for the standard LSTM trained on the same data. This improvement in AUC-ROC was accompanied by a substantial drop in accuracy and F1-score at this sequence length (from 70.07% to 48.95% accuracy), so the temporal variant should be understood as trading raw classification accuracy for improved false-positive/false-negative balance (Section 5.5.2) rather than as a strict improvement on every metric. This confirms that modelling the temporal ordering of network flows captures domain-invariant ranking signal that persists across different dataset distributions, even where absolute accuracy declines.
The comparison matrix confirms that no single model dominates every operating condition. Random Forest is the best within-dataset baseline because it minimizes false alarms, but its cross-dataset behavior is unstable. CNN is the least attractive option because its false-positive and false-negative rates remain elevated in both transfer directions. LSTM provides the most balanced security profile under domain shift, making it the strongest recommendation when deployment must tolerate dataset mismatch and preserve acceptable false-alarm behavior.
6.2Contributions
The primary contributions of this thesis are:
A systematic comparative evaluation of Random Forest, CNN, and LSTM for binary network intrusion detection across two independent benchmark datasets with different characteristics.
An analysis of training efficiency versus detection accuracy trade-offs across classical and deep learning models, providing practical guidance for IDS deployment decisions.
A temporal sequence learning experiment demonstrating that sliding-window LSTM improves cross-dataset AUC-ROC (achieving 0.8159 in the CIC→UNSW forward transfer at sequence length 20), while revealing directional asymmetries in domain-shift behavior between source and target datasets.
A privacy-preserving LLM integration architecture for automated threat explanation generation, bridging the accessibility gap between technical IDS outputs and non-expert security analysts.
An interactive dashboard for IDS log visualization with integrated AI-powered threat analysis, architecturally designed for production real-time deployment via streaming data sources (CICFlowMeter, Zeek), with the streaming integration empirically validated in future work.
A SHAP based explainability analysis that identifies the mechanism behind the cross-dataset generalization gap, corrects an earlier feature importance comparison for CNN and LSTM, and explains why LSTM's saturating gate architecture tolerates the same feature distortion that destabilizes CNN's predictions.
6.3Future Work
Several directions for future research emerge from this study. First, extending the evaluation to multi-class attack categorization would provide finer-grained detection capability and more nuanced comparative analysis. Second, integration of the trained models with a live packet capture pipeline, for example, using TShark (Orebaugh et al., 2006) for command-line packet dissection and flow export, would enable real-time production deployment and evaluation under realistic network conditions. Third, Section 5.8 traced the cross-dataset generalization gap to a feature scale mismatch that survives the semantic 15-feature mapping. Future work could build on this diagnosis directly, for example through domain adaptation techniques that align feature distributions rather than only their semantics, or through scalers fit jointly across both domains where a small amount of target-domain data is available. Fourth, exploration of more recent deep learning architectures, including Transformer-based models, may yield performance improvements over the LSTM baseline for sequential network traffic analysis. Fifth, adversarial robustness evaluation against traffic obfuscation and evasion attacks would strengthen the practical security guarantees of the proposed system.
The Temporal Sequence LSTM results suggest that longer sequence lengths, attention mechanisms, and transformer-based architectures for network flow sequences are promising directions for further improving cross-dataset generalisation in intrusion detection systems.
Lunt, T. F. (1993). A survey of intrusion detection techniques. Computers & Security, 12(4), 405-418.
More, S., Idrissi, M., Mahmoud, H., & Asyhari, A. T. (2024). Enhanced intrusion detection systems performance with UNSW-NB15 data analysis. Algorithms, 17(2), 64.
Moustafa, N., & Slay, J. (2015). UNSW-NB15: A comprehensive data set for network intrusion detection systems. In 2015 Military Communications and Information Systems Conference (MilCIS) (pp. 1-6). IEEE.
Mukkamala, S., Janoski, G., & Sung, A. (2002). Intrusion detection using neural networks and support vector machines. Proceedings of the 2002 International Joint Conference on Neural Networks, 1702-1707.
Orebaugh, A., Ramirez, G., & Beale, J. (2006). Wireshark & Ethereal Network Protocol Analyzer Toolkit. Syngress Publishing.
Qwen Team. (2025). Qwen3 technical report. arXiv preprint arXiv:2505.09388.
Scarfone, K., & Mell, P. (2007). Guide to intrusion detection and prevention systems (IDPS). NIST Special Publication 800-94. National Institute of Standards and Technology.
Sharafaldin, I., Habibi Lashkari, A., & Ghorbani, A. A. (2018). Toward generating a new intrusion detection dataset and intrusion traffic characterization. Proceedings of the 4th International Conference on Information Systems Security and Privacy, 108-116.
Soumik, M. S. (2024). A comparative analysis of network intrusion detection (NID) using artificial intelligence techniques for increase network security. International Journal of Science and Research Archive, 13(2), 4014-4025.
Strobl, C., Boulesteix, A. L., Zeileis, A., & Hothorn, T. (2007). Bias in random forest variable importance measures: Illustrations, sources and a solution. BMC Bioinformatics, 8, 25.
Sundararajan, M., Taly, A., & Yan, Q. (2017). Axiomatic attribution for deep networks. Proceedings of the 34th International Conference on Machine Learning, 70, 3319-3328.
Tavallaee, M., Bagheri, E., Lu, W., & Ghorbani, A. A. (2009). A detailed analysis of the KDD CUP 99 data set. IEEE Symposium on Computational Intelligence for Security and Defense Applications, 1-6.
Touvron, H., Lavril, T., Izacard, G., Martinet, X., Lachaux, M. A., Lacroix, T., ... & Lample, G. (2023a). LLaMA: Open and efficient foundation language models. arXiv preprint arXiv:2302.13971.
Touvron, H., Martin, L., Stone, K., Albert, J., Almahairi, A., Babaei, Y., Bashlykov, N., Batra, S., Bhargava, P., Bhosale, S., Bikel, D., Blecher, L., Ferrer, C. C., Chen, M., Cucurull, G., Esiobu, D., Fernandes, J., Fu, J., Fu, W., Fuller, B., Gao, C., Goswami, V., Goyal, N., Hartshorn, A., Hosseini, S., Hou, R., Inan, H., Kardas, M., Kerkez, V., Khabsa, M., Kloumann, I., Korenev, A., Koura, P. S., Lachaux, M. A., Lavril, T., Lee, J., Liskovich, D., Lu, Y., Mao, Y., Martinet, X., Mihaylov, T., Mishra, P., Molybog, I., Nie, Y., Poulton, A., Reizenstein, J., Rungta, R., Saladi, P., Schelten, A., Silva, R., Smith, E. M., Subramanian, R., Tan, X., Tang, B., Taylor, R., Williams, A., Kuan, J. X., Xu, P., Yan, Z., Zarov, I., Zhang, Y., Fan, A., Kambadur, M., Narang, S., Rodriguez, A., Stojnic, R., Edunov, S., & Scialom, T. (2023b). Llama 2: Open foundation and fine-tuned chat models. arXiv preprint arXiv:2307.09288.
Tsai, C. F., Hsu, Y. F., Lin, C. Y., & Lin, W. Y. (2009). Intrusion detection by machine learning: A review. Expert Systems with Applications, 36(10), 11994-12000.
Yin, C., Zhu, Y., Fei, J., & He, X. (2017). A deep learning approach for intrusion detection using recurrent neural networks. IEEE Access, 5, 21954-21961.