IoTProber commited on
Commit
f0f80e0
·
verified ·
1 Parent(s): 0f10ae8

score_table10 v1.1.0: recover the ORIGINAL Stage-3 matching rule from svm.py (commit 25f6a47) — reproduces paper cells bit-exactly; replaces the wrong philipshue alias

Browse files
Files changed (1) hide show
  1. evaluation/drift/score_table10.py +81 -59
evaluation/drift/score_table10.py CHANGED
@@ -3,7 +3,7 @@
3
 
4
  Reproduces every number of paper Table 10 from the released prediction
5
  CSVs (HuggingFace dataset ``IoTProber/raw_dataset``, path prefix
6
- ``evaluation/drift/CADE``) under an EXPLICIT label-matching rule, so the
7
  matching strategy is no longer notebook folklore.
8
 
9
  Inputs (all columns: ip,vendor,label,label_pred,correct)
@@ -13,29 +13,45 @@ Inputs (all columns: ip,vendor,label,label_pred,correct)
13
  Drift detection: SVM_validation/{IoTProber,CADE}/{detected,correct}_ips.csv
14
 
15
  Matching rules (--match)
16
- exact byte equality of label vs label_pred.
17
- normalized casefold + strip every non [a-z0-9] character, then equality.
18
- ("NVR-Merit Lilin" == "NVR-Merit LILIN" == "NVR-Merit Li-Lin")
19
- canonical normalized + the vendor alias map below (e.g. "Philips Hue"
20
- counts as "Philips").
21
-
22
- Published finding (v1.0.0): the paper's Stage-2 row was scored with the
23
- ``exact`` rule (0.4937 / 0.7403 / 0.6892, reproduced to the fourth decimal)
24
- while the Stage-3 rows were produced by an unversioned notebook whose rule
25
- corresponds to ``normalized``/``canonical`` (paper 0.5509/0.8711/0.8483 vs
26
- recomputed 0.5478/0.8707/0.8478 normalized, 0.5506/0.8726/0.8514 canonical).
27
- Under ONE consistent rule the Stage2->Stage3 accuracy delta is:
28
- exact 0.6892 -> 0.6709 (-1.83 pp)
29
- normalized 0.8335 -> 0.8478 (+1.43 pp) <- the reviewer's ~1.42 pp
30
- canonical 0.8460 -> 0.8514 (+0.54 pp)
31
- The 15.91 pp headline therefore mixes two matching rules and must not be
32
- quoted as a retraining gain. The drift-detection correctness figures
33
- (IoTProber 773/814 = 94.96%, CADE 767/1112 = 68.97%) are rule-independent
34
- (they compare detected IPs against ground-truth drift IPs) and stand.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
 
36
  Usage
37
- python score_table10.py # all three rules + detection stage
38
- python score_table10.py --match normalized # one rule
39
  python score_table10.py --json out.json # machine-readable record
