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.
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 logData
| 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.
Architecture
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 |
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.
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:
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.