2525import logging
2626from typing import Callable , List , Optional , Tuple , Union , TYPE_CHECKING
2727
28+ import warnings
29+ from tqdm import tqdm
2830import numpy as np
2931
3032from art .estimators .classification .tensorflow import TensorFlowV2Classifier
3133from art .estimators .certification .randomized_smoothing .randomized_smoothing import RandomizedSmoothingMixin
34+ from art .utils import check_and_transform_label_format
3235
3336if TYPE_CHECKING :
3437 # pylint: disable=C0412
@@ -91,6 +94,12 @@ def __init__(
9194 :param scale: Standard deviation of Gaussian noise added.
9295 :param alpha: The failure probability of smoothing.
9396 """
97+ if preprocessing_defences is not None :
98+ warnings .warn (
99+ "\n With the current backend (Tensorflow), Gaussian noise will be added by Randomized Smoothing "
100+ "AFTER the application of preprocessing defences. Please ensure this conforms to your use case.\n "
101+ )
102+
94103 super ().__init__ (
95104 model = model ,
96105 nb_classes = nb_classes ,
@@ -113,21 +122,41 @@ def _predict_classifier(self, x: np.ndarray, batch_size: int, training_mode: boo
113122 def _fit_classifier (self , x : np .ndarray , y : np .ndarray , batch_size : int , nb_epochs : int , ** kwargs ) -> None :
114123 return TensorFlowV2Classifier .fit (self , x , y , batch_size = batch_size , nb_epochs = nb_epochs , ** kwargs )
115124
116- def fit (self , x : np .ndarray , y : np .ndarray , batch_size : int = 128 , nb_epochs : int = 10 , ** kwargs ):
125+ def fit (self , x : np .ndarray , y : np .ndarray , batch_size : int = 128 , nb_epochs : int = 10 , ** kwargs ) -> None :
117126 """
118127 Fit the classifier on the training set `(x, y)`.
119128
120129 :param x: Training data.
121- :param y: Target values (class labels) one-hot-encoded of shape (nb_samples, nb_classes) or indices of shape
122- (nb_samples,).
123- :param batch_size: Batch size.
124- :key nb_epochs: Number of epochs to use for training
125- :param kwargs: Dictionary of framework-specific arguments. This parameter is not currently supported for PyTorch
126- and providing it takes no effect.
127- :type kwargs: `dict`
128- :return: `None`
130+ :param y: Labels, one-hot-encoded of shape (nb_samples, nb_classes) or index labels of
131+ shape (nb_samples,).
132+ :param batch_size: Size of batches.
133+ :param nb_epochs: Number of epochs to use for training.
134+ :param kwargs: Dictionary of framework-specific arguments. This parameter is not currently supported for
135+ TensorFlow and providing it takes no effect.
129136 """
130- RandomizedSmoothingMixin .fit (self , x , y , batch_size = batch_size , nb_epochs = nb_epochs , ** kwargs )
137+ import tensorflow as tf # lgtm [py/repeated-import]
138+
139+ if self ._train_step is None : # pragma: no cover
140+ raise TypeError (
141+ "The training function `train_step` is required for fitting a model but it has not been " "defined."
142+ )
143+
144+ y = check_and_transform_label_format (y , self .nb_classes )
145+
146+ # Apply preprocessing
147+ x_preprocessed , y_preprocessed = self ._apply_preprocessing (x , y , fit = True )
148+
149+ # Check label shape
150+ if self ._reduce_labels :
151+ y_preprocessed = np .argmax (y_preprocessed , axis = 1 )
152+
153+ train_ds = tf .data .Dataset .from_tensor_slices ((x_preprocessed , y_preprocessed )).shuffle (10000 ).batch (batch_size )
154+
155+ for _ in tqdm (range (nb_epochs )):
156+ for images , labels in train_ds :
157+ # Add random noise for randomized smoothing
158+ images += tf .random .normal (shape = images .shape , mean = 0.0 , stddev = self .scale )
159+ self ._train_step (self .model , images , labels )
131160
132161 def predict (self , x : np .ndarray , batch_size : int = 128 , ** kwargs ) -> np .ndarray : # type: ignore
133162 """
0 commit comments