40
  """
41
  import argparse
@@ -48,37 +64,41 @@ import re
48
  import sys
49
 
50
  import pandas as pd
51
- import sklearn
52
 
53
- SCORER_VERSION = "1.0.0"
54
 
55
- # Vendor aliases applied (after normalization) in --match canonical.
56
- # Keys/values are lowercase alphanumerics of the vendor token.
57
  VENDOR_ALIASES = {
58
- "philipshue": "philips",
59
  }
60
 
61
- STAGES = {
62
- "stage2_svm": "SVM_test/predict",
63
- "stage3_iotprober": "SVM_validation/performance/IoTProber/predict",
64
- "stage3_cade": "SVM_validation/performance/CADE/predict",
65
- }
66
 
67
 
68
  def normalize(label: str) -> str:
69
  return re.sub(r"[^a-z0-9]", "", str(label).lower())
70
 
71
 
72
- def canonical(label: str) -> str:
73
- tok = normalize(label)
74
- for alias, repl in VENDOR_ALIASES.items():
75
- if tok.endswith(alias):
76
- tok = tok[: -len(alias)] + repl
77
- return tok
 
 
 
 
 
 
 
 
 
78
 
79
 
80
  def load_stage(data_root: str, sub: str):
81
- """Return (labels, preds) lists over all per-type CSVs of a stage."""
82
  files = sorted(glob.glob(os.path.join(data_root, sub, "*.csv")))
83
  if not files:
84
  sys.exit(f"no prediction CSVs under {os.path.join(data_root, sub)}")
@@ -106,12 +126,11 @@ def sha256(path: str) -> str:
106
 
107
 
108
  def score(labels, preds, rule: str):
109
- f = {"exact": str, "normalized": normalize, "canonical": canonical}[rule]
110
  y = [f(x) for x in labels]
111
  p = [f(x) for x in preds]
112
  n = len(y)
113
  acc = sum(a == b for a, b in zip(y, p)) / n
114
- # macro / weighted F1 over the classes present in y
115
  classes = sorted(set(y) | set(p))
116
  f1s, support = [], []
117
  for c in classes:
@@ -124,7 +143,8 @@ def score(labels, preds, rule: str):
124
  support.append(tp + fn)
125
  macro = sum(f1s) / len(f1s)
126
  weighted = sum(s * f for s, f in zip(support, f1s)) / sum(support)
127
- return {"n": n, "accuracy": round(acc, 4), "macro_f1": round(macro, 4),
 
128
  "weighted_f1": round(weighted, 4)}
129
 
130
 
@@ -135,22 +155,24 @@ def main():
135
  default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "CADE"),
136
  help="directory containing SVM_test/, SVM_validation/ "
137
  "(default: <script dir>/CADE)")
138
- ap.add_argument("--match", choices=["exact", "normalized", "canonical", "all"],
139
  default="all")
140
  ap.add_argument("--json", help="write a machine-readable record here")
141
  args = ap.parse_args()
142
 
143
- rules = ["exact", "normalized", "canonical"] if args.match == "all" else [args.match]
144
  record = {
145
  "scorer_version": SCORER_VERSION,
146
  "matching_rules": {
147
- "exact": "byte equality on label/label_pred",
148
- "normalized": "casefold + strip non [a-z0-9]",
149
- "canonical": "normalized + vendor aliases " + json.dumps(VENDOR_ALIASES),
 
 
 
150
  },
151
  "python": platform.python_version(),
152
  "pandas": pd.__version__,
153
- "scikit-learn": sklearn.__version__,
154
  "inputs": {},
155
  "stages": {},
156
  "detection": {},
@@ -166,7 +188,7 @@ def main():
166
  "sha256": {os.path.relpath(f, args.data_root): sha256(f) for f in files},
167
  }
168
 
169
- header = f"{'stage':<20}{'rule':<12}{'n':>7}{'macroF1':>9}{'wF1':>8}{'acc':>8}"
170
  lines = [header, "-" * len(header)]
171
  for stage in STAGES:
172
  labels, preds = stage_data[stage]
@@ -174,16 +196,16 @@ def main():
174
  for rule in rules:
175
  m = score(labels, preds, rule)
176
  record["stages"][stage][rule] = m
177
- lines.append(f"{stage:<20}{rule:<12}{m['n']:>7}{m['macro_f1']:>9}"
178
- f"{m['weighted_f1']:>8}{m['accuracy']:>8}")
179
- if rules == ["exact", "normalized", "canonical"]:
180
- s2 = record["stages"].get("stage2_svm", {}).get(rules[0])
181
- if s2 and stage != "stage2_svm":
182
- for rule in rules:
183
- a0 = record["stages"]["stage2_svm"][rule]["accuracy"]
184
- a1 = record["stages"][stage][rule]["accuracy"]
185
- lines.append(f"{stage:<20}{rule + ' delta':<12}{'':>7}"
186
- f"{'':>9}{'':>8}{a1 - a0:>+8.4f}")
187
 
188
  lines.append("")
189
  for method in ("IoTProber", "CADE"):
 
3
 
4
  Reproduces every number of paper Table 10 from the released prediction
5
  CSVs (HuggingFace dataset ``IoTProber/raw_dataset``, path prefix
6
+ ``evaluation/drift/CADE``) under EXPLICIT label-matching rules, so the
7
  matching strategy is no longer notebook folklore.
8
 
9
  Inputs (all columns: ip,vendor,label,label_pred,correct)
 
13
  Drift detection: SVM_validation/{IoTProber,CADE}/{detected,correct}_ips.csv
14
 
15
  Matching rules (--match)
16
+ exact byte equality of label vs label_pred. This is what the original
17
+ trainer/scorer (evaluation/drift/CADE/svm.py, run_test) used for
18
+ the STAGE-2 row of the paper.
19
+ normalized casefold + strip every non [a-z0-9] character of the whole label
20
+ ("NVR-Merit Lilin" == "NVR-Merit LILIN" == "NVR-Merit Li-Lin").
21
+ original THE RULE THAT PRODUCED THE PAPER'S STAGE-3 ROWS, recovered
22
+ verbatim from svm.py::normalize_label (initial commit 25f6a47):
23
+ split the label on the FIRST '-', lowercase the device-type part
24
+ as-is, strip non [a-z0-9] from the vendor part only, then apply
25
+ the vendor alias {"electroind": "electroindustries"}. This rule
26
+ agrees with the shipped ``correct`` column of the Stage-3 CSVs on
27
+ 7,239/7,239 rows for both methods.
28
+
29
+ Verified findings (scorer v1.1.0, sklearn-free, deterministic):
30
+ Stage 2 exact 0.4937 / 0.7403 / 0.6892 == paper row exactly
31
+ Stage 2 original 0.5180 / 0.8633 / 0.8341 (what Stage 2 is under the
32
+ same rule as Stage 3)
33
+ Stage 3 IoTProber
34
+ exact 0.5270 / 0.7047 / 0.6709
35
+ original 0.5509 / 0.8711 / 0.8483 == paper row exactly (6141/7239)
36
+ Stage 3 CADE
37
+ exact 0.5191 / 0.7050 / 0.6654
38
+ original 0.5430 / 0.8649 / 0.8402 == paper row exactly (6082/7239)
39
+
40
+ Therefore the paper's Stage2 -> Stage3 accuracy gain mixes two rules
41
+ (Stage 2 byte-equality, Stage 3 the fuzzy ``original`` rule). Under ONE
42
+ consistent rule the deltas are:
43
+ exact 0.6892 -> 0.6709 (-1.83 pp, IoTProber)
44
+ original 0.8341 -> 0.8483 (+1.42 pp, IoTProber) <- matches the
45
+ reviewer's ~1.42 pp
46
+ original 0.8341 -> 0.8402 (+0.61 pp, CADE)
47
+ The 15.91 pp headline (0.6892 -> 0.8483) must not be quoted as a
48
+ retraining gain. The drift-detection correctness figures
49
+ (IoTProber 773/814 = 94.96%, CADE 767/1112 = 68.97%) compare detected IPs
50
+ against ground-truth drift IPs and are rule-independent; they stand.
51
 
52
  Usage
53
+ python score_table10.py # all rules + detection stage
54
+ python score_table10.py --match original # the paper's Stage-3 rule
55
  python score_table10.py --json out.json # machine-readable record
56
  """
