Intro Video
Watch a short introduction to the NSL-KDD intrusion-detection problem:
Story
Welcome to EPCC’s Blue Team. You’ve just joined the campus IT security group as a blue-team analyst. Your mission is to train a model that flags malicious network connections before they cause damage—especially the hard-to-catch minority attacks R2L and U2R.
Using the NSL-KDD dataset, build and refine a reproducible ML pipeline that classifies each connection as Attack or Normal. Evaluate with macro-F1 and PR-AUC, and explain your model’s behavior using SHAP and calibration.
Possible Improvements of the Basic Example
1) Model Variants
- Starter models:
LogisticRegression,RandomForestClassifier,DecisionTreeClassifier. - Support Vector Machines:
SVC(linear & RBF),LinearSVC. - Discriminant Analysis:
LinearDiscriminantAnalysis,QuadraticDiscriminantAnalysis. - k-Nearest Neighbors:
KNeighborsClassifier. - Naive Bayes:
GaussianNB,MultinomialNB,BernoulliNB,ComplementNB. - Linear/Online:
SGDClassifier,PassiveAggressiveClassifier,Perceptron,RidgeClassifier. - Ensembles:
RandomForestClassifier,ExtraTreesClassifier,AdaBoostClassifier,GradientBoostingClassifier,XGBClassifier,LGBMClassifier,CatBoostClassifier. - Neural Nets:
MLPClassifier.
2) Hyperparameter Tuning
Explore parameters systematically using GridSearchCV or RandomizedSearchCV. Grid search tries all combinations; random search samples a subset—faster on large grids.
Example: tune a Random Forest with 5-fold CV on the training split only.
from sklearn.model_selection import GridSearchCV
from sklearn.ensemble import RandomForestClassifier
param_grid = {
"n_estimators": [200, 400, 800],
"max_depth": [None, 10, 20, 40],
"min_samples_leaf": [1, 2, 4]
}
# Set class_weight directly on the estimator (preferred when always using balanced)
rf = RandomForestClassifier(random_state=42, n_jobs=-1, class_weight="balanced")
gs = GridSearchCV(estimator=rf, param_grid=param_grid, scoring="f1_macro", cv=5, n_jobs=-1)
gs.fit(X_train, y_train)
best_model = gs.best_estimator_
print(gs.best_params_, gs.best_score_)
Optional: If you want to tune whether to use class weights, include it in the grid:
param_grid = {
"n_estimators": [200, 400, 800],
"max_depth": [None, 10, 20, 40],
"min_samples_leaf": [1, 2, 4],
"class_weight": ["balanced", None] # tune on/off
}
Alternative: RandomizedSearchCV—good for larger spaces; specify distributions and n_iter:
from sklearn.model_selection import RandomizedSearchCV
from scipy.stats import randint
param_dist = {
"n_estimators": randint(100, 1000),
"max_depth": [None] + list(range(8, 48, 8)),
"min_samples_leaf": randint(1, 6)
}
rs = RandomizedSearchCV(
rf,
param_distributions=param_dist,
n_iter=40,
scoring="f1_macro", # consistent with macro-F1 objective
cv=5,
random_state=42,
n_jobs=-1
)
rs.fit(X_train, y_train)
3) Threshold & Calibration
Threshold optimization helps balance false alarms and missed attacks. Default 0.5 may not work for imbalanced data. Optimize thresholds to maximize your objective metric (e.g., Fβ).
- Fβ score: balances precision and recall, giving recall β times more weight. Use β=2 to prioritize recall for R2L/U2R, where missing attacks is worse than raising extra alerts.
- Consider per-class thresholds or a cost matrix; visualize PR curves and select operating points that meet constraints.
- Apply probability calibration (Platt or isotonic) and verify with Brier score and reliability diagrams.
4) Imbalance & Resampling
- Prefer macro-F1 and per-class PR-AUC; use
StratifiedKFold(orStratifiedGroupKFoldwhen applicable). - Use class_weight="balanced" or manual weights for base models.
- Resampling (train-only): SMOTE, Borderline-SMOTE, ADASYN; under-sampling with Tomek Links or ENN. Always wrap in a
Pipelineto avoid leakage. - Hybrid ensembles: BalancedRandomForest, EasyEnsemble, RUSBoost work well in highly imbalanced regimes.
- Post-resampling calibration: Resampling changes score distributions; re-calibrate if deploying probability-based decisions.
5) Explainability & Diagnostics
- Global: tree importance + permutation importance to verify stability.
- Local: SHAP (Tree/Kernel) on correctly detected vs. missed R2L/U2R samples.
- Response: Partial Dependence & ICE for non-linear effects.
- Embedding & slices: t-SNE/UMAP and error-slice analysis (e.g., by
service,flag). - Robustness: leakage audits, time-split validation if applicable, and shuffle-label sanity checks.
Grading Rubric (Computer Science–Focused)
| Category | Description | Points |
|---|---|---|
| 1. Technical Design & Implementation | Clean, modular code; proper use of functions/classes; version control; reproducible pipelines and consistent naming/documentation. | 20 |
| 2. Algorithmic Understanding & Model Design | Clear reasoning for algorithm choice and trade-offs; correct preprocessing; thoughtful comparisons across model families. | 20 |
| 3. Data Analysis & Experimental Methodology | Sound experiments (train/val/test), CV usage, parameter tuning; statistical comparisons (e.g., CIs, tests) when appropriate. | 15 |
| 4. ML Performance & Evaluation | Strong results on macro-F1, PR-AUC, per-class metrics, and confusion matrices; correct interpretation of trade-offs. | 15 |
| 5. Visualization, Explainability & Diagnostics | Effective plots (ROC/PR, SHAP, PDP/ICE, embeddings) and narrative that links visuals to decisions. | 10 |
| 6. System Reproducibility & Automation | Deterministic runs (seeds), dependency management, clear setup, and optional automation scripts (e.g., Makefile, bash, or Colab cells). | 10 |
| 7. Research Communication & Documentation | Concise executive summary; well-structured notebook; coherent story from problem to results and conclusions. | 10 |
| Total | 100 | |
![]() |
![]() |
|---|

