class_docstr: Implementation of the adversarial patch attack for square and rectangular images and videos in PyTorch.
  
  | Paper link: https://arxiv.org/abs/1712.09665
docstr: Create an instance of the :class:`.AdversarialPatchPyTorch`.
  
  :param estimator: A trained estimator.
  :param rotation_max: The maximum rotation applied to random patches. The value is expected to be in the
         range `[0, 180]`.
  :param scale_min: The minimum scaling applied to random patches. The value should be in the range `[0, 1]`,
         but less than `scale_max`.
  :param scale_max: The maximum scaling applied to random patches. The value should be in the range `[0, 1]`, but
         larger than `scale_min`.
  :param distortion_scale_max: The maximum distortion scale for perspective transformation in range `[0, 1]`. If
         distortion_scale_max=0.0 the perspective transformation sampling will be disabled.
  :param learning_rate: The learning rate of the optimization. For `optimizer="pgd"` the learning rate gets
                        multiplied with the sign of the loss gradients.
  :param max_iter: The number of optimization steps.
  :param batch_size: The size of the training batch.
  :param patch_shape: The shape of the adversarial patch as a tuple of shape CHW (nb_channels, height, width).
  :param patch_location: The location of the adversarial patch as a tuple of shape (upper left x, upper left y).
  :param patch_type: The patch type, either circle or square.
  :param optimizer: The optimization algorithm. Supported values: "Adam", and "pgd". "pgd" corresponds to
                    projected gradient descent in L-Inf norm.
  :param targeted: Indicates whether the attack is targeted (True) or untargeted (False).
  :param summary_writer: Activate summary writer for TensorBoard.
                         Default is `False` and deactivated summary writer.
                         If `True` save runs/CURRENT_DATETIME_HOSTNAME in current directory.
                         If of type `str` save in path.
                         If of type `SummaryWriter` apply provided custom summary writer.
                         Use hierarchical folder structure to compare between runs easily. e.g. pass in
                         ‘runs/exp1’, ‘runs/exp2’, etc. for each new experiment to compare across them.
  :param verbose: Show progress bars.
docstr_tok: ["Create","an","instance","of","the",":","class",":","`",".AdversarialPatchPyTorch","`",".",":","param","estimator",":","A","trained","estimator",".",":","param","rotation_max",":","The","maximum","rotation","applied","to","random","patches",".","The","value","is","expected","to","be","in","the","range","`","[","0",",","180","]","`",".",":","param","scale_min",":","The","minimum","scaling","applied","to","random","patches",".","The","value","should","be","in","the","range","`","[","0",",","1","]","`",",","but","less","than","`","scale_max","`",".",":","param","scale_max",":","The","maximum","scaling","applied","to","random","patches",".","The","value","should","be","in","the","range","`","[","0",",","1","]","`",",","but","larger","than","`","scale_min","`",".",":","param","distortion_scale_max",":","The","maximum","distortion","scale","for","perspective","transformation","in","range","`","[","0",",","1","]","`",".","If","distortion_scale_max=0.0","the","perspective","transformation","sampling","will","be","disabled",".",":","param","learning_rate",":","The","learning","rate","of","the","optimization",".","For","`","optimizer=","''","pgd","''","`","the","learning","rate","gets","multiplied","with","the","sign","of","the","loss","gradients",".",":","param","max_iter",":","The","number","of","optimization","steps",".",":","param","batch_size",":","The","size","of","the","training","batch",".",":","param","patch_shape",":","The","shape","of","the","adversarial","patch","as","a","tuple","of","shape","CHW","(","nb_channels",",","height",",","width",")",".",":","param","patch_location",":","The","location","of","the","adversarial","patch","as","a","tuple","of","shape","(","upper","left","x",",","upper","left","y",")",".",":","param","patch_type",":","The","patch","type",",","either","circle","or","square",".",":","param","optimizer",":","The","optimization","algorithm",".","Supported","values",":","``","Adam","''",",","and","``","pgd","''",".","``","pgd","''","corresponds","to","projected","gradient","descent","in","L-Inf","norm",".",":","param","targeted",":","Indicates","whether","the","attack","is","targeted","(","True",")","or","untargeted","(","False",")",".",":","param","summary_writer",":","Activate","summary","writer","for","TensorBoard",".","Default","is","`","False","`","and","deactivated","summary","writer",".","If","`","True","`","save","runs\/CURRENT_DATETIME_HOSTNAME","in","current","directory",".","If","of","type","`","str","`","save","in","path",".","If","of","type","`","SummaryWriter","`","apply","provided","custom","summary","writer",".","Use","hierarchical","folder","structure","to","compare","between","runs","easily",".","e.g",".","pass","in","\u2018","runs\/exp1","\u2019",",","\u2018","runs\/exp2","\u2019",",","etc",".","for","each","new","experiment","to","compare","across","them",".",":","param","verbose",":","Show","progress","bars","."]
code: def __init__(
      self,
      estimator: "CLASSIFIER_NEURALNETWORK_TYPE",
      rotation_max: float = 22.5,
      scale_min: float = 0.1,
      scale_max: float = 1.0,
      distortion_scale_max: float = 0.0,
      learning_rate: float = 5.0,
      max_iter: int = 500,
      batch_size: int = 16,
      patch_shape: Tuple[int, int, int] = (3, 224, 224),
      patch_location: Optional[Tuple[int, int]] = None,
      patch_type: str = "circle",
      optimizer: str = "Adam",
      targeted: bool = True,
      summary_writer: Union[str, bool, SummaryWriter] = False,
      verbose: bool = True,
  ):
      """
      Create an instance of the :class:`.AdversarialPatchPyTorch`.
  
      :param estimator: A trained estimator.
      :param rotation_max: The maximum rotation applied to random patches. The value is expected to be in the
             range `[0, 180]`.
      :param scale_min: The minimum scaling applied to random patches. The value should be in the range `[0, 1]`,
             but less than `scale_max`.
      :param scale_max: The maximum scaling applied to random patches. The value should be in the range `[0, 1]`, but
             larger than `scale_min`.
      :param distortion_scale_max: The maximum distortion scale for perspective transformation in range `[0, 1]`. If
             distortion_scale_max=0.0 the perspective transformation sampling will be disabled.
      :param learning_rate: The learning rate of the optimization. For `optimizer="pgd"` the learning rate gets
                            multiplied with the sign of the loss gradients.
      :param max_iter: The number of optimization steps.
      :param batch_size: The size of the training batch.
      :param patch_shape: The shape of the adversarial patch as a tuple of shape CHW (nb_channels, height, width).
      :param patch_location: The location of the adversarial patch as a tuple of shape (upper left x, upper left y).
      :param patch_type: The patch type, either circle or square.
      :param optimizer: The optimization algorithm. Supported values: "Adam", and "pgd". "pgd" corresponds to
                        projected gradient descent in L-Inf norm.
      :param targeted: Indicates whether the attack is targeted (True) or untargeted (False).
      :param summary_writer: Activate summary writer for TensorBoard.
                             Default is `False` and deactivated summary writer.
                             If `True` save runs/CURRENT_DATETIME_HOSTNAME in current directory.
                             If of type `str` save in path.
                             If of type `SummaryWriter` apply provided custom summary writer.
                             Use hierarchical folder structure to compare between runs easily. e.g. pass in
                             ‘runs/exp1’, ‘runs/exp2’, etc. for each new experiment to compare across them.
      :param verbose: Show progress bars.
      """
      import torch
      import torchvision
  
      torch_version = list(
          map(
              int,
              torch.__version__.lower()
              .split("+", maxsplit=1)[0]
              .split("."),
          )
      )
      torchvision_version = list(
          map(
              int,
              torchvision.__version__.lower()
              .split("+", maxsplit=1)[0]
              .split("."),
          )
      )
      assert (
          torch_version[0] >= 1
          and torch_version[1] >= 7
          or (torch_version[0] >= 2)
      ), "AdversarialPatchPyTorch requires torch>=1.7.0"
      assert (
          torchvision_version[0] >= 0 and torchvision_version[1] >= 8
      ), "AdversarialPatchPyTorch requires torchvision>=0.8.0"
  
      super().__init__(
          estimator=estimator, summary_writer=summary_writer
      )
      self.rotation_max = rotation_max
      self.scale_min = scale_min
      self.scale_max = scale_max
      self.distortion_scale_max = distortion_scale_max
      self.learning_rate = learning_rate
      self.max_iter = max_iter
      self.batch_size = batch_size
      self.patch_shape = patch_shape
      self.patch_location = patch_location
      self.patch_type = patch_type
  
      self.image_shape = estimator.input_shape
      self.targeted = targeted
      self.verbose = verbose
      self._check_params()
  
      self.i_h_patch = 1
      self.i_w_patch = 2
  
      self.input_shape = self.estimator.input_shape
  
      self.nb_dims = len(self.image_shape)
      if self.nb_dims == 3:
          self.i_h = 1
          self.i_w = 2
      elif self.nb_dims == 4:
          self.i_h = 2
          self.i_w = 3
  
      if self.patch_shape[1] != self.patch_shape[2]:  # pragma: no cover
          raise ValueError(
              "Patch height and width need to be the same."
          )
  
      if not (  # pragma: no cover
          self.estimator.postprocessing_defences is None
          or self.estimator.postprocessing_defences == []
      ):
          raise ValueError(
              "Framework-specific implementation of Adversarial Patch attack does not yet support "
              + "postprocessing defences."
          )
  
      mean_value = (
          self.estimator.clip_values[1] - self.estimator.clip_values[0]
      ) / 2.0 + self.estimator.clip_values[0]
      self._initial_value = np.ones(self.patch_shape) * mean_value
      self._patch = torch.tensor(
          self._initial_value,
          requires_grad=True,
          device=self.estimator.device,
      )
  
      self._optimizer_string = optimizer
      if self._optimizer_string == "Adam":
          self._optimizer = torch.optim.Adam(
              [self._patch], lr=self.learning_rate
          )
  
imports: from __future__ import absolute_import, division, print_function, unicode_literals
  import logging
  import math
  from typing import Any, Optional, Tuple, Union, TYPE_CHECKING
  import numpy
  from tqdm.auto import trange
  from art.attacks.attack import EvasionAttack
  from art.attacks.evasion.adversarial_patch.utils import insert_transformed_patch
  from art.estimators.estimator import BaseEstimator, NeuralNetworkMixin
  from art.utils import check_and_transform_label_format, is_probability, to_categorical
  from art.summary_writer import SummaryWriter
label_desc: Use image node_id 1 to create a new AdversarialPatchPyTorch object from inherited base classes: EvasionAttack with example: obj = AdversarialPatchPyTorch(estimator, rotation_max, scale_min, scale_max, distortion_scale_max, learning_rate, max_iter, batch_size, patch_shape, patch_location, patch_type, optimizer, targeted, summary_writer, verbose)