57
  import argparse
 
64
  import sys
65
 
66
  import pandas as pd
 
67
 
68
+ SCORER_VERSION = "1.1.0"
69
 
70
+ # Recovered verbatim from svm.py (initial commit 25f6a47).
 
71
  VENDOR_ALIASES = {
72
+ "electroind": "electroindustries",
73
  }
74
 
75
+
76
+ def _normalize_vendor(v):
77
+ return re.sub(r"[^a-z0-9]", "", v.lower())
 
 
78
 
79
 
80
  def normalize(label: str) -> str:
81
  return re.sub(r"[^a-z0-9]", "", str(label).lower())
82
 
83
 
84
+ def original_rule(label: str) -> str:
85
+ parts = str(label).split("-", 1)
86
+ if len(parts) != 2:
87
+ return str(label).lower()
88
+ dt, vendor = parts
89
+ nv = _normalize_vendor(vendor)
90
+ nv = VENDOR_ALIASES.get(nv, nv)
91
+ return dt.lower() + "-" + nv
92
+
93
+
94
+ STAGES = {
95
+ "stage2_svm": "SVM_test/predict",
96
+ "stage3_iotprober": "SVM_validation/performance/IoTProber/predict",
97
+ "stage3_cade": "SVM_validation/performance/CADE/predict",
98
+ }
99
 
