Download impl/src/pipeline/step08_baselines.py from pramodkachare/Cyber: direct link, hf CLI and curl.
- Browser
- Download file 10.4 kB
-
https://huggingface.co/datasets/pramodkachare/Cyber/resolve/main/impl/src/pipeline/step08_baselines.py
- Command line
-
hf download hf://datasets/pramodkachare/Cyber/impl/src/pipeline/step08_baselines.py
-
curl -L -o step08_baselines.py https://huggingface.co/datasets/pramodkachare/Cyber/resolve/main/impl/src/pipeline/step08_baselines.py
10.4 kB
| """STEP 08: baselines under the frozen protocols (RQ2). Resumable: every run is keyed model|protocol|featset and skipped if present. | |
| Models: xgb (GPU), lgbm (CPU), rf (sklearn), mlp (PyTorch, GPU); control baselines that every score must be read against: | |
| majority predict the most frequent training label | |
| source predict the most frequent training label of the flow's source dataset (only where the source is seen in training: p1-p3) | |
| idonly xgb on the six identifier features only (IPs, ports, timestamps): measures how much shortcut features alone explain | |
| Feature sets: A (53, incl. identifiers), B (47). Test rows for B are the clean rows (no same-label B duplicate in train, no cross-label conflict). | |
| Labels per protocol: Attack (p1-p4), benign/attack (p4b), family (p5 taxonomy v1, p5v0 taxonomy v0). Only labels evaluable under the protocol | |
| (evaluability_matrix.csv, thresholds in step 07) are trained and scored. Per-label caps: train 150k (RF 30k, MLP 100k), val 20k, test 100k. | |
| Environment: BF_MODELS, BF_PROTOCOLS, BF_FEATSETS (comma lists) select a subset; CUDA_VISIBLE_DEVICES selects the GPU. | |
| Outputs: artifacts/step08/results.csv, per_class.csv, confusion/<run_id>.npy | |
| """ | |
| import csv, time, warnings | |
| import numpy as np, pandas as pd | |
| from .common import * | |
| from .lib_data import * | |
| from .lib_metrics import * | |
| NAME = "step08" | |
| CAPS = {"xgb": 150_000, "lgbm": 150_000, "rf": 30_000, "mlp": 100_000, "idonly": 150_000} | |
| VAL_CAP, TEST_CAP = 20_000, 100_000 | |
| RES_FIELDS = ["run_id", "model", "protocol", "featset", "n_labels", "n_train", "n_test", "macro_f1", "f1_lo", "f1_hi", "mcc", "mcc_lo", "mcc_hi", | |
| "balanced_acc", "accuracy", "weighted_f1", "majority_macro_f1", "majority_accuracy", "source_macro_f1", "seconds"] | |
| def protocols_all(): | |
| ps = ["p1", "p2", "p3"] | |
| for p in ("p4", "p4b", "p5", "p5v0"): | |
| ps += [f"{p}_{SRC_SHORT[s]}" for s in SOURCES] | |
| return ps | |
| def feature_columns(con, featset): | |
| return {"A": features_A(con), "B": features_B(con), "ID": IDENTIFIERS}[featset] | |
| def get_frames(con, protocol, featset, cap_train): | |
| fs_for_eval = "A" if featset == "ID" else featset | |
| tr, labs = load(con, protocol, fs_for_eval, "train", cap_train, extra_cols=()) | |
| if tr is None or len(labs) < 2: return None | |
| va, _ = load(con, protocol, fs_for_eval, "val", VAL_CAP) | |
| te, _ = load(con, protocol, fs_for_eval, "test", TEST_CAP) | |
| return tr, va, te, labs | |
| def to_matrix(df, featset, con): | |
| cols = feature_columns(con, featset) | |
| if featset == "ID": | |
| return df[cols].astype("float32") | |
| return xy(df, cols) | |
| def fit_predict(model, Xtr, ytr, Xva, yva, Xte, n_classes): | |
| t = time.time() | |
| if model in ("xgb", "idonly"): | |
| import xgboost as xgb | |
| m = xgb.XGBClassifier(n_estimators=400, learning_rate=0.1, max_depth=8, subsample=0.8, colsample_bytree=0.8, tree_method="hist", device="cuda:0", | |
| n_jobs=8, max_bin=128, early_stopping_rounds=20, eval_metric="mlogloss" if n_classes > 2 else "logloss", random_state=SEED, | |
| objective="multi:softprob" if n_classes > 2 else "binary:logistic") | |
| m.fit(Xtr, ytr, eval_set=[(Xva, yva)] if len(Xva) else None, verbose=False) | |
| return m.predict(Xte), time.time() - t | |
| if model == "lgbm": | |
| import lightgbm as lgb | |
| m = lgb.LGBMClassifier(n_estimators=400, learning_rate=0.1, num_leaves=63, subsample=0.8, subsample_freq=1, colsample_bytree=0.8, n_jobs=THREADS, verbose=-1, random_state=SEED) | |
| cb = [lgb.early_stopping(20, verbose=False)] if len(Xva) else [] | |
| m.fit(Xtr, ytr, eval_set=[(Xva, yva)] if len(Xva) else None, callbacks=cb) | |
| return m.predict(Xte), time.time() - t | |
| if model == "rf": | |
| from sklearn.ensemble import RandomForestClassifier | |
| m = RandomForestClassifier(n_estimators=200, n_jobs=THREADS, random_state=SEED, min_samples_leaf=1, max_features="sqrt") | |
| m.fit(Xtr.fillna(-1), ytr) | |
| return m.predict(Xte.fillna(-1)), time.time() - t | |
| if model == "mlp": | |
| return mlp_fit_predict(Xtr, ytr, Xva, yva, Xte, n_classes, t) | |
| raise ValueError(model) | |
| def mlp_fit_predict(Xtr, ytr, Xva, yva, Xte, n_classes, t0, epochs=12, bs=4096): | |
| import torch, torch.nn as nn | |
| dev = "cuda:0" if torch.cuda.is_available() else "cpu" | |
| def prep(X, stats=None): | |
| A = X.values.astype("float32"); miss = np.isnan(A); A = np.nan_to_num(A, nan=0.0) | |
| A = np.sign(A) * np.log1p(np.abs(A)) # heavy-tailed counts -> log scale | |
| if stats is None: stats = (A.mean(0), A.std(0) + 1e-6) | |
| A = (A - stats[0]) / stats[1] | |
| ind = miss[:, [X.columns.get_loc(c) for c in X.columns if c.endswith("SECOND_BYTES") and c in X.columns]] if any(c.endswith("SECOND_BYTES") for c in X.columns) else np.zeros((len(A), 0), bool) | |
| return np.hstack([A, ind.astype("float32")]), stats | |
| A_tr, st = prep(Xtr); A_va, _ = prep(Xva, st); A_te, _ = prep(Xte, st) | |
| torch.manual_seed(SEED) | |
| net = nn.Sequential(nn.Linear(A_tr.shape[1], 512), nn.ReLU(), nn.Dropout(0.1), nn.Linear(512, 512), nn.ReLU(), nn.Dropout(0.1), nn.Linear(512, 256), nn.ReLU(), nn.Linear(256, n_classes)).to(dev) | |
| opt = torch.optim.AdamW(net.parameters(), lr=1e-3, weight_decay=1e-4) | |
| Xt = torch.tensor(A_tr, device=dev); yt = torch.tensor(ytr, device=dev, dtype=torch.long) | |
| best, best_state = 1e9, None | |
| for ep in range(epochs): | |
| net.train(); perm = torch.randperm(len(Xt), device=dev) | |
| for i in range(0, len(Xt), bs): | |
| idx = perm[i:i + bs]; opt.zero_grad(); loss = nn.functional.cross_entropy(net(Xt[idx]), yt[idx]); loss.backward(); opt.step() | |
| if len(A_va): | |
| net.eval() | |
| with torch.no_grad(): vl = nn.functional.cross_entropy(net(torch.tensor(A_va, device=dev)), torch.tensor(yva, device=dev, dtype=torch.long)).item() | |
| if vl < best: best, best_state = vl, {k: v.clone() for k, v in net.state_dict().items()} | |
| if best_state: net.load_state_dict(best_state) | |
| net.eval(); out = [] | |
| with torch.no_grad(): | |
| for i in range(0, len(A_te), 65536): out.append(net(torch.tensor(A_te[i:i + 65536], device=dev)).argmax(1).cpu().numpy()) | |
| return np.concatenate(out), time.time() - t0 | |
| def run(force=False): | |
| out = step_dir(NAME); os.makedirs(os.path.join(out, "confusion"), exist_ok=True) | |
| models = os.environ.get("BF_MODELS", "xgb").split(","); featsets = os.environ.get("BF_FEATSETS", "A,B").split(",") | |
| protos = os.environ.get("BF_PROTOCOLS", ",".join(protocols_all())).split(",") | |
| res_path, pc_path = os.path.join(out, "results.csv"), os.path.join(out, "per_class.csv") | |
| done = set() | |
| if os.path.exists(res_path): | |
| with open(res_path) as f: done = {r["run_id"] for r in csv.DictReader(f)} | |
| else: | |
| with open(res_path, "w", newline="") as f: csv.writer(f).writerow(RES_FIELDS) | |
| with open(pc_path, "w", newline="") as f: csv.writer(f).writerow(["run_id", "label", "support", "precision", "recall", "f1", "recall_lo", "recall_hi"]) | |
| con = connect() | |
| for model in models: | |
| for fs in (["ID"] if model == "idonly" else featsets): | |
| for p in protos: | |
| if model == "idonly" and p not in ("p1", "p2", "p3"): continue | |
| rid = f"{model}|{p}|{fs}" | |
| if rid in done and not force: continue | |
| with timed(rid): | |
| fr = get_frames(con, p, fs, CAPS[model]) | |
| if fr is None: | |
| print(" skipped (not enough evaluable labels)"); continue | |
| tr, va, te, labs = fr | |
| if te is None or len(te) == 0: print(" skipped (no clean test rows)"); continue | |
| names = sorted(set(tr.label)); idx = {n: i for i, n in enumerate(names)} | |
| assert set(te.label) <= set(names), (set(te.label) - set(names)) | |
| ytr, yva, yte = tr.label.map(idx).values, (va.label.map(idx).values if va is not None and len(va) else np.array([], int)), te.label.map(idx).values | |
| Xtr, Xva, Xte = to_matrix(tr, fs, con), (to_matrix(va, fs, con) if len(yva) else pd.DataFrame(columns=to_matrix(tr.head(1), fs, con).columns)), to_matrix(te, fs, con) | |
| pred, secs = fit_predict(model, Xtr, ytr, Xva, yva, Xte, len(names)) | |
| cm = confusion(yte, pred, len(names)); s = summarise(cm); ci = bootstrap_ci(cm) | |
| maj = np.bincount(ytr).argmax(); cm_m = confusion(yte, np.full_like(yte, maj), len(names)); sm = summarise(cm_m) | |
| src_f1 = "" | |
| if p in ("p1", "p2", "p3"): | |
| top = tr.groupby("source").label.agg(lambda x: x.value_counts().index[0]); pr = te.source.map(top).map(idx) | |
| if pr.notna().all(): src_f1 = round(summarise(confusion(yte, pr.astype(int).values, len(names)))["macro_f1"], 4) | |
| with open(res_path, "a", newline="") as f: | |
| csv.writer(f).writerow([rid, model, p, fs, len(names), len(tr), len(te), round(s["macro_f1"], 4), round(ci["macro_f1"][0], 4), round(ci["macro_f1"][1], 4), | |
| round(s["mcc"], 4), round(ci["mcc"][0], 4), round(ci["mcc"][1], 4), round(s["balanced_acc"], 4), round(s["accuracy"], 4), | |
| round(s["weighted_f1"], 4), round(sm["macro_f1"], 4), round(sm["accuracy"], 4), src_f1, round(secs, 1)]) | |
| with open(pc_path, "a", newline="") as f: | |
| w = csv.writer(f) | |
| for n, sup, pp, rr, ff in per_class(cm, names): | |
| lo, hi = wilson(int(round(rr * sup)), sup); w.writerow([rid, n, sup, round(pp, 4), round(rr, 4), round(ff, 4), round(lo, 4), round(hi, 4)]) | |
| np.save(os.path.join(out, "confusion", rid.replace("|", "__") + ".npy"), cm) | |
| with open(os.path.join(out, "confusion", rid.replace("|", "__") + ".labels.json"), "w") as f: json.dump(names, f) | |
| print(f" macroF1={s['macro_f1']:.4f} [{ci['macro_f1'][0]:.4f},{ci['macro_f1'][1]:.4f}] MCC={s['mcc']:.4f} acc={s['accuracy']:.4f} " | |
| f"majorityF1={sm['macro_f1']:.4f} source-only F1={src_f1} labels={len(names)} train={len(tr)} test={len(te)} {secs:.0f}s", flush=True) | |