Download impl/src/pipeline/step06_source_probe.py from pramodkachare/Cyber: direct link, hf CLI and curl.
- Browser
- Download file 7.15 kB
-
https://huggingface.co/datasets/pramodkachare/Cyber/resolve/main/impl/src/pipeline/step06_source_probe.py
- Command line
-
hf download hf://datasets/pramodkachare/Cyber/impl/src/pipeline/step06_source_probe.py
-
curl -L -o step06_source_probe.py https://huggingface.co/datasets/pramodkachare/Cyber/resolve/main/impl/src/pipeline/step06_source_probe.py
7.15 kB
| """STEP 06: how well can the SOURCE dataset be predicted from the features? (RQ1) + definition of feature set C. | |
| Population: rows that are first occurrences of their B-hash (is_first_B), for ALL feature sets (stricter, identical sample for A/B/C). | |
| Sample: equal number of flows per source (cap N_PER_SOURCE), deterministic by hash(row_id, SEED); random 70/30 split (stratified by source). | |
| Probes (LightGBM, 4-class source identification): | |
| 1. overall, feature sets A / B / C | |
| 2. within one class only: Benign (4 sources), DoS (3), DDoS (2): same label, different source | |
| Feature set C rule (stated before looking at results): drop every B feature whose SINGLE-feature decision tree identifies the source with | |
| balanced accuracy >= C_THRESHOLD (0.90). Chance = 1/#sources. | |
| Outputs (artifacts/step06/): probe_results.csv, univariate.csv, feature_set_C.json, importance_B.csv, confusion_B.csv | |
| """ | |
| import csv | |
| import numpy as np, pandas as pd | |
| import lightgbm as lgb | |
| from sklearn.tree import DecisionTreeClassifier | |
| from sklearn.metrics import accuracy_score, f1_score, confusion_matrix | |
| from .common import * | |
| NAME = "step06" | |
| N_PER_SOURCE = 150_000 | |
| C_THRESHOLD = 0.90 | |
| KEYS = os.path.join(DATA, "dedup_keys.parquet") | |
| S = f"read_parquet('{PARQUET_SRC}')" | |
| K = f"read_parquet('{KEYS}')" | |
| def sample(con, cols, per_source, where="TRUE"): | |
| q = f"""SELECT * FROM ( | |
| SELECT s.source, s.Attack, {feat_select(cols, 's.')}, row_number() OVER (PARTITION BY s.source ORDER BY hash(s.row_id, {SEED})) rk | |
| FROM {S} s JOIN {K} k USING (row_id) WHERE k.is_first_B AND {where}) WHERE rk <= {per_source}""" | |
| return con.execute(q).df() # keeps rk (rank within source, deterministic by hash) | |
| def prep(df, cols): | |
| X = df[cols].astype("float32").replace([np.inf, -np.inf], np.nan) | |
| return X | |
| def probe(con, name, cols, where, per_source, results, feats): | |
| df = sample(con, feats, per_source, where) | |
| counts = df.source.value_counts() | |
| n = int(counts.min()) # equalise sources: keep the first n ranks of every source | |
| df = df[df.rk <= n].reset_index(drop=True) | |
| y = df.source.map({s: i for i, s in enumerate(SOURCES)}).values | |
| rng = np.random.RandomState(SEED); idx = rng.permutation(len(df)); cut = int(0.7 * len(df)) | |
| tr, te = idx[:cut], idx[cut:] | |
| present = sorted(set(y)); remap = {v: i for i, v in enumerate(present)}; yy = np.array([remap[v] for v in y]) | |
| out = {} | |
| for fs_name, fs in cols.items(): | |
| X = prep(df, fs) | |
| m = lgb.LGBMClassifier(n_estimators=300, learning_rate=0.1, num_leaves=63, n_jobs=THREADS, verbose=-1, random_state=SEED, | |
| objective="multiclass" if len(present) > 2 else "binary") | |
| m.fit(X.iloc[tr], yy[tr]) | |
| p = m.predict(X.iloc[te]) | |
| acc, f1 = accuracy_score(yy[te], p), f1_score(yy[te], p, average="macro") | |
| results.append([name, fs_name, len(fs), len(present), n, len(df), round(1 / len(present), 3), round(acc, 4), round(f1, 4)]) | |
| print(f" {name:10s} {fs_name}: n_feat={len(fs)} sources={len(present)} per_src={n} acc={acc:.4f} macroF1={f1:.4f}", flush=True) | |
| out[fs_name] = (m, X.iloc[te], yy[te], p, present) | |
| return out | |
| def run(force=False): | |
| out = step_dir(NAME); con = connect() | |
| A, B = features_A(con), features_B(con) | |
| results = [] | |
| # --- univariate scan on B (balanced sample) to define C | |
| df = sample(con, B, N_PER_SOURCE) | |
| n = int(df.source.value_counts().min()) | |
| df = df[df.rk <= n].reset_index(drop=True) | |
| y = df.source.map({s: i for i, s in enumerate(SOURCES)}).values | |
| rng = np.random.RandomState(SEED); idx = rng.permutation(len(df)); cut = int(0.7 * len(df)); tr, te = idx[:cut], idx[cut:] | |
| uni = [] | |
| for c in B: | |
| x = df[[c]].astype("float32").replace([np.inf, -np.inf], np.nan).fillna(-1e9).values | |
| t = DecisionTreeClassifier(max_leaf_nodes=64, random_state=SEED).fit(x[tr], y[tr]) | |
| uni.append((c, accuracy_score(y[te], t.predict(x[te])))) | |
| uni.sort(key=lambda r: -r[1]) | |
| with open(os.path.join(out, "univariate.csv"), "w", newline="") as f: | |
| w = csv.writer(f); w.writerow(["feature", "single_feature_source_accuracy"]); w.writerows([(c, round(a, 4)) for c, a in uni]) | |
| dropped = [c for c, a in uni if a >= C_THRESHOLD] | |
| C = [c for c in B if c not in dropped] | |
| save_json({"rule": f"drop B features with single-feature source accuracy >= {C_THRESHOLD}", "threshold": C_THRESHOLD, "chance": 0.25, | |
| "dropped": dropped, "n_features_C": len(C), "features_C": C}, os.path.join(out, "feature_set_C.json")) | |
| print("feature set C drops:", dropped) | |
| sets = {"A": A, "B": B, "C": C} | |
| # --- overall and within-class probes | |
| probes = [("overall", "TRUE", N_PER_SOURCE), ("Benign", "s.Attack='Benign'", 50_000), ("DoS", "s.Attack='DoS'", 50_000), ("DDoS", "s.Attack='DDoS'", 50_000)] | |
| detail = None | |
| for name, where, per in probes: | |
| with timed(f"probe {name}"): | |
| r = probe(con, name, sets, where, per, results, A) | |
| if name == "overall": detail = r | |
| with open(os.path.join(out, "probe_results.csv"), "w", newline="") as f: | |
| w = csv.writer(f); w.writerow(["probe", "feature_set", "n_features", "n_sources", "per_source_n", "total_n", "chance", "accuracy", "macro_f1"]); w.writerows(results) | |
| m, Xte, yte, p, present = detail["B"] | |
| imp = sorted(zip(B, m.booster_.feature_importance("gain")), key=lambda r: -r[1]) | |
| with open(os.path.join(out, "importance_B.csv"), "w", newline="") as f: | |
| w = csv.writer(f); w.writerow(["feature", "gain"]); w.writerows([(c, round(float(g), 1)) for c, g in imp]) | |
| # ablation: remove the k most source-informative B features (by gain in the overall B model), retrain, re-measure | |
| order = [c for c, _ in imp] | |
| dfa = sample(con, B, N_PER_SOURCE); na = int(dfa.source.value_counts().min()); dfa = dfa[dfa.rk <= na].reset_index(drop=True) | |
| ya = dfa.source.map({s_: i for i, s_ in enumerate(SOURCES)}).values | |
| idx = np.random.RandomState(SEED).permutation(len(dfa)); cut = int(0.7 * len(dfa)); tr, te = idx[:cut], idx[cut:] | |
| abl = [] | |
| for k in [0, 1, 2, 3, 5, 8, 12, 16, 20, 25, 30, 35, 40]: | |
| keep = order[k:] | |
| if len(keep) < 2: break | |
| X = prep(dfa, keep) | |
| mm = lgb.LGBMClassifier(n_estimators=200, learning_rate=0.1, num_leaves=63, n_jobs=THREADS, verbose=-1, random_state=SEED).fit(X.iloc[tr], ya[tr]) | |
| pa = mm.predict(X.iloc[te]); abl.append((k, len(keep), round(accuracy_score(ya[te], pa), 4), round(f1_score(ya[te], pa, average="macro"), 4))) | |
| print(f" ablation remove top-{k}: {len(keep)} features left, source accuracy {abl[-1][2]}", flush=True) | |
| with open(os.path.join(out, "ablation_source_identifiability.csv"), "w", newline="") as f: | |
| w = csv.writer(f); w.writerow(["removed_top_k", "n_features_left", "accuracy", "macro_f1"]); w.writerows(abl) | |
| cm = confusion_matrix(yte, p) | |
| pd.DataFrame(cm, index=[SOURCES[i] for i in present], columns=[SOURCES[i] for i in present]).to_csv(os.path.join(out, "confusion_B.csv")) | |
| print(open(os.path.join(out, "probe_results.csv")).read()) | |