Cyber / impl /src /pipeline /step04_class_by_source.py
pramodkachare's picture
Upload project files (excluding raw/derived dataset and venv)
aefa98b verified
Raw History Blame Contribute Delete
4.86 kB
"""STEP 04: class x source table, source/label confounding, and what each split protocol can evaluate.
Outputs (artifacts/step04/): class_by_source.csv, loso_coverage.csv, time_split_coverage.csv, confounding.json
Thresholds (stated in the thesis): MIN_TRAIN = 100 flows of the class available for training,
MIN_TEST = 50 flows of the class in the evaluation set; below that a class is "not evaluable" for that protocol.
"""
import csv, math
import numpy as np
from .common import *
NAME = "step04"
MIN_TRAIN, MIN_TEST = 100, 50
S = f"read_parquet('{PARQUET_SRC}')"
def _entropy(p):
p = p[p > 0]; return float(-(p * np.log(p)).sum())
def run(force=False):
out = step_dir(NAME); con = connect()
rows = con.execute(f"SELECT Attack, source, count(*) FROM {S} GROUP BY ALL").fetchall()
classes = sorted({r[0] for r in rows}); srcs = SOURCES
M = np.zeros((len(classes), len(srcs)), dtype=np.int64)
for a, s, c in rows: M[classes.index(a), srcs.index(s)] = c
tot = M.sum(1); N = int(M.sum())
order = np.argsort(-tot)
with open(os.path.join(out, "class_by_source.csv"), "w", newline="") as f:
w = csv.writer(f); w.writerow(["Attack", "total"] + srcs + ["n_sources", "dominant_source", "dominant_share", "single_source"])
for i in order:
ns = int((M[i] > 0).sum()); d = int(M[i].argmax())
w.writerow([classes[i], int(tot[i])] + [int(x) for x in M[i]] + [ns, srcs[d], round(M[i, d] / tot[i], 4), int(ns == 1)])
# confounding between source and label
P = M / N; ps, pc = P.sum(0), P.sum(1)
mi = sum(P[i, j] * math.log(P[i, j] / (pc[i] * ps[j])) for i in range(len(classes)) for j in range(len(srcs)) if P[i, j] > 0)
nmi = mi / math.sqrt(_entropy(ps) * _entropy(pc))
bi = np.array([[M[classes.index("Benign"), j], M[:, j].sum() - M[classes.index("Benign"), j]] for j in range(len(srcs))])
conf = {
"n_rows": N, "classes": len(classes),
"normalised_mutual_information_source_vs_class": round(nmi, 4),
"source_only_accuracy_binary": round(float(bi.max(1).sum() / N), 4),
"source_only_accuracy_32class": round(float(M.max(0).sum() / N), 4),
"majority_class_accuracy_32class": round(float(tot.max() / N), 4),
"single_source_classes": [classes[i] for i in range(len(classes)) if (M[i] > 0).sum() == 1],
"n_classes_by_n_sources": {int(k): int(((M > 0).sum(1) == k).sum()) for k in range(1, 5)},
}
# coverage-aware LOSO
loso = []
for j, s in enumerate(srcs):
for i in order:
te, tr = int(M[i, j]), int(M[i].sum() - M[i, j])
loso.append([s, classes[i], te, tr, int(te >= MIN_TEST and tr >= MIN_TRAIN)])
with open(os.path.join(out, "loso_coverage.csv"), "w", newline="") as f:
w = csv.writer(f); w.writerow(["held_out_source", "Attack", "n_test_in_heldout", "n_train_other_sources", "evaluable"]); w.writerows(loso)
conf["loso_evaluable_classes_per_heldout_source"] = {s: sum(r[4] for r in loso if r[0] == s) for s in srcs}
conf["loso_test_rows_evaluable_share"] = {s: round(sum(r[2] for r in loso if r[0] == s and r[4]) / M[:, j].sum(), 4) for j, s in enumerate(srcs)}
# within-source time split: windows by source-wide time quantiles 70% / 85%
q = con.execute(f"""SELECT source, quantile_cont(FLOW_START_MILLISECONDS, 0.70), quantile_cont(FLOW_START_MILLISECONDS, 0.85) FROM {S} GROUP BY 1""").fetchall()
qd = {r[0]: (r[1], r[2]) for r in q}
t = con.execute(f"""WITH w AS (SELECT s.source, s.Attack, s.FLOW_START_MILLISECONDS ts, q.q70, q.q85 FROM {S} s
JOIN (SELECT source, quantile_cont(FLOW_START_MILLISECONDS, 0.70) q70, quantile_cont(FLOW_START_MILLISECONDS, 0.85) q85 FROM {S} GROUP BY 1) q USING (source))
SELECT source, Attack, count(*) FILTER (WHERE ts <= q70), count(*) FILTER (WHERE ts > q70 AND ts <= q85), count(*) FILTER (WHERE ts > q85),
count(DISTINCT CAST(to_timestamp(ts/1000) AS DATE))
FROM w GROUP BY ALL ORDER BY 1, 3 DESC""").fetchall()
with open(os.path.join(out, "time_split_coverage.csv"), "w", newline="") as f:
w = csv.writer(f); w.writerow(["source", "Attack", "n_train_window", "n_val_window", "n_test_window", "n_capture_days", "evaluable"])
for r in t: w.writerow(list(r) + [int(r[2] >= MIN_TRAIN and r[4] >= MIN_TEST)])
conf["time_split_evaluable_classes_per_source"] = {s: sum(1 for r in t if r[0] == s and r[2] >= MIN_TRAIN and r[4] >= MIN_TEST) for s in srcs}
conf["time_split_present_classes_per_source"] = {s: sum(1 for r in t if r[0] == s) for s in srcs}
conf["time_split_classes_with_empty_train_window"] = sorted({r[1] for r in t if r[2] == 0})
conf["thresholds"] = {"MIN_TRAIN": MIN_TRAIN, "MIN_TEST": MIN_TEST}
save_json(conf, os.path.join(out, "confounding.json"))
print(json.dumps(conf, indent=1))