Data Science in Cybersecurity: An Intrusion Detection Test
Data science in cybersecurity is often sold with accuracy figures above 99%. This article reproduces such a figure on a well-known intrusion dataset, then shows why it collapses on the dataset’s own test file. The point is not that machine learning fails at security; it is that how you split the data decides whether a result means anything. All numbers below come from the code shown, run on the real data.

The data: NSL-KDD network connections
NSL-KDD is a cleaned version of the classic KDD Cup 1999 intrusion data. Each row describes one network connection with 41 features (protocol, service, bytes sent, error rates and so on) and a label: normal, or one of many named attacks. It is old and synthetic in origin, so treat it as a teaching dataset, not a picture of today’s traffic. The files used are KDDTrain+ (125,973 connections) and KDDTest+ (22,544), mirrored on GitHub. Code was run with pandas 3.0.5 and scikit-learn 1.9.1.
import pandas as pd
base = "https://raw.githubusercontent.com/jmnwong/NSL-KDD-Dataset/master/"
cols = ["duration","protocol_type","service","flag","src_bytes","dst_bytes","land","wrong_fragment",
"urgent","hot","num_failed_logins","logged_in","num_compromised","root_shell","su_attempted",
"num_root","num_file_creations","num_shells","num_access_files","num_outbound_cmds",
"is_host_login","is_guest_login","count","srv_count","serror_rate","srv_serror_rate",
"rerror_rate","srv_rerror_rate","same_srv_rate","diff_srv_rate","srv_diff_host_rate",
"dst_host_count","dst_host_srv_count","dst_host_same_srv_rate","dst_host_diff_srv_rate",
"dst_host_same_src_port_rate","dst_host_srv_diff_host_rate","dst_host_serror_rate",
"dst_host_srv_serror_rate","dst_host_rerror_rate","dst_host_srv_rerror_rate","label","difficulty"]
train = pd.read_csv(base + "KDDTrain%2B.txt", names=cols)
test = pd.read_csv(base + "KDDTest%2B.txt", names=cols)
for df in (train, test):
df["attack"] = (df.label != "normal").astype(int)
print(len(train), len(test))
print("attack share train", round(train.attack.mean(), 3), " test", round(test.attack.mean(), 3))
new = ~test.label.isin(train.label)
print("test rows whose attack type never appears in training:", int(new.sum()),
"in", test.label[new].nunique(), "types")
125973 22544
attack share train 0.465 test 0.569
test rows whose attack type never appears in training: 3750 in 17 typesThe test file is deliberately different from the training file. Attacks make up 56.9% of test connections against 46.5% of training, and 3,750 test connections belong to 17 attack types that never appear in training. That mirrors the real situation: tomorrow’s attacks are not the ones you trained on.
Two ways to score the same model
A random forest is trained twice with identical settings. The first score uses a random 25% hold-out from the training file; the second uses the official test file.
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, recall_score, precision_score, roc_auc_score
feat = [c for c in cols if c not in ("label", "difficulty", "attack")]
both = pd.get_dummies(pd.concat([train, test])[feat],
columns=["protocol_type", "service", "flag"]).astype(float)
Xtr, Xte = both.iloc[:len(train)], both.iloc[len(train):]
# 1) the flattering test: random split of the training file
a, b, ya, yb = train_test_split(Xtr, train.attack, test_size=0.25, random_state=0, stratify=train.attack)
rf = RandomForestClassifier(200, random_state=0, n_jobs=2).fit(a, ya)
print("random split accuracy:", round(accuracy_score(yb, rf.predict(b)), 3))
# 2) the honest test: the official, separate test file
rf = RandomForestClassifier(200, random_state=0, n_jobs=2).fit(Xtr, train.attack)
p = rf.predict(Xte); prob = rf.predict_proba(Xte)[:, 1]
print("official test: accuracy", round(accuracy_score(test.attack, p), 3),
"recall", round(recall_score(test.attack, p), 3),
"precision", round(precision_score(test.attack, p), 3),
"AUC", round(roc_auc_score(test.attack, prob), 3))
test["pred"] = p
print("flagged as attack, novel types:", round(test.pred[new].mean(), 3),
"| known types:", round(test.pred[test.attack.eq(1) & ~new].mean(), 3),
"| normal traffic:", round(test.pred[test.attack.eq(0)].mean(), 3))
for t in (0.5, 0.9, 0.99):
q = prob >= t
print("threshold", t, "recall", round(q[test.attack == 1].mean(), 3),
"false alarms", round(q[test.attack == 0].mean(), 3))
random split accuracy: 0.999
official test: accuracy 0.768 recall 0.613 precision 0.968 AUC 0.961
flagged as attack, novel types: 0.238 | known types: 0.768 | normal traffic: 0.027
threshold 0.5 recall 0.615 false alarms 0.027
threshold 0.9 recall 0.523 false alarms 0.022
threshold 0.99 recall 0.453 false alarms 0.008The same model scores 99.9% accuracy on the random split and 76.8% on the official test file. A likely reason is that connections from the same attack campaign look alike, so held-out rows have close twins in the training rows, while the test file contains attacks the model has not seen; this explanation was not tested separately here.
What the model actually catches
On the test file the model flags 76.8% of attacks whose type it saw in training, but only 23.8% of the 3,750 attacks of types it never saw. Normal traffic is flagged 2.7% of the time. Precision is high (0.968: when it raises an alarm it is nearly always right) but recall is 0.613, so roughly four in ten attack connections slip through. The AUC of 0.961 says the model ranks attacks above normal traffic well; the cut-off is a separate choice. Only thresholds from 0.5 upward were tried, and raising it does not help: at 0.99 false alarms fall to 0.8% but recall drops to 45.3%. The table summarises the trade-off.
| Alarm threshold | Attacks caught | False alarms on normal traffic |
|---|---|---|
| 0.5 | 61.5% | 2.7% |
| 0.9 | 52.3% | 2.2% |
| 0.99 | 45.3% | 0.8% |
Lessons for security analytics
First, report results on data that is separated from training in the way deployment will be separated, usually by time or by attack campaign. Second, measure recall on unseen attack types separately; a supervised classifier learns known patterns, which is why many teams pair it with anomaly detection on normal behaviour. Third, remember that a 2.7% false-alarm rate sounds small but, on millions of connections a day, means a very large alert queue. Related reading: our guide to building a scikit-learn model step by step covers the split and leakage ideas used here, and the dark side of big data article looks at privacy risks in the same kind of log data. Forest options are documented in the RandomForestClassifier reference. This analysis did not test deep learning, other attack-family breakdowns or any live network.
Frequently asked questions
How is data science used in cybersecurity?
Typical uses include classifying malicious traffic, spotting anomalies in logins or network flows, detecting phishing, and ranking alerts so analysts see the riskiest first. Each depends on labelled history or a stable definition of normal behaviour.
Why is accuracy misleading for intrusion detection?
Accuracy mixes both classes and depends on how common attacks are in the data. Recall on attacks, false alarms on normal traffic and performance on unseen attack types tell you far more, as the 99.9% versus 76.8% gap above shows.
Is NSL-KDD still a good dataset?
It is good for learning evaluation technique because it ships with a separate, harder test file. It is not representative of modern networks, so do not use its scores to judge a production system.
