Text Classification
Scikit-learn
English
tfidf-logreg+urlflags
cybersecurity
security
phishing
malware
malicious-url
url-classification
explainable-ai
tfidf
logistic-regression
skops
Eval Results (legacy)
Instructions to use DaveyD347/malicious-url-classifier with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Scikit-learn
How to use DaveyD347/malicious-url-classifier with Scikit-learn:
# ⚠️ Model filename not specified in config.json
- Notebooks
- Google Colab
- Kaggle
Download src/evaluate.py from DaveyD347/malicious-url-classifier: direct link, hf CLI and curl.
- Browser
- Download file 5.67 kB
-
https://huggingface.co/DaveyD347/malicious-url-classifier/resolve/main/src/evaluate.py
- Command line
-
hf download hf://DaveyD347/malicious-url-classifier/src/evaluate.py
-
curl -L -o evaluate.py https://huggingface.co/DaveyD347/malicious-url-classifier/resolve/main/src/evaluate.py
5.67 kB
| """Evaluate the trained model on the template-disjoint test split and the hand-written challenge set. | |
| Also fits two ablations on the same training data for comparison: red flags only, and TF-IDF only. | |
| Usage: python src/evaluate.py --data data --model outputs/model --out eval | |
| """ | |
| import argparse | |
| import json | |
| import os | |
| import matplotlib | |
| import numpy as np | |
| import pandas as pd | |
| from scipy.sparse import csr_matrix, hstack | |
| from skops.io import get_untrusted_types, load | |
| from sklearn.linear_model import LogisticRegression | |
| from sklearn.metrics import (accuracy_score, confusion_matrix, precision_recall_fscore_support, roc_auc_score) | |
| from train import docs, featurize, flag_matrix, fit_vectorizers | |
| matplotlib.use("Agg") | |
| import matplotlib.pyplot as plt # noqa: E402 | |
| def load_model(path): | |
| f = f"{path}/model.skops" | |
| return load(f, trusted=get_untrusted_types(file=f)) | |
| def proba(m, urls): | |
| return m["clf"].predict_proba(featurize(m["char"], m["toks"], list(urls), m["flag_scale"]))[:, 1] | |
| def metrics(y, p, thr=0.5): | |
| pred = (p >= thr).astype(int) | |
| pr, rc, f1, _ = precision_recall_fscore_support(y, pred, average="binary", zero_division=0) | |
| _, _, f1m, _ = precision_recall_fscore_support(y, pred, average="macro", zero_division=0) | |
| tn, fp, fn, tp = confusion_matrix(y, pred, labels=[0, 1]).ravel() | |
| return {"n": int(len(y)), "accuracy": round(accuracy_score(y, pred), 4), "precision": round(pr, 4), | |
| "recall": round(rc, 4), "f1": round(f1, 4), "f1_macro": round(f1m, 4), | |
| "roc_auc": round(roc_auc_score(y, p), 4), "false_positive_rate": round(fp / max(fp + tn, 1), 4), | |
| "confusion": {"tn": int(tn), "fp": int(fp), "fn": int(fn), "tp": int(tp)}} | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--data", default="data") | |
| ap.add_argument("--model", default="outputs/model") | |
| ap.add_argument("--out", default="eval") | |
| args = ap.parse_args() | |
| m = load_model(args.model) | |
| thr = m.get("threshold", 0.5) | |
| held = set(json.load(open(f"{args.data}/split_variants.json"))["held_out_families"]) | |
| os.makedirs(args.out, exist_ok=True) | |
| res = {} | |
| sets = {n: pd.read_parquet(f"{args.data}/{n}.parquet") for n in ("test", "challenge")} | |
| for name, df in sets.items(): | |
| p = proba(m, df.url) | |
| df["p"] = p | |
| res[name] = {"threshold": thr, **metrics(df.label.values, p, thr)} | |
| fam = {} | |
| for f, g in df.groupby("family"): | |
| fam[f] = {"n": int(len(g)), "label": g.label_name.iloc[0], "held_out_family": f in held, | |
| "accuracy": round(float(((g.p >= thr).astype(int) == g.label).mean()), 4)} | |
| res[name]["per_family"] = fam | |
| if name == "test": | |
| ho = df.family.isin(held) | |
| res[name]["held_out_families_only"] = metrics(df.label.values[ho], p[ho], thr) | |
| res[name]["seen_families_new_templates"] = metrics(df.label.values[~ho], p[~ho], thr) | |
| cm = confusion_matrix(df.label, (p >= thr).astype(int)) | |
| fig, ax = plt.subplots(figsize=(4.2, 3.6)) | |
| ax.imshow(cm, cmap="Blues") | |
| for (i, j), v in np.ndenumerate(cm): | |
| ax.text(j, i, str(v), ha="center", va="center", color="white" if v > cm.max() / 2 else "black") | |
| ax.set_xticks([0, 1], ["benign", "malicious"]) | |
| ax.set_yticks([0, 1], ["benign", "malicious"]) | |
| ax.set_xlabel("predicted") | |
| ax.set_ylabel("true") | |
| ax.set_title(f"Template-disjoint test split (threshold {thr})") | |
| fig.tight_layout() | |
| fig.savefig(f"{args.out}/confusion_matrix.png", dpi=150) | |
| else: | |
| res[name]["errors"] = [{"id": r.id, "label": r.label_name, "p_malicious": round(float(r.p), 3), | |
| "url": r.url} for r in df.itertuples() if int(r.p >= thr) != r.label] | |
| res[name]["scores"] = [{"url": r.url, "label": r.label_name, "p_malicious": round(float(r.p), 4)} | |
| for r in df.itertuples()] | |
| print(name, {k: v for k, v in res[name].items() if k in ("accuracy", "f1_macro", "roc_auc", "false_positive_rate", "recall")}) | |
| # ablations, same training rows and hyper-parameters | |
| tr = pd.concat([pd.read_parquet(f"{args.data}/{s}.parquet") for s in ("train", "validation")], ignore_index=True) | |
| Ftr = flag_matrix(tr.url) | |
| cd, td = docs(tr.url) | |
| char, toks = fit_vectorizers(cd, td) | |
| Ttr = hstack([char.transform(cd), toks.transform(td)]).tocsr() | |
| C = m["clf"].C | |
| abl = {} | |
| for name, df in sets.items(): | |
| Fx = flag_matrix(df.url) | |
| cdx, tdx = docs(df.url) | |
| Tx = hstack([char.transform(cdx), toks.transform(tdx)]).tocsr() | |
| for kind, Xtr, Xte in (("red_flags_only", csr_matrix(Ftr), csr_matrix(Fx)), ("tfidf_only", Ttr, Tx)): | |
| clf = LogisticRegression(C=C, max_iter=3000, class_weight="balanced", random_state=0).fit(Xtr, tr.label) | |
| pp = clf.predict_proba(Xte)[:, 1] | |
| abl.setdefault(kind, {})[name] = {k: v for k, v in metrics(df.label.values, pp, 0.5).items() | |
| if k in ("accuracy", "f1_macro", "roc_auc", "false_positive_rate", "recall")} | |
| res["ablations"] = abl | |
| print("ablations", json.dumps(abl)) | |
| with open(f"{args.out}/metrics.json", "w") as f: | |
| json.dump(res, f, indent=1, ensure_ascii=False) | |
| for e in res["challenge"]["errors"]: | |
| print(" challenge miss:", e["label"], e["p_malicious"], e["url"]) | |
| for f, v in sorted(res["test"]["per_family"].items(), key=lambda kv: kv[1]["accuracy"])[:12]: | |
| print(" test family", f, v) | |
| if __name__ == "__main__": | |
| main() | |