-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
detector.py
259 lines (211 loc) · 10.4 KB
/
detector.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
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
# MIT License
#
# Copyright (C) IBM Corporation 2018
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
# documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
# Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""
Module containing different methods for the detection of adversarial examples. All models are considered to be binary
detectors.
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
import six
from art.classifiers.classifier import Classifier, ClassifierNeuralNetwork, ClassifierGradients
logger = logging.getLogger(__name__)
class BinaryInputDetector(ClassifierNeuralNetwork, ClassifierGradients, Classifier):
"""
Binary detector of adversarial samples coming from evasion attacks. The detector uses an architecture provided by
the user and trains it on data labeled as clean (label 0) or adversarial (label 1).
"""
def __init__(self, detector):
"""
Create a `BinaryInputDetector` instance which performs binary classification on input data.
:param detector: The detector architecture to be trained and applied for the binary classification.
:type detector: :class:`.Classifier`
"""
super(BinaryInputDetector, self).__init__(clip_values=detector.clip_values,
channel_index=detector.channel_index,
defences=detector.defences,
preprocessing=detector.preprocessing)
self.detector = detector
def fit(self, x, y, batch_size=128, nb_epochs=20, **kwargs):
"""
Fit the detector using clean and adversarial samples.
:param x: Training set to fit the detector.
:type x: `np.ndarray`
:param y: Labels for the training set.
:type y: `np.ndarray`
:param batch_size: Size of batches.
:type batch_size: `int`
:param nb_epochs: Number of epochs to use for training.
:type nb_epochs: `int`
:param kwargs: Other parameters.
:type kwargs: `dict`
:return: None
"""
self.detector.fit(x, y, batch_size=batch_size, nb_epochs=nb_epochs, **kwargs)
def predict(self, x, **kwargs):
"""
Perform detection of adversarial data and return prediction as tuple.
:param x: Data sample on which to perform detection.
:type x: `np.ndarray`
:param batch_size: Size of batches.
:type batch_size: `int`
:return: Per-sample prediction whether data is adversarial or not, where `0` means non-adversarial.
Return variable has the same `batch_size` (first dimension) as `x`.
:rtype: `np.ndarray`
"""
batch_size = kwargs['batch_size'] if 'batch_size' in kwargs else 128
return self.detector.predict(x, batch_size=batch_size)
def fit_generator(self, generator, nb_epochs=20, **kwargs):
"""
Fit the classifier using the generator gen that yields batches as specified. This function is not supported
for this detector.
:raises: `NotImplementedException`
"""
raise NotImplementedError
def nb_classes(self):
return self.detector.nb_classes()
@property
def input_shape(self):
return self.detector.input_shape
@property
def clip_values(self):
return self.detector.clip_values
@property
def channel_index(self):
return self.detector.channel_index
@property
def learning_phase(self):
return self.detector._learning_phase
def class_gradient(self, x, label=None, **kwargs):
return self.detector.class_gradient(x, label=label)
def loss_gradient(self, x, y, **kwargs):
return self.detector.loss_gradient(x, y)
def get_activations(self, x, layer, batch_size):
"""
Return the output of the specified layer for input `x`. `layer` is specified by layer index (between 0 and
`nb_layers - 1`) or by name. The number of layers can be determined by counting the results returned by
calling `layer_names`. This function is not supported for this detector.
:raises: `NotImplementedException`
"""
raise NotImplementedError
def set_learning_phase(self, train):
self.detector.set_learning_phase(train)
def save(self, filename, path=None):
self.detector.save(filename, path)
class BinaryActivationDetector(ClassifierNeuralNetwork, ClassifierGradients, Classifier):
"""
Binary detector of adversarial samples coming from evasion attacks. The detector uses an architecture provided by
the user and is trained on the values of the activations of a classifier at a given layer.
"""
def __init__(self, classifier, detector, layer): # lgtm [py/similar-function]
"""
Create a `BinaryActivationDetector` instance which performs binary classification on activation information.
The shape of the input of the detector has to match that of the output of the chosen layer.
:param classifier: The classifier of which the activation information is to be used for detection.
:type classifier: `art.classifier.Classifier`
:param detector: The detector architecture to be trained and applied for the binary classification.
:type detector: `art.classifier.Classifier`
:param layer: Layer for computing the activations to use for training the detector.
:type layer: `int` or `str`
"""
super(BinaryActivationDetector, self).__init__(clip_values=detector.clip_values,
channel_index=detector.channel_index,
defences=detector.defences,
preprocessing=detector.preprocessing)
self.classifier = classifier
self.detector = detector
# Ensure that layer is well-defined:
if isinstance(layer, six.string_types):
if layer not in classifier.layer_names:
raise ValueError('Layer name %s is not part of the graph.' % layer)
self._layer_name = layer
elif isinstance(layer, int):
if layer < 0 or layer >= len(classifier.layer_names):
raise ValueError('Layer index %d is outside of range (0 to %d included).'
% (layer, len(classifier.layer_names) - 1))
self._layer_name = classifier.layer_names[layer]
else:
raise TypeError('Layer must be of type `str` or `int`.')
def fit(self, x, y, batch_size=128, nb_epochs=20, **kwargs):
"""
Fit the detector using training data.
:param x: Training set to fit the detector.
:type x: `np.ndarray`
:param y: Labels for the training set.
:type y: `np.ndarray`
:param batch_size: Size of batches.
:type batch_size: `int`
:param nb_epochs: Number of epochs to use for training.
:type nb_epochs: `int`
:param kwargs: Other parameters.
:type kwargs: `dict`
:return: `None`
"""
x_activations = self.classifier.get_activations(x, self._layer_name, batch_size)
self.detector.fit(x_activations, y, batch_size=batch_size, nb_epochs=nb_epochs, **kwargs)
def predict(self, x, batch_size=128, **kwargs):
"""
Perform detection of adversarial data and return prediction as tuple.
:param x: Data sample on which to perform detection.
:type x: `np.ndarray`
:param batch_size: Size of batches.
:type batch_size: `int`
:return: Per-sample prediction whether data is adversarial or not, where `0` means non-adversarial.
Return variable has the same `batch_size` (first dimension) as `x`.
:rtype: `np.ndarray`
"""
return self.detector.predict(self.classifier.get_activations(x, self._layer_name, batch_size))
def fit_generator(self, generator, nb_epochs=20, **kwargs):
"""
Fit the classifier using the generator gen that yields batches as specified. This function is not supported
for this detector.
:raises: `NotImplementedException`
"""
raise NotImplementedError
def nb_classes(self):
return self.detector.nb_classes()
@property
def input_shape(self):
return self.detector.input_shape
@property
def clip_values(self):
return self.detector.clip_values
@property
def channel_index(self):
return self.detector.channel_index
@property
def learning_phase(self):
return self.detector._learning_phase
@property
def layer_names(self):
raise NotImplementedError
def class_gradient(self, x, label=None, **kwargs):
return self.detector.class_gradient(x, label=label)
def loss_gradient(self, x, y, **kwargs):
return self.detector.loss_gradient(x, y)
def get_activations(self, x, layer, batch_size):
"""
Return the output of the specified layer for input `x`. `layer` is specified by layer index (between 0 and
`nb_layers - 1`) or by name. The number of layers can be determined by counting the results returned by
calling `layer_names`. This function is not supported for this detector.
:raises: `NotImplementedException`
"""
raise NotImplementedError
def set_learning_phase(self, train):
self.detector.set_learning_phase(train)
def save(self, filename, path=None):
self.detector.save(filename, path)