-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplot_perf.py
More file actions
375 lines (299 loc) · 9.26 KB
/
plot_perf.py
File metadata and controls
375 lines (299 loc) · 9.26 KB
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
import argparse
import json
import matplotlib.pyplot as plt
from pathlib import Path
import numpy as np
from matplotlib.ticker import FuncFormatter
# -----------------------
# I/O utilities
# -----------------------
def load_json(path):
with open(path, "r") as f:
return json.load(f)
# -----------------------
# Tick Helpers
# -----------------------
def select_log_ticks(values, min_ticks=3, max_ticks=7):
"""
Select reasonable ticks for log-scale x-axis.
Always includes first, middle, last.
"""
values = np.array(values)
if len(values) <= max_ticks:
return values.tolist()
first = values[0]
last = values[-1]
middle = values[len(values) // 2]
ticks = np.unique([first, middle, last])
return ticks.tolist(), middle
def sci_notation_1dec(x, _):
"""
Format ticks as 1 decimal scientific notation.
Example: 3300 -> 3.3×10³
"""
if x == 0:
return "0"
exp = int(np.floor(np.log10(x)))
mant = x / (10 ** exp)
return rf"${mant:.1f}\times10^{{{exp}}}$"
# -----------------------
# AUC
# -----------------------
def compute_auc(eps, err):
return np.trapz(err, eps)
# -----------------------
# Data extraction
# -----------------------
def extract_train_base_performance(train_results, dataset, model):
"""
Returns lists sorted by number of parameters:
params, train_error, cap_list
"""
records = []
for key, v in train_results.items():
if not key.startswith(f"{dataset}::{model}::cap"):
continue
records.append({
"cap": v["capacity"],
"params": v["num_parameters"],
"train_error": v["train_error"],
})
records = sorted(records, key=lambda x: x["params"])
params = [r["params"] for r in records]
train_error = [r["train_error"] for r in records]
caps = [r["cap"] for r in records]
return params, train_error, caps
def extract_test_base_performance(test_results, caps):
"""
Align test error rates to the given capacity order.
"""
test_error = []
for cap in caps:
cap_key = f"cap_{cap}"
test_error.append(
test_results["results"][cap_key]["clean"]["error_rate"]
)
return test_error
# -----------------------
# Plotting
# -----------------------
def plot_base_performance(
dataset,
model,
train_results_path,
test_results_path,
save_dir="plots",
regime_boundary=None
):
train_results = load_json(train_results_path)
test_results = load_json(test_results_path)
params, train_error, caps = extract_train_base_performance(
train_results, dataset, model
)
test_error = extract_test_base_performance(test_results, caps)
plt.figure(figsize=(7, 4.5))
plt.semilogx(params, train_error, marker="o", label="train")
plt.semilogx(params, test_error, marker="o", label="test")
xticks, _ = select_log_ticks(params)
# regime_boundary = interp
# Always safe: add line only if value is provided
if regime_boundary is not None:
interp = params[regime_boundary-1]
plt.axvline(
interp,
linestyle="--",
color="black",
linewidth=1.5
)
plt.xlabel("Number of parameters", fontsize=16)
plt.ylabel("Error rate", fontsize=14)
plt.title(f"Performance on benign samples {dataset.upper()}: {model.upper()}", fontsize=18)
# Explicit ticks + rotation
plt.xticks(xticks, fontsize=14)
plt.gca().xaxis.set_major_formatter(FuncFormatter(sci_notation_1dec))
plt.legend(fontsize=12)
plt.grid(True, which="both", linestyle="--", linewidth=0.5, alpha=0.6)
Path(save_dir).mkdir(exist_ok=True)
save_path = Path(save_dir) / f"{dataset}_{model}_base_performance.png"
plt.tight_layout()
plt.savefig(save_path, dpi=200)
plt.show()
print(f"[SAVED] {save_path}")
def plot_sec(
dataset,
model,
attack,
results_dir="results",
save_dir="plots",
):
"""
Plots Security Evaluation Curves (SEC):
x-axis: epsilon
y-axis: error rate
One curve per capacity
"""
if attack == "pgdl2":
title = "PGD-L2"
elif attack == "autoattack":
title = "AutoAttack"
elif attack == "pgdlinf":
title = "PGD-L∞"
else:
title = attack.upper()
# ---------- Load clean results (ε = 0) ----------
clean_file = f"{results_dir}/sec_eval_{dataset}_{model}_clean_results.json"
with open(clean_file, "r") as f:
clean_data = json.load(f)["results"]
# ---------- Load attack results ----------
attack_file = f"{results_dir}/sec_eval_{dataset}_{model}_{attack}_results.json"
with open(attack_file, "r") as f:
attack_data = json.load(f)["results"]
# ---------- Sort capacities ----------
caps = sorted(clean_data.keys(), key=lambda x: int(x.split("_")[1]))
plt.figure(figsize=(8, 6))
for idx, cap in enumerate(caps, start=1):
# ε = 0
eps = [0.0]
err = [clean_data[cap]["clean"]["error_rate"]]
# attacked eps
attack_eps = sorted(
float(k.replace("eps_", ""))
for k in attack_data[cap].keys()
)
for e in attack_eps:
eps.append(e)
err.append(1- (attack_data[cap][f"eps_{e}"]))
eps = np.array(eps)
err = np.array(err)
auc = compute_auc(eps, err)
plt.plot(
eps,
err,
marker="o",
linewidth=2,
label=f"M{idx} (AUC={auc:.3f})"
)
# ---------- Styling ----------
plt.xlabel("Perturbation Budget $\epsilon$", fontsize=16)
# plt.ylabel("Error rate", fontsize=16)
plt.title(
f"SEC for {dataset.upper()}-{model.upper()}: {title}",
fontsize=18,
)
plt.grid(True, which="both", linestyle="--", alpha=0.6)
plt.legend(fontsize=12)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
Path(save_dir).mkdir(exist_ok=True)
save_path = Path(save_dir) / f"sec_{dataset}_{model}_{attack}.png"
if save_path:
plt.tight_layout()
plt.savefig(save_path, dpi=300)
else:
plt.show()
print(f"[SAVED] {save_path}")
# -----------------------
# Lipschitz plotting
# -----------------------
def plot_lipschitz(
dataset: str,
model: str,
results_dir: str = "results",
regime_boundary: int | None = None,
save_dir: str = "plots"
):
"""
Plot Lipschitz upper bound vs model capacity.
"""
lipschitz_path = (
Path(results_dir)
/ f"lipschitz_{dataset}_{model}.json"
)
if not lipschitz_path.exists():
raise FileNotFoundError(f"Missing Lipschitz file: {lipschitz_path}")
with open(lipschitz_path, "r") as f:
data = json.load(f)
# Sort by capacity (keys are strings)
capacities = sorted(int(k) for k in data.keys())
lipschitz_vals = [
data[str(c)]["lipschitz_upper_bound"] for c in capacities
]
plt.figure(figsize=(6, 4))
plt.plot(capacities, lipschitz_vals, marker="o")
plt.yscale("log")
plt.xlabel("Model capacity")
plt.ylabel("Lipschitz upper bound (log scale)")
plt.title(f"Lipschitz scaling — {dataset.upper()} - {model.upper()}")
if regime_boundary is not None:
plt.axvline(
regime_boundary,
linestyle="--",
color="gray",
label="Regime boundary"
)
plt.legend()
Path(save_dir).mkdir(exist_ok=True)
save_path = Path(save_dir) / f"lipschitz_{dataset}_{model}.png"
plt.grid(True, which="both", linestyle="--", alpha=0.5)
plt.tight_layout()
plt.savefig(save_path, dpi=300)
print(f"[SAVED] {save_path}")
# -----------------------
# Main
# -----------------------
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--dataset", required=True, type=str)
parser.add_argument("--model", required=True, type=str)
parser.add_argument(
"--plot_type",
required=True,
choices=["base", "sec", "lipschitz"]
)
parser.add_argument(
"--attack",
type=str,
choices=["pgdl2", "autoattack", "pgdlinf"]
)
parser.add_argument(
"--train_results",
default="train_results.json"
)
parser.add_argument(
"--results_dir",
default="results"
)
parser.add_argument(
"--regime_boundary",
type=int,
default=None,
help="Optional x-value for vertical dashed line"
)
args = parser.parse_args()
test_results_path = (
Path(args.results_dir)
/ f"sec_eval_{args.dataset}_{args.model}_clean_results.json"
)
if args.plot_type == "base":
plot_base_performance(
dataset=args.dataset,
model=args.model,
train_results_path=args.train_results,
test_results_path=test_results_path,
regime_boundary=args.regime_boundary
)
elif args.plot_type == "sec":
plot_sec(
dataset=args.dataset,
model=args.model,
attack=args.attack
)
elif args.plot_type == "lipschitz":
plot_lipschitz(
dataset=args.dataset,
model=args.model,
results_dir="results",
regime_boundary=args.regime_boundary
)
if __name__ == "__main__":
main()