This repository has been archived by the owner on Oct 3, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pgd.py
74 lines (60 loc) · 2.35 KB
/
pgd.py
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
from __future__ import absolute_import, division, print_function, \
unicode_literals
import logging
from typing import TYPE_CHECKING, Optional, Union
import numpy as np
# noinspection PyPackageRequirements
from art.attacks.evasion import ProjectedGradientDescent, \
ProjectedGradientDescentNumpy
# noinspection PyPackageRequirements
from art.summary_writer import SummaryWriter
from exp import Validatable
if TYPE_CHECKING:
# noinspection PyPackageRequirements
from art.utils import CLASSIFIER_LOSS_GRADIENTS_TYPE, \
OBJECT_DETECTOR_TYPE
logger = logging.getLogger(__name__)
class PGDNumpyConstr(ProjectedGradientDescentNumpy, Validatable):
def _compute(
self,
x: np.ndarray,
x_init: np.ndarray,
y: np.ndarray,
mask: Optional[np.ndarray],
eps: Union[int, float, np.ndarray],
eps_step: Union[int, float, np.ndarray],
project: bool,
random_init: bool,
batch_id_ext: Optional[int] = None,
decay: Optional[float] = None,
momentum: Optional[np.ndarray] = None,
) -> np.ndarray:
x_adv = super()._compute(
x, x_init, y, mask, eps, eps_step, project,
random_init, batch_id_ext, decay, momentum)
return self.cge.enforce(x, x_adv) # NEW
class VPGD(ProjectedGradientDescent, Validatable):
def __init__(
self,
estimator: Union["CLASSIFIER_LOSS_GRADIENTS_TYPE",
"OBJECT_DETECTOR_TYPE"],
norm: Union[int, float, str] = np.inf,
eps: Union[int, float, np.ndarray] = 0.3,
eps_step: Union[int, float, np.ndarray] = 0.1,
decay: Optional[float] = None,
max_iter: int = 100,
targeted: bool = False,
num_random_init: int = 0,
batch_size: int = 32,
random_eps: bool = False,
summary_writer: Union[str, bool, SummaryWriter] = False,
verbose: bool = True,
):
args = (estimator, norm, eps, eps_step, decay, max_iter,
targeted, num_random_init, batch_size, random_eps,
summary_writer, verbose)
super().__init__(*args)
self._attack = PGDNumpyConstr(*args)
def vhost(self):
"""attach validation model to attack"""
return self._attack