DaveyD347's picture
Add malicious URL classifier
84f95cd verified
Raw History Blame Contribute Delete
5.63 kB
"""Train the TF-IDF + red-flag logistic regression URL classifier on CPU.
Usage: python src/train.py --data data --out outputs/model
Features (all reproducible in plain JavaScript, so the same weights run in the browser Space):
1. character 3-5-grams of the URL without its scheme, TF-IDF (catches c0ntoso, -secure-, .top, /wp-content/)
2. part-tagged tokens, TF-IDF: h:login is "login" in the hostname, p:login in the path, tld:xyz, ext:exe ...
3. 31 binary red flags from urlflags.py, times flag_scale
C and flag_scale are chosen by 5-fold *grouped* cross-validation over train + validation URL templates, so each
fold scores URL shapes the model never saw. The final model is refit on train + validation. The test split and the
challenge set are never touched here.
"""
import argparse
import json
import os
import zipfile
from itertools import product
import numpy as np
import pandas as pd
from scipy.sparse import csr_matrix, hstack
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import f1_score
from sklearn.model_selection import GroupKFold
from skops.io import dump
from urlflags import FLAG_IDS, flag_vector, model_docs
CHAR = dict(analyzer="char", lowercase=True, ngram_range=(3, 5), min_df=5, max_features=30000, sublinear_tf=True)
TOKS = dict(analyzer="word", lowercase=False, token_pattern=r"[^ ]+", min_df=3, max_features=8000, sublinear_tf=True)
GRID_C = (0.3, 1.0, 3.0, 10.0)
GRID_SCALE = (0.5, 1.0, 2.0)
def docs(urls):
d = [model_docs(u) for u in urls]
return [a for a, _ in d], [b for _, b in d]
def flag_matrix(urls):
return np.array([flag_vector(u) for u in urls], dtype=np.float64)
def fit_vectorizers(cd, td):
return TfidfVectorizer(**CHAR).fit(cd), TfidfVectorizer(**TOKS).fit(td)
def featurize(char, toks, urls, flag_scale, flags=None, d=None):
cd, td = docs(urls) if d is None else d
F = flag_matrix(urls) if flags is None else flags
return hstack([char.transform(cd), toks.transform(td), csr_matrix(F * flag_scale)]).tocsr()
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--data", default="data")
ap.add_argument("--out", default="outputs/model")
ap.add_argument("--folds", type=int, default=5)
ap.add_argument("--seed", type=int, default=42)
args = ap.parse_args()
df = pd.concat([pd.read_parquet(f"{args.data}/{s}.parquet") for s in ("train", "validation")], ignore_index=True)
urls, y, groups = df.url.tolist(), df.label.values, df.variant_id.values
F = flag_matrix(urls)
cd, td = docs(urls)
print(f"{len(df)} URLs from {df.variant_id.nunique()} templates")
scores = {k: [] for k in product(GRID_C, GRID_SCALE)}
oof = {k: np.zeros(len(df)) for k in scores}
for fold, (tr, va) in enumerate(GroupKFold(n_splits=args.folds).split(urls, y, groups)):
char, toks = fit_vectorizers([cd[i] for i in tr], [td[i] for i in tr])
Ttr = hstack([char.transform([cd[i] for i in tr]), toks.transform([td[i] for i in tr])]).tocsr()
Tva = hstack([char.transform([cd[i] for i in va]), toks.transform([td[i] for i in va])]).tocsr()
for C, s in scores:
clf = LogisticRegression(C=C, max_iter=3000, class_weight="balanced", random_state=args.seed)
clf.fit(hstack([Ttr, csr_matrix(F[tr] * s)]).tocsr(), y[tr])
pv = clf.predict_proba(hstack([Tva, csr_matrix(F[va] * s)]).tocsr())[:, 1]
oof[(C, s)][va] = pv
scores[(C, s)].append(f1_score(y[va], (pv >= 0.5).astype(int), average="macro"))
print(f"fold {fold + 1}/{args.folds} done", flush=True)
table = sorted(((np.mean(v), np.std(v), C, s) for (C, s), v in scores.items()), reverse=True)
for m, sd, C, s in table:
print(f"C={C:<5} flag_scale={s:<5} grouped-CV macro-F1 {m:.4f} ± {sd:.4f}")
cv_f1, cv_sd, C, scale = table[0]
print(f"selected C={C}, flag_scale={scale}")
thr_grid = np.round(np.arange(0.10, 0.91, 0.05), 2)
thr_f1 = [f1_score(y, (oof[(C, scale)] >= t).astype(int), average="macro") for t in thr_grid]
threshold = float(thr_grid[int(np.argmax(thr_f1))])
print(f"threshold={threshold} (out-of-fold macro-F1 {max(thr_f1):.4f} vs {thr_f1[list(thr_grid).index(0.5)]:.4f} at 0.5)")
char, toks = fit_vectorizers(cd, td)
clf = LogisticRegression(C=C, max_iter=3000, class_weight="balanced", random_state=args.seed)
X = featurize(char, toks, urls, scale, flags=F, d=(cd, td))
clf.fit(X, y)
for v in (char, toks):
if hasattr(v, "stop_words_"):
delattr(v, "stop_words_")
os.makedirs(args.out, exist_ok=True)
dump({"char": char, "toks": toks, "clf": clf, "flag_scale": scale, "flag_ids": FLAG_IDS, "threshold": threshold},
f"{args.out}/model.skops", compression=zipfile.ZIP_DEFLATED, compresslevel=9)
with open(f"{args.out}/config.json", "w") as f:
json.dump({"model_type": "tfidf-logreg+urlflags", "labels": ["benign", "malicious"], "threshold": threshold,
"oof_macro_f1_at_threshold": round(max(thr_f1), 4),
"char_vectorizer": CHAR, "token_vectorizer": TOKS, "logreg_C": C, "flag_scale": scale,
"red_flag_features": FLAG_IDS, "grouped_cv_macro_f1": round(cv_f1, 4),
"grouped_cv_macro_f1_std": round(cv_sd, 4), "cv_folds": args.folds,
"cv_grid": [{"C": C_, "flag_scale": s_, "macro_f1": round(m_, 4)} for m_, _, C_, s_ in table],
"train_rows": len(df), "n_features": int(X.shape[1])}, f, indent=1)
if __name__ == "__main__":
main()