File size: 5,672 Bytes
84f95cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
"""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()