class_docstr: Wrapper thats adds adversarial regularization to a given `tf.keras.Model`.
  
  This model will reuse the layers and variables as the given `base_model`, so
  training this model will also update the variables in the `base_model`. The
  adversarial regularization can be configured by `adv_config`. (See
  `nsl.configs.AdvRegConfig` for the hyperparameters.) The regularization term
  will be added into training objective, and will be minimized during training
  together with other losses specified in `compile()`.
  
  This model expects its input to be a dictionary mapping feature names to
  feature values. The dictionary should contain both input data (`x`) and target
  data (`y`). The feature names of the target data should be passed to this
  model's constructor in `label_keys`, so the model can distinguish between
  input data and target data. If your samples are weighted, the sample weight
  should also be a feature in the dictionary, and its name should be passed to
  the constructor in `sample_weight_key`. When calling this model's `fit()` or
  `evaluate()` method, the argument `y` should not be set because the target
  data is already in the input dictionary. The dictionary format also implies
  that the input has to be named, i.e. the `name` argument of `tf.keras.Input()`
  should be set.
  
  Example:
  
  ```python
  # A linear regression model (for demonstrating the usage only)
  base_model = tf.keras.Sequential([
      tf.keras.Input(shape=(2,), name='input'),
      tf.keras.layers.Dense(1),
  ])
  
  # Applies the wrapper, with 0.2 as regularization weight.
  adv_config = nsl.configs.make_adv_reg_config(multiplier=0.2)
  adv_model = nsl.keras.AdversarialRegularization(base_model,
                                                  label_keys=['label'],
                                                  adv_config=adv_config)
  
  # Compiles the model as usual.
  adv_model.compile(optimizer='adam', loss='mean_squared_error')
  
  # Trains the model. (The actual training data is omitted for clarity.)
  # The model minimizes (mean_squared_error + 0.2 * adversarial_regularization).
  adv_model.fit(x={'input': x_train, 'label': y_train}, batch_size=32)
  ```
  
  It is recommended to use `tf.data.Dataset` to handle the dictionary format
  requirement of the input, especially when using the `validation_data` argument
  in `fit()`.
  
  ```python
  train_data = tf.data.Dataset.from_tensor_slices(
      {'input': x_train, 'label': y_train}).batch(batch_size)
  val_data = tf.data.Dataset.from_tensor_slices(
      {'input': x_val, 'label': y_val}).batch(batch_size)
  val_steps = x_val.shape[0] / batch_size
  adv_model.fit(train_data, validation_data=val_data,
                validation_steps=val_steps, epochs=2, verbose=1)
  ```
docstr: Perturbs the given input to generates adversarial examples.
  
  Args:
    x: Input examples to be perturbed, in a dictionary of Numpy arrays,
      `Tensor`, `SparseTensor`, or `RaggedTensor` objects. The first
      dimension of all tensors or arrays should be the same (i.e. batch size).
    **config_kwargs: (optional) hyperparameters for generating adversarial
      preturbation. Any keyword argument here will overwrite the corresponding
      field in `nsl.configs.AdvNeighborConfig` specified in `__init__`.
      Acceptable keys: `feature_mask`, `adv_step_size`, `adv_grad_norm`,
      `clip_value_min`, `clip_value_max`, `pgd_iterations`, and `pgd_epsilon`.
  
  Returns:
    A dictionary of NumPy arrays, `SparseTensor`, or `RaggedTensor` objects of
    the generated adversarial examples.
docstr_tok: ["Perturbs","the","given","input","to","generates","adversarial","examples",".","Args",":","x",":","Input","examples","to","be","perturbed",",","in","a","dictionary","of","Numpy","arrays",",","`","Tensor","`",",","`","SparseTensor","`",",","or","`","RaggedTensor","`","objects",".","The","first","dimension","of","all","tensors","or","arrays","should","be","the","same","(","i.e",".","batch","size",")",".","*","*","config_kwargs",":","(","optional",")","hyperparameters","for","generating","adversarial","preturbation",".","Any","keyword","argument","here","will","overwrite","the","corresponding","field","in","`","nsl.configs.AdvNeighborConfig","`","specified","in","`","__init__","`",".","Acceptable","keys",":","`","feature_mask","`",",","`","adv_step_size","`",",","`","adv_grad_norm","`",",","`","clip_value_min","`",",","`","clip_value_max","`",",","`","pgd_iterations","`",",","and","`","pgd_epsilon","`",".","Returns",":","A","dictionary","of","NumPy","arrays",",","`","SparseTensor","`",",","or","`","RaggedTensor","`","objects","of","the","generated","adversarial","examples","."]
code: def perturb_on_batch(self, x, **config_kwargs):
      """Perturbs the given input to generates adversarial examples.
  
      Args:
        x: Input examples to be perturbed, in a dictionary of Numpy arrays,
          `Tensor`, `SparseTensor`, or `RaggedTensor` objects. The first
          dimension of all tensors or arrays should be the same (i.e. batch size).
        **config_kwargs: (optional) hyperparameters for generating adversarial
          preturbation. Any keyword argument here will overwrite the corresponding
          field in `nsl.configs.AdvNeighborConfig` specified in `__init__`.
          Acceptable keys: `feature_mask`, `adv_step_size`, `adv_grad_norm`,
          `clip_value_min`, `clip_value_max`, `pgd_iterations`, and `pgd_epsilon`.
  
      Returns:
        A dictionary of NumPy arrays, `SparseTensor`, or `RaggedTensor` objects of
        the generated adversarial examples.
      """
      inputs = tf.nest.map_structure(
          tf.convert_to_tensor, x, expand_composites=True
      )
      labels, sample_weights = self._extract_labels_and_weights(inputs)
      _, labeled_loss, _, tape = self._forward_pass(
          inputs, labels, sample_weights, {"training": False}
      )
  
      config_kwargs = {
          k: v for k, v in config_kwargs.items() if v is not None
      }
      config = attr.evolve(
          self.adv_config.adv_neighbor_config, **config_kwargs
      )
      adv_inputs, _ = adversarial_neighbor.gen_adv_neighbor(
          inputs,
          labeled_loss,
          config=config,
          gradient_tape=tape,
          pgd_model_fn=self._call_base_model,
          pgd_loss_fn=self._compute_total_loss,
          pgd_labels=labels,
          use_while_loop=True,
      )
  
      if tf.executing_eagerly():
          # Converts `Tensor` objects to NumPy arrays and keeps other objects (e.g.
          # `SparseTensor`) as-is.
          adv_inputs = tf.nest.map_structure(
              lambda x: x.numpy() if hasattr(x, "numpy") else x,
              adv_inputs,
              expand_composites=False,
          )
      else:
          adv_inputs = tf.keras.backend.function([], adv_inputs)([])
  
      # Inserts the labels and sample_weights back to the input dictionary, so
      # the returned input has the same structure as the original input.
      for label_key, label in zip(self.label_keys, labels):
          adv_inputs[label_key] = label
      if self.sample_weight_key is not None:
          adv_inputs[self.sample_weight_key] = sample_weights
  
      return adv_inputs
  
imports: from __future__ import absolute_import
  from __future__ import division
  from __future__ import print_function
  import collections
  import functools
  import types
  import attr
  import neural_structured_learning.configs
  from neural_structured_learning.lib import adversarial_neighbor
  import six
  import tensorflow
label_desc: Use image node_id 15 for calling the AdversarialRegularization obj's underlying member method code with example usage: obj.perturb_on_batch(x) and returns: adv_inputs