100
 
101
  def load_stage(data_root: str, sub: str):
 
102
  files = sorted(glob.glob(os.path.join(data_root, sub, "*.csv")))
103
  if not files:
104
  sys.exit(f"no prediction CSVs under {os.path.join(data_root, sub)}")
 
126
 
127
 
128
  def score(labels, preds, rule: str):
129
+ f = {"exact": str, "normalized": normalize, "original": original_rule}[rule]
130
  y = [f(x) for x in labels]
131
  p = [f(x) for x in preds]
132
  n = len(y)
133
  acc = sum(a == b for a, b in zip(y, p)) / n
 
134
  classes = sorted(set(y) | set(p))
135
  f1s, support = [], []
136
  for c in classes:
 
143
  support.append(tp + fn)
144
  macro = sum(f1s) / len(f1s)
145
  weighted = sum(s * f for s, f in zip(support, f1s)) / sum(support)
146
+ return {"n": n, "correct": sum(a == b for a, b in zip(y, p)),
147
+ "accuracy": round(acc, 4), "macro_f1": round(macro, 4),
148
  "weighted_f1": round(weighted, 4)}
149
 
150
 
 
155
  default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "CADE"),
156
  help="directory containing SVM_test/, SVM_validation/ "
157
  "(default: <script dir>/CADE)")
158
+ ap.add_argument("--match", choices=["exact", "normalized", "original", "all"],
159
  default="all")
160
  ap.add_argument("--json", help="write a machine-readable record here")
161
  args = ap.parse_args()
162
 
163
+ rules = ["exact", "normalized", "original"] if args.match == "all" else [args.match]
164
  record = {
165
  "scorer_version": SCORER_VERSION,
166
  "matching_rules": {
167
+ "exact": "byte equality on label/label_pred (paper Stage-2 rule)",
168
+ "normalized": "casefold + strip non [a-z0-9] from the whole label",
169
+ "original": "svm.py::normalize_label (commit 25f6a47): split on first '-', "
170
+ "lowercase type part, strip non [a-z0-9] from vendor part only, "
171
+ "alias " + json.dumps(VENDOR_ALIASES)
172
+ + " (paper Stage-3 rule; == shipped 'correct' column 7239/7239)",
173
  },
174
  "python": platform.python_version(),
175
  "pandas": pd.__version__,
 
176
  "inputs": {},
177
  "stages": {},
178
  "detection": {},
 
188
  "sha256": {os.path.relpath(f, args.data_root): sha256(f) for f in files},
189
  }
190
 
191
+ header = f"{'stage':<20}{'rule':<12}{'correct':>9}{'macroF1':>9}{'wF1':>8}{'acc':>8}"
192
  lines = [header, "-" * len(header)]
193
  for stage in STAGES:
194
  labels, preds = stage_data[stage]
 
196
  for rule in rules:
197
  m = score(labels, preds, rule)
198
  record["stages"][stage][rule] = m
199
+ lines.append(f"{stage:<20}{rule:<12}{m['correct']:>7}/{m['n']}"
200
+ f"{m['macro_f1']:>9}{m['weighted_f1']:>8}{m['accuracy']:>8}")
201
+ if len(rules) > 1:
202
+ lines.append("")
203
+ for stage in ("stage3_iotprober", "stage3_cade"):
204
+ for rule in rules:
205
+ a0 = record["stages"]["stage2_svm"][rule]["accuracy"]
206
+ a1 = record["stages"][stage][rule]["accuracy"]
207
+ lines.append(f"{stage:<20}{rule + ' delta':<16}"
208
+ f"{'':>9}{'':>9}{'':>8}{a1 - a0:>+8.4f}")
209
 
210
  lines.append("")
211
  for method in ("IoTProber", "CADE"):