-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathtest_structural_attack.py
More file actions
364 lines (331 loc) · 12.7 KB
/
test_structural_attack.py
File metadata and controls
364 lines (331 loc) · 12.7 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
"""Test structural attacks."""
from __future__ import annotations
import numpy as np
import pytest
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import AdaBoostClassifier, RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from xgboost.sklearn import XGBClassifier
import sacroml.attacks.structural_attack as sa
from sacroml.attacks.target import Target
def get_target(modeltype: str, **kwparams: dict) -> Target:
"""Load dataset and create target of the desired type."""
X, y = load_breast_cancer(return_X_y=True, as_frame=False)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)
# these types should be handled
if modeltype == "dt":
target_model = DecisionTreeClassifier(**kwparams)
elif modeltype == "rf":
target_model = RandomForestClassifier(**kwparams)
elif modeltype == "xgb":
target_model = XGBClassifier(**kwparams)
elif modeltype == "adaboost":
target_model = AdaBoostClassifier(**kwparams)
elif modeltype == "mlpclassifier":
target_model = MLPClassifier(**kwparams)
# should get polite error but not DoF yet
elif modeltype == "svc":
target_model = SVC(**kwparams)
else:
raise NotImplementedError("model type passed to get_model unknown")
# Train the classifier
target_model.fit(X_train, y_train)
# Wrap the model and data in a Target object
target = Target(model=target_model)
target.add_processed_data(X_train, y_train, X_test, y_test)
return target
def test_unnecessary_risk():
"""Check the unnecessary rules."""
# non-tree we have no evidence yet
model = SVC()
assert not sa.get_unnecessary_risk(model), "no risk without evidence"
# decision tree next
risky_param_dicts = [
{
"max_features": "log2",
"max_depth": 8,
"min_samples_leaf": 7,
"min_samples_split": 14,
},
{
"splitter": "best",
"max_depth": 8,
"min_samples_leaf": 7,
"min_samples_split": 16,
},
{
"splitter": "best",
"max_depth": 8,
"min_samples_leaf": 10,
"max_features": None,
},
{
"splitter": "best",
"max_depth": 4,
"max_features": None,
"min_samples_leaf": 7,
},
{
"splitter": "random",
"max_depth": 8,
"min_samples_leaf": 7,
"max_features": None,
"min_samples_split": 25,
},
]
for idx, paramdict in enumerate(risky_param_dicts):
model = DecisionTreeClassifier(**paramdict)
errstr = f" unnecessary risk with rule {idx}params are {model.get_params()}"
assert sa.get_unnecessary_risk(model), errstr
model = DecisionTreeClassifier(max_depth=1, min_samples_leaf=150)
assert not sa.get_unnecessary_risk(model), (
f"should be non-disclosive with {model.get_params}"
)
# now random forest
risky_param_dicts = [
{"max_depth": 50, "n_estimators": 50, "max_features": None},
{
"max_depth": 50,
"n_estimators": 50,
"min_samples_split": 5,
"max_features": None,
"bootstrap": True,
},
{
"max_depth": 25,
"n_estimators": 25,
"min_samples_leaf": 5,
"bootstrap": False,
},
]
for idx, paramdict in enumerate(risky_param_dicts):
model = RandomForestClassifier(**paramdict)
errstr = f" unnecessary risk with rule {idx}params are {model.get_params()}"
assert sa.get_unnecessary_risk(model), errstr
model = RandomForestClassifier(max_depth=1, n_estimators=25, min_samples_leaf=150)
assert not sa.get_unnecessary_risk(model), (
f"should be non-disclosive with {model.get_params}"
)
# finally xgboost
risky_param_dicts = [
{
"max_depth": 5, # > 3.5
"n_estimators": 10, # and 3.5 < n_estimators <= 12.5
"min_child_weight": 1, # and model.min_child_weight <= 1.5
},
{
"max_depth": 5, # > 3.5
"n_estimators": 25, # > 12.5
"min_child_weight": 1, # <= 3
},
{
"max_depth": 5, # > 3.5
"n_estimators": 100, # > 62.5
"min_child_weight": 5, # and 3 < model.min_child_weight <= 6
},
]
for idx, paramdict in enumerate(risky_param_dicts):
model = XGBClassifier(**paramdict)
errstr = f" unnecessary risk with rule {idx}params are {model.get_params()}"
assert sa.get_unnecessary_risk(model), errstr
model = XGBClassifier(min_child_weight=10)
assert not sa.get_unnecessary_risk(model), (
f"should be non-disclosive with {model.get_params}"
)
def test_non_trees():
"""Test behaviour if model type not tree-based."""
param_dict = {"probability": True}
target = get_target("svc", **param_dict)
myattack = sa.StructuralAttack()
myattack.attack(target)
# remove model
target.model = None
myattack2 = sa.StructuralAttack()
with pytest.raises(NotImplementedError):
myattack2.attack(target)
def test_dt():
"""Test for decision tree classifier."""
# 'non' disclosive'
param_dict = {"max_depth": 1, "min_samples_leaf": 150}
target = get_target("dt", **param_dict)
myattack = sa.StructuralAttack()
myattack.attack(target)
assert not myattack.dof_risk, "should be no DoF risk with decision stump"
assert not myattack.k_anonymity_risk, (
"should be no k-anonymity risk with min_samples_leaf 150"
)
assert not myattack.class_disclosure_risk, (
"no class disclosure risk for stump with min samples leaf 150"
)
assert not myattack.unnecessary_risk, "not unnecessary risk if max_depth < 3.5"
# highly disclosive
param_dict2 = {"max_depth": None, "min_samples_leaf": 1, "min_samples_split": 2}
target = get_target("dt", **param_dict2)
myattack = sa.StructuralAttack()
myattack.attack(target)
assert not myattack.dof_risk, "should be no DoF risk with decision stump"
assert myattack.k_anonymity_risk, (
"should be k-anonymity risk with unlimited depth and min_samples_leaf 5"
)
assert myattack.class_disclosure_risk, (
"should be class disclosure risk with unlimited depth and min_samples_leaf 5"
)
assert myattack.unnecessary_risk, (
" unnecessary risk with unlimited depth and min_samples_leaf 5"
)
def test_adaboost():
"""Test for adaboost classifier."""
# 'non' disclosive'
# - base estimator =None => DecisionTreeClassifier with max_depth 1
# also set THRESHOLD to 4
np.random.seed(42)
param_dict = {"n_estimators": 2, "estimator": None}
target = get_target("adaboost", **param_dict)
myattack = sa.StructuralAttack()
myattack.THRESHOLD = 2
myattack.attack(target)
assert not myattack.dof_risk, "should be no DoF risk with just 2 decision stumps"
assert not myattack.k_anonymity_risk, (
"should be no k-anonymity risk with only 2 stumps"
)
assert not myattack.class_disclosure_risk, "no class disclosure risk for 2 stumps"
assert not myattack.unnecessary_risk, " unnecessary risk not defined for adaboost"
# highly disclosive
kwargs = {"max_depth": None, "min_samples_leaf": 2}
param_dict2 = {
"estimator": DecisionTreeClassifier(**kwargs),
"n_estimators": 1000,
}
target = get_target("adaboost", **param_dict2)
myattack2 = sa.StructuralAttack()
myattack2.attack(target)
assert myattack2.dof_risk, "should be DoF risk with adaboost of deep trees"
assert myattack2.k_anonymity_risk, (
"should be k-anonymity risk with adaboost unlimited depth and min_samples_leaf 2"
)
assert myattack2.class_disclosure_risk, (
"should be class risk with adaboost unlimited depth and min_samples_leaf 2"
)
assert not myattack2.unnecessary_risk, " unnecessary risk not define for adaboost"
def test_rf():
"""Test for random forest classifier."""
# 'non' disclosive'
param_dict = {"max_depth": 1, "min_samples_leaf": 150, "n_estimators": 10}
target = get_target("rf", **param_dict)
myattack = sa.StructuralAttack()
myattack.attack(target)
assert not myattack.dof_risk, (
"should be no DoF risk with small forest of decision stumps"
)
assert not myattack.k_anonymity_risk, (
"should be no k-anonymity risk with min_samples_leaf 150"
)
assert not myattack.class_disclosure_risk, (
"no class disclosure risk for stumps with min samples leaf 150"
)
assert not myattack.unnecessary_risk, "not unnecessary risk if max_depth < 3.5"
# highly disclosive
param_dict2 = {
"max_depth": None,
"min_samples_leaf": 2,
"min_samples_split": 2,
"n_estimators": 1000,
}
target = get_target("rf", **param_dict2)
myattack = sa.StructuralAttack()
myattack.attack(target)
assert myattack.dof_risk, "should be DoF risk with forest of deep trees"
assert myattack.k_anonymity_risk, (
"should be k-anonymity risk with unlimited depth and min_samples_leaf 5"
)
assert myattack.class_disclosure_risk, (
"should be class disclsoure risk with unlimited depth and min_samples_leaf 5"
)
assert myattack.unnecessary_risk, (
" unnecessary risk with unlimited depth and min_samples_leaf 5"
)
def test_xgb():
"""Test for xgboost."""
# non-disclosive
param_dict = {"max_depth": 1, "min_child_weight": 50, "n_estimators": 5}
target = get_target("xgb", **param_dict)
myattack = sa.StructuralAttack()
myattack.attack(target)
assert not myattack.dof_risk, (
"should be no DoF risk with small xgb of decision stumps"
)
assert not myattack.k_anonymity_risk, (
"should be no k-anonymity risk with min_samples_leaf 150"
)
assert not myattack.class_disclosure_risk, (
"no class disclosure risk for stumps with min child weight 50"
)
assert myattack.unnecessary_risk == 0, "not unnecessary risk if max_depth < 3.5"
# highly disclosive
param_dict2 = {"max_depth": 50, "n_estimators": 100, "min_child_weight": 1}
target2 = get_target("xgb", **param_dict2)
myattack2 = sa.StructuralAttack()
myattack2.attack(target2)
assert myattack2.dof_risk, "should be DoF risk with xgb of deep trees"
assert myattack2.k_anonymity_risk, (
"should be k-anonymity risk with depth 50 and min_child_weight 1"
)
assert myattack2.class_disclosure_risk, (
"should be class disclosure risk with xgb lots of deep trees"
)
assert myattack2.unnecessary_risk, " unnecessary risk with these xgb params"
def test_sklearnmlp():
"""Test for sklearn MLPClassifier."""
# non-disclosive
safeparams = {
"hidden_layer_sizes": (10,),
"random_state": 12345,
"activation": "identity",
"max_iter": 1,
}
target = get_target("mlpclassifier", **safeparams)
myattack = sa.StructuralAttack()
myattack.attack(target)
paramstr = ""
for key, val in safeparams.items():
paramstr += f"{key}:{val}\n"
assert not myattack.dof_risk, (
f"should be no DoF risk with small mlp with params {paramstr}"
)
assert not myattack.k_anonymity_risk, (
f"should be no k-anonymity risk with params {paramstr}"
)
assert myattack.class_disclosure_risk, (
f"should be class disclosure risk with params {paramstr}"
)
assert not myattack.unnecessary_risk, "not unnecessary risk for mlps at present"
# highly disclosive
unsafeparams = {
"hidden_layer_sizes": (50, 50),
"random_state": 12345,
"activation": "relu",
"max_iter": 100,
}
uparamstr = ""
for key, val in unsafeparams.items():
uparamstr += f"{key}:{val}\n"
target2 = get_target("mlpclassifier", **unsafeparams)
myattack2 = sa.StructuralAttack()
myattack2.attack(target2)
assert myattack2.dof_risk, f"should be DoF risk with this MLP:\n{uparamstr}"
assert myattack2.k_anonymity_risk, (
"559/560 records should be k-anonymity risk with this MLP:\n{uparamstr}"
)
assert myattack2.class_disclosure_risk, (
"should be class disclosure risk with this MLP:\n{uparamstr}"
)
assert not myattack2.unnecessary_risk, "no unnecessary risk yet for MLPClassifiers"
def test_reporting():
"""Test reporting functionality."""
param_dict = {"max_depth": 1, "min_samples_leaf": 150}
target = get_target("dt", **param_dict)
myattack = sa.StructuralAttack()
myattack.attack(target)