Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
"""
This module implements the Expectation Over Transformation applied to classifier predictions and gradients.
| Paper link: https://arxiv.org/abs/1707.07397
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
from art.wrappers.wrapper import ClassifierWrapper
from art.classifiers.classifier import Classifier, ClassifierNeuralNetwork, ClassifierGradients
logger = logging.getLogger(__name__)
class ExpectationOverTransformations(ClassifierWrapper, ClassifierGradients, ClassifierNeuralNetwork, Classifier):
"""
Implementation of Expectation Over Transformations applied to classifier predictions and gradients, as introduced
in Athalye et al. (2017).
| Paper link: https://arxiv.org/abs/1707.07397
"""
def __init__(self, classifier, sample_size, transformation):
"""
Create an expectation over transformations wrapper.
:param classifier: The Classifier we want to wrap the functionality for the purpose of an attack.
:type classifier: :class:`.Classifier`
:param sample_size: Number of transformations to sample
:type sample_size: `int`
:param transformation: An iterator over transformations.
This module implements the classifier `PyTorchClassifier` for PyTorch models.
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
import random
import numpy as np
import six
from art.classifiers.classifier import Classifier, ClassifierNeuralNetwork, ClassifierGradients
logger = logging.getLogger(__name__)
class PyTorchClassifier(ClassifierNeuralNetwork, ClassifierGradients, Classifier):
"""
This class implements a classifier with the PyTorch framework.
"""
def __init__(self, model, loss, optimizer, input_shape, nb_classes, channel_index=1, clip_values=None,
defences=None, preprocessing=(0, 1)):
"""
Initialization specifically for the PyTorch-based implementation.
:param model: PyTorch model. The output of the model can be logits, probabilities or anything else. Logits
output should be preferred where possible to ensure attack efficiency.
:type model: `torch.nn.Module`
:param loss: The loss function for which to compute gradients for training. The target label must be raw
categorical, i.e. not converted to one-hot encoding.
:type loss: `torch.nn.modules.loss._Loss`
:param optimizer: The optimizer used to train the classifier.
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`
# SOFTWARE.
"""
This module implements the classifier `EnsembleClassifier` for ensembles of multiple classifiers.
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
import numpy as np
from art.classifiers.classifier import Classifier, ClassifierNeuralNetwork, ClassifierGradients
logger = logging.getLogger(__name__)
class EnsembleClassifier(ClassifierNeuralNetwork, ClassifierGradients, Classifier):
"""
Class allowing to aggregate multiple classifiers as an ensemble. The individual classifiers are expected to be
trained when the ensemble is created and no training procedures are provided through this class.
"""
def __init__(self, classifiers, classifier_weights=None, channel_index=3, clip_values=None, defences=None,
preprocessing=(0, 1)):
"""
Initialize a :class:`.EnsembleClassifier` object. The data range values and colour channel index have to
be consistent for all the classifiers in the ensemble.
:param classifiers: List of :class:`.Classifier` instances to be ensembled together.
:type classifiers: `list`
:param classifier_weights: List of weights, one scalar per classifier, to assign to their prediction when
aggregating results. If `None`, all classifiers are assigned the same weight.
:type classifier_weights: `list` or `np.ndarray` or `None`
class_weight[0] * (1.0 - y_preprocessed[i_sample, 0])) * (
y_pred[i_sample, 0] * y_pred[i_sample, 1] * weights[0, :])
else:
w_weighted = np.matmul(y_pred, weights)
for i_sample in range(num_samples):
for i_class in range(self.nb_classes()):
gradients[i_sample, :] += class_weight[i_class] * (1.0 - y_preprocessed[i_sample, i_class]) * (
weights[i_class, :] - w_weighted[i_sample, :])
gradients = self._apply_preprocessing_gradient(x, gradients)
return gradients
class ScikitlearnSVC(ScikitlearnClassifier, ClassifierGradients):
"""
Wrapper class for scikit-learn C-Support Vector Classification models.
"""
def __init__(self, model, clip_values=None, defences=None, preprocessing=(0, 1)):
"""
Create a `Classifier` instance from a scikit-learn C-Support Vector Classification model.
:param model: scikit-learn C-Support Vector Classification model.
:type model: `sklearn.svm.SVC` or `sklearn.svm.LinearSVC`
:param clip_values: Tuple of the form `(min, max)` representing the minimum and maximum values allowed
for features.
:type clip_values: `tuple`
:param defences: Defences to be activated with the classifier.
:type defences: :class:`.Preprocessor` or `list(Preprocessor)` instances
:param preprocessing: Tuple of the form `(subtractor, divider)` of floats or `np.ndarray` of values to be
This module implements the classifier `TensorFlowClassifier` for TensorFlow models.
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
import random
import numpy as np
import six
from art.classifiers.classifier import Classifier, ClassifierNeuralNetwork, ClassifierGradients
logger = logging.getLogger(__name__)
class TensorFlowClassifier(ClassifierNeuralNetwork, ClassifierGradients, Classifier):
"""
This class implements a classifier with the TensorFlow framework.
"""
def __init__(self, input_ph, output, labels_ph=None, train=None, loss=None, learning=None, sess=None,
channel_index=3, clip_values=None, defences=None, preprocessing=(0, 1)):
"""
Initialization specific to TensorFlow models implementation.
:param input_ph: The input placeholder.
:type input_ph: `tf.Placeholder`
:param output: The output layer of the model. This can be logits, probabilities or anything else. Logits
output should be preferred where possible to ensure attack efficiency.
:type output: `tf.Tensor`
:param labels_ph: The labels placeholder of the model. This parameter is necessary when training the model and
when computing gradients w.r.t. the loss function.
def __repr__(self):
repr_ = "%s(input_ph=%r, output=%r, labels_ph=%r, train=%r, loss=%r, learning=%r, " \
"sess=%r, channel_index=%r, clip_values=%r, defences=%r, preprocessing=%r)" \
% (self.__module__ + '.' + self.__class__.__name__,
self._input_ph, self._output, self._labels_ph, self._train, self._loss, self._learning, self._sess,
self.channel_index, self.clip_values, self.defences, self.preprocessing)
return repr_
# backward compatibility for ART v0.10 and earlier
TFClassifier = TensorFlowClassifier
class TensorFlowV2Classifier(ClassifierNeuralNetwork, ClassifierGradients, Classifier):
"""
This class implements a classifier with the TensorFlow v2 framework.
"""
def __init__(self, model, nb_classes, loss_object=None, train_step=None, channel_index=3, clip_values=None,
defences=None, preprocessing=(0, 1)):
"""
Initialization specific to TensorFlow v2 models.
:param model: a python functions or callable class defining the model and providing it prediction as output.
:type model: `function` or `callable class`
:param nb_classes: the number of classes in the classification task
:type nb_classes: `int`
:param loss_object: The loss function for which to compute gradients. This parameter is applied for training
the model and computing gradients of the loss w.r.t. the input.
:type loss_object: `tf.keras.losses`
# SOFTWARE.
"""
This module implements a wrapper class for GPy Gaussian Process classification models.
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
import numpy as np
from art.classifiers.classifier import Classifier, ClassifierGradients
logger = logging.getLogger(__name__)
class GPyGaussianProcessClassifier(Classifier, ClassifierGradients):
"""
Wrapper class for GPy Gaussian Process classification models.
"""
def __init__(self, model=None, clip_values=None, defences=None, preprocessing=(0, 1)):
"""
Create a `Classifier` instance GPY Gaussian Process classification models.
:param clip_values: Tuple of the form `(min, max)` representing the minimum and maximum values allowed
for features.
:type clip_values: `tuple`
:param model: GPY Gaussian Process Classification model.
:type model: `Gpy.models.GPClassification`
:param defences: Defences to be activated with the classifier.
:type defences: :class:`.Preprocessor` or `list(Preprocessor)` instances
:param preprocessing: Tuple of the form `(subtractor, divider)` of floats or `np.ndarray` of values to be
'deepfool', 'fgsm', 'bim', 'pgd', 'margin', 'ead', 'newtonfool', 'jsma', 'vat'.
:type attacker: `str`
:param attacker_params: Parameters specific to the adversarial attack. If this parameter is not specified,
the default parameters of the chosen attack will be used.
:type attacker_params: `dict`
:param delta: desired accuracy
:type delta: `float`
:param max_iter: The maximum number of iterations for computing universal perturbation.
:type max_iter: `int`
:param eps: Attack step size (input variation)
:type eps: `float`
:param norm: The norm of the adversarial perturbation. Possible values: np.inf, 2
:type norm: `int`
"""
super(UniversalPerturbation, self).__init__(classifier)
if not isinstance(classifier, ClassifierNeuralNetwork) or not isinstance(classifier, ClassifierGradients):
raise (TypeError('For `' + self.__class__.__name__ + '` classifier must be an instance of '
'`art.classifiers.classifier.ClassifierNeuralNetwork` and '
'`art.classifiers.classifier.ClassifierGradients`, the provided classifier is instance of '
+ str(classifier.__class__.__bases__) + '. '
' The classifier needs to be a Neural Network and provide gradients.'))
kwargs = {'attacker': attacker,
'attacker_params': attacker_params,
'delta': delta,
'max_iter': max_iter,
'eps': eps,
'norm': norm
}
self.set_params(**kwargs)
# else:
# class_label = i_tree % num_classes
decision_tree_classifier = ScikitlearnDecisionTreeClassifier(model=decision_tree_model)
for i_class in range(self._model.n_classes_):
class_label = i_class
# pylint: disable=W0212
trees.append(Tree(class_id=class_label,
leaf_nodes=decision_tree_classifier._get_leaf_nodes(0, i_tree, class_label, box)))
return trees
class ScikitlearnLogisticRegression(ScikitlearnClassifier, ClassifierGradients):
"""
Wrapper class for scikit-learn Logistic Regression models.
"""
def __init__(self, model, clip_values=None, defences=None, preprocessing=(0, 1)):
"""
Create a `Classifier` instance from a scikit-learn Logistic Regression model.
:param model: scikit-learn LogisticRegression model
:type model: `sklearn.linear_model.LogisticRegression`
:param clip_values: Tuple of the form `(min, max)` representing the minimum and maximum values allowed
for features.
:type clip_values: `tuple`
:param defences: Defences to be activated with the classifier.
:type defences: :class:`.Preprocessor` or `list(Preprocessor)` instances
:param preprocessing: Tuple of the form `(subtractor, divider)` of floats or `np.ndarray` of values to be