Ahmed Benlafqih

All projects

Comparing machine learning models for intrusion detection on NSL-KDD

Academic project · 2025

Decision trees, Random Forest and an SVM compared for detecting network intrusions on NSL-KDD. Best macro-F1 in the saved run: 0.8165, from bagged SVMs.

Source code

In short

What it is
A Jupyter notebook that trains and compares classical classifiers (Decision Tree, Random Forest, SVM, plus ensembles) to label network connection records as normal or anomaly on the public NSL-KDD benchmark.
Why
To build a full supervised pipeline for a security decision, from raw files to tuned models, and to compare what each model gets right and wrong on attacks.
My role
Coursework, team of 3. I built most of the pipeline: data loading and encoding, SMOTE and scaling, model training and tuning, and the ensembles. A teammate helped debug it.
Domains and tech
AI/ML security, ML engineering. Python, pandas, scikit-learn, imbalanced-learn (SMOTE), matplotlib, Jupyter.
Status
Academic project. Best single model in the saved run: the tuned SVM, 81.60 % accuracy on the 22,544-record test set, with 96.19 % precision and 70.46 % recall on attacks. Two flaws in the method are stated below.
Period
Nov 2025 – Dec 2025

Context and problem

NSL-KDD is a public benchmark of network connection records, each described by 41 features (protocol, service, connection flags, byte counts, connection statistics) and labelled normal or anomaly. The task here is binary: decide for each record whether it is an intrusion. This is machine learning used for a security decision, not the security of a model.

The project was coursework for a team of three, documented as “4th year students”, dated December 2025. The repository’s commits run from 6 November to 7 December 2025.

README.md, lines 1–13; notebook cell 1 (cells are counted from 0 on this page); git log

Data

Set Records Normal Anomaly
KDDTrain+ (training) 125,973 67,343 58,630
KDDTest+ (evaluation) 22,544 9,711 12,833

Every score below is measured on KDDTest+, the benchmark’s own test file, with anomaly as the positive class. The notebook also computes an 80/20 random split, but never uses it.

Notebook cells 9, 13, 23 and the classification reports in cells 23–58

Architecture

NSL-KDD pipeline, as in the notebookThe ARFF files are parsed by a custom loader, three categorical features are one-hot encoded to 122 columns and the test columns aligned. SMOTE rebalances the training set only, then a scaler is fitted on it. Decision Tree, Random Forest and SVM baselines are trained, tuned by grid or randomized search on F1-macro, then combined by bagging, voting and stacking; separately, a new Random Forest is trained on PCA components. Everything is scored on KDDTest+. Two flaws are marked: the tree models are fitted on unscaled data but scored on scaled data, and cross-validation runs on SMOTE output.KDDTrain+ / KDDTest+ (ARFF)125,973 and 22,544 connection recordsCustom loader, 42 named columnslines after @data, read with pandasOne-hot encoding, 122 columnsprotocol_type, service, flag; test alignedSMOTE on the training set only67,343 normal / 67,343 anomalyStandardScaler (with_mean=False)fitted on the balanced training setDT, RF, SVM: baseline, then tunedgrid / randomized search on F1-macroBagging, voting, stacking; PCAensembles of the tuned models; PCA separatelyEvaluation on KDDTest+anomaly as the positive class! Flaws in the saved run (see Limitations):Decision Tree and Random Forest are fitted beforescaling, then scored on scaled test data.Cross-validation runs on SMOTE-oversampled data.
The pipeline in the order the notebook runs it. The two highlighted steps are where the method goes wrong; both flaws are explained under Limitations.KDD_notebook.ipynb, cells 7–60

Implementation

Loading and encoding. A small loader keeps the lines after @data in each ARFF file, writes them to a temporary CSV and reads them with pandas. The 42 column names are set by hand. Three categorical features (protocol_type, service, flag) are one-hot encoded, which gives 122 columns, and the test set’s columns are aligned on the training set’s, filling missing categories with 0.

Class balance. The training set is 53 % normal and 47 % anomaly. SMOTE, applied to the training set only, brings it to 67,343 records of each class. A StandardScaler is then fitted on that balanced set and applied to the test set.

Models. Three baselines: a Decision Tree (entropy, depth 10), a Random Forest (300 trees, balanced class weights) and an SVM with an RBF kernel. Each is then tuned on F1-macro:

  • Decision Tree: grid search, 48 candidates, 5-fold;
  • Random Forest: randomized search, 20 candidates, 3-fold;
  • SVM: grid search on a 30 % stratified sample (40,405 records), 12 candidates, 3-fold, then retrained on the full balanced set with C = 100 and gamma = 0.01.

From the tuned models, the notebook builds bagging (over the Decision Tree and over the SVM), hard voting and stacking with a logistic regression meta-learner. Separately, it trains a new 100-tree Random Forest on 89 PCA components (95 % of the variance) and draws a t-SNE plot of 5,000 training records.

Results

Model (KDDTest+) Accuracy Precision (anomaly) Recall (anomaly) F1-macro
Decision Tree, base 75.20 % 86.60 % 66.76 % 0.7519
Random Forest, base 77.22 % 89.06 % 68.38 % 0.7722
SVM, base 79.00 % 92.40 % 68.76 % 0.7900
Decision Tree, tuned 73.19 % 79.80 % 70.83 % 0.7304
Random Forest, tuned 76.23 % 90.32 % 65.24 % 0.7622
SVM, tuned 81.60 % 96.19 % 70.46 % 0.8159
Notebook cell 41, saved run

The tuned SVM is the best single model. Of 12,833 attacks in the test set it flags 9,042 and misses 3,791; of 9,711 normal connections it wrongly flags 358. High precision with lower recall means few false alarms but many missed intrusions, which is the weaker side for a detection system. Its ROC-AUC is 0.9401.

F1-macro on KDDTest+, saved notebook runDecision Tree, base 0.7519; Random Forest, base 0.7722; SVM, base 0.7900; Decision Tree, tuned 0.7304; Random Forest, tuned 0.7622; SVM, tuned 0.8159; Bagging (tuned DT) 0.7842; Bagging (tuned SVM) 0.8165; Hard voting 0.7969; Stacking 0.7958.0.700.740.780.82F1-macroDecision Tree, baseDecision Tree, base: 0.75190.7519Random Forest, baseRandom Forest, base: 0.77220.7722SVM, baseSVM, base: 0.79000.7900Decision Tree, tunedDecision Tree, tuned: 0.73040.7304Random Forest, tunedRandom Forest, tuned: 0.76220.7622SVM, tunedSVM, tuned: 0.81590.8159Bagging (tuned DT)Bagging (tuned DT): 0.78420.7842Bagging (tuned SVM)Bagging (tuned SVM): 0.81650.8165Hard votingHard voting: 0.79690.7969StackingStacking: 0.79580.7958fitted on unscaled data, scored on scaled dataconsistent scaling
F1-macro of every configuration. Hollow dots are the tree models scored with the scaling mismatch described under Limitations, so their positions are not a fair comparison. Bagging over the tuned SVM is the highest point, 0.0006 above the SVM alone, and takes 155.83 s to train in that run.KDD_notebook.ipynb, cells 41, 47, 49, 51, 53

Tuning made two of the three models worse on the test set: the Decision Tree dropped from 75.20 % to 73.19 % accuracy and the Random Forest from 77.22 % to 76.23 %. Only the SVM improved, from 79.00 % to 81.60 %. The ensembles add little: hard voting reaches 0.7969 F1-macro, stacking 0.7958, and bagging over the SVM 0.8165 against 0.8159 without it.

Limitations

Tree models are scored on data they weren’t trained on. The Decision Tree and the Random Forest (base and tuned), plus the bagged Decision Tree, are fitted on the unscaled balanced set, then asked to predict on the scaled test set:

KDD_notebook.ipynb, cell 27

dt_model.fit(X_train_bal, y_train_bal)
y_pred_dt = dt_model.predict(X_test_scaled)

A tree’s thresholds are learned on the original values, so they don’t apply to scaled inputs. Their test scores therefore don’t show what these models would do in a consistent pipeline, and comparing them with the SVM is unfair. A hint, not a measurement: a Random Forest refitted on scaled data (on 89 PCA components) reaches about 0.80 accuracy, against 0.76 for the tuned Random Forest.

Cross-validation runs on oversampled data. SMOTE creates synthetic records by interpolating between real ones, and it runs before the three hyperparameter searches. A synthetic record can then sit in a validation fold next to the records it was made from. The cross-validation F1-macro is 0.995 to 0.999, while the test F1-macro is 0.73 to 0.82. How much of that gap comes from this, and how much from a possible difference in distribution between NSL-KDD’s training and test files, wasn’t measured.

Other limits.

  • Both SVM fits stopped at their iteration cap with a convergence warning.
  • The results come from one run on one machine.
  • The labels are binary only: the project doesn’t identify attack types.
  • NSL-KDD is an old benchmark of static connection features, with no time dimension, which the team itself notes in the notebook’s conclusion.
  • Some statements in that conclusion have no run behind them, such as a recall gain from SMOTE (no run without SMOTE exists), and its hand-typed AUC table doesn’t match the computed values. The figures on this page come from the printed outputs only.

Possible next steps

The notebook’s conclusion lists newer datasets (CICIDS2017, UNSW-NB15), multi-class attack types, sequence models and explainability (SHAP, LIME) as future work. None of it was done. Before that, the two flaws above have direct fixes: put the scaler inside a pipeline used by every model, and apply SMOTE inside each cross-validation fold rather than before the search.