class_docstr: Class performing adversarial training following TRADES protocol.
  
  | Paper link: https://proceedings.mlr.press/v97/zhang19p.html
class_docstr_tok: ["Class","performing","adversarial","training","following","TRADES","protocol",".","|","Paper","link",":","https",":","\/\/proceedings.mlr.press\/v97\/zhang19p.html"]
docstr: Train a model adversarially with TRADES protocol.
  See class documentation for more information on the exact procedure.
  
  :param x: Training set.
  :param y: Labels for the training set.
  :param validation_data: Tuple consisting of validation data, (x_val, y_val)
  :param batch_size: Size of batches.
  :param nb_epochs: Number of epochs to use for trainings.
  :param scheduler: Learning rate scheduler to run at the end of every epoch.
  :param kwargs: Dictionary of framework-specific arguments. These will be passed as such to the `fit` function of
                            the target classifier.
docstr_tok: ["Train","a","model","adversarially","with","TRADES","protocol",".","See","class","documentation","for","more","information","on","the","exact","procedure",".",":","param","x",":","Training","set",".",":","param","y",":","Labels","for","the","training","set",".",":","param","validation_data",":","Tuple","consisting","of","validation","data",",","(","x_val",",","y_val",")",":","param","batch_size",":","Size","of","batches",".",":","param","nb_epochs",":","Number","of","epochs","to","use","for","trainings",".",":","param","scheduler",":","Learning","rate","scheduler","to","run","at","the","end","of","every","epoch",".",":","param","kwargs",":","Dictionary","of","framework-specific","arguments",".","These","will","be","passed","as","such","to","the","`","fit","`","function","of","the","target","classifier","."]
code: def fit(
      self,
      x: np.ndarray,
      y: np.ndarray,
      validation_data: Optional[Tuple[np.ndarray, np.ndarray]] = None,
      batch_size: int = 128,
      nb_epochs: int = 20,
      scheduler: Optional[
          "torch.optim.lr_scheduler._LRScheduler"
      ] = None,
      **kwargs,
  ):  # pylint: disable=W0221
      """
      Train a model adversarially with TRADES protocol.
      See class documentation for more information on the exact procedure.
  
      :param x: Training set.
      :param y: Labels for the training set.
      :param validation_data: Tuple consisting of validation data, (x_val, y_val)
      :param batch_size: Size of batches.
      :param nb_epochs: Number of epochs to use for trainings.
      :param scheduler: Learning rate scheduler to run at the end of every epoch.
      :param kwargs: Dictionary of framework-specific arguments. These will be passed as such to the `fit` function of
                                the target classifier.
      """
      import torch
  
      logger.info(
          "Performing adversarial training with TRADES protocol"
      )
      # pylint: disable=W0212
      if (scheduler is not None) and (
          not isinstance(
              scheduler, torch.optim.lr_scheduler._LRScheduler
          )
      ):  # pylint: enable=W0212
          raise ValueError(
              "Invalid Pytorch scheduler is provided for adversarial training."
          )
  
      nb_batches = int(np.ceil(len(x) / batch_size))
      ind = np.arange(len(x))
  
      logger.info("Adversarial Training TRADES")
      y = check_and_transform_label_format(
          y, nb_classes=self.classifier.nb_classes
      )
  
      if validation_data is not None:
          (x_test, y_test) = validation_data
          y_test = check_and_transform_label_format(
              y_test, nb_classes=self.classifier.nb_classes
          )
  
          (
              x_preprocessed_test,
              y_preprocessed_test,
          ) = self._classifier._apply_preprocessing(  # pylint: disable=W0212
              x_test, y_test, fit=True
          )
  
      for i_epoch in trange(
          nb_epochs, desc="Adversarial Training TRADES - Epochs"
      ):
          # Shuffle the examples
          np.random.shuffle(ind)
          start_time = time.time()
          train_loss = 0.0
          train_acc = 0.0
          train_n = 0.0
  
          for batch_id in range(nb_batches):
              # Create batch data
              x_batch = x[
                  ind[
                      batch_id
                      * batch_size : min(
                          (batch_id + 1) * batch_size, x.shape[0]
                      )
                  ]
              ].copy()
              y_batch = y[
                  ind[
                      batch_id
                      * batch_size : min(
                          (batch_id + 1) * batch_size, x.shape[0]
                      )
                  ]
              ]
  
              _train_loss, _train_acc, _train_n = self._batch_process(
                  x_batch, y_batch
              )
  
              train_loss += _train_loss
              train_acc += _train_acc
              train_n += _train_n
  
          if scheduler:
              scheduler.step()
  
          train_time = time.time()
  
          # compute accuracy
          if validation_data is not None:
              output = np.argmax(
                  self.predict(x_preprocessed_test), axis=1
              )
              nb_correct_pred = np.sum(
                  output == np.argmax(y_preprocessed_test, axis=1)
              )
  
              logger.info(
                  "epoch: %s time(s): %.1f loss: %.4f acc(tr): %.4f acc(val): %.4f",
                  i_epoch,
                  train_time - start_time,
                  train_loss / train_n,
                  train_acc / train_n,
                  nb_correct_pred / x_test.shape[0],
              )
          else:
              logger.info(
                  "epoch: %s time(s): %.1f loss: %.4f acc: %.4f",
                  i_epoch,
                  train_time - start_time,
                  train_loss / train_n,
                  train_acc / train_n,
              )
  
file_path: adversarial-robustness-toolbox/art/defences/trainer/adversarial_trainer_trades_pytorch.py
imports: from __future__ import absolute_import, division, print_function, unicode_literals
  import logging
  import time
  from typing import Optional, Tuple, TYPE_CHECKING
  import numpy
  from tqdm.auto import trange
  from art.defences.trainer.adversarial_trainer_trades import AdversarialTrainerTRADES
  from art.estimators.classification.pytorch import PyTorchClassifier
  from art.data_generators import DataGenerator
  from art.attacks.attack import EvasionAttack
  from art.utils import check_and_transform_label_format
label_desc: Use image node_id 2 for calling the AdversarialTrainerTRADESPyTorch obj's underlying member method code with example usage: obj.fit(x, y, validation_data, batch_size, nb_epochs, scheduler) without return types