class_docstr: Implementation of SmoothAdv training, as introduced in Salman et al. (2019)
  
  | Paper link: https://arxiv.org/abs/1906.04584
class_docstr_tok: ["Implementation","of","SmoothAdv","training",",","as","introduced","in","Salman","et","al",".","(","2019",")","|","Paper","link",":","https",":","\/\/arxiv.org\/abs\/1906.04584"]
docstr: Fit the classifier on the training set `(x, y)`.
  
  :param x: Training data.
  :param y: Labels, one-hot-encoded of shape (nb_samples, nb_classes) or index labels of
            shape (nb_samples,).
  :param batch_size: Size of batches.
  :param nb_epochs: Number of epochs to use for training.
  :param verbose: Display the training progress bar.
  :param kwargs: Dictionary of framework-specific arguments. This parameter currently only supports
                 "scheduler" which is an optional function that will be called at the end of every
                 epoch to adjust the learning rate.
docstr_tok: ["Fit","the","classifier","on","the","training","set","`","(","x",",","y",")","`",".",":","param","x",":","Training","data",".",":","param","y",":","Labels",",","one-hot-encoded","of","shape","(","nb_samples",",","nb_classes",")","or","index","labels","of","shape","(","nb_samples",",",")",".",":","param","batch_size",":","Size","of","batches",".",":","param","nb_epochs",":","Number","of","epochs","to","use","for","training",".",":","param","verbose",":","Display","the","training","progress","bar",".",":","param","kwargs",":","Dictionary","of","framework-specific","arguments",".","This","parameter","currently","only","supports","``","scheduler","''","which","is","an","optional","function","that","will","be","called","at","the","end","of","every","epoch","to","adjust","the","learning","rate","."]
code: def fit(
      self,
      x: np.ndarray,
      y: np.ndarray,
      batch_size: int = 128,
      nb_epochs: int = 10,
      verbose: bool = False,
      **kwargs,
  ) -> None:
      """
      Fit the classifier on the training set `(x, y)`.
  
      :param x: Training data.
      :param y: Labels, one-hot-encoded of shape (nb_samples, nb_classes) or index labels of
                shape (nb_samples,).
      :param batch_size: Size of batches.
      :param nb_epochs: Number of epochs to use for training.
      :param verbose: Display the training progress bar.
      :param kwargs: Dictionary of framework-specific arguments. This parameter currently only supports
                     "scheduler" which is an optional function that will be called at the end of every
                     epoch to adjust the learning rate.
      """
      import tensorflow as tf
  
      if self._train_step is None:  # pragma: no cover
          if self._loss_object is None:  # pragma: no cover
              raise TypeError(
                  "A loss function `loss_object` or training function `train_step` is required for fitting the "
                  "model, but it has not been defined."
              )
          if self._optimizer is None:  # pragma: no cover
              raise ValueError(
                  "An optimizer `optimizer` or training function `train_step` is required for fitting the "
                  "model, but it has not been defined."
              )
  
          @tf.function
          def train_step(model, images, labels):
              with tf.GradientTape() as tape:
                  predictions = model(images, training=True)
                  loss = self.loss_object(labels, predictions)
              gradients = tape.gradient(loss, model.trainable_variables)
              self.optimizer.apply_gradients(
                  zip(gradients, model.trainable_variables)
              )
  
      else:
          train_step = self._train_step
  
      scheduler = kwargs.get("scheduler")
  
      y = check_and_transform_label_format(
          y, nb_classes=self.nb_classes
      )
  
      # Apply preprocessing
      x_preprocessed, y_preprocessed = self._apply_preprocessing(
          x, y, fit=True
      )
  
      # Check label shape
      if self._reduce_labels:
          y_preprocessed = np.argmax(y_preprocessed, axis=1)
  
      train_ds = (
          tf.data.Dataset.from_tensor_slices(
              (x_preprocessed, y_preprocessed)
          )
          .shuffle(10000)
          .batch(batch_size)
      )
  
      for epoch in trange(nb_epochs, disable=not verbose):
          self.attack.norm = min(
              self.epsilon, (epoch + 1) * self.epsilon / self.warmup
          )
  
          for x_batch, y_batch in train_ds:
              mini_batch_size = len(x_batch) // self.num_noise_vec
  
              for mini_batch in range(self.num_noise_vec):
                  # Create mini batch
                  inputs = x_batch[
                      mini_batch
                      * mini_batch_size : (mini_batch + 1)
                      * mini_batch_size
                  ]
                  labels = y_batch[
                      mini_batch
                      * mini_batch_size : (mini_batch + 1)
                      * mini_batch_size
                  ]
  
                  # Tile samples for Gaussian augmentation
                  inputs = tf.reshape(
                      tf.tile(inputs, (1, self.num_noise_vec, 1, 1)),
                      x_batch.shape,
                  )
                  noise = tf.random.normal(
                      inputs.shape, mean=0.0, stddev=self.scale
                  )
  
                  original_inputs = inputs.numpy()
                  noise_for_attack = noise.numpy()
                  perturbation_delta = np.zeros_like(original_inputs)
                  for _ in range(self.num_steps):
                      perturbed_inputs = (
                          original_inputs + perturbation_delta
                      )
                      adv_ex = self.attack.generate(
                          perturbed_inputs + noise_for_attack
                      )
                      perturbation_delta = (
                          adv_ex - perturbed_inputs - noise_for_attack
                      )
  
                  # Add random noise for randomized smoothing
                  perturbed_inputs = (
                      original_inputs + perturbation_delta
                  )
                  noisy_inputs = (
                      tf.convert_to_tensor(perturbed_inputs) + noise
                  )
  
                  train_step(self.model, noisy_inputs, labels)
  
          if scheduler is not None:
              scheduler(epoch)
  
file_path: adversarial-robustness-toolbox/art/estimators/certification/randomized_smoothing/smooth_adv/tensorflow.py
imports: from __future__ import absolute_import, division, print_function, unicode_literals
  import logging
  from typing import Callable, List, Optional, Tuple, Union, TYPE_CHECKING
  from tqdm.auto import trange
  import numpy
  from art.attacks.evasion.projected_gradient_descent.projected_gradient_descent import ProjectedGradientDescent
  from art.estimators.certification.randomized_smoothing.tensorflow import TensorFlowV2RandomizedSmoothing
  from art.estimators.classification.tensorflow import TensorFlowV2Classifier
  from art.utils import check_and_transform_label_format
label_desc: Use image node_id 2 for calling the TensorFlowV2SmoothAdv obj's underlying member method code with example usage: obj.fit(x, y, batch_size, nb_epochs, verbose) without return types