DaveyD347's picture
Add context-aware log anomaly detector
a56b6dd verified
Raw History Blame Contribute Delete
5.76 kB
"""Train the context-aware log anomaly detector and the leaderboard baselines on CPU.
Usage: python src/train.py --data ../incident-logs-dataset/data --out outputs
(without --data, the dataset is downloaded from the Hub: DaveyD347/sanitized-incident-logs)
Every model is fit on the train split; the validation split is used only to set the Isolation Forest threshold.
The test split and the shifted challenge set are never touched here (see evaluate.py).
Models
rules 16 one-line regex signatures (rules.py), no training
isoforest Isolation Forest on the same features as ours, fit on events from *benign* sessions only
(the classic unsupervised "learn normal, flag the rest" setup)
line_tfidf TF-IDF character 3-5-grams of the (number/IP-masked) raw line + logistic regression
tokens_only our per-line tokens + logistic regression, with the context features switched off (ablation)
hgb gradient-boosted trees on our full feature set
ours our per-line tokens (down-weighted x0.3) + 40 streaming context features, logistic regression
"""
import argparse
import json
import os
import time
import numpy as np
from scipy.sparse import csr_matrix, hstack
from sklearn.ensemble import HistGradientBoostingClassifier, IsolationForest
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import f1_score
from skops.io import dump
from common import build_vocab, featurize_df, feature_names, load_events, mask_line, token_matrix
from features import NUMERIC
TOKEN_SCALE = 0.3 # per-line tokens are surface strings; down-weighting them makes the model lean on behaviour
C = 1.0
THRESHOLD = 0.5
CHAR = dict(analyzer="char_wb", ngram_range=(3, 5), min_df=5, max_features=50000, sublinear_tf=True)
def ours_matrix(toks, nums, vocab, token_scale=TOKEN_SCALE):
return hstack([token_matrix(toks, vocab) * token_scale, csr_matrix(nums)]).tocsr()
def best_f1_threshold(scores, y):
ts = np.unique(np.quantile(scores, np.linspace(0, 1, 401)))
f = [f1_score(y, scores >= t) for t in ts]
return float(ts[int(np.argmax(f))])
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--data", default=None, help="local copy of the dataset's data/ folder (optional)")
ap.add_argument("--out", default="outputs")
ap.add_argument("--seed", type=int, default=0)
args = ap.parse_args()
os.makedirs(f"{args.out}/model", exist_ok=True)
os.makedirs(f"{args.out}/baselines", exist_ok=True)
tr, va = load_events(args.data, "train"), load_events(args.data, "validation")
ytr, yva = tr.is_malicious.values.astype(int), va.is_malicious.values.astype(int)
t0 = time.time()
Ttr, Ntr = featurize_df(tr)
Tva, Nva = featurize_df(va)
print(f"featurized {len(tr)} + {len(va)} events in {time.time() - t0:.1f}s")
vocab = build_vocab(Ttr)
Xtr, Xva = ours_matrix(Ttr, Ntr, vocab), ours_matrix(Tva, Nva, vocab)
# ---- ours -------------------------------------------------------------------------------------------
clf = LogisticRegression(C=C, max_iter=10000).fit(Xtr, ytr)
pva = clf.predict_proba(Xva)[:, 1]
print(f"ours: validation F1 = {f1_score(yva, pva >= THRESHOLD):.4f}")
dump({"vocab": vocab, "clf": clf, "token_scale": TOKEN_SCALE, "threshold": THRESHOLD, "numeric": NUMERIC},
f"{args.out}/model/model.skops")
names = feature_names(vocab)
coef = clf.coef_[0]
w_tok = {t: round(float(coef[i]) * TOKEN_SCALE, 6) for t, i in vocab.items()} # scale folded into weights
w_num = {n: round(float(coef[len(vocab) + i]), 6) for i, n in enumerate(NUMERIC)}
model_json = {"format": "stream-logreg-v1", "labels": ["normal", "anomalous"], "threshold": THRESHOLD,
"intercept": round(float(clf.intercept_[0]), 6), "token_weights": w_tok, "numeric_weights": w_num}
with open(f"{args.out}/model/model.json", "w") as fh:
json.dump(model_json, fh, indent=0, separators=(",", ":"))
cfg = {"model_type": "logistic_regression", "C": C, "token_scale": TOKEN_SCALE, "threshold": THRESHOLD,
"n_tokens": len(vocab), "n_numeric": len(NUMERIC), "n_features": len(names),
"train_events": int(len(tr)), "train_sessions": int(tr.session_id.nunique()),
"dataset": "DaveyD347/sanitized-incident-logs", "dataset_config": "events"}
with open(f"{args.out}/model/config.json", "w") as fh:
json.dump(cfg, fh, indent=2)
# ---- baselines --------------------------------------------------------------------------------------
base = {}
tok_only = LogisticRegression(C=C, max_iter=10000).fit(token_matrix(Ttr, vocab), ytr)
base["tokens_only"] = {"clf": tok_only, "threshold": THRESHOLD}
hgb = HistGradientBoostingClassifier(max_iter=300, random_state=args.seed).fit(Xtr.toarray(), ytr)
base["hgb"] = {"clf": hgb, "threshold": THRESHOLD}
vec = TfidfVectorizer(**CHAR).fit([mask_line(l) for l in tr.raw_log])
lt = LogisticRegression(C=1.0, max_iter=5000).fit(vec.transform([mask_line(l) for l in tr.raw_log]), ytr)
base["line_tfidf"] = {"vec": vec, "clf": lt, "threshold": THRESHOLD}
benign = tr.scenario.str.startswith("benign").values
iso = IsolationForest(n_estimators=200, random_state=args.seed, n_jobs=-1).fit(Xtr[benign].toarray())
thr = best_f1_threshold(-iso.score_samples(Xva.toarray()), yva)
base["isoforest"] = {"clf": iso, "threshold": thr}
print(f"isoforest threshold (best validation F1) = {thr:.4f}")
dump({"vocab": vocab, "models": base}, f"{args.out}/baselines/baselines.skops")
print(f"saved to {args.out}/ in {time.time() - t0:.0f}s")
if __name__ == "__main__":
main()