-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathcustom_attack.py
More file actions
36 lines (27 loc) · 1.14 KB
/
custom_attack.py
File metadata and controls
36 lines (27 loc) · 1.14 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
import numpy as np
from art.attacks.evasion import ProjectedGradientDescent
class CustomAttack(ProjectedGradientDescent):
def __init__(self, estimator, **kwargs):
modified_kwargs = kwargs.copy()
modified_kwargs["targeted"] = True
super().__init__(estimator, **modified_kwargs)
def generate(self, x, y):
x_adv = []
for x_sample, y_sample in zip(x, y):
for target in range(10):
# Do not target correct class
if target == y_sample:
continue
# Generate sample targeting `target` class
y_target = np.zeros((1, 10), dtype=np.int64)
y_target[0, target] = 1
x_adv_sample = super().generate(
np.expand_dims(x_sample, axis=0), y_target
)
# Check - does this example fool the classifier?
x_adv_pred = np.argmax(self.estimator.predict(x_adv_sample))
if x_adv_pred != y_sample:
break
x_adv.append(x_adv_sample)
x_adv = np.concatenate(x_adv, axis=0)
return x_adv