Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
used for data preprocessing. The first value will be subtracted from the input. The input will then
be divided by the second one.
:type preprocessing: `tuple`
"""
if model.__class__.__module__.split('.')[0] != 'sklearn':
raise TypeError("Model is not an sklearn model. Received '%s'" % model.__class__)
sklearn_name = model.__class__.__name__
module = importlib.import_module('art.classifiers.scikitlearn')
if hasattr(module, 'Scikitlearn%s' % sklearn_name):
return getattr(module, 'Scikitlearn%s' % sklearn_name)(model=model, clip_values=clip_values, defences=defences,
preprocessing=preprocessing)
# This basic class at least generically handles `fit`, `predict` and `save`
return ScikitlearnClassifier(model, clip_values, defences, preprocessing)
class ScikitlearnClassifier(Classifier):
"""
Wrapper class for scikit-learn classifier models.
"""
def __init__(self, model, clip_values=None, defences=None, preprocessing=(0, 1)):
"""
Create a `Classifier` instance from a scikit-learn classifier model.
:param clip_values: Tuple of the form `(min, max)` representing the minimum and maximum values allowed
for features.
:type clip_values: `tuple`
:param model: scikit-learn classifier model.
:type model: `sklearn.base.BaseEstimator`
: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
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""
This module implements the classifier `XGBoostClassifier` for XGBoost models.
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
import numpy as np
from art.classifiers.classifier import Classifier, ClassifierDecisionTree
logger = logging.getLogger(__name__)
class XGBoostClassifier(Classifier, ClassifierDecisionTree):
"""
Wrapper class for importing XGBoost models.
"""
def __init__(self, model=None, clip_values=None, defences=None, preprocessing=None, num_features=None,
nb_classes=None):
"""
Create a `Classifier` instance from a XGBoost model.
:param model: XGBoost model
:type model: `xgboost.Booster` or `xgboost.XGBClassifier`
: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
x = Conv2D(filters2, kernel_size, padding='same', name=conv_name_base + '2b')(x)
if bnorm:
x = BatchNormalization(axis=bn_axis, name=bn_name_base + '2b')(x)
x = Activation('relu')(x)
x = Conv2D(filters3, (1, 1), name=conv_name_base + '2c')(x)
if bnorm:
x = BatchNormalization(axis=bn_axis, name=bn_name_base + '2c')(x)
x = layers.add([x, input_tensor])
x = Activation('relu')(x)
return x
class ResNet(Classifier):
"""Instantiates a ResNet model using Keras sequential model."""
def __init__(self, input_shape=None, include_end=True, act='relu', bnorm=False, input_ph=None, nb_filters=64,
nb_classes=10, act_params={}, model=None, defences=None, preproc=None, dataset='mnist'):
"""Instantiates a ResNet model using Keras sequential model
:param tuple input_shape: shape of the input images
:param bool include_end: whether to include a softmax layer at the end or not
:param str act: type of the intermediate activation functions
:param bool bnorm: whether to apply batch normalization after each layer or not
:param input_ph: The TensorFlow tensor for the input
(needed if returning logits)
("ph" stands for placeholder but it need not actually be a
placeholder)
:param int nb_filters: number of convolutional filters per layer
:param int nb_classes: the number of output classes
:param dict act_params: dict of params for activation layers
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
import numpy as np
from scipy.stats import entropy
from art.wrappers.wrapper import ClassifierWrapper
from art.classifiers.classifier import Classifier, ClassifierGradients
from art.utils import clip_and_round
logger = logging.getLogger(__name__)
class QueryEfficientBBGradientEstimation(ClassifierWrapper, ClassifierGradients, Classifier):
"""
Implementation of Query-Efficient Black-box Adversarial Examples. The attack approximates the gradient by
maximizing the loss function over samples drawn from random Gaussian noise around the input.
| Paper link: https://arxiv.org/abs/1712.07113
"""
attack_params = ['num_basis', 'sigma', 'round_samples']
def __init__(self, classifier, num_basis, sigma, round_samples=0):
"""
:param classifier: An instance of a `Classifier` whose loss_gradient is being approximated
:type classifier: `Classifier`
:param num_basis: The number of samples to draw to approximate the gradient
:type num_basis: `int`
:param sigma: Scaling on the Gaussian noise N(0,1)
:type sigma: `float`
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
# pylint: disable=E0001
import numpy as np
import six
from art.classifiers.classifier import Classifier, ClassifierNeuralNetwork, ClassifierGradients
from art.detection.subsetscanning.scanner import Scanner
logger = logging.getLogger(__name__)
class SubsetScanningDetector(ClassifierNeuralNetwork, ClassifierGradients, Classifier):
"""
Fast generalized subset scan based detector by McFowland, E., Speakman, S., and Neill, D. B. (2013).
| Paper link: https://www.cs.cmu.edu/~neill/papers/mcfowland13a.pdf
"""
def __init__(self, classifier, bgd_data, layer):
"""
Create a `SubsetScanningDetector` instance which is used to the detect the presence of adversarial samples.
:param classifier: The model being evaluated for its robustness to anomalies (eg. adversarial samples)
:type classifier: :class:`.Classifier`
:bgd_data: The background data used to learn a null model. Typically dataset used to train the classifier.
:type bgd_data: `np.ndarray`
:layer: The layer from which to extract activations to perform scan
:type layer: `int` or `str`
"""
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""
This module implements a classifier wrapper which returns class labels.
"""
import logging
import numpy as np
from art.wrappers.wrapper import ClassifierWrapper
from art.classifiers.classifier import Classifier
logger = logging.getLogger(__name__)
class ClassLabels(ClassifierWrapper, Classifier):
"""
Implementation of a classifier wrapper which returns class labels.
"""
def __init__(self, classifier):
"""
Create a wrapper for class label predictions.
:param classifier: A trained classifier.
:type classifier: :class:`.Classifier`
"""
super(ClassLabels, self).__init__(classifier)
# pylint: disable=W0221
def predict(self, x, batch_size=128, **kwargs):
"""
"""
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)