Join us at TensorFlow World, Oct 28-31. Use code TF20 for 20% off select passes. Register now


View source on GitHub

Functional interface of _GenAdvNeighbor.


This function provides a tensor/config-in & tensor-out functional interface that does the following: (a) Instantiates '_GenAdvNeighbor' (b) Invokes 'gen_neighbor' method (c) Returns the adversarial neighbors generated.


  • input_features: a dense (float32) tensor or a dictionary of feature names and dense tensors. The shape of the tensor(s) should be either: (a) pointwise samples: [batch_size, feat_len], or (b) sequence samples: [batch_size, seq_len, feat_len]. Note that if the input_features is a dictionary, only dense (float) tensors in it will be perturbed and all other features (int, string, or sparse tensors) will be kept as-is in the returning adv_neighbor.
  • labeled_loss: a scalar (float32) tensor calculated from true labels (or supervisions).
  • config: AdvNeighborConfig object containing the following hyperparameters for generating adversarial samples. - 'feature_mask': mask (w/ 0-1 values) applied on graident. - 'adv_step_size': step size to find the adversarial sample. - 'adv_grad_norm': type of tensor norm to normalize the gradient.
  • raise_invalid_gradient: (optional, default=False) a Boolean flag indicating whether to raise an error when gradients cannot be computed on some input features. There are three cases where gradients cannot be computed: (1) The feature is a SparseTensor. (2) The feature has a non-differentiable tf.DType, like string or integer. (3) The feature is not involved in loss computation. If set to False (default), those inputs without gradient will be ignored silently and not perturbed.
  • gradient_tape: a tf.GradientTape object watching the calculation from input_features to labeled_loss. Can be omitted if running in graph mode.


  • adv_neighbor: the perturbed example, with the same shape and structure as input_features
  • adv_weight: a dense (float32) tensor with shape of [batch_size, 1], representing the weight for each neighbor


  • ValueError: if raise_invalid_gradient is set and some of the input features cannot be perturbed. See raise_invalid_gradient for situations where this can happen.