repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
tensorflow/cleverhans
cleverhans/future/tf2/attacks/fast_gradient_method.py
compute_gradient
def compute_gradient(model_fn, x, y, targeted): """ Computes the gradient of the loss with respect to the input tensor. :param model_fn: a callable that takes an input tensor and returns the model logits. :param x: input tensor :param y: Tensor with true labels. If targeted is true, then provide the target label. :param targeted: bool. Is the attack targeted or untargeted? Untargeted, the default, will try to make the label incorrect. Targeted will instead try to move in the direction of being more like y. :return: A tensor containing the gradient of the loss with respect to the input tensor. """ loss_fn = tf.nn.sparse_softmax_cross_entropy_with_logits with tf.GradientTape() as g: g.watch(x) # Compute loss loss = loss_fn(labels=y, logits=model_fn(x)) if targeted: # attack is targeted, minimize loss of target label rather than maximize loss of correct label loss = -loss # Define gradient of loss wrt input grad = g.gradient(loss, x) return grad
python
def compute_gradient(model_fn, x, y, targeted): """ Computes the gradient of the loss with respect to the input tensor. :param model_fn: a callable that takes an input tensor and returns the model logits. :param x: input tensor :param y: Tensor with true labels. If targeted is true, then provide the target label. :param targeted: bool. Is the attack targeted or untargeted? Untargeted, the default, will try to make the label incorrect. Targeted will instead try to move in the direction of being more like y. :return: A tensor containing the gradient of the loss with respect to the input tensor. """ loss_fn = tf.nn.sparse_softmax_cross_entropy_with_logits with tf.GradientTape() as g: g.watch(x) # Compute loss loss = loss_fn(labels=y, logits=model_fn(x)) if targeted: # attack is targeted, minimize loss of target label rather than maximize loss of correct label loss = -loss # Define gradient of loss wrt input grad = g.gradient(loss, x) return grad
[ "def", "compute_gradient", "(", "model_fn", ",", "x", ",", "y", ",", "targeted", ")", ":", "loss_fn", "=", "tf", ".", "nn", ".", "sparse_softmax_cross_entropy_with_logits", "with", "tf", ".", "GradientTape", "(", ")", "as", "g", ":", "g", ".", "watch", "(", "x", ")", "# Compute loss", "loss", "=", "loss_fn", "(", "labels", "=", "y", ",", "logits", "=", "model_fn", "(", "x", ")", ")", "if", "targeted", ":", "# attack is targeted, minimize loss of target label rather than maximize loss of correct label", "loss", "=", "-", "loss", "# Define gradient of loss wrt input", "grad", "=", "g", ".", "gradient", "(", "loss", ",", "x", ")", "return", "grad" ]
Computes the gradient of the loss with respect to the input tensor. :param model_fn: a callable that takes an input tensor and returns the model logits. :param x: input tensor :param y: Tensor with true labels. If targeted is true, then provide the target label. :param targeted: bool. Is the attack targeted or untargeted? Untargeted, the default, will try to make the label incorrect. Targeted will instead try to move in the direction of being more like y. :return: A tensor containing the gradient of the loss with respect to the input tensor.
[ "Computes", "the", "gradient", "of", "the", "loss", "with", "respect", "to", "the", "input", "tensor", ".", ":", "param", "model_fn", ":", "a", "callable", "that", "takes", "an", "input", "tensor", "and", "returns", "the", "model", "logits", ".", ":", "param", "x", ":", "input", "tensor", ":", "param", "y", ":", "Tensor", "with", "true", "labels", ".", "If", "targeted", "is", "true", "then", "provide", "the", "target", "label", ".", ":", "param", "targeted", ":", "bool", ".", "Is", "the", "attack", "targeted", "or", "untargeted?", "Untargeted", "the", "default", "will", "try", "to", "make", "the", "label", "incorrect", ".", "Targeted", "will", "instead", "try", "to", "move", "in", "the", "direction", "of", "being", "more", "like", "y", ".", ":", "return", ":", "A", "tensor", "containing", "the", "gradient", "of", "the", "loss", "with", "respect", "to", "the", "input", "tensor", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/future/tf2/attacks/fast_gradient_method.py#L66-L87
train
tensorflow/cleverhans
cleverhans/future/tf2/attacks/fast_gradient_method.py
optimize_linear
def optimize_linear(grad, eps, ord=np.inf): """ Solves for the optimal input to a linear function under a norm constraint. Optimal_perturbation = argmax_{eta, ||eta||_{ord} < eps} dot(eta, grad) :param grad: tf tensor containing a batch of gradients :param eps: float scalar specifying size of constraint region :param ord: int specifying order of norm :returns: tf tensor containing optimal perturbation """ # Convert the iterator returned by `range` into a list. axis = list(range(1, len(grad.get_shape()))) avoid_zero_div = 1e-12 if ord == np.inf: # Take sign of gradient optimal_perturbation = tf.sign(grad) # The following line should not change the numerical results. It applies only because # `optimal_perturbation` is the output of a `sign` op, which has zero derivative anyway. # It should not be applied for the other norms, where the perturbation has a non-zero derivative. optimal_perturbation = tf.stop_gradient(optimal_perturbation) elif ord == 1: abs_grad = tf.abs(grad) sign = tf.sign(grad) max_abs_grad = tf.reduce_max(abs_grad, axis, keepdims=True) tied_for_max = tf.dtypes.cast(tf.equal(abs_grad, max_abs_grad), dtype=tf.float32) num_ties = tf.reduce_sum(tied_for_max, axis, keepdims=True) optimal_perturbation = sign * tied_for_max / num_ties elif ord == 2: square = tf.maximum(avoid_zero_div, tf.reduce_sum(tf.square(grad), axis, keepdims=True)) optimal_perturbation = grad / tf.sqrt(square) else: raise NotImplementedError("Only L-inf, L1 and L2 norms are currently implemented.") # Scale perturbation to be the solution for the norm=eps rather than norm=1 problem scaled_perturbation = tf.multiply(eps, optimal_perturbation) return scaled_perturbation
python
def optimize_linear(grad, eps, ord=np.inf): """ Solves for the optimal input to a linear function under a norm constraint. Optimal_perturbation = argmax_{eta, ||eta||_{ord} < eps} dot(eta, grad) :param grad: tf tensor containing a batch of gradients :param eps: float scalar specifying size of constraint region :param ord: int specifying order of norm :returns: tf tensor containing optimal perturbation """ # Convert the iterator returned by `range` into a list. axis = list(range(1, len(grad.get_shape()))) avoid_zero_div = 1e-12 if ord == np.inf: # Take sign of gradient optimal_perturbation = tf.sign(grad) # The following line should not change the numerical results. It applies only because # `optimal_perturbation` is the output of a `sign` op, which has zero derivative anyway. # It should not be applied for the other norms, where the perturbation has a non-zero derivative. optimal_perturbation = tf.stop_gradient(optimal_perturbation) elif ord == 1: abs_grad = tf.abs(grad) sign = tf.sign(grad) max_abs_grad = tf.reduce_max(abs_grad, axis, keepdims=True) tied_for_max = tf.dtypes.cast(tf.equal(abs_grad, max_abs_grad), dtype=tf.float32) num_ties = tf.reduce_sum(tied_for_max, axis, keepdims=True) optimal_perturbation = sign * tied_for_max / num_ties elif ord == 2: square = tf.maximum(avoid_zero_div, tf.reduce_sum(tf.square(grad), axis, keepdims=True)) optimal_perturbation = grad / tf.sqrt(square) else: raise NotImplementedError("Only L-inf, L1 and L2 norms are currently implemented.") # Scale perturbation to be the solution for the norm=eps rather than norm=1 problem scaled_perturbation = tf.multiply(eps, optimal_perturbation) return scaled_perturbation
[ "def", "optimize_linear", "(", "grad", ",", "eps", ",", "ord", "=", "np", ".", "inf", ")", ":", "# Convert the iterator returned by `range` into a list.", "axis", "=", "list", "(", "range", "(", "1", ",", "len", "(", "grad", ".", "get_shape", "(", ")", ")", ")", ")", "avoid_zero_div", "=", "1e-12", "if", "ord", "==", "np", ".", "inf", ":", "# Take sign of gradient", "optimal_perturbation", "=", "tf", ".", "sign", "(", "grad", ")", "# The following line should not change the numerical results. It applies only because", "# `optimal_perturbation` is the output of a `sign` op, which has zero derivative anyway.", "# It should not be applied for the other norms, where the perturbation has a non-zero derivative.", "optimal_perturbation", "=", "tf", ".", "stop_gradient", "(", "optimal_perturbation", ")", "elif", "ord", "==", "1", ":", "abs_grad", "=", "tf", ".", "abs", "(", "grad", ")", "sign", "=", "tf", ".", "sign", "(", "grad", ")", "max_abs_grad", "=", "tf", ".", "reduce_max", "(", "abs_grad", ",", "axis", ",", "keepdims", "=", "True", ")", "tied_for_max", "=", "tf", ".", "dtypes", ".", "cast", "(", "tf", ".", "equal", "(", "abs_grad", ",", "max_abs_grad", ")", ",", "dtype", "=", "tf", ".", "float32", ")", "num_ties", "=", "tf", ".", "reduce_sum", "(", "tied_for_max", ",", "axis", ",", "keepdims", "=", "True", ")", "optimal_perturbation", "=", "sign", "*", "tied_for_max", "/", "num_ties", "elif", "ord", "==", "2", ":", "square", "=", "tf", ".", "maximum", "(", "avoid_zero_div", ",", "tf", ".", "reduce_sum", "(", "tf", ".", "square", "(", "grad", ")", ",", "axis", ",", "keepdims", "=", "True", ")", ")", "optimal_perturbation", "=", "grad", "/", "tf", ".", "sqrt", "(", "square", ")", "else", ":", "raise", "NotImplementedError", "(", "\"Only L-inf, L1 and L2 norms are currently implemented.\"", ")", "# Scale perturbation to be the solution for the norm=eps rather than norm=1 problem", "scaled_perturbation", "=", "tf", ".", "multiply", "(", "eps", ",", "optimal_perturbation", ")", "return", "scaled_perturbation" ]
Solves for the optimal input to a linear function under a norm constraint. Optimal_perturbation = argmax_{eta, ||eta||_{ord} < eps} dot(eta, grad) :param grad: tf tensor containing a batch of gradients :param eps: float scalar specifying size of constraint region :param ord: int specifying order of norm :returns: tf tensor containing optimal perturbation
[ "Solves", "for", "the", "optimal", "input", "to", "a", "linear", "function", "under", "a", "norm", "constraint", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/future/tf2/attacks/fast_gradient_method.py#L90-L128
train
tensorflow/cleverhans
cleverhans/plot/save_pdf.py
save_pdf
def save_pdf(path): """ Saves a pdf of the current matplotlib figure. :param path: str, filepath to save to """ pp = PdfPages(path) pp.savefig(pyplot.gcf()) pp.close()
python
def save_pdf(path): """ Saves a pdf of the current matplotlib figure. :param path: str, filepath to save to """ pp = PdfPages(path) pp.savefig(pyplot.gcf()) pp.close()
[ "def", "save_pdf", "(", "path", ")", ":", "pp", "=", "PdfPages", "(", "path", ")", "pp", ".", "savefig", "(", "pyplot", ".", "gcf", "(", ")", ")", "pp", ".", "close", "(", ")" ]
Saves a pdf of the current matplotlib figure. :param path: str, filepath to save to
[ "Saves", "a", "pdf", "of", "the", "current", "matplotlib", "figure", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/plot/save_pdf.py#L8-L17
train
tensorflow/cleverhans
cleverhans/future/tf2/utils_tf.py
clip_eta
def clip_eta(eta, ord, eps): """ Helper function to clip the perturbation to epsilon norm ball. :param eta: A tensor with the current perturbation. :param ord: Order of the norm (mimics Numpy). Possible values: np.inf, 1 or 2. :param eps: Epsilon, bound of the perturbation. """ # Clipping perturbation eta to self.ord norm ball if ord not in [np.inf, 1, 2]: raise ValueError('ord must be np.inf, 1, or 2.') axis = list(range(1, len(eta.get_shape()))) avoid_zero_div = 1e-12 if ord == np.inf: eta = tf.clip_by_value(eta, -eps, eps) else: if ord == 1: raise NotImplementedError("") # This is not the correct way to project on the L1 norm ball: # norm = tf.maximum(avoid_zero_div, reduce_sum(tf.abs(eta), reduc_ind, keepdims=True)) elif ord == 2: # avoid_zero_div must go inside sqrt to avoid a divide by zero in the gradient through this operation norm = tf.sqrt( tf.maximum(avoid_zero_div, tf.reduce_sum(tf.square(eta), axis, keepdims=True))) # We must *clip* to within the norm ball, not *normalize* onto the surface of the ball factor = tf.minimum(1., tf.math.divide(eps, norm)) eta = eta * factor return eta
python
def clip_eta(eta, ord, eps): """ Helper function to clip the perturbation to epsilon norm ball. :param eta: A tensor with the current perturbation. :param ord: Order of the norm (mimics Numpy). Possible values: np.inf, 1 or 2. :param eps: Epsilon, bound of the perturbation. """ # Clipping perturbation eta to self.ord norm ball if ord not in [np.inf, 1, 2]: raise ValueError('ord must be np.inf, 1, or 2.') axis = list(range(1, len(eta.get_shape()))) avoid_zero_div = 1e-12 if ord == np.inf: eta = tf.clip_by_value(eta, -eps, eps) else: if ord == 1: raise NotImplementedError("") # This is not the correct way to project on the L1 norm ball: # norm = tf.maximum(avoid_zero_div, reduce_sum(tf.abs(eta), reduc_ind, keepdims=True)) elif ord == 2: # avoid_zero_div must go inside sqrt to avoid a divide by zero in the gradient through this operation norm = tf.sqrt( tf.maximum(avoid_zero_div, tf.reduce_sum(tf.square(eta), axis, keepdims=True))) # We must *clip* to within the norm ball, not *normalize* onto the surface of the ball factor = tf.minimum(1., tf.math.divide(eps, norm)) eta = eta * factor return eta
[ "def", "clip_eta", "(", "eta", ",", "ord", ",", "eps", ")", ":", "# Clipping perturbation eta to self.ord norm ball", "if", "ord", "not", "in", "[", "np", ".", "inf", ",", "1", ",", "2", "]", ":", "raise", "ValueError", "(", "'ord must be np.inf, 1, or 2.'", ")", "axis", "=", "list", "(", "range", "(", "1", ",", "len", "(", "eta", ".", "get_shape", "(", ")", ")", ")", ")", "avoid_zero_div", "=", "1e-12", "if", "ord", "==", "np", ".", "inf", ":", "eta", "=", "tf", ".", "clip_by_value", "(", "eta", ",", "-", "eps", ",", "eps", ")", "else", ":", "if", "ord", "==", "1", ":", "raise", "NotImplementedError", "(", "\"\"", ")", "# This is not the correct way to project on the L1 norm ball:", "# norm = tf.maximum(avoid_zero_div, reduce_sum(tf.abs(eta), reduc_ind, keepdims=True))", "elif", "ord", "==", "2", ":", "# avoid_zero_div must go inside sqrt to avoid a divide by zero in the gradient through this operation", "norm", "=", "tf", ".", "sqrt", "(", "tf", ".", "maximum", "(", "avoid_zero_div", ",", "tf", ".", "reduce_sum", "(", "tf", ".", "square", "(", "eta", ")", ",", "axis", ",", "keepdims", "=", "True", ")", ")", ")", "# We must *clip* to within the norm ball, not *normalize* onto the surface of the ball", "factor", "=", "tf", ".", "minimum", "(", "1.", ",", "tf", ".", "math", ".", "divide", "(", "eps", ",", "norm", ")", ")", "eta", "=", "eta", "*", "factor", "return", "eta" ]
Helper function to clip the perturbation to epsilon norm ball. :param eta: A tensor with the current perturbation. :param ord: Order of the norm (mimics Numpy). Possible values: np.inf, 1 or 2. :param eps: Epsilon, bound of the perturbation.
[ "Helper", "function", "to", "clip", "the", "perturbation", "to", "epsilon", "norm", "ball", ".", ":", "param", "eta", ":", "A", "tensor", "with", "the", "current", "perturbation", ".", ":", "param", "ord", ":", "Order", "of", "the", "norm", "(", "mimics", "Numpy", ")", ".", "Possible", "values", ":", "np", ".", "inf", "1", "or", "2", ".", ":", "param", "eps", ":", "Epsilon", "bound", "of", "the", "perturbation", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/future/tf2/utils_tf.py#L5-L33
train
tensorflow/cleverhans
cleverhans_tutorials/mnist_blackbox.py
prep_bbox
def prep_bbox(sess, x, y, x_train, y_train, x_test, y_test, nb_epochs, batch_size, learning_rate, rng, nb_classes=10, img_rows=28, img_cols=28, nchannels=1): """ Define and train a model that simulates the "remote" black-box oracle described in the original paper. :param sess: the TF session :param x: the input placeholder for MNIST :param y: the ouput placeholder for MNIST :param x_train: the training data for the oracle :param y_train: the training labels for the oracle :param x_test: the testing data for the oracle :param y_test: the testing labels for the oracle :param nb_epochs: number of epochs to train model :param batch_size: size of training batches :param learning_rate: learning rate for training :param rng: numpy.random.RandomState :return: """ # Define TF model graph (for the black-box model) nb_filters = 64 model = ModelBasicCNN('model1', nb_classes, nb_filters) loss = CrossEntropy(model, smoothing=0.1) predictions = model.get_logits(x) print("Defined TensorFlow model graph.") # Train an MNIST model train_params = { 'nb_epochs': nb_epochs, 'batch_size': batch_size, 'learning_rate': learning_rate } train(sess, loss, x_train, y_train, args=train_params, rng=rng) # Print out the accuracy on legitimate data eval_params = {'batch_size': batch_size} accuracy = model_eval(sess, x, y, predictions, x_test, y_test, args=eval_params) print('Test accuracy of black-box on legitimate test ' 'examples: ' + str(accuracy)) return model, predictions, accuracy
python
def prep_bbox(sess, x, y, x_train, y_train, x_test, y_test, nb_epochs, batch_size, learning_rate, rng, nb_classes=10, img_rows=28, img_cols=28, nchannels=1): """ Define and train a model that simulates the "remote" black-box oracle described in the original paper. :param sess: the TF session :param x: the input placeholder for MNIST :param y: the ouput placeholder for MNIST :param x_train: the training data for the oracle :param y_train: the training labels for the oracle :param x_test: the testing data for the oracle :param y_test: the testing labels for the oracle :param nb_epochs: number of epochs to train model :param batch_size: size of training batches :param learning_rate: learning rate for training :param rng: numpy.random.RandomState :return: """ # Define TF model graph (for the black-box model) nb_filters = 64 model = ModelBasicCNN('model1', nb_classes, nb_filters) loss = CrossEntropy(model, smoothing=0.1) predictions = model.get_logits(x) print("Defined TensorFlow model graph.") # Train an MNIST model train_params = { 'nb_epochs': nb_epochs, 'batch_size': batch_size, 'learning_rate': learning_rate } train(sess, loss, x_train, y_train, args=train_params, rng=rng) # Print out the accuracy on legitimate data eval_params = {'batch_size': batch_size} accuracy = model_eval(sess, x, y, predictions, x_test, y_test, args=eval_params) print('Test accuracy of black-box on legitimate test ' 'examples: ' + str(accuracy)) return model, predictions, accuracy
[ "def", "prep_bbox", "(", "sess", ",", "x", ",", "y", ",", "x_train", ",", "y_train", ",", "x_test", ",", "y_test", ",", "nb_epochs", ",", "batch_size", ",", "learning_rate", ",", "rng", ",", "nb_classes", "=", "10", ",", "img_rows", "=", "28", ",", "img_cols", "=", "28", ",", "nchannels", "=", "1", ")", ":", "# Define TF model graph (for the black-box model)", "nb_filters", "=", "64", "model", "=", "ModelBasicCNN", "(", "'model1'", ",", "nb_classes", ",", "nb_filters", ")", "loss", "=", "CrossEntropy", "(", "model", ",", "smoothing", "=", "0.1", ")", "predictions", "=", "model", ".", "get_logits", "(", "x", ")", "print", "(", "\"Defined TensorFlow model graph.\"", ")", "# Train an MNIST model", "train_params", "=", "{", "'nb_epochs'", ":", "nb_epochs", ",", "'batch_size'", ":", "batch_size", ",", "'learning_rate'", ":", "learning_rate", "}", "train", "(", "sess", ",", "loss", ",", "x_train", ",", "y_train", ",", "args", "=", "train_params", ",", "rng", "=", "rng", ")", "# Print out the accuracy on legitimate data", "eval_params", "=", "{", "'batch_size'", ":", "batch_size", "}", "accuracy", "=", "model_eval", "(", "sess", ",", "x", ",", "y", ",", "predictions", ",", "x_test", ",", "y_test", ",", "args", "=", "eval_params", ")", "print", "(", "'Test accuracy of black-box on legitimate test '", "'examples: '", "+", "str", "(", "accuracy", ")", ")", "return", "model", ",", "predictions", ",", "accuracy" ]
Define and train a model that simulates the "remote" black-box oracle described in the original paper. :param sess: the TF session :param x: the input placeholder for MNIST :param y: the ouput placeholder for MNIST :param x_train: the training data for the oracle :param y_train: the training labels for the oracle :param x_test: the testing data for the oracle :param y_test: the testing labels for the oracle :param nb_epochs: number of epochs to train model :param batch_size: size of training batches :param learning_rate: learning rate for training :param rng: numpy.random.RandomState :return:
[ "Define", "and", "train", "a", "model", "that", "simulates", "the", "remote", "black", "-", "box", "oracle", "described", "in", "the", "original", "paper", ".", ":", "param", "sess", ":", "the", "TF", "session", ":", "param", "x", ":", "the", "input", "placeholder", "for", "MNIST", ":", "param", "y", ":", "the", "ouput", "placeholder", "for", "MNIST", ":", "param", "x_train", ":", "the", "training", "data", "for", "the", "oracle", ":", "param", "y_train", ":", "the", "training", "labels", "for", "the", "oracle", ":", "param", "x_test", ":", "the", "testing", "data", "for", "the", "oracle", ":", "param", "y_test", ":", "the", "testing", "labels", "for", "the", "oracle", ":", "param", "nb_epochs", ":", "number", "of", "epochs", "to", "train", "model", ":", "param", "batch_size", ":", "size", "of", "training", "batches", ":", "param", "learning_rate", ":", "learning", "rate", "for", "training", ":", "param", "rng", ":", "numpy", ".", "random", ".", "RandomState", ":", "return", ":" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans_tutorials/mnist_blackbox.py#L59-L101
train
tensorflow/cleverhans
cleverhans_tutorials/mnist_blackbox.py
train_sub
def train_sub(sess, x, y, bbox_preds, x_sub, y_sub, nb_classes, nb_epochs_s, batch_size, learning_rate, data_aug, lmbda, aug_batch_size, rng, img_rows=28, img_cols=28, nchannels=1): """ This function creates the substitute by alternatively augmenting the training data and training the substitute. :param sess: TF session :param x: input TF placeholder :param y: output TF placeholder :param bbox_preds: output of black-box model predictions :param x_sub: initial substitute training data :param y_sub: initial substitute training labels :param nb_classes: number of output classes :param nb_epochs_s: number of epochs to train substitute model :param batch_size: size of training batches :param learning_rate: learning rate for training :param data_aug: number of times substitute training data is augmented :param lmbda: lambda from arxiv.org/abs/1602.02697 :param rng: numpy.random.RandomState instance :return: """ # Define TF model graph (for the black-box model) model_sub = ModelSubstitute('model_s', nb_classes) preds_sub = model_sub.get_logits(x) loss_sub = CrossEntropy(model_sub, smoothing=0) print("Defined TensorFlow model graph for the substitute.") # Define the Jacobian symbolically using TensorFlow grads = jacobian_graph(preds_sub, x, nb_classes) # Train the substitute and augment dataset alternatively for rho in xrange(data_aug): print("Substitute training epoch #" + str(rho)) train_params = { 'nb_epochs': nb_epochs_s, 'batch_size': batch_size, 'learning_rate': learning_rate } with TemporaryLogLevel(logging.WARNING, "cleverhans.utils.tf"): train(sess, loss_sub, x_sub, to_categorical(y_sub, nb_classes), init_all=False, args=train_params, rng=rng, var_list=model_sub.get_params()) # If we are not at last substitute training iteration, augment dataset if rho < data_aug - 1: print("Augmenting substitute training data.") # Perform the Jacobian augmentation lmbda_coef = 2 * int(int(rho / 3) != 0) - 1 x_sub = jacobian_augmentation(sess, x, x_sub, y_sub, grads, lmbda_coef * lmbda, aug_batch_size) print("Labeling substitute training data.") # Label the newly generated synthetic points using the black-box y_sub = np.hstack([y_sub, y_sub]) x_sub_prev = x_sub[int(len(x_sub)/2):] eval_params = {'batch_size': batch_size} bbox_val = batch_eval(sess, [x], [bbox_preds], [x_sub_prev], args=eval_params)[0] # Note here that we take the argmax because the adversary # only has access to the label (not the probabilities) output # by the black-box model y_sub[int(len(x_sub)/2):] = np.argmax(bbox_val, axis=1) return model_sub, preds_sub
python
def train_sub(sess, x, y, bbox_preds, x_sub, y_sub, nb_classes, nb_epochs_s, batch_size, learning_rate, data_aug, lmbda, aug_batch_size, rng, img_rows=28, img_cols=28, nchannels=1): """ This function creates the substitute by alternatively augmenting the training data and training the substitute. :param sess: TF session :param x: input TF placeholder :param y: output TF placeholder :param bbox_preds: output of black-box model predictions :param x_sub: initial substitute training data :param y_sub: initial substitute training labels :param nb_classes: number of output classes :param nb_epochs_s: number of epochs to train substitute model :param batch_size: size of training batches :param learning_rate: learning rate for training :param data_aug: number of times substitute training data is augmented :param lmbda: lambda from arxiv.org/abs/1602.02697 :param rng: numpy.random.RandomState instance :return: """ # Define TF model graph (for the black-box model) model_sub = ModelSubstitute('model_s', nb_classes) preds_sub = model_sub.get_logits(x) loss_sub = CrossEntropy(model_sub, smoothing=0) print("Defined TensorFlow model graph for the substitute.") # Define the Jacobian symbolically using TensorFlow grads = jacobian_graph(preds_sub, x, nb_classes) # Train the substitute and augment dataset alternatively for rho in xrange(data_aug): print("Substitute training epoch #" + str(rho)) train_params = { 'nb_epochs': nb_epochs_s, 'batch_size': batch_size, 'learning_rate': learning_rate } with TemporaryLogLevel(logging.WARNING, "cleverhans.utils.tf"): train(sess, loss_sub, x_sub, to_categorical(y_sub, nb_classes), init_all=False, args=train_params, rng=rng, var_list=model_sub.get_params()) # If we are not at last substitute training iteration, augment dataset if rho < data_aug - 1: print("Augmenting substitute training data.") # Perform the Jacobian augmentation lmbda_coef = 2 * int(int(rho / 3) != 0) - 1 x_sub = jacobian_augmentation(sess, x, x_sub, y_sub, grads, lmbda_coef * lmbda, aug_batch_size) print("Labeling substitute training data.") # Label the newly generated synthetic points using the black-box y_sub = np.hstack([y_sub, y_sub]) x_sub_prev = x_sub[int(len(x_sub)/2):] eval_params = {'batch_size': batch_size} bbox_val = batch_eval(sess, [x], [bbox_preds], [x_sub_prev], args=eval_params)[0] # Note here that we take the argmax because the adversary # only has access to the label (not the probabilities) output # by the black-box model y_sub[int(len(x_sub)/2):] = np.argmax(bbox_val, axis=1) return model_sub, preds_sub
[ "def", "train_sub", "(", "sess", ",", "x", ",", "y", ",", "bbox_preds", ",", "x_sub", ",", "y_sub", ",", "nb_classes", ",", "nb_epochs_s", ",", "batch_size", ",", "learning_rate", ",", "data_aug", ",", "lmbda", ",", "aug_batch_size", ",", "rng", ",", "img_rows", "=", "28", ",", "img_cols", "=", "28", ",", "nchannels", "=", "1", ")", ":", "# Define TF model graph (for the black-box model)", "model_sub", "=", "ModelSubstitute", "(", "'model_s'", ",", "nb_classes", ")", "preds_sub", "=", "model_sub", ".", "get_logits", "(", "x", ")", "loss_sub", "=", "CrossEntropy", "(", "model_sub", ",", "smoothing", "=", "0", ")", "print", "(", "\"Defined TensorFlow model graph for the substitute.\"", ")", "# Define the Jacobian symbolically using TensorFlow", "grads", "=", "jacobian_graph", "(", "preds_sub", ",", "x", ",", "nb_classes", ")", "# Train the substitute and augment dataset alternatively", "for", "rho", "in", "xrange", "(", "data_aug", ")", ":", "print", "(", "\"Substitute training epoch #\"", "+", "str", "(", "rho", ")", ")", "train_params", "=", "{", "'nb_epochs'", ":", "nb_epochs_s", ",", "'batch_size'", ":", "batch_size", ",", "'learning_rate'", ":", "learning_rate", "}", "with", "TemporaryLogLevel", "(", "logging", ".", "WARNING", ",", "\"cleverhans.utils.tf\"", ")", ":", "train", "(", "sess", ",", "loss_sub", ",", "x_sub", ",", "to_categorical", "(", "y_sub", ",", "nb_classes", ")", ",", "init_all", "=", "False", ",", "args", "=", "train_params", ",", "rng", "=", "rng", ",", "var_list", "=", "model_sub", ".", "get_params", "(", ")", ")", "# If we are not at last substitute training iteration, augment dataset", "if", "rho", "<", "data_aug", "-", "1", ":", "print", "(", "\"Augmenting substitute training data.\"", ")", "# Perform the Jacobian augmentation", "lmbda_coef", "=", "2", "*", "int", "(", "int", "(", "rho", "/", "3", ")", "!=", "0", ")", "-", "1", "x_sub", "=", "jacobian_augmentation", "(", "sess", ",", "x", ",", "x_sub", ",", "y_sub", ",", "grads", ",", "lmbda_coef", "*", "lmbda", ",", "aug_batch_size", ")", "print", "(", "\"Labeling substitute training data.\"", ")", "# Label the newly generated synthetic points using the black-box", "y_sub", "=", "np", ".", "hstack", "(", "[", "y_sub", ",", "y_sub", "]", ")", "x_sub_prev", "=", "x_sub", "[", "int", "(", "len", "(", "x_sub", ")", "/", "2", ")", ":", "]", "eval_params", "=", "{", "'batch_size'", ":", "batch_size", "}", "bbox_val", "=", "batch_eval", "(", "sess", ",", "[", "x", "]", ",", "[", "bbox_preds", "]", ",", "[", "x_sub_prev", "]", ",", "args", "=", "eval_params", ")", "[", "0", "]", "# Note here that we take the argmax because the adversary", "# only has access to the label (not the probabilities) output", "# by the black-box model", "y_sub", "[", "int", "(", "len", "(", "x_sub", ")", "/", "2", ")", ":", "]", "=", "np", ".", "argmax", "(", "bbox_val", ",", "axis", "=", "1", ")", "return", "model_sub", ",", "preds_sub" ]
This function creates the substitute by alternatively augmenting the training data and training the substitute. :param sess: TF session :param x: input TF placeholder :param y: output TF placeholder :param bbox_preds: output of black-box model predictions :param x_sub: initial substitute training data :param y_sub: initial substitute training labels :param nb_classes: number of output classes :param nb_epochs_s: number of epochs to train substitute model :param batch_size: size of training batches :param learning_rate: learning rate for training :param data_aug: number of times substitute training data is augmented :param lmbda: lambda from arxiv.org/abs/1602.02697 :param rng: numpy.random.RandomState instance :return:
[ "This", "function", "creates", "the", "substitute", "by", "alternatively", "augmenting", "the", "training", "data", "and", "training", "the", "substitute", ".", ":", "param", "sess", ":", "TF", "session", ":", "param", "x", ":", "input", "TF", "placeholder", ":", "param", "y", ":", "output", "TF", "placeholder", ":", "param", "bbox_preds", ":", "output", "of", "black", "-", "box", "model", "predictions", ":", "param", "x_sub", ":", "initial", "substitute", "training", "data", ":", "param", "y_sub", ":", "initial", "substitute", "training", "labels", ":", "param", "nb_classes", ":", "number", "of", "output", "classes", ":", "param", "nb_epochs_s", ":", "number", "of", "epochs", "to", "train", "substitute", "model", ":", "param", "batch_size", ":", "size", "of", "training", "batches", ":", "param", "learning_rate", ":", "learning", "rate", "for", "training", ":", "param", "data_aug", ":", "number", "of", "times", "substitute", "training", "data", "is", "augmented", ":", "param", "lmbda", ":", "lambda", "from", "arxiv", ".", "org", "/", "abs", "/", "1602", ".", "02697", ":", "param", "rng", ":", "numpy", ".", "random", ".", "RandomState", "instance", ":", "return", ":" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans_tutorials/mnist_blackbox.py#L123-L188
train
tensorflow/cleverhans
cleverhans_tutorials/mnist_blackbox.py
mnist_blackbox
def mnist_blackbox(train_start=0, train_end=60000, test_start=0, test_end=10000, nb_classes=NB_CLASSES, batch_size=BATCH_SIZE, learning_rate=LEARNING_RATE, nb_epochs=NB_EPOCHS, holdout=HOLDOUT, data_aug=DATA_AUG, nb_epochs_s=NB_EPOCHS_S, lmbda=LMBDA, aug_batch_size=AUG_BATCH_SIZE): """ MNIST tutorial for the black-box attack from arxiv.org/abs/1602.02697 :param train_start: index of first training set example :param train_end: index of last training set example :param test_start: index of first test set example :param test_end: index of last test set example :return: a dictionary with: * black-box model accuracy on test set * substitute model accuracy on test set * black-box model accuracy on adversarial examples transferred from the substitute model """ # Set logging level to see debug information set_log_level(logging.DEBUG) # Dictionary used to keep track and return key accuracies accuracies = {} # Perform tutorial setup assert setup_tutorial() # Create TF session sess = tf.Session() # Get MNIST data mnist = MNIST(train_start=train_start, train_end=train_end, test_start=test_start, test_end=test_end) x_train, y_train = mnist.get_set('train') x_test, y_test = mnist.get_set('test') # Initialize substitute training set reserved for adversary x_sub = x_test[:holdout] y_sub = np.argmax(y_test[:holdout], axis=1) # Redefine test set as remaining samples unavailable to adversaries x_test = x_test[holdout:] y_test = y_test[holdout:] # Obtain Image parameters img_rows, img_cols, nchannels = x_train.shape[1:4] nb_classes = y_train.shape[1] # Define input TF placeholder x = tf.placeholder(tf.float32, shape=(None, img_rows, img_cols, nchannels)) y = tf.placeholder(tf.float32, shape=(None, nb_classes)) # Seed random number generator so tutorial is reproducible rng = np.random.RandomState([2017, 8, 30]) # Simulate the black-box model locally # You could replace this by a remote labeling API for instance print("Preparing the black-box model.") prep_bbox_out = prep_bbox(sess, x, y, x_train, y_train, x_test, y_test, nb_epochs, batch_size, learning_rate, rng, nb_classes, img_rows, img_cols, nchannels) model, bbox_preds, accuracies['bbox'] = prep_bbox_out # Train substitute using method from https://arxiv.org/abs/1602.02697 print("Training the substitute model.") train_sub_out = train_sub(sess, x, y, bbox_preds, x_sub, y_sub, nb_classes, nb_epochs_s, batch_size, learning_rate, data_aug, lmbda, aug_batch_size, rng, img_rows, img_cols, nchannels) model_sub, preds_sub = train_sub_out # Evaluate the substitute model on clean test examples eval_params = {'batch_size': batch_size} acc = model_eval(sess, x, y, preds_sub, x_test, y_test, args=eval_params) accuracies['sub'] = acc # Initialize the Fast Gradient Sign Method (FGSM) attack object. fgsm_par = {'eps': 0.3, 'ord': np.inf, 'clip_min': 0., 'clip_max': 1.} fgsm = FastGradientMethod(model_sub, sess=sess) # Craft adversarial examples using the substitute eval_params = {'batch_size': batch_size} x_adv_sub = fgsm.generate(x, **fgsm_par) # Evaluate the accuracy of the "black-box" model on adversarial examples accuracy = model_eval(sess, x, y, model.get_logits(x_adv_sub), x_test, y_test, args=eval_params) print('Test accuracy of oracle on adversarial examples generated ' 'using the substitute: ' + str(accuracy)) accuracies['bbox_on_sub_adv_ex'] = accuracy return accuracies
python
def mnist_blackbox(train_start=0, train_end=60000, test_start=0, test_end=10000, nb_classes=NB_CLASSES, batch_size=BATCH_SIZE, learning_rate=LEARNING_RATE, nb_epochs=NB_EPOCHS, holdout=HOLDOUT, data_aug=DATA_AUG, nb_epochs_s=NB_EPOCHS_S, lmbda=LMBDA, aug_batch_size=AUG_BATCH_SIZE): """ MNIST tutorial for the black-box attack from arxiv.org/abs/1602.02697 :param train_start: index of first training set example :param train_end: index of last training set example :param test_start: index of first test set example :param test_end: index of last test set example :return: a dictionary with: * black-box model accuracy on test set * substitute model accuracy on test set * black-box model accuracy on adversarial examples transferred from the substitute model """ # Set logging level to see debug information set_log_level(logging.DEBUG) # Dictionary used to keep track and return key accuracies accuracies = {} # Perform tutorial setup assert setup_tutorial() # Create TF session sess = tf.Session() # Get MNIST data mnist = MNIST(train_start=train_start, train_end=train_end, test_start=test_start, test_end=test_end) x_train, y_train = mnist.get_set('train') x_test, y_test = mnist.get_set('test') # Initialize substitute training set reserved for adversary x_sub = x_test[:holdout] y_sub = np.argmax(y_test[:holdout], axis=1) # Redefine test set as remaining samples unavailable to adversaries x_test = x_test[holdout:] y_test = y_test[holdout:] # Obtain Image parameters img_rows, img_cols, nchannels = x_train.shape[1:4] nb_classes = y_train.shape[1] # Define input TF placeholder x = tf.placeholder(tf.float32, shape=(None, img_rows, img_cols, nchannels)) y = tf.placeholder(tf.float32, shape=(None, nb_classes)) # Seed random number generator so tutorial is reproducible rng = np.random.RandomState([2017, 8, 30]) # Simulate the black-box model locally # You could replace this by a remote labeling API for instance print("Preparing the black-box model.") prep_bbox_out = prep_bbox(sess, x, y, x_train, y_train, x_test, y_test, nb_epochs, batch_size, learning_rate, rng, nb_classes, img_rows, img_cols, nchannels) model, bbox_preds, accuracies['bbox'] = prep_bbox_out # Train substitute using method from https://arxiv.org/abs/1602.02697 print("Training the substitute model.") train_sub_out = train_sub(sess, x, y, bbox_preds, x_sub, y_sub, nb_classes, nb_epochs_s, batch_size, learning_rate, data_aug, lmbda, aug_batch_size, rng, img_rows, img_cols, nchannels) model_sub, preds_sub = train_sub_out # Evaluate the substitute model on clean test examples eval_params = {'batch_size': batch_size} acc = model_eval(sess, x, y, preds_sub, x_test, y_test, args=eval_params) accuracies['sub'] = acc # Initialize the Fast Gradient Sign Method (FGSM) attack object. fgsm_par = {'eps': 0.3, 'ord': np.inf, 'clip_min': 0., 'clip_max': 1.} fgsm = FastGradientMethod(model_sub, sess=sess) # Craft adversarial examples using the substitute eval_params = {'batch_size': batch_size} x_adv_sub = fgsm.generate(x, **fgsm_par) # Evaluate the accuracy of the "black-box" model on adversarial examples accuracy = model_eval(sess, x, y, model.get_logits(x_adv_sub), x_test, y_test, args=eval_params) print('Test accuracy of oracle on adversarial examples generated ' 'using the substitute: ' + str(accuracy)) accuracies['bbox_on_sub_adv_ex'] = accuracy return accuracies
[ "def", "mnist_blackbox", "(", "train_start", "=", "0", ",", "train_end", "=", "60000", ",", "test_start", "=", "0", ",", "test_end", "=", "10000", ",", "nb_classes", "=", "NB_CLASSES", ",", "batch_size", "=", "BATCH_SIZE", ",", "learning_rate", "=", "LEARNING_RATE", ",", "nb_epochs", "=", "NB_EPOCHS", ",", "holdout", "=", "HOLDOUT", ",", "data_aug", "=", "DATA_AUG", ",", "nb_epochs_s", "=", "NB_EPOCHS_S", ",", "lmbda", "=", "LMBDA", ",", "aug_batch_size", "=", "AUG_BATCH_SIZE", ")", ":", "# Set logging level to see debug information", "set_log_level", "(", "logging", ".", "DEBUG", ")", "# Dictionary used to keep track and return key accuracies", "accuracies", "=", "{", "}", "# Perform tutorial setup", "assert", "setup_tutorial", "(", ")", "# Create TF session", "sess", "=", "tf", ".", "Session", "(", ")", "# Get MNIST data", "mnist", "=", "MNIST", "(", "train_start", "=", "train_start", ",", "train_end", "=", "train_end", ",", "test_start", "=", "test_start", ",", "test_end", "=", "test_end", ")", "x_train", ",", "y_train", "=", "mnist", ".", "get_set", "(", "'train'", ")", "x_test", ",", "y_test", "=", "mnist", ".", "get_set", "(", "'test'", ")", "# Initialize substitute training set reserved for adversary", "x_sub", "=", "x_test", "[", ":", "holdout", "]", "y_sub", "=", "np", ".", "argmax", "(", "y_test", "[", ":", "holdout", "]", ",", "axis", "=", "1", ")", "# Redefine test set as remaining samples unavailable to adversaries", "x_test", "=", "x_test", "[", "holdout", ":", "]", "y_test", "=", "y_test", "[", "holdout", ":", "]", "# Obtain Image parameters", "img_rows", ",", "img_cols", ",", "nchannels", "=", "x_train", ".", "shape", "[", "1", ":", "4", "]", "nb_classes", "=", "y_train", ".", "shape", "[", "1", "]", "# Define input TF placeholder", "x", "=", "tf", ".", "placeholder", "(", "tf", ".", "float32", ",", "shape", "=", "(", "None", ",", "img_rows", ",", "img_cols", ",", "nchannels", ")", ")", "y", "=", "tf", ".", "placeholder", "(", "tf", ".", "float32", ",", "shape", "=", "(", "None", ",", "nb_classes", ")", ")", "# Seed random number generator so tutorial is reproducible", "rng", "=", "np", ".", "random", ".", "RandomState", "(", "[", "2017", ",", "8", ",", "30", "]", ")", "# Simulate the black-box model locally", "# You could replace this by a remote labeling API for instance", "print", "(", "\"Preparing the black-box model.\"", ")", "prep_bbox_out", "=", "prep_bbox", "(", "sess", ",", "x", ",", "y", ",", "x_train", ",", "y_train", ",", "x_test", ",", "y_test", ",", "nb_epochs", ",", "batch_size", ",", "learning_rate", ",", "rng", ",", "nb_classes", ",", "img_rows", ",", "img_cols", ",", "nchannels", ")", "model", ",", "bbox_preds", ",", "accuracies", "[", "'bbox'", "]", "=", "prep_bbox_out", "# Train substitute using method from https://arxiv.org/abs/1602.02697", "print", "(", "\"Training the substitute model.\"", ")", "train_sub_out", "=", "train_sub", "(", "sess", ",", "x", ",", "y", ",", "bbox_preds", ",", "x_sub", ",", "y_sub", ",", "nb_classes", ",", "nb_epochs_s", ",", "batch_size", ",", "learning_rate", ",", "data_aug", ",", "lmbda", ",", "aug_batch_size", ",", "rng", ",", "img_rows", ",", "img_cols", ",", "nchannels", ")", "model_sub", ",", "preds_sub", "=", "train_sub_out", "# Evaluate the substitute model on clean test examples", "eval_params", "=", "{", "'batch_size'", ":", "batch_size", "}", "acc", "=", "model_eval", "(", "sess", ",", "x", ",", "y", ",", "preds_sub", ",", "x_test", ",", "y_test", ",", "args", "=", "eval_params", ")", "accuracies", "[", "'sub'", "]", "=", "acc", "# Initialize the Fast Gradient Sign Method (FGSM) attack object.", "fgsm_par", "=", "{", "'eps'", ":", "0.3", ",", "'ord'", ":", "np", ".", "inf", ",", "'clip_min'", ":", "0.", ",", "'clip_max'", ":", "1.", "}", "fgsm", "=", "FastGradientMethod", "(", "model_sub", ",", "sess", "=", "sess", ")", "# Craft adversarial examples using the substitute", "eval_params", "=", "{", "'batch_size'", ":", "batch_size", "}", "x_adv_sub", "=", "fgsm", ".", "generate", "(", "x", ",", "*", "*", "fgsm_par", ")", "# Evaluate the accuracy of the \"black-box\" model on adversarial examples", "accuracy", "=", "model_eval", "(", "sess", ",", "x", ",", "y", ",", "model", ".", "get_logits", "(", "x_adv_sub", ")", ",", "x_test", ",", "y_test", ",", "args", "=", "eval_params", ")", "print", "(", "'Test accuracy of oracle on adversarial examples generated '", "'using the substitute: '", "+", "str", "(", "accuracy", ")", ")", "accuracies", "[", "'bbox_on_sub_adv_ex'", "]", "=", "accuracy", "return", "accuracies" ]
MNIST tutorial for the black-box attack from arxiv.org/abs/1602.02697 :param train_start: index of first training set example :param train_end: index of last training set example :param test_start: index of first test set example :param test_end: index of last test set example :return: a dictionary with: * black-box model accuracy on test set * substitute model accuracy on test set * black-box model accuracy on adversarial examples transferred from the substitute model
[ "MNIST", "tutorial", "for", "the", "black", "-", "box", "attack", "from", "arxiv", ".", "org", "/", "abs", "/", "1602", ".", "02697", ":", "param", "train_start", ":", "index", "of", "first", "training", "set", "example", ":", "param", "train_end", ":", "index", "of", "last", "training", "set", "example", ":", "param", "test_start", ":", "index", "of", "first", "test", "set", "example", ":", "param", "test_end", ":", "index", "of", "last", "test", "set", "example", ":", "return", ":", "a", "dictionary", "with", ":", "*", "black", "-", "box", "model", "accuracy", "on", "test", "set", "*", "substitute", "model", "accuracy", "on", "test", "set", "*", "black", "-", "box", "model", "accuracy", "on", "adversarial", "examples", "transferred", "from", "the", "substitute", "model" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans_tutorials/mnist_blackbox.py#L191-L284
train
tensorflow/cleverhans
cleverhans/augmentation.py
random_shift
def random_shift(x, pad=(4, 4), mode='REFLECT'): """Pad a single image and then crop to the original size with a random offset.""" assert mode in 'REFLECT SYMMETRIC CONSTANT'.split() assert x.get_shape().ndims == 3 xp = tf.pad(x, [[pad[0], pad[0]], [pad[1], pad[1]], [0, 0]], mode) return tf.random_crop(xp, tf.shape(x))
python
def random_shift(x, pad=(4, 4), mode='REFLECT'): """Pad a single image and then crop to the original size with a random offset.""" assert mode in 'REFLECT SYMMETRIC CONSTANT'.split() assert x.get_shape().ndims == 3 xp = tf.pad(x, [[pad[0], pad[0]], [pad[1], pad[1]], [0, 0]], mode) return tf.random_crop(xp, tf.shape(x))
[ "def", "random_shift", "(", "x", ",", "pad", "=", "(", "4", ",", "4", ")", ",", "mode", "=", "'REFLECT'", ")", ":", "assert", "mode", "in", "'REFLECT SYMMETRIC CONSTANT'", ".", "split", "(", ")", "assert", "x", ".", "get_shape", "(", ")", ".", "ndims", "==", "3", "xp", "=", "tf", ".", "pad", "(", "x", ",", "[", "[", "pad", "[", "0", "]", ",", "pad", "[", "0", "]", "]", ",", "[", "pad", "[", "1", "]", ",", "pad", "[", "1", "]", "]", ",", "[", "0", ",", "0", "]", "]", ",", "mode", ")", "return", "tf", ".", "random_crop", "(", "xp", ",", "tf", ".", "shape", "(", "x", ")", ")" ]
Pad a single image and then crop to the original size with a random offset.
[ "Pad", "a", "single", "image", "and", "then", "crop", "to", "the", "original", "size", "with", "a", "random", "offset", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/augmentation.py#L19-L25
train
tensorflow/cleverhans
cleverhans/augmentation.py
batch_augment
def batch_augment(x, func, device='/CPU:0'): """ Apply dataset augmentation to a batch of exmaples. :param x: Tensor representing a batch of examples. :param func: Callable implementing dataset augmentation, operating on a single image. :param device: String specifying which device to use. """ with tf.device(device): return tf.map_fn(func, x)
python
def batch_augment(x, func, device='/CPU:0'): """ Apply dataset augmentation to a batch of exmaples. :param x: Tensor representing a batch of examples. :param func: Callable implementing dataset augmentation, operating on a single image. :param device: String specifying which device to use. """ with tf.device(device): return tf.map_fn(func, x)
[ "def", "batch_augment", "(", "x", ",", "func", ",", "device", "=", "'/CPU:0'", ")", ":", "with", "tf", ".", "device", "(", "device", ")", ":", "return", "tf", ".", "map_fn", "(", "func", ",", "x", ")" ]
Apply dataset augmentation to a batch of exmaples. :param x: Tensor representing a batch of examples. :param func: Callable implementing dataset augmentation, operating on a single image. :param device: String specifying which device to use.
[ "Apply", "dataset", "augmentation", "to", "a", "batch", "of", "exmaples", ".", ":", "param", "x", ":", "Tensor", "representing", "a", "batch", "of", "examples", ".", ":", "param", "func", ":", "Callable", "implementing", "dataset", "augmentation", "operating", "on", "a", "single", "image", ".", ":", "param", "device", ":", "String", "specifying", "which", "device", "to", "use", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/augmentation.py#L28-L37
train
tensorflow/cleverhans
cleverhans/augmentation.py
random_crop_and_flip
def random_crop_and_flip(x, pad_rows=4, pad_cols=4): """Augment a batch by randomly cropping and horizontally flipping it.""" rows = tf.shape(x)[1] cols = tf.shape(x)[2] channels = x.get_shape()[3] def _rand_crop_img(img): """Randomly crop an individual image""" return tf.random_crop(img, [rows, cols, channels]) # Some of these ops are only on CPU. # This function will often be called with the device set to GPU. # We need to set it to CPU temporarily to avoid an exception. with tf.device('/CPU:0'): x = tf.image.resize_image_with_crop_or_pad(x, rows + pad_rows, cols + pad_cols) x = tf.map_fn(_rand_crop_img, x) x = tf.image.random_flip_left_right(x) return x
python
def random_crop_and_flip(x, pad_rows=4, pad_cols=4): """Augment a batch by randomly cropping and horizontally flipping it.""" rows = tf.shape(x)[1] cols = tf.shape(x)[2] channels = x.get_shape()[3] def _rand_crop_img(img): """Randomly crop an individual image""" return tf.random_crop(img, [rows, cols, channels]) # Some of these ops are only on CPU. # This function will often be called with the device set to GPU. # We need to set it to CPU temporarily to avoid an exception. with tf.device('/CPU:0'): x = tf.image.resize_image_with_crop_or_pad(x, rows + pad_rows, cols + pad_cols) x = tf.map_fn(_rand_crop_img, x) x = tf.image.random_flip_left_right(x) return x
[ "def", "random_crop_and_flip", "(", "x", ",", "pad_rows", "=", "4", ",", "pad_cols", "=", "4", ")", ":", "rows", "=", "tf", ".", "shape", "(", "x", ")", "[", "1", "]", "cols", "=", "tf", ".", "shape", "(", "x", ")", "[", "2", "]", "channels", "=", "x", ".", "get_shape", "(", ")", "[", "3", "]", "def", "_rand_crop_img", "(", "img", ")", ":", "\"\"\"Randomly crop an individual image\"\"\"", "return", "tf", ".", "random_crop", "(", "img", ",", "[", "rows", ",", "cols", ",", "channels", "]", ")", "# Some of these ops are only on CPU.", "# This function will often be called with the device set to GPU.", "# We need to set it to CPU temporarily to avoid an exception.", "with", "tf", ".", "device", "(", "'/CPU:0'", ")", ":", "x", "=", "tf", ".", "image", ".", "resize_image_with_crop_or_pad", "(", "x", ",", "rows", "+", "pad_rows", ",", "cols", "+", "pad_cols", ")", "x", "=", "tf", ".", "map_fn", "(", "_rand_crop_img", ",", "x", ")", "x", "=", "tf", ".", "image", ".", "random_flip_left_right", "(", "x", ")", "return", "x" ]
Augment a batch by randomly cropping and horizontally flipping it.
[ "Augment", "a", "batch", "by", "randomly", "cropping", "and", "horizontally", "flipping", "it", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/augmentation.py#L40-L58
train
tensorflow/cleverhans
cleverhans_tutorials/mnist_tutorial_picklable.py
mnist_tutorial
def mnist_tutorial(train_start=0, train_end=60000, test_start=0, test_end=10000, nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE, learning_rate=LEARNING_RATE, clean_train=CLEAN_TRAIN, testing=False, backprop_through_attack=BACKPROP_THROUGH_ATTACK, nb_filters=NB_FILTERS, num_threads=None, label_smoothing=0.1): """ MNIST cleverhans tutorial :param train_start: index of first training set example :param train_end: index of last training set example :param test_start: index of first test set example :param test_end: index of last test set example :param nb_epochs: number of epochs to train model :param batch_size: size of training batches :param learning_rate: learning rate for training :param clean_train: perform normal training on clean examples only before performing adversarial training. :param testing: if true, complete an AccuracyReport for unit tests to verify that performance is adequate :param backprop_through_attack: If True, backprop through adversarial example construction process during adversarial training. :param label_smoothing: float, amount of label smoothing for cross entropy :return: an AccuracyReport object """ # Object used to keep track of (and return) key accuracies report = AccuracyReport() # Set TF random seed to improve reproducibility tf.set_random_seed(1234) # Set logging level to see debug information set_log_level(logging.DEBUG) # Create TF session if num_threads: config_args = dict(intra_op_parallelism_threads=1) else: config_args = {} sess = tf.Session(config=tf.ConfigProto(**config_args)) # Get MNIST test data mnist = MNIST(train_start=train_start, train_end=train_end, test_start=test_start, test_end=test_end) x_train, y_train = mnist.get_set('train') x_test, y_test = mnist.get_set('test') # Use Image Parameters img_rows, img_cols, nchannels = x_train.shape[1:4] nb_classes = y_train.shape[1] # Define input TF placeholder x = tf.placeholder(tf.float32, shape=(None, img_rows, img_cols, nchannels)) y = tf.placeholder(tf.float32, shape=(None, nb_classes)) # Train an MNIST model train_params = { 'nb_epochs': nb_epochs, 'batch_size': batch_size, 'learning_rate': learning_rate } eval_params = {'batch_size': batch_size} fgsm_params = { 'eps': 0.3, 'clip_min': 0., 'clip_max': 1. } rng = np.random.RandomState([2017, 8, 30]) def do_eval(preds, x_set, y_set, report_key, is_adv=None): """ Run the evaluation and print the results. """ acc = model_eval(sess, x, y, preds, x_set, y_set, args=eval_params) setattr(report, report_key, acc) if is_adv is None: report_text = None elif is_adv: report_text = 'adversarial' else: report_text = 'legitimate' if report_text: print('Test accuracy on %s examples: %0.4f' % (report_text, acc)) if clean_train: model = make_basic_picklable_cnn() # Tag the model so that when it is saved to disk, future scripts will # be able to tell what data it was trained on model.dataset_factory = mnist.get_factory() preds = model.get_logits(x) assert len(model.get_params()) > 0 loss = CrossEntropy(model, smoothing=label_smoothing) def evaluate(): """ Run evaluation for the naively trained model on clean examples. """ do_eval(preds, x_test, y_test, 'clean_train_clean_eval', False) train(sess, loss, x_train, y_train, evaluate=evaluate, args=train_params, rng=rng, var_list=model.get_params()) with sess.as_default(): save("clean_model.joblib", model) print("Now that the model has been saved, you can evaluate it in a" " separate process using `evaluate_pickled_model.py`. " "You should get exactly the same result for both clean and " "adversarial accuracy as you get within this program.") # Calculate training error if testing: do_eval(preds, x_train, y_train, 'train_clean_train_clean_eval') # Initialize the Fast Gradient Sign Method (FGSM) attack object and # graph fgsm = FastGradientMethod(model, sess=sess) adv_x = fgsm.generate(x, **fgsm_params) preds_adv = model.get_logits(adv_x) # Evaluate the accuracy of the MNIST model on adversarial examples do_eval(preds_adv, x_test, y_test, 'clean_train_adv_eval', True) # Calculate training error if testing: do_eval(preds_adv, x_train, y_train, 'train_clean_train_adv_eval') print('Repeating the process, using adversarial training') # Create a new model and train it to be robust to FastGradientMethod model2 = make_basic_picklable_cnn() # Tag the model so that when it is saved to disk, future scripts will # be able to tell what data it was trained on model2.dataset_factory = mnist.get_factory() fgsm2 = FastGradientMethod(model2, sess=sess) def attack(x): """Return an adversarial example near clean example `x`""" return fgsm2.generate(x, **fgsm_params) loss2 = CrossEntropy(model2, smoothing=label_smoothing, attack=attack) preds2 = model2.get_logits(x) adv_x2 = attack(x) if not backprop_through_attack: # For the fgsm attack used in this tutorial, the attack has zero # gradient so enabling this flag does not change the gradient. # For some other attacks, enabling this flag increases the cost of # training, but gives the defender the ability to anticipate how # the atacker will change their strategy in response to updates to # the defender's parameters. adv_x2 = tf.stop_gradient(adv_x2) preds2_adv = model2.get_logits(adv_x2) def evaluate_adv(): """ Evaluate the adversarially trained model. """ # Accuracy of adversarially trained model on legitimate test inputs do_eval(preds2, x_test, y_test, 'adv_train_clean_eval', False) # Accuracy of the adversarially trained model on adversarial examples do_eval(preds2_adv, x_test, y_test, 'adv_train_adv_eval', True) # Perform and evaluate adversarial training train(sess, loss2, x_train, y_train, evaluate=evaluate_adv, args=train_params, rng=rng, var_list=model2.get_params()) with sess.as_default(): save("adv_model.joblib", model2) print("Now that the model has been saved, you can evaluate it in a " "separate process using " "`python evaluate_pickled_model.py adv_model.joblib`. " "You should get exactly the same result for both clean and " "adversarial accuracy as you get within this program." " You can also move beyond the tutorials directory and run the " " real `compute_accuracy.py` script (make sure cleverhans/scripts " "is in your PATH) to see that this FGSM-trained " "model is actually not very robust---it's just a model that trains " " quickly so the tutorial does not take a long time") # Calculate training errors if testing: do_eval(preds2, x_train, y_train, 'train_adv_train_clean_eval') do_eval(preds2_adv, x_train, y_train, 'train_adv_train_adv_eval') return report
python
def mnist_tutorial(train_start=0, train_end=60000, test_start=0, test_end=10000, nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE, learning_rate=LEARNING_RATE, clean_train=CLEAN_TRAIN, testing=False, backprop_through_attack=BACKPROP_THROUGH_ATTACK, nb_filters=NB_FILTERS, num_threads=None, label_smoothing=0.1): """ MNIST cleverhans tutorial :param train_start: index of first training set example :param train_end: index of last training set example :param test_start: index of first test set example :param test_end: index of last test set example :param nb_epochs: number of epochs to train model :param batch_size: size of training batches :param learning_rate: learning rate for training :param clean_train: perform normal training on clean examples only before performing adversarial training. :param testing: if true, complete an AccuracyReport for unit tests to verify that performance is adequate :param backprop_through_attack: If True, backprop through adversarial example construction process during adversarial training. :param label_smoothing: float, amount of label smoothing for cross entropy :return: an AccuracyReport object """ # Object used to keep track of (and return) key accuracies report = AccuracyReport() # Set TF random seed to improve reproducibility tf.set_random_seed(1234) # Set logging level to see debug information set_log_level(logging.DEBUG) # Create TF session if num_threads: config_args = dict(intra_op_parallelism_threads=1) else: config_args = {} sess = tf.Session(config=tf.ConfigProto(**config_args)) # Get MNIST test data mnist = MNIST(train_start=train_start, train_end=train_end, test_start=test_start, test_end=test_end) x_train, y_train = mnist.get_set('train') x_test, y_test = mnist.get_set('test') # Use Image Parameters img_rows, img_cols, nchannels = x_train.shape[1:4] nb_classes = y_train.shape[1] # Define input TF placeholder x = tf.placeholder(tf.float32, shape=(None, img_rows, img_cols, nchannels)) y = tf.placeholder(tf.float32, shape=(None, nb_classes)) # Train an MNIST model train_params = { 'nb_epochs': nb_epochs, 'batch_size': batch_size, 'learning_rate': learning_rate } eval_params = {'batch_size': batch_size} fgsm_params = { 'eps': 0.3, 'clip_min': 0., 'clip_max': 1. } rng = np.random.RandomState([2017, 8, 30]) def do_eval(preds, x_set, y_set, report_key, is_adv=None): """ Run the evaluation and print the results. """ acc = model_eval(sess, x, y, preds, x_set, y_set, args=eval_params) setattr(report, report_key, acc) if is_adv is None: report_text = None elif is_adv: report_text = 'adversarial' else: report_text = 'legitimate' if report_text: print('Test accuracy on %s examples: %0.4f' % (report_text, acc)) if clean_train: model = make_basic_picklable_cnn() # Tag the model so that when it is saved to disk, future scripts will # be able to tell what data it was trained on model.dataset_factory = mnist.get_factory() preds = model.get_logits(x) assert len(model.get_params()) > 0 loss = CrossEntropy(model, smoothing=label_smoothing) def evaluate(): """ Run evaluation for the naively trained model on clean examples. """ do_eval(preds, x_test, y_test, 'clean_train_clean_eval', False) train(sess, loss, x_train, y_train, evaluate=evaluate, args=train_params, rng=rng, var_list=model.get_params()) with sess.as_default(): save("clean_model.joblib", model) print("Now that the model has been saved, you can evaluate it in a" " separate process using `evaluate_pickled_model.py`. " "You should get exactly the same result for both clean and " "adversarial accuracy as you get within this program.") # Calculate training error if testing: do_eval(preds, x_train, y_train, 'train_clean_train_clean_eval') # Initialize the Fast Gradient Sign Method (FGSM) attack object and # graph fgsm = FastGradientMethod(model, sess=sess) adv_x = fgsm.generate(x, **fgsm_params) preds_adv = model.get_logits(adv_x) # Evaluate the accuracy of the MNIST model on adversarial examples do_eval(preds_adv, x_test, y_test, 'clean_train_adv_eval', True) # Calculate training error if testing: do_eval(preds_adv, x_train, y_train, 'train_clean_train_adv_eval') print('Repeating the process, using adversarial training') # Create a new model and train it to be robust to FastGradientMethod model2 = make_basic_picklable_cnn() # Tag the model so that when it is saved to disk, future scripts will # be able to tell what data it was trained on model2.dataset_factory = mnist.get_factory() fgsm2 = FastGradientMethod(model2, sess=sess) def attack(x): """Return an adversarial example near clean example `x`""" return fgsm2.generate(x, **fgsm_params) loss2 = CrossEntropy(model2, smoothing=label_smoothing, attack=attack) preds2 = model2.get_logits(x) adv_x2 = attack(x) if not backprop_through_attack: # For the fgsm attack used in this tutorial, the attack has zero # gradient so enabling this flag does not change the gradient. # For some other attacks, enabling this flag increases the cost of # training, but gives the defender the ability to anticipate how # the atacker will change their strategy in response to updates to # the defender's parameters. adv_x2 = tf.stop_gradient(adv_x2) preds2_adv = model2.get_logits(adv_x2) def evaluate_adv(): """ Evaluate the adversarially trained model. """ # Accuracy of adversarially trained model on legitimate test inputs do_eval(preds2, x_test, y_test, 'adv_train_clean_eval', False) # Accuracy of the adversarially trained model on adversarial examples do_eval(preds2_adv, x_test, y_test, 'adv_train_adv_eval', True) # Perform and evaluate adversarial training train(sess, loss2, x_train, y_train, evaluate=evaluate_adv, args=train_params, rng=rng, var_list=model2.get_params()) with sess.as_default(): save("adv_model.joblib", model2) print("Now that the model has been saved, you can evaluate it in a " "separate process using " "`python evaluate_pickled_model.py adv_model.joblib`. " "You should get exactly the same result for both clean and " "adversarial accuracy as you get within this program." " You can also move beyond the tutorials directory and run the " " real `compute_accuracy.py` script (make sure cleverhans/scripts " "is in your PATH) to see that this FGSM-trained " "model is actually not very robust---it's just a model that trains " " quickly so the tutorial does not take a long time") # Calculate training errors if testing: do_eval(preds2, x_train, y_train, 'train_adv_train_clean_eval') do_eval(preds2_adv, x_train, y_train, 'train_adv_train_adv_eval') return report
[ "def", "mnist_tutorial", "(", "train_start", "=", "0", ",", "train_end", "=", "60000", ",", "test_start", "=", "0", ",", "test_end", "=", "10000", ",", "nb_epochs", "=", "NB_EPOCHS", ",", "batch_size", "=", "BATCH_SIZE", ",", "learning_rate", "=", "LEARNING_RATE", ",", "clean_train", "=", "CLEAN_TRAIN", ",", "testing", "=", "False", ",", "backprop_through_attack", "=", "BACKPROP_THROUGH_ATTACK", ",", "nb_filters", "=", "NB_FILTERS", ",", "num_threads", "=", "None", ",", "label_smoothing", "=", "0.1", ")", ":", "# Object used to keep track of (and return) key accuracies", "report", "=", "AccuracyReport", "(", ")", "# Set TF random seed to improve reproducibility", "tf", ".", "set_random_seed", "(", "1234", ")", "# Set logging level to see debug information", "set_log_level", "(", "logging", ".", "DEBUG", ")", "# Create TF session", "if", "num_threads", ":", "config_args", "=", "dict", "(", "intra_op_parallelism_threads", "=", "1", ")", "else", ":", "config_args", "=", "{", "}", "sess", "=", "tf", ".", "Session", "(", "config", "=", "tf", ".", "ConfigProto", "(", "*", "*", "config_args", ")", ")", "# Get MNIST test data", "mnist", "=", "MNIST", "(", "train_start", "=", "train_start", ",", "train_end", "=", "train_end", ",", "test_start", "=", "test_start", ",", "test_end", "=", "test_end", ")", "x_train", ",", "y_train", "=", "mnist", ".", "get_set", "(", "'train'", ")", "x_test", ",", "y_test", "=", "mnist", ".", "get_set", "(", "'test'", ")", "# Use Image Parameters", "img_rows", ",", "img_cols", ",", "nchannels", "=", "x_train", ".", "shape", "[", "1", ":", "4", "]", "nb_classes", "=", "y_train", ".", "shape", "[", "1", "]", "# Define input TF placeholder", "x", "=", "tf", ".", "placeholder", "(", "tf", ".", "float32", ",", "shape", "=", "(", "None", ",", "img_rows", ",", "img_cols", ",", "nchannels", ")", ")", "y", "=", "tf", ".", "placeholder", "(", "tf", ".", "float32", ",", "shape", "=", "(", "None", ",", "nb_classes", ")", ")", "# Train an MNIST model", "train_params", "=", "{", "'nb_epochs'", ":", "nb_epochs", ",", "'batch_size'", ":", "batch_size", ",", "'learning_rate'", ":", "learning_rate", "}", "eval_params", "=", "{", "'batch_size'", ":", "batch_size", "}", "fgsm_params", "=", "{", "'eps'", ":", "0.3", ",", "'clip_min'", ":", "0.", ",", "'clip_max'", ":", "1.", "}", "rng", "=", "np", ".", "random", ".", "RandomState", "(", "[", "2017", ",", "8", ",", "30", "]", ")", "def", "do_eval", "(", "preds", ",", "x_set", ",", "y_set", ",", "report_key", ",", "is_adv", "=", "None", ")", ":", "\"\"\"\n Run the evaluation and print the results.\n \"\"\"", "acc", "=", "model_eval", "(", "sess", ",", "x", ",", "y", ",", "preds", ",", "x_set", ",", "y_set", ",", "args", "=", "eval_params", ")", "setattr", "(", "report", ",", "report_key", ",", "acc", ")", "if", "is_adv", "is", "None", ":", "report_text", "=", "None", "elif", "is_adv", ":", "report_text", "=", "'adversarial'", "else", ":", "report_text", "=", "'legitimate'", "if", "report_text", ":", "print", "(", "'Test accuracy on %s examples: %0.4f'", "%", "(", "report_text", ",", "acc", ")", ")", "if", "clean_train", ":", "model", "=", "make_basic_picklable_cnn", "(", ")", "# Tag the model so that when it is saved to disk, future scripts will", "# be able to tell what data it was trained on", "model", ".", "dataset_factory", "=", "mnist", ".", "get_factory", "(", ")", "preds", "=", "model", ".", "get_logits", "(", "x", ")", "assert", "len", "(", "model", ".", "get_params", "(", ")", ")", ">", "0", "loss", "=", "CrossEntropy", "(", "model", ",", "smoothing", "=", "label_smoothing", ")", "def", "evaluate", "(", ")", ":", "\"\"\"\n Run evaluation for the naively trained model on clean examples.\n \"\"\"", "do_eval", "(", "preds", ",", "x_test", ",", "y_test", ",", "'clean_train_clean_eval'", ",", "False", ")", "train", "(", "sess", ",", "loss", ",", "x_train", ",", "y_train", ",", "evaluate", "=", "evaluate", ",", "args", "=", "train_params", ",", "rng", "=", "rng", ",", "var_list", "=", "model", ".", "get_params", "(", ")", ")", "with", "sess", ".", "as_default", "(", ")", ":", "save", "(", "\"clean_model.joblib\"", ",", "model", ")", "print", "(", "\"Now that the model has been saved, you can evaluate it in a\"", "\" separate process using `evaluate_pickled_model.py`. \"", "\"You should get exactly the same result for both clean and \"", "\"adversarial accuracy as you get within this program.\"", ")", "# Calculate training error", "if", "testing", ":", "do_eval", "(", "preds", ",", "x_train", ",", "y_train", ",", "'train_clean_train_clean_eval'", ")", "# Initialize the Fast Gradient Sign Method (FGSM) attack object and", "# graph", "fgsm", "=", "FastGradientMethod", "(", "model", ",", "sess", "=", "sess", ")", "adv_x", "=", "fgsm", ".", "generate", "(", "x", ",", "*", "*", "fgsm_params", ")", "preds_adv", "=", "model", ".", "get_logits", "(", "adv_x", ")", "# Evaluate the accuracy of the MNIST model on adversarial examples", "do_eval", "(", "preds_adv", ",", "x_test", ",", "y_test", ",", "'clean_train_adv_eval'", ",", "True", ")", "# Calculate training error", "if", "testing", ":", "do_eval", "(", "preds_adv", ",", "x_train", ",", "y_train", ",", "'train_clean_train_adv_eval'", ")", "print", "(", "'Repeating the process, using adversarial training'", ")", "# Create a new model and train it to be robust to FastGradientMethod", "model2", "=", "make_basic_picklable_cnn", "(", ")", "# Tag the model so that when it is saved to disk, future scripts will", "# be able to tell what data it was trained on", "model2", ".", "dataset_factory", "=", "mnist", ".", "get_factory", "(", ")", "fgsm2", "=", "FastGradientMethod", "(", "model2", ",", "sess", "=", "sess", ")", "def", "attack", "(", "x", ")", ":", "\"\"\"Return an adversarial example near clean example `x`\"\"\"", "return", "fgsm2", ".", "generate", "(", "x", ",", "*", "*", "fgsm_params", ")", "loss2", "=", "CrossEntropy", "(", "model2", ",", "smoothing", "=", "label_smoothing", ",", "attack", "=", "attack", ")", "preds2", "=", "model2", ".", "get_logits", "(", "x", ")", "adv_x2", "=", "attack", "(", "x", ")", "if", "not", "backprop_through_attack", ":", "# For the fgsm attack used in this tutorial, the attack has zero", "# gradient so enabling this flag does not change the gradient.", "# For some other attacks, enabling this flag increases the cost of", "# training, but gives the defender the ability to anticipate how", "# the atacker will change their strategy in response to updates to", "# the defender's parameters.", "adv_x2", "=", "tf", ".", "stop_gradient", "(", "adv_x2", ")", "preds2_adv", "=", "model2", ".", "get_logits", "(", "adv_x2", ")", "def", "evaluate_adv", "(", ")", ":", "\"\"\"\n Evaluate the adversarially trained model.\n \"\"\"", "# Accuracy of adversarially trained model on legitimate test inputs", "do_eval", "(", "preds2", ",", "x_test", ",", "y_test", ",", "'adv_train_clean_eval'", ",", "False", ")", "# Accuracy of the adversarially trained model on adversarial examples", "do_eval", "(", "preds2_adv", ",", "x_test", ",", "y_test", ",", "'adv_train_adv_eval'", ",", "True", ")", "# Perform and evaluate adversarial training", "train", "(", "sess", ",", "loss2", ",", "x_train", ",", "y_train", ",", "evaluate", "=", "evaluate_adv", ",", "args", "=", "train_params", ",", "rng", "=", "rng", ",", "var_list", "=", "model2", ".", "get_params", "(", ")", ")", "with", "sess", ".", "as_default", "(", ")", ":", "save", "(", "\"adv_model.joblib\"", ",", "model2", ")", "print", "(", "\"Now that the model has been saved, you can evaluate it in a \"", "\"separate process using \"", "\"`python evaluate_pickled_model.py adv_model.joblib`. \"", "\"You should get exactly the same result for both clean and \"", "\"adversarial accuracy as you get within this program.\"", "\" You can also move beyond the tutorials directory and run the \"", "\" real `compute_accuracy.py` script (make sure cleverhans/scripts \"", "\"is in your PATH) to see that this FGSM-trained \"", "\"model is actually not very robust---it's just a model that trains \"", "\" quickly so the tutorial does not take a long time\"", ")", "# Calculate training errors", "if", "testing", ":", "do_eval", "(", "preds2", ",", "x_train", ",", "y_train", ",", "'train_adv_train_clean_eval'", ")", "do_eval", "(", "preds2_adv", ",", "x_train", ",", "y_train", ",", "'train_adv_train_adv_eval'", ")", "return", "report" ]
MNIST cleverhans tutorial :param train_start: index of first training set example :param train_end: index of last training set example :param test_start: index of first test set example :param test_end: index of last test set example :param nb_epochs: number of epochs to train model :param batch_size: size of training batches :param learning_rate: learning rate for training :param clean_train: perform normal training on clean examples only before performing adversarial training. :param testing: if true, complete an AccuracyReport for unit tests to verify that performance is adequate :param backprop_through_attack: If True, backprop through adversarial example construction process during adversarial training. :param label_smoothing: float, amount of label smoothing for cross entropy :return: an AccuracyReport object
[ "MNIST", "cleverhans", "tutorial", ":", "param", "train_start", ":", "index", "of", "first", "training", "set", "example", ":", "param", "train_end", ":", "index", "of", "last", "training", "set", "example", ":", "param", "test_start", ":", "index", "of", "first", "test", "set", "example", ":", "param", "test_end", ":", "index", "of", "last", "test", "set", "example", ":", "param", "nb_epochs", ":", "number", "of", "epochs", "to", "train", "model", ":", "param", "batch_size", ":", "size", "of", "training", "batches", ":", "param", "learning_rate", ":", "learning", "rate", "for", "training", ":", "param", "clean_train", ":", "perform", "normal", "training", "on", "clean", "examples", "only", "before", "performing", "adversarial", "training", ".", ":", "param", "testing", ":", "if", "true", "complete", "an", "AccuracyReport", "for", "unit", "tests", "to", "verify", "that", "performance", "is", "adequate", ":", "param", "backprop_through_attack", ":", "If", "True", "backprop", "through", "adversarial", "example", "construction", "process", "during", "adversarial", "training", ".", ":", "param", "label_smoothing", ":", "float", "amount", "of", "label", "smoothing", "for", "cross", "entropy", ":", "return", ":", "an", "AccuracyReport", "object" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans_tutorials/mnist_tutorial_picklable.py#L36-L226
train
tensorflow/cleverhans
cleverhans/attacks/spsa.py
_project_perturbation
def _project_perturbation(perturbation, epsilon, input_image, clip_min=None, clip_max=None): """Project `perturbation` onto L-infinity ball of radius `epsilon`. Also project into hypercube such that the resulting adversarial example is between clip_min and clip_max, if applicable. """ if clip_min is None or clip_max is None: raise NotImplementedError("_project_perturbation currently has clipping " "hard-coded in.") # Ensure inputs are in the correct range with tf.control_dependencies([ utils_tf.assert_less_equal(input_image, tf.cast(clip_max, input_image.dtype)), utils_tf.assert_greater_equal(input_image, tf.cast(clip_min, input_image.dtype)) ]): clipped_perturbation = utils_tf.clip_by_value( perturbation, -epsilon, epsilon) new_image = utils_tf.clip_by_value( input_image + clipped_perturbation, clip_min, clip_max) return new_image - input_image
python
def _project_perturbation(perturbation, epsilon, input_image, clip_min=None, clip_max=None): """Project `perturbation` onto L-infinity ball of radius `epsilon`. Also project into hypercube such that the resulting adversarial example is between clip_min and clip_max, if applicable. """ if clip_min is None or clip_max is None: raise NotImplementedError("_project_perturbation currently has clipping " "hard-coded in.") # Ensure inputs are in the correct range with tf.control_dependencies([ utils_tf.assert_less_equal(input_image, tf.cast(clip_max, input_image.dtype)), utils_tf.assert_greater_equal(input_image, tf.cast(clip_min, input_image.dtype)) ]): clipped_perturbation = utils_tf.clip_by_value( perturbation, -epsilon, epsilon) new_image = utils_tf.clip_by_value( input_image + clipped_perturbation, clip_min, clip_max) return new_image - input_image
[ "def", "_project_perturbation", "(", "perturbation", ",", "epsilon", ",", "input_image", ",", "clip_min", "=", "None", ",", "clip_max", "=", "None", ")", ":", "if", "clip_min", "is", "None", "or", "clip_max", "is", "None", ":", "raise", "NotImplementedError", "(", "\"_project_perturbation currently has clipping \"", "\"hard-coded in.\"", ")", "# Ensure inputs are in the correct range", "with", "tf", ".", "control_dependencies", "(", "[", "utils_tf", ".", "assert_less_equal", "(", "input_image", ",", "tf", ".", "cast", "(", "clip_max", ",", "input_image", ".", "dtype", ")", ")", ",", "utils_tf", ".", "assert_greater_equal", "(", "input_image", ",", "tf", ".", "cast", "(", "clip_min", ",", "input_image", ".", "dtype", ")", ")", "]", ")", ":", "clipped_perturbation", "=", "utils_tf", ".", "clip_by_value", "(", "perturbation", ",", "-", "epsilon", ",", "epsilon", ")", "new_image", "=", "utils_tf", ".", "clip_by_value", "(", "input_image", "+", "clipped_perturbation", ",", "clip_min", ",", "clip_max", ")", "return", "new_image", "-", "input_image" ]
Project `perturbation` onto L-infinity ball of radius `epsilon`. Also project into hypercube such that the resulting adversarial example is between clip_min and clip_max, if applicable.
[ "Project", "perturbation", "onto", "L", "-", "infinity", "ball", "of", "radius", "epsilon", ".", "Also", "project", "into", "hypercube", "such", "that", "the", "resulting", "adversarial", "example", "is", "between", "clip_min", "and", "clip_max", "if", "applicable", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/spsa.py#L209-L231
train
tensorflow/cleverhans
cleverhans/attacks/spsa.py
margin_logit_loss
def margin_logit_loss(model_logits, label, nb_classes=10, num_classes=None): """Computes difference between logit for `label` and next highest logit. The loss is high when `label` is unlikely (targeted by default). This follows the same interface as `loss_fn` for TensorOptimizer and projected_optimization, i.e. it returns a batch of loss values. """ if num_classes is not None: warnings.warn("`num_classes` is depreciated. Switch to `nb_classes`." " `num_classes` may be removed on or after 2019-04-23.") nb_classes = num_classes del num_classes if 'int' in str(label.dtype): logit_mask = tf.one_hot(label, depth=nb_classes, axis=-1) else: logit_mask = label if 'int' in str(logit_mask.dtype): logit_mask = tf.to_float(logit_mask) try: label_logits = reduce_sum(logit_mask * model_logits, axis=-1) except TypeError: raise TypeError("Could not take row-wise dot product between " "logit mask, of dtype " + str(logit_mask.dtype) + " and model_logits, of dtype " + str(model_logits.dtype)) logits_with_target_label_neg_inf = model_logits - logit_mask * 99999 highest_nonlabel_logits = reduce_max( logits_with_target_label_neg_inf, axis=-1) loss = highest_nonlabel_logits - label_logits return loss
python
def margin_logit_loss(model_logits, label, nb_classes=10, num_classes=None): """Computes difference between logit for `label` and next highest logit. The loss is high when `label` is unlikely (targeted by default). This follows the same interface as `loss_fn` for TensorOptimizer and projected_optimization, i.e. it returns a batch of loss values. """ if num_classes is not None: warnings.warn("`num_classes` is depreciated. Switch to `nb_classes`." " `num_classes` may be removed on or after 2019-04-23.") nb_classes = num_classes del num_classes if 'int' in str(label.dtype): logit_mask = tf.one_hot(label, depth=nb_classes, axis=-1) else: logit_mask = label if 'int' in str(logit_mask.dtype): logit_mask = tf.to_float(logit_mask) try: label_logits = reduce_sum(logit_mask * model_logits, axis=-1) except TypeError: raise TypeError("Could not take row-wise dot product between " "logit mask, of dtype " + str(logit_mask.dtype) + " and model_logits, of dtype " + str(model_logits.dtype)) logits_with_target_label_neg_inf = model_logits - logit_mask * 99999 highest_nonlabel_logits = reduce_max( logits_with_target_label_neg_inf, axis=-1) loss = highest_nonlabel_logits - label_logits return loss
[ "def", "margin_logit_loss", "(", "model_logits", ",", "label", ",", "nb_classes", "=", "10", ",", "num_classes", "=", "None", ")", ":", "if", "num_classes", "is", "not", "None", ":", "warnings", ".", "warn", "(", "\"`num_classes` is depreciated. Switch to `nb_classes`.\"", "\" `num_classes` may be removed on or after 2019-04-23.\"", ")", "nb_classes", "=", "num_classes", "del", "num_classes", "if", "'int'", "in", "str", "(", "label", ".", "dtype", ")", ":", "logit_mask", "=", "tf", ".", "one_hot", "(", "label", ",", "depth", "=", "nb_classes", ",", "axis", "=", "-", "1", ")", "else", ":", "logit_mask", "=", "label", "if", "'int'", "in", "str", "(", "logit_mask", ".", "dtype", ")", ":", "logit_mask", "=", "tf", ".", "to_float", "(", "logit_mask", ")", "try", ":", "label_logits", "=", "reduce_sum", "(", "logit_mask", "*", "model_logits", ",", "axis", "=", "-", "1", ")", "except", "TypeError", ":", "raise", "TypeError", "(", "\"Could not take row-wise dot product between \"", "\"logit mask, of dtype \"", "+", "str", "(", "logit_mask", ".", "dtype", ")", "+", "\" and model_logits, of dtype \"", "+", "str", "(", "model_logits", ".", "dtype", ")", ")", "logits_with_target_label_neg_inf", "=", "model_logits", "-", "logit_mask", "*", "99999", "highest_nonlabel_logits", "=", "reduce_max", "(", "logits_with_target_label_neg_inf", ",", "axis", "=", "-", "1", ")", "loss", "=", "highest_nonlabel_logits", "-", "label_logits", "return", "loss" ]
Computes difference between logit for `label` and next highest logit. The loss is high when `label` is unlikely (targeted by default). This follows the same interface as `loss_fn` for TensorOptimizer and projected_optimization, i.e. it returns a batch of loss values.
[ "Computes", "difference", "between", "logit", "for", "label", "and", "next", "highest", "logit", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/spsa.py#L444-L473
train
tensorflow/cleverhans
cleverhans/attacks/spsa.py
spm
def spm(x, model, y=None, n_samples=None, dx_min=-0.1, dx_max=0.1, n_dxs=5, dy_min=-0.1, dy_max=0.1, n_dys=5, angle_min=-30, angle_max=30, n_angles=31, black_border_size=0): """ TensorFlow implementation of the Spatial Transformation Method. :return: a tensor for the adversarial example """ if y is None: preds = model.get_probs(x) # Using model predictions as ground truth to avoid label leaking preds_max = reduce_max(preds, 1, keepdims=True) y = tf.to_float(tf.equal(preds, preds_max)) y = tf.stop_gradient(y) del preds y = y / reduce_sum(y, 1, keepdims=True) # Define the range of transformations dxs = np.linspace(dx_min, dx_max, n_dxs) dys = np.linspace(dy_min, dy_max, n_dys) angles = np.linspace(angle_min, angle_max, n_angles) if n_samples is None: import itertools transforms = list(itertools.product(*[dxs, dys, angles])) else: sampled_dxs = np.random.choice(dxs, n_samples) sampled_dys = np.random.choice(dys, n_samples) sampled_angles = np.random.choice(angles, n_samples) transforms = zip(sampled_dxs, sampled_dys, sampled_angles) transformed_ims = parallel_apply_transformations( x, transforms, black_border_size) def _compute_xent(x): preds = model.get_logits(x) return tf.nn.softmax_cross_entropy_with_logits_v2( labels=y, logits=preds) all_xents = tf.map_fn( _compute_xent, transformed_ims, parallel_iterations=1) # Must be 1 to avoid keras race conditions # Return the adv_x with worst accuracy # all_xents is n_total_samples x batch_size (SB) all_xents = tf.stack(all_xents) # SB # We want the worst case sample, with the largest xent_loss worst_sample_idx = tf.argmax(all_xents, axis=0) # B batch_size = tf.shape(x)[0] keys = tf.stack([ tf.range(batch_size, dtype=tf.int32), tf.cast(worst_sample_idx, tf.int32) ], axis=1) transformed_ims_bshwc = tf.einsum('sbhwc->bshwc', transformed_ims) after_lookup = tf.gather_nd(transformed_ims_bshwc, keys) # BHWC return after_lookup
python
def spm(x, model, y=None, n_samples=None, dx_min=-0.1, dx_max=0.1, n_dxs=5, dy_min=-0.1, dy_max=0.1, n_dys=5, angle_min=-30, angle_max=30, n_angles=31, black_border_size=0): """ TensorFlow implementation of the Spatial Transformation Method. :return: a tensor for the adversarial example """ if y is None: preds = model.get_probs(x) # Using model predictions as ground truth to avoid label leaking preds_max = reduce_max(preds, 1, keepdims=True) y = tf.to_float(tf.equal(preds, preds_max)) y = tf.stop_gradient(y) del preds y = y / reduce_sum(y, 1, keepdims=True) # Define the range of transformations dxs = np.linspace(dx_min, dx_max, n_dxs) dys = np.linspace(dy_min, dy_max, n_dys) angles = np.linspace(angle_min, angle_max, n_angles) if n_samples is None: import itertools transforms = list(itertools.product(*[dxs, dys, angles])) else: sampled_dxs = np.random.choice(dxs, n_samples) sampled_dys = np.random.choice(dys, n_samples) sampled_angles = np.random.choice(angles, n_samples) transforms = zip(sampled_dxs, sampled_dys, sampled_angles) transformed_ims = parallel_apply_transformations( x, transforms, black_border_size) def _compute_xent(x): preds = model.get_logits(x) return tf.nn.softmax_cross_entropy_with_logits_v2( labels=y, logits=preds) all_xents = tf.map_fn( _compute_xent, transformed_ims, parallel_iterations=1) # Must be 1 to avoid keras race conditions # Return the adv_x with worst accuracy # all_xents is n_total_samples x batch_size (SB) all_xents = tf.stack(all_xents) # SB # We want the worst case sample, with the largest xent_loss worst_sample_idx = tf.argmax(all_xents, axis=0) # B batch_size = tf.shape(x)[0] keys = tf.stack([ tf.range(batch_size, dtype=tf.int32), tf.cast(worst_sample_idx, tf.int32) ], axis=1) transformed_ims_bshwc = tf.einsum('sbhwc->bshwc', transformed_ims) after_lookup = tf.gather_nd(transformed_ims_bshwc, keys) # BHWC return after_lookup
[ "def", "spm", "(", "x", ",", "model", ",", "y", "=", "None", ",", "n_samples", "=", "None", ",", "dx_min", "=", "-", "0.1", ",", "dx_max", "=", "0.1", ",", "n_dxs", "=", "5", ",", "dy_min", "=", "-", "0.1", ",", "dy_max", "=", "0.1", ",", "n_dys", "=", "5", ",", "angle_min", "=", "-", "30", ",", "angle_max", "=", "30", ",", "n_angles", "=", "31", ",", "black_border_size", "=", "0", ")", ":", "if", "y", "is", "None", ":", "preds", "=", "model", ".", "get_probs", "(", "x", ")", "# Using model predictions as ground truth to avoid label leaking", "preds_max", "=", "reduce_max", "(", "preds", ",", "1", ",", "keepdims", "=", "True", ")", "y", "=", "tf", ".", "to_float", "(", "tf", ".", "equal", "(", "preds", ",", "preds_max", ")", ")", "y", "=", "tf", ".", "stop_gradient", "(", "y", ")", "del", "preds", "y", "=", "y", "/", "reduce_sum", "(", "y", ",", "1", ",", "keepdims", "=", "True", ")", "# Define the range of transformations", "dxs", "=", "np", ".", "linspace", "(", "dx_min", ",", "dx_max", ",", "n_dxs", ")", "dys", "=", "np", ".", "linspace", "(", "dy_min", ",", "dy_max", ",", "n_dys", ")", "angles", "=", "np", ".", "linspace", "(", "angle_min", ",", "angle_max", ",", "n_angles", ")", "if", "n_samples", "is", "None", ":", "import", "itertools", "transforms", "=", "list", "(", "itertools", ".", "product", "(", "*", "[", "dxs", ",", "dys", ",", "angles", "]", ")", ")", "else", ":", "sampled_dxs", "=", "np", ".", "random", ".", "choice", "(", "dxs", ",", "n_samples", ")", "sampled_dys", "=", "np", ".", "random", ".", "choice", "(", "dys", ",", "n_samples", ")", "sampled_angles", "=", "np", ".", "random", ".", "choice", "(", "angles", ",", "n_samples", ")", "transforms", "=", "zip", "(", "sampled_dxs", ",", "sampled_dys", ",", "sampled_angles", ")", "transformed_ims", "=", "parallel_apply_transformations", "(", "x", ",", "transforms", ",", "black_border_size", ")", "def", "_compute_xent", "(", "x", ")", ":", "preds", "=", "model", ".", "get_logits", "(", "x", ")", "return", "tf", ".", "nn", ".", "softmax_cross_entropy_with_logits_v2", "(", "labels", "=", "y", ",", "logits", "=", "preds", ")", "all_xents", "=", "tf", ".", "map_fn", "(", "_compute_xent", ",", "transformed_ims", ",", "parallel_iterations", "=", "1", ")", "# Must be 1 to avoid keras race conditions", "# Return the adv_x with worst accuracy", "# all_xents is n_total_samples x batch_size (SB)", "all_xents", "=", "tf", ".", "stack", "(", "all_xents", ")", "# SB", "# We want the worst case sample, with the largest xent_loss", "worst_sample_idx", "=", "tf", ".", "argmax", "(", "all_xents", ",", "axis", "=", "0", ")", "# B", "batch_size", "=", "tf", ".", "shape", "(", "x", ")", "[", "0", "]", "keys", "=", "tf", ".", "stack", "(", "[", "tf", ".", "range", "(", "batch_size", ",", "dtype", "=", "tf", ".", "int32", ")", ",", "tf", ".", "cast", "(", "worst_sample_idx", ",", "tf", ".", "int32", ")", "]", ",", "axis", "=", "1", ")", "transformed_ims_bshwc", "=", "tf", ".", "einsum", "(", "'sbhwc->bshwc'", ",", "transformed_ims", ")", "after_lookup", "=", "tf", ".", "gather_nd", "(", "transformed_ims_bshwc", ",", "keys", ")", "# BHWC", "return", "after_lookup" ]
TensorFlow implementation of the Spatial Transformation Method. :return: a tensor for the adversarial example
[ "TensorFlow", "implementation", "of", "the", "Spatial", "Transformation", "Method", ".", ":", "return", ":", "a", "tensor", "for", "the", "adversarial", "example" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/spsa.py#L524-L581
train
tensorflow/cleverhans
cleverhans/attacks/spsa.py
parallel_apply_transformations
def parallel_apply_transformations(x, transforms, black_border_size=0): """ Apply image transformations in parallel. :param transforms: TODO :param black_border_size: int, size of black border to apply Returns: Transformed images """ transforms = tf.convert_to_tensor(transforms, dtype=tf.float32) x = _apply_black_border(x, black_border_size) num_transforms = transforms.get_shape().as_list()[0] im_shape = x.get_shape().as_list()[1:] # Pass a copy of x and a transformation to each iteration of the map_fn # callable tiled_x = tf.reshape( tf.tile(x, [num_transforms, 1, 1, 1]), [num_transforms, -1] + im_shape) elems = [tiled_x, transforms] transformed_ims = tf.map_fn( _apply_transformation, elems, dtype=tf.float32, parallel_iterations=1, # Must be 1 to avoid keras race conditions ) return transformed_ims
python
def parallel_apply_transformations(x, transforms, black_border_size=0): """ Apply image transformations in parallel. :param transforms: TODO :param black_border_size: int, size of black border to apply Returns: Transformed images """ transforms = tf.convert_to_tensor(transforms, dtype=tf.float32) x = _apply_black_border(x, black_border_size) num_transforms = transforms.get_shape().as_list()[0] im_shape = x.get_shape().as_list()[1:] # Pass a copy of x and a transformation to each iteration of the map_fn # callable tiled_x = tf.reshape( tf.tile(x, [num_transforms, 1, 1, 1]), [num_transforms, -1] + im_shape) elems = [tiled_x, transforms] transformed_ims = tf.map_fn( _apply_transformation, elems, dtype=tf.float32, parallel_iterations=1, # Must be 1 to avoid keras race conditions ) return transformed_ims
[ "def", "parallel_apply_transformations", "(", "x", ",", "transforms", ",", "black_border_size", "=", "0", ")", ":", "transforms", "=", "tf", ".", "convert_to_tensor", "(", "transforms", ",", "dtype", "=", "tf", ".", "float32", ")", "x", "=", "_apply_black_border", "(", "x", ",", "black_border_size", ")", "num_transforms", "=", "transforms", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "[", "0", "]", "im_shape", "=", "x", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "[", "1", ":", "]", "# Pass a copy of x and a transformation to each iteration of the map_fn", "# callable", "tiled_x", "=", "tf", ".", "reshape", "(", "tf", ".", "tile", "(", "x", ",", "[", "num_transforms", ",", "1", ",", "1", ",", "1", "]", ")", ",", "[", "num_transforms", ",", "-", "1", "]", "+", "im_shape", ")", "elems", "=", "[", "tiled_x", ",", "transforms", "]", "transformed_ims", "=", "tf", ".", "map_fn", "(", "_apply_transformation", ",", "elems", ",", "dtype", "=", "tf", ".", "float32", ",", "parallel_iterations", "=", "1", ",", "# Must be 1 to avoid keras race conditions", ")", "return", "transformed_ims" ]
Apply image transformations in parallel. :param transforms: TODO :param black_border_size: int, size of black border to apply Returns: Transformed images
[ "Apply", "image", "transformations", "in", "parallel", ".", ":", "param", "transforms", ":", "TODO", ":", "param", "black_border_size", ":", "int", "size", "of", "black", "border", "to", "apply", "Returns", ":", "Transformed", "images" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/spsa.py#L584-L610
train
tensorflow/cleverhans
cleverhans/attacks/spsa.py
projected_optimization
def projected_optimization(loss_fn, input_image, label, epsilon, num_steps, clip_min=None, clip_max=None, optimizer=TensorAdam(), project_perturbation=_project_perturbation, early_stop_loss_threshold=None, is_debug=False): """Generic projected optimization, generalized to work with approximate gradients. Used for e.g. the SPSA attack. Args: :param loss_fn: A callable which takes `input_image` and `label` as arguments, and returns a batch of loss values. Same interface as TensorOptimizer. :param input_image: Tensor, a batch of images :param label: Tensor, a batch of labels :param epsilon: float, the L-infinity norm of the maximum allowable perturbation :param num_steps: int, the number of steps of gradient descent :param clip_min: float, minimum pixel value :param clip_max: float, maximum pixel value :param optimizer: A `TensorOptimizer` object :param project_perturbation: A function, which will be used to enforce some constraint. It should have the same signature as `_project_perturbation`. :param early_stop_loss_threshold: A float or None. If specified, the attack will end if the loss is below `early_stop_loss_threshold`. Enabling this option can have several different effects: - Setting the threshold to 0. guarantees that if a successful attack is found, it is returned. This increases the attack success rate, because without early stopping the optimizer can accidentally bounce back to a point where the attack fails. - Early stopping can make the attack run faster because it may run for fewer steps. - Early stopping can make the attack run slower because the loss must be calculated at each step. The loss is not calculated as part of the normal SPSA optimization procedure. For most reasonable choices of hyperparameters, early stopping makes the attack much faster because it decreases the number of steps dramatically. :param is_debug: A bool. If True, print debug info for attack progress. Returns: adversarial version of `input_image`, with L-infinity difference less than epsilon, which tries to minimize loss_fn. Note that this function is not intended as an Attack by itself. Rather, it is designed as a helper function which you can use to write your own attack methods. The method uses a tf.while_loop to optimize a loss function in a single sess.run() call. """ assert num_steps is not None if is_debug: with tf.device("/cpu:0"): input_image = tf.Print( input_image, [], "Starting PGD attack with epsilon: %s" % epsilon) init_perturbation = tf.random_uniform( tf.shape(input_image), minval=tf.cast(-epsilon, input_image.dtype), maxval=tf.cast(epsilon, input_image.dtype), dtype=input_image.dtype) init_perturbation = project_perturbation(init_perturbation, epsilon, input_image, clip_min=clip_min, clip_max=clip_max) init_optim_state = optimizer.init_state([init_perturbation]) nest = tf.contrib.framework.nest def loop_body(i, perturbation, flat_optim_state): """Update perturbation to input image.""" optim_state = nest.pack_sequence_as( structure=init_optim_state, flat_sequence=flat_optim_state) def wrapped_loss_fn(x): return loss_fn(input_image + x, label) new_perturbation_list, new_optim_state = optimizer.minimize( wrapped_loss_fn, [perturbation], optim_state) projected_perturbation = project_perturbation(new_perturbation_list[0], epsilon, input_image, clip_min=clip_min, clip_max=clip_max) # Be careful with this bool. A value of 0. is a valid threshold but evaluates to False, so we must explicitly # check whether the value is None. early_stop = early_stop_loss_threshold is not None compute_loss = is_debug or early_stop # Don't waste time building the loss graph if we're not going to use it if compute_loss: # NOTE: this step is not actually redundant with the optimizer step. # SPSA calculates the loss at randomly perturbed points but doesn't calculate the loss at the current point. loss = reduce_mean(wrapped_loss_fn(projected_perturbation), axis=0) if is_debug: with tf.device("/cpu:0"): loss = tf.Print(loss, [loss], "Total batch loss") if early_stop: i = tf.cond(tf.less(loss, early_stop_loss_threshold), lambda: float(num_steps), lambda: i) return i + 1, projected_perturbation, nest.flatten(new_optim_state) def cond(i, *_): return tf.less(i, num_steps) flat_init_optim_state = nest.flatten(init_optim_state) _, final_perturbation, _ = tf.while_loop( cond, loop_body, loop_vars=(tf.constant(0.), init_perturbation, flat_init_optim_state), parallel_iterations=1, back_prop=False, maximum_iterations=num_steps) if project_perturbation is _project_perturbation: # TODO: this assert looks totally wrong. # Not bothering to fix it now because it's only an assert. # 1) Multiplying by 1.1 gives a huge margin of error. This should probably # take the difference and allow a tolerance of 1e-6 or something like # that. # 2) I think it should probably check the *absolute value* of # final_perturbation perturbation_max = epsilon * 1.1 check_diff = utils_tf.assert_less_equal( final_perturbation, tf.cast(perturbation_max, final_perturbation.dtype), message="final_perturbation must change no pixel by more than " "%s" % perturbation_max) else: # TODO: let caller pass in a check_diff function as well as # project_perturbation check_diff = tf.no_op() if clip_min is None or clip_max is None: raise NotImplementedError("This function only supports clipping for now") check_range = [utils_tf.assert_less_equal(input_image, tf.cast(clip_max, input_image.dtype)), utils_tf.assert_greater_equal(input_image, tf.cast(clip_min, input_image.dtype))] with tf.control_dependencies([check_diff] + check_range): adversarial_image = input_image + final_perturbation return tf.stop_gradient(adversarial_image)
python
def projected_optimization(loss_fn, input_image, label, epsilon, num_steps, clip_min=None, clip_max=None, optimizer=TensorAdam(), project_perturbation=_project_perturbation, early_stop_loss_threshold=None, is_debug=False): """Generic projected optimization, generalized to work with approximate gradients. Used for e.g. the SPSA attack. Args: :param loss_fn: A callable which takes `input_image` and `label` as arguments, and returns a batch of loss values. Same interface as TensorOptimizer. :param input_image: Tensor, a batch of images :param label: Tensor, a batch of labels :param epsilon: float, the L-infinity norm of the maximum allowable perturbation :param num_steps: int, the number of steps of gradient descent :param clip_min: float, minimum pixel value :param clip_max: float, maximum pixel value :param optimizer: A `TensorOptimizer` object :param project_perturbation: A function, which will be used to enforce some constraint. It should have the same signature as `_project_perturbation`. :param early_stop_loss_threshold: A float or None. If specified, the attack will end if the loss is below `early_stop_loss_threshold`. Enabling this option can have several different effects: - Setting the threshold to 0. guarantees that if a successful attack is found, it is returned. This increases the attack success rate, because without early stopping the optimizer can accidentally bounce back to a point where the attack fails. - Early stopping can make the attack run faster because it may run for fewer steps. - Early stopping can make the attack run slower because the loss must be calculated at each step. The loss is not calculated as part of the normal SPSA optimization procedure. For most reasonable choices of hyperparameters, early stopping makes the attack much faster because it decreases the number of steps dramatically. :param is_debug: A bool. If True, print debug info for attack progress. Returns: adversarial version of `input_image`, with L-infinity difference less than epsilon, which tries to minimize loss_fn. Note that this function is not intended as an Attack by itself. Rather, it is designed as a helper function which you can use to write your own attack methods. The method uses a tf.while_loop to optimize a loss function in a single sess.run() call. """ assert num_steps is not None if is_debug: with tf.device("/cpu:0"): input_image = tf.Print( input_image, [], "Starting PGD attack with epsilon: %s" % epsilon) init_perturbation = tf.random_uniform( tf.shape(input_image), minval=tf.cast(-epsilon, input_image.dtype), maxval=tf.cast(epsilon, input_image.dtype), dtype=input_image.dtype) init_perturbation = project_perturbation(init_perturbation, epsilon, input_image, clip_min=clip_min, clip_max=clip_max) init_optim_state = optimizer.init_state([init_perturbation]) nest = tf.contrib.framework.nest def loop_body(i, perturbation, flat_optim_state): """Update perturbation to input image.""" optim_state = nest.pack_sequence_as( structure=init_optim_state, flat_sequence=flat_optim_state) def wrapped_loss_fn(x): return loss_fn(input_image + x, label) new_perturbation_list, new_optim_state = optimizer.minimize( wrapped_loss_fn, [perturbation], optim_state) projected_perturbation = project_perturbation(new_perturbation_list[0], epsilon, input_image, clip_min=clip_min, clip_max=clip_max) # Be careful with this bool. A value of 0. is a valid threshold but evaluates to False, so we must explicitly # check whether the value is None. early_stop = early_stop_loss_threshold is not None compute_loss = is_debug or early_stop # Don't waste time building the loss graph if we're not going to use it if compute_loss: # NOTE: this step is not actually redundant with the optimizer step. # SPSA calculates the loss at randomly perturbed points but doesn't calculate the loss at the current point. loss = reduce_mean(wrapped_loss_fn(projected_perturbation), axis=0) if is_debug: with tf.device("/cpu:0"): loss = tf.Print(loss, [loss], "Total batch loss") if early_stop: i = tf.cond(tf.less(loss, early_stop_loss_threshold), lambda: float(num_steps), lambda: i) return i + 1, projected_perturbation, nest.flatten(new_optim_state) def cond(i, *_): return tf.less(i, num_steps) flat_init_optim_state = nest.flatten(init_optim_state) _, final_perturbation, _ = tf.while_loop( cond, loop_body, loop_vars=(tf.constant(0.), init_perturbation, flat_init_optim_state), parallel_iterations=1, back_prop=False, maximum_iterations=num_steps) if project_perturbation is _project_perturbation: # TODO: this assert looks totally wrong. # Not bothering to fix it now because it's only an assert. # 1) Multiplying by 1.1 gives a huge margin of error. This should probably # take the difference and allow a tolerance of 1e-6 or something like # that. # 2) I think it should probably check the *absolute value* of # final_perturbation perturbation_max = epsilon * 1.1 check_diff = utils_tf.assert_less_equal( final_perturbation, tf.cast(perturbation_max, final_perturbation.dtype), message="final_perturbation must change no pixel by more than " "%s" % perturbation_max) else: # TODO: let caller pass in a check_diff function as well as # project_perturbation check_diff = tf.no_op() if clip_min is None or clip_max is None: raise NotImplementedError("This function only supports clipping for now") check_range = [utils_tf.assert_less_equal(input_image, tf.cast(clip_max, input_image.dtype)), utils_tf.assert_greater_equal(input_image, tf.cast(clip_min, input_image.dtype))] with tf.control_dependencies([check_diff] + check_range): adversarial_image = input_image + final_perturbation return tf.stop_gradient(adversarial_image)
[ "def", "projected_optimization", "(", "loss_fn", ",", "input_image", ",", "label", ",", "epsilon", ",", "num_steps", ",", "clip_min", "=", "None", ",", "clip_max", "=", "None", ",", "optimizer", "=", "TensorAdam", "(", ")", ",", "project_perturbation", "=", "_project_perturbation", ",", "early_stop_loss_threshold", "=", "None", ",", "is_debug", "=", "False", ")", ":", "assert", "num_steps", "is", "not", "None", "if", "is_debug", ":", "with", "tf", ".", "device", "(", "\"/cpu:0\"", ")", ":", "input_image", "=", "tf", ".", "Print", "(", "input_image", ",", "[", "]", ",", "\"Starting PGD attack with epsilon: %s\"", "%", "epsilon", ")", "init_perturbation", "=", "tf", ".", "random_uniform", "(", "tf", ".", "shape", "(", "input_image", ")", ",", "minval", "=", "tf", ".", "cast", "(", "-", "epsilon", ",", "input_image", ".", "dtype", ")", ",", "maxval", "=", "tf", ".", "cast", "(", "epsilon", ",", "input_image", ".", "dtype", ")", ",", "dtype", "=", "input_image", ".", "dtype", ")", "init_perturbation", "=", "project_perturbation", "(", "init_perturbation", ",", "epsilon", ",", "input_image", ",", "clip_min", "=", "clip_min", ",", "clip_max", "=", "clip_max", ")", "init_optim_state", "=", "optimizer", ".", "init_state", "(", "[", "init_perturbation", "]", ")", "nest", "=", "tf", ".", "contrib", ".", "framework", ".", "nest", "def", "loop_body", "(", "i", ",", "perturbation", ",", "flat_optim_state", ")", ":", "\"\"\"Update perturbation to input image.\"\"\"", "optim_state", "=", "nest", ".", "pack_sequence_as", "(", "structure", "=", "init_optim_state", ",", "flat_sequence", "=", "flat_optim_state", ")", "def", "wrapped_loss_fn", "(", "x", ")", ":", "return", "loss_fn", "(", "input_image", "+", "x", ",", "label", ")", "new_perturbation_list", ",", "new_optim_state", "=", "optimizer", ".", "minimize", "(", "wrapped_loss_fn", ",", "[", "perturbation", "]", ",", "optim_state", ")", "projected_perturbation", "=", "project_perturbation", "(", "new_perturbation_list", "[", "0", "]", ",", "epsilon", ",", "input_image", ",", "clip_min", "=", "clip_min", ",", "clip_max", "=", "clip_max", ")", "# Be careful with this bool. A value of 0. is a valid threshold but evaluates to False, so we must explicitly", "# check whether the value is None.", "early_stop", "=", "early_stop_loss_threshold", "is", "not", "None", "compute_loss", "=", "is_debug", "or", "early_stop", "# Don't waste time building the loss graph if we're not going to use it", "if", "compute_loss", ":", "# NOTE: this step is not actually redundant with the optimizer step.", "# SPSA calculates the loss at randomly perturbed points but doesn't calculate the loss at the current point.", "loss", "=", "reduce_mean", "(", "wrapped_loss_fn", "(", "projected_perturbation", ")", ",", "axis", "=", "0", ")", "if", "is_debug", ":", "with", "tf", ".", "device", "(", "\"/cpu:0\"", ")", ":", "loss", "=", "tf", ".", "Print", "(", "loss", ",", "[", "loss", "]", ",", "\"Total batch loss\"", ")", "if", "early_stop", ":", "i", "=", "tf", ".", "cond", "(", "tf", ".", "less", "(", "loss", ",", "early_stop_loss_threshold", ")", ",", "lambda", ":", "float", "(", "num_steps", ")", ",", "lambda", ":", "i", ")", "return", "i", "+", "1", ",", "projected_perturbation", ",", "nest", ".", "flatten", "(", "new_optim_state", ")", "def", "cond", "(", "i", ",", "*", "_", ")", ":", "return", "tf", ".", "less", "(", "i", ",", "num_steps", ")", "flat_init_optim_state", "=", "nest", ".", "flatten", "(", "init_optim_state", ")", "_", ",", "final_perturbation", ",", "_", "=", "tf", ".", "while_loop", "(", "cond", ",", "loop_body", ",", "loop_vars", "=", "(", "tf", ".", "constant", "(", "0.", ")", ",", "init_perturbation", ",", "flat_init_optim_state", ")", ",", "parallel_iterations", "=", "1", ",", "back_prop", "=", "False", ",", "maximum_iterations", "=", "num_steps", ")", "if", "project_perturbation", "is", "_project_perturbation", ":", "# TODO: this assert looks totally wrong.", "# Not bothering to fix it now because it's only an assert.", "# 1) Multiplying by 1.1 gives a huge margin of error. This should probably", "# take the difference and allow a tolerance of 1e-6 or something like", "# that.", "# 2) I think it should probably check the *absolute value* of", "# final_perturbation", "perturbation_max", "=", "epsilon", "*", "1.1", "check_diff", "=", "utils_tf", ".", "assert_less_equal", "(", "final_perturbation", ",", "tf", ".", "cast", "(", "perturbation_max", ",", "final_perturbation", ".", "dtype", ")", ",", "message", "=", "\"final_perturbation must change no pixel by more than \"", "\"%s\"", "%", "perturbation_max", ")", "else", ":", "# TODO: let caller pass in a check_diff function as well as", "# project_perturbation", "check_diff", "=", "tf", ".", "no_op", "(", ")", "if", "clip_min", "is", "None", "or", "clip_max", "is", "None", ":", "raise", "NotImplementedError", "(", "\"This function only supports clipping for now\"", ")", "check_range", "=", "[", "utils_tf", ".", "assert_less_equal", "(", "input_image", ",", "tf", ".", "cast", "(", "clip_max", ",", "input_image", ".", "dtype", ")", ")", ",", "utils_tf", ".", "assert_greater_equal", "(", "input_image", ",", "tf", ".", "cast", "(", "clip_min", ",", "input_image", ".", "dtype", ")", ")", "]", "with", "tf", ".", "control_dependencies", "(", "[", "check_diff", "]", "+", "check_range", ")", ":", "adversarial_image", "=", "input_image", "+", "final_perturbation", "return", "tf", ".", "stop_gradient", "(", "adversarial_image", ")" ]
Generic projected optimization, generalized to work with approximate gradients. Used for e.g. the SPSA attack. Args: :param loss_fn: A callable which takes `input_image` and `label` as arguments, and returns a batch of loss values. Same interface as TensorOptimizer. :param input_image: Tensor, a batch of images :param label: Tensor, a batch of labels :param epsilon: float, the L-infinity norm of the maximum allowable perturbation :param num_steps: int, the number of steps of gradient descent :param clip_min: float, minimum pixel value :param clip_max: float, maximum pixel value :param optimizer: A `TensorOptimizer` object :param project_perturbation: A function, which will be used to enforce some constraint. It should have the same signature as `_project_perturbation`. :param early_stop_loss_threshold: A float or None. If specified, the attack will end if the loss is below `early_stop_loss_threshold`. Enabling this option can have several different effects: - Setting the threshold to 0. guarantees that if a successful attack is found, it is returned. This increases the attack success rate, because without early stopping the optimizer can accidentally bounce back to a point where the attack fails. - Early stopping can make the attack run faster because it may run for fewer steps. - Early stopping can make the attack run slower because the loss must be calculated at each step. The loss is not calculated as part of the normal SPSA optimization procedure. For most reasonable choices of hyperparameters, early stopping makes the attack much faster because it decreases the number of steps dramatically. :param is_debug: A bool. If True, print debug info for attack progress. Returns: adversarial version of `input_image`, with L-infinity difference less than epsilon, which tries to minimize loss_fn. Note that this function is not intended as an Attack by itself. Rather, it is designed as a helper function which you can use to write your own attack methods. The method uses a tf.while_loop to optimize a loss function in a single sess.run() call.
[ "Generic", "projected", "optimization", "generalized", "to", "work", "with", "approximate", "gradients", ".", "Used", "for", "e", ".", "g", ".", "the", "SPSA", "attack", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/spsa.py#L613-L758
train
tensorflow/cleverhans
cleverhans/attacks/spsa.py
SPSA.generate
def generate(self, x, y=None, y_target=None, eps=None, clip_min=None, clip_max=None, nb_iter=None, is_targeted=None, early_stop_loss_threshold=None, learning_rate=DEFAULT_LEARNING_RATE, delta=DEFAULT_DELTA, spsa_samples=DEFAULT_SPSA_SAMPLES, batch_size=None, spsa_iters=DEFAULT_SPSA_ITERS, is_debug=False, epsilon=None, num_steps=None): """ Generate symbolic graph for adversarial examples. :param x: The model's symbolic inputs. Must be a batch of size 1. :param y: A Tensor or None. The index of the correct label. :param y_target: A Tensor or None. The index of the target label in a targeted attack. :param eps: The size of the maximum perturbation, measured in the L-infinity norm. :param clip_min: If specified, the minimum input value :param clip_max: If specified, the maximum input value :param nb_iter: The number of optimization steps. :param early_stop_loss_threshold: A float or None. If specified, the attack will end as soon as the loss is below `early_stop_loss_threshold`. :param learning_rate: Learning rate of ADAM optimizer. :param delta: Perturbation size used for SPSA approximation. :param spsa_samples: Number of inputs to evaluate at a single time. The true batch size (the number of evaluated inputs for each update) is `spsa_samples * spsa_iters` :param batch_size: Deprecated param that is an alias for spsa_samples :param spsa_iters: Number of model evaluations before performing an update, where each evaluation is on `spsa_samples` different inputs. :param is_debug: If True, print the adversarial loss after each update. :param epsilon: Deprecated alias for `eps` :param num_steps: Deprecated alias for `nb_iter`. :param is_targeted: Deprecated argument. Ignored. """ if epsilon is not None: if eps is not None: raise ValueError("Should not specify both eps and its deprecated " "alias, epsilon") warnings.warn("`epsilon` is deprecated. Switch to `eps`. `epsilon` may " "be removed on or after 2019-04-15.") eps = epsilon del epsilon if num_steps is not None: if nb_iter is not None: raise ValueError("Should not specify both nb_iter and its deprecated " "alias, num_steps") warnings.warn("`num_steps` is deprecated. Switch to `nb_iter`. " "`num_steps` may be removed on or after 2019-04-15.") nb_iter = num_steps del num_steps assert nb_iter is not None if (y is not None) + (y_target is not None) != 1: raise ValueError("Must specify exactly one of y (untargeted attack, " "cause the input not to be classified as this true " "label) and y_target (targeted attack, cause the " "input to be classified as this target label).") if is_targeted is not None: warnings.warn("`is_targeted` is deprecated. Simply do not specify it." " It may become an error to specify it on or after " "2019-04-15.") assert is_targeted == y_target is not None is_targeted = y_target is not None if x.get_shape().as_list()[0] is None: check_batch = utils_tf.assert_equal(tf.shape(x)[0], 1) with tf.control_dependencies([check_batch]): x = tf.identity(x) elif x.get_shape().as_list()[0] != 1: raise ValueError("For SPSA, input tensor x must have batch_size of 1.") if batch_size is not None: warnings.warn( 'The "batch_size" argument to SPSA is deprecated, and will ' 'be removed on 2019-03-17. ' 'Please use spsa_samples instead.') spsa_samples = batch_size optimizer = SPSAAdam( lr=learning_rate, delta=delta, num_samples=spsa_samples, num_iters=spsa_iters) def loss_fn(x, label): """ Margin logit loss, with correct sign for targeted vs untargeted loss. """ logits = self.model.get_logits(x) loss_multiplier = 1 if is_targeted else -1 return loss_multiplier * margin_logit_loss( logits, label, nb_classes=self.model.nb_classes or logits.get_shape()[-1]) y_attack = y_target if is_targeted else y adv_x = projected_optimization( loss_fn, x, y_attack, eps, num_steps=nb_iter, optimizer=optimizer, early_stop_loss_threshold=early_stop_loss_threshold, is_debug=is_debug, clip_min=clip_min, clip_max=clip_max ) return adv_x
python
def generate(self, x, y=None, y_target=None, eps=None, clip_min=None, clip_max=None, nb_iter=None, is_targeted=None, early_stop_loss_threshold=None, learning_rate=DEFAULT_LEARNING_RATE, delta=DEFAULT_DELTA, spsa_samples=DEFAULT_SPSA_SAMPLES, batch_size=None, spsa_iters=DEFAULT_SPSA_ITERS, is_debug=False, epsilon=None, num_steps=None): """ Generate symbolic graph for adversarial examples. :param x: The model's symbolic inputs. Must be a batch of size 1. :param y: A Tensor or None. The index of the correct label. :param y_target: A Tensor or None. The index of the target label in a targeted attack. :param eps: The size of the maximum perturbation, measured in the L-infinity norm. :param clip_min: If specified, the minimum input value :param clip_max: If specified, the maximum input value :param nb_iter: The number of optimization steps. :param early_stop_loss_threshold: A float or None. If specified, the attack will end as soon as the loss is below `early_stop_loss_threshold`. :param learning_rate: Learning rate of ADAM optimizer. :param delta: Perturbation size used for SPSA approximation. :param spsa_samples: Number of inputs to evaluate at a single time. The true batch size (the number of evaluated inputs for each update) is `spsa_samples * spsa_iters` :param batch_size: Deprecated param that is an alias for spsa_samples :param spsa_iters: Number of model evaluations before performing an update, where each evaluation is on `spsa_samples` different inputs. :param is_debug: If True, print the adversarial loss after each update. :param epsilon: Deprecated alias for `eps` :param num_steps: Deprecated alias for `nb_iter`. :param is_targeted: Deprecated argument. Ignored. """ if epsilon is not None: if eps is not None: raise ValueError("Should not specify both eps and its deprecated " "alias, epsilon") warnings.warn("`epsilon` is deprecated. Switch to `eps`. `epsilon` may " "be removed on or after 2019-04-15.") eps = epsilon del epsilon if num_steps is not None: if nb_iter is not None: raise ValueError("Should not specify both nb_iter and its deprecated " "alias, num_steps") warnings.warn("`num_steps` is deprecated. Switch to `nb_iter`. " "`num_steps` may be removed on or after 2019-04-15.") nb_iter = num_steps del num_steps assert nb_iter is not None if (y is not None) + (y_target is not None) != 1: raise ValueError("Must specify exactly one of y (untargeted attack, " "cause the input not to be classified as this true " "label) and y_target (targeted attack, cause the " "input to be classified as this target label).") if is_targeted is not None: warnings.warn("`is_targeted` is deprecated. Simply do not specify it." " It may become an error to specify it on or after " "2019-04-15.") assert is_targeted == y_target is not None is_targeted = y_target is not None if x.get_shape().as_list()[0] is None: check_batch = utils_tf.assert_equal(tf.shape(x)[0], 1) with tf.control_dependencies([check_batch]): x = tf.identity(x) elif x.get_shape().as_list()[0] != 1: raise ValueError("For SPSA, input tensor x must have batch_size of 1.") if batch_size is not None: warnings.warn( 'The "batch_size" argument to SPSA is deprecated, and will ' 'be removed on 2019-03-17. ' 'Please use spsa_samples instead.') spsa_samples = batch_size optimizer = SPSAAdam( lr=learning_rate, delta=delta, num_samples=spsa_samples, num_iters=spsa_iters) def loss_fn(x, label): """ Margin logit loss, with correct sign for targeted vs untargeted loss. """ logits = self.model.get_logits(x) loss_multiplier = 1 if is_targeted else -1 return loss_multiplier * margin_logit_loss( logits, label, nb_classes=self.model.nb_classes or logits.get_shape()[-1]) y_attack = y_target if is_targeted else y adv_x = projected_optimization( loss_fn, x, y_attack, eps, num_steps=nb_iter, optimizer=optimizer, early_stop_loss_threshold=early_stop_loss_threshold, is_debug=is_debug, clip_min=clip_min, clip_max=clip_max ) return adv_x
[ "def", "generate", "(", "self", ",", "x", ",", "y", "=", "None", ",", "y_target", "=", "None", ",", "eps", "=", "None", ",", "clip_min", "=", "None", ",", "clip_max", "=", "None", ",", "nb_iter", "=", "None", ",", "is_targeted", "=", "None", ",", "early_stop_loss_threshold", "=", "None", ",", "learning_rate", "=", "DEFAULT_LEARNING_RATE", ",", "delta", "=", "DEFAULT_DELTA", ",", "spsa_samples", "=", "DEFAULT_SPSA_SAMPLES", ",", "batch_size", "=", "None", ",", "spsa_iters", "=", "DEFAULT_SPSA_ITERS", ",", "is_debug", "=", "False", ",", "epsilon", "=", "None", ",", "num_steps", "=", "None", ")", ":", "if", "epsilon", "is", "not", "None", ":", "if", "eps", "is", "not", "None", ":", "raise", "ValueError", "(", "\"Should not specify both eps and its deprecated \"", "\"alias, epsilon\"", ")", "warnings", ".", "warn", "(", "\"`epsilon` is deprecated. Switch to `eps`. `epsilon` may \"", "\"be removed on or after 2019-04-15.\"", ")", "eps", "=", "epsilon", "del", "epsilon", "if", "num_steps", "is", "not", "None", ":", "if", "nb_iter", "is", "not", "None", ":", "raise", "ValueError", "(", "\"Should not specify both nb_iter and its deprecated \"", "\"alias, num_steps\"", ")", "warnings", ".", "warn", "(", "\"`num_steps` is deprecated. Switch to `nb_iter`. \"", "\"`num_steps` may be removed on or after 2019-04-15.\"", ")", "nb_iter", "=", "num_steps", "del", "num_steps", "assert", "nb_iter", "is", "not", "None", "if", "(", "y", "is", "not", "None", ")", "+", "(", "y_target", "is", "not", "None", ")", "!=", "1", ":", "raise", "ValueError", "(", "\"Must specify exactly one of y (untargeted attack, \"", "\"cause the input not to be classified as this true \"", "\"label) and y_target (targeted attack, cause the \"", "\"input to be classified as this target label).\"", ")", "if", "is_targeted", "is", "not", "None", ":", "warnings", ".", "warn", "(", "\"`is_targeted` is deprecated. Simply do not specify it.\"", "\" It may become an error to specify it on or after \"", "\"2019-04-15.\"", ")", "assert", "is_targeted", "==", "y_target", "is", "not", "None", "is_targeted", "=", "y_target", "is", "not", "None", "if", "x", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "[", "0", "]", "is", "None", ":", "check_batch", "=", "utils_tf", ".", "assert_equal", "(", "tf", ".", "shape", "(", "x", ")", "[", "0", "]", ",", "1", ")", "with", "tf", ".", "control_dependencies", "(", "[", "check_batch", "]", ")", ":", "x", "=", "tf", ".", "identity", "(", "x", ")", "elif", "x", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "[", "0", "]", "!=", "1", ":", "raise", "ValueError", "(", "\"For SPSA, input tensor x must have batch_size of 1.\"", ")", "if", "batch_size", "is", "not", "None", ":", "warnings", ".", "warn", "(", "'The \"batch_size\" argument to SPSA is deprecated, and will '", "'be removed on 2019-03-17. '", "'Please use spsa_samples instead.'", ")", "spsa_samples", "=", "batch_size", "optimizer", "=", "SPSAAdam", "(", "lr", "=", "learning_rate", ",", "delta", "=", "delta", ",", "num_samples", "=", "spsa_samples", ",", "num_iters", "=", "spsa_iters", ")", "def", "loss_fn", "(", "x", ",", "label", ")", ":", "\"\"\"\n Margin logit loss, with correct sign for targeted vs untargeted loss.\n \"\"\"", "logits", "=", "self", ".", "model", ".", "get_logits", "(", "x", ")", "loss_multiplier", "=", "1", "if", "is_targeted", "else", "-", "1", "return", "loss_multiplier", "*", "margin_logit_loss", "(", "logits", ",", "label", ",", "nb_classes", "=", "self", ".", "model", ".", "nb_classes", "or", "logits", ".", "get_shape", "(", ")", "[", "-", "1", "]", ")", "y_attack", "=", "y_target", "if", "is_targeted", "else", "y", "adv_x", "=", "projected_optimization", "(", "loss_fn", ",", "x", ",", "y_attack", ",", "eps", ",", "num_steps", "=", "nb_iter", ",", "optimizer", "=", "optimizer", ",", "early_stop_loss_threshold", "=", "early_stop_loss_threshold", ",", "is_debug", "=", "is_debug", ",", "clip_min", "=", "clip_min", ",", "clip_max", "=", "clip_max", ")", "return", "adv_x" ]
Generate symbolic graph for adversarial examples. :param x: The model's symbolic inputs. Must be a batch of size 1. :param y: A Tensor or None. The index of the correct label. :param y_target: A Tensor or None. The index of the target label in a targeted attack. :param eps: The size of the maximum perturbation, measured in the L-infinity norm. :param clip_min: If specified, the minimum input value :param clip_max: If specified, the maximum input value :param nb_iter: The number of optimization steps. :param early_stop_loss_threshold: A float or None. If specified, the attack will end as soon as the loss is below `early_stop_loss_threshold`. :param learning_rate: Learning rate of ADAM optimizer. :param delta: Perturbation size used for SPSA approximation. :param spsa_samples: Number of inputs to evaluate at a single time. The true batch size (the number of evaluated inputs for each update) is `spsa_samples * spsa_iters` :param batch_size: Deprecated param that is an alias for spsa_samples :param spsa_iters: Number of model evaluations before performing an update, where each evaluation is on `spsa_samples` different inputs. :param is_debug: If True, print the adversarial loss after each update. :param epsilon: Deprecated alias for `eps` :param num_steps: Deprecated alias for `nb_iter`. :param is_targeted: Deprecated argument. Ignored.
[ "Generate", "symbolic", "graph", "for", "adversarial", "examples", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/spsa.py#L51-L176
train
tensorflow/cleverhans
cleverhans/attacks/spsa.py
TensorOptimizer._compute_gradients
def _compute_gradients(self, loss_fn, x, unused_optim_state): """Compute a new value of `x` to minimize `loss_fn`. Args: loss_fn: a callable that takes `x`, a batch of images, and returns a batch of loss values. `x` will be optimized to minimize `loss_fn(x)`. x: A list of Tensors, the values to be updated. This is analogous to the `var_list` argument in standard TF Optimizer. unused_optim_state: A (possibly nested) dict, containing any state info needed for the optimizer. Returns: new_x: A list of Tensors, the same length as `x`, which are updated new_optim_state: A dict, with the same structure as `optim_state`, which have been updated. """ # Assumes `x` is a list, # and contains a tensor representing a batch of images assert len(x) == 1 and isinstance(x, list), \ 'x should be a list and contain only one image tensor' x = x[0] loss = reduce_mean(loss_fn(x), axis=0) return tf.gradients(loss, x)
python
def _compute_gradients(self, loss_fn, x, unused_optim_state): """Compute a new value of `x` to minimize `loss_fn`. Args: loss_fn: a callable that takes `x`, a batch of images, and returns a batch of loss values. `x` will be optimized to minimize `loss_fn(x)`. x: A list of Tensors, the values to be updated. This is analogous to the `var_list` argument in standard TF Optimizer. unused_optim_state: A (possibly nested) dict, containing any state info needed for the optimizer. Returns: new_x: A list of Tensors, the same length as `x`, which are updated new_optim_state: A dict, with the same structure as `optim_state`, which have been updated. """ # Assumes `x` is a list, # and contains a tensor representing a batch of images assert len(x) == 1 and isinstance(x, list), \ 'x should be a list and contain only one image tensor' x = x[0] loss = reduce_mean(loss_fn(x), axis=0) return tf.gradients(loss, x)
[ "def", "_compute_gradients", "(", "self", ",", "loss_fn", ",", "x", ",", "unused_optim_state", ")", ":", "# Assumes `x` is a list,", "# and contains a tensor representing a batch of images", "assert", "len", "(", "x", ")", "==", "1", "and", "isinstance", "(", "x", ",", "list", ")", ",", "'x should be a list and contain only one image tensor'", "x", "=", "x", "[", "0", "]", "loss", "=", "reduce_mean", "(", "loss_fn", "(", "x", ")", ",", "axis", "=", "0", ")", "return", "tf", ".", "gradients", "(", "loss", ",", "x", ")" ]
Compute a new value of `x` to minimize `loss_fn`. Args: loss_fn: a callable that takes `x`, a batch of images, and returns a batch of loss values. `x` will be optimized to minimize `loss_fn(x)`. x: A list of Tensors, the values to be updated. This is analogous to the `var_list` argument in standard TF Optimizer. unused_optim_state: A (possibly nested) dict, containing any state info needed for the optimizer. Returns: new_x: A list of Tensors, the same length as `x`, which are updated new_optim_state: A dict, with the same structure as `optim_state`, which have been updated.
[ "Compute", "a", "new", "value", "of", "x", "to", "minimize", "loss_fn", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/spsa.py#L246-L270
train
tensorflow/cleverhans
cleverhans/attacks/spsa.py
TensorOptimizer.minimize
def minimize(self, loss_fn, x, optim_state): """ Analogous to tf.Optimizer.minimize :param loss_fn: tf Tensor, representing the loss to minimize :param x: list of Tensor, analogous to tf.Optimizer's var_list :param optim_state: A possibly nested dict, containing any optimizer state. Returns: new_x: list of Tensor, updated version of `x` new_optim_state: dict, updated version of `optim_state` """ grads = self._compute_gradients(loss_fn, x, optim_state) return self._apply_gradients(grads, x, optim_state)
python
def minimize(self, loss_fn, x, optim_state): """ Analogous to tf.Optimizer.minimize :param loss_fn: tf Tensor, representing the loss to minimize :param x: list of Tensor, analogous to tf.Optimizer's var_list :param optim_state: A possibly nested dict, containing any optimizer state. Returns: new_x: list of Tensor, updated version of `x` new_optim_state: dict, updated version of `optim_state` """ grads = self._compute_gradients(loss_fn, x, optim_state) return self._apply_gradients(grads, x, optim_state)
[ "def", "minimize", "(", "self", ",", "loss_fn", ",", "x", ",", "optim_state", ")", ":", "grads", "=", "self", ".", "_compute_gradients", "(", "loss_fn", ",", "x", ",", "optim_state", ")", "return", "self", ".", "_apply_gradients", "(", "grads", ",", "x", ",", "optim_state", ")" ]
Analogous to tf.Optimizer.minimize :param loss_fn: tf Tensor, representing the loss to minimize :param x: list of Tensor, analogous to tf.Optimizer's var_list :param optim_state: A possibly nested dict, containing any optimizer state. Returns: new_x: list of Tensor, updated version of `x` new_optim_state: dict, updated version of `optim_state`
[ "Analogous", "to", "tf", ".", "Optimizer", ".", "minimize" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/spsa.py#L287-L300
train
tensorflow/cleverhans
cleverhans/attacks/spsa.py
TensorAdam.init_state
def init_state(self, x): """ Initialize t, m, and u """ optim_state = {} optim_state["t"] = 0. optim_state["m"] = [tf.zeros_like(v) for v in x] optim_state["u"] = [tf.zeros_like(v) for v in x] return optim_state
python
def init_state(self, x): """ Initialize t, m, and u """ optim_state = {} optim_state["t"] = 0. optim_state["m"] = [tf.zeros_like(v) for v in x] optim_state["u"] = [tf.zeros_like(v) for v in x] return optim_state
[ "def", "init_state", "(", "self", ",", "x", ")", ":", "optim_state", "=", "{", "}", "optim_state", "[", "\"t\"", "]", "=", "0.", "optim_state", "[", "\"m\"", "]", "=", "[", "tf", ".", "zeros_like", "(", "v", ")", "for", "v", "in", "x", "]", "optim_state", "[", "\"u\"", "]", "=", "[", "tf", ".", "zeros_like", "(", "v", ")", "for", "v", "in", "x", "]", "return", "optim_state" ]
Initialize t, m, and u
[ "Initialize", "t", "m", "and", "u" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/spsa.py#L340-L348
train
tensorflow/cleverhans
cleverhans/attacks/spsa.py
TensorAdam._apply_gradients
def _apply_gradients(self, grads, x, optim_state): """Refer to parent class documentation.""" new_x = [None] * len(x) new_optim_state = { "t": optim_state["t"] + 1., "m": [None] * len(x), "u": [None] * len(x) } t = new_optim_state["t"] for i in xrange(len(x)): g = grads[i] m_old = optim_state["m"][i] u_old = optim_state["u"][i] new_optim_state["m"][i] = ( self._beta1 * m_old + (1. - self._beta1) * g) new_optim_state["u"][i] = ( self._beta2 * u_old + (1. - self._beta2) * g * g) m_hat = new_optim_state["m"][i] / (1. - tf.pow(self._beta1, t)) u_hat = new_optim_state["u"][i] / (1. - tf.pow(self._beta2, t)) new_x[i] = ( x[i] - self._lr * m_hat / (tf.sqrt(u_hat) + self._epsilon)) return new_x, new_optim_state
python
def _apply_gradients(self, grads, x, optim_state): """Refer to parent class documentation.""" new_x = [None] * len(x) new_optim_state = { "t": optim_state["t"] + 1., "m": [None] * len(x), "u": [None] * len(x) } t = new_optim_state["t"] for i in xrange(len(x)): g = grads[i] m_old = optim_state["m"][i] u_old = optim_state["u"][i] new_optim_state["m"][i] = ( self._beta1 * m_old + (1. - self._beta1) * g) new_optim_state["u"][i] = ( self._beta2 * u_old + (1. - self._beta2) * g * g) m_hat = new_optim_state["m"][i] / (1. - tf.pow(self._beta1, t)) u_hat = new_optim_state["u"][i] / (1. - tf.pow(self._beta2, t)) new_x[i] = ( x[i] - self._lr * m_hat / (tf.sqrt(u_hat) + self._epsilon)) return new_x, new_optim_state
[ "def", "_apply_gradients", "(", "self", ",", "grads", ",", "x", ",", "optim_state", ")", ":", "new_x", "=", "[", "None", "]", "*", "len", "(", "x", ")", "new_optim_state", "=", "{", "\"t\"", ":", "optim_state", "[", "\"t\"", "]", "+", "1.", ",", "\"m\"", ":", "[", "None", "]", "*", "len", "(", "x", ")", ",", "\"u\"", ":", "[", "None", "]", "*", "len", "(", "x", ")", "}", "t", "=", "new_optim_state", "[", "\"t\"", "]", "for", "i", "in", "xrange", "(", "len", "(", "x", ")", ")", ":", "g", "=", "grads", "[", "i", "]", "m_old", "=", "optim_state", "[", "\"m\"", "]", "[", "i", "]", "u_old", "=", "optim_state", "[", "\"u\"", "]", "[", "i", "]", "new_optim_state", "[", "\"m\"", "]", "[", "i", "]", "=", "(", "self", ".", "_beta1", "*", "m_old", "+", "(", "1.", "-", "self", ".", "_beta1", ")", "*", "g", ")", "new_optim_state", "[", "\"u\"", "]", "[", "i", "]", "=", "(", "self", ".", "_beta2", "*", "u_old", "+", "(", "1.", "-", "self", ".", "_beta2", ")", "*", "g", "*", "g", ")", "m_hat", "=", "new_optim_state", "[", "\"m\"", "]", "[", "i", "]", "/", "(", "1.", "-", "tf", ".", "pow", "(", "self", ".", "_beta1", ",", "t", ")", ")", "u_hat", "=", "new_optim_state", "[", "\"u\"", "]", "[", "i", "]", "/", "(", "1.", "-", "tf", ".", "pow", "(", "self", ".", "_beta2", ",", "t", ")", ")", "new_x", "[", "i", "]", "=", "(", "x", "[", "i", "]", "-", "self", ".", "_lr", "*", "m_hat", "/", "(", "tf", ".", "sqrt", "(", "u_hat", ")", "+", "self", ".", "_epsilon", ")", ")", "return", "new_x", ",", "new_optim_state" ]
Refer to parent class documentation.
[ "Refer", "to", "parent", "class", "documentation", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/spsa.py#L350-L371
train
tensorflow/cleverhans
cleverhans/attacks/spsa.py
SPSAAdam._compute_gradients
def _compute_gradients(self, loss_fn, x, unused_optim_state): """Compute gradient estimates using SPSA.""" # Assumes `x` is a list, containing a [1, H, W, C] image # If static batch dimension is None, tf.reshape to batch size 1 # so that static shape can be inferred assert len(x) == 1 static_x_shape = x[0].get_shape().as_list() if static_x_shape[0] is None: x[0] = tf.reshape(x[0], [1] + static_x_shape[1:]) assert x[0].get_shape().as_list()[0] == 1 x = x[0] x_shape = x.get_shape().as_list() def body(i, grad_array): delta = self._delta delta_x = self._get_delta(x, delta) delta_x = tf.concat([delta_x, -delta_x], axis=0) loss_vals = tf.reshape( loss_fn(x + delta_x), [2 * self._num_samples] + [1] * (len(x_shape) - 1)) avg_grad = reduce_mean(loss_vals * delta_x, axis=0) / delta avg_grad = tf.expand_dims(avg_grad, axis=0) new_grad_array = grad_array.write(i, avg_grad) return i + 1, new_grad_array def cond(i, _): return i < self._num_iters _, all_grads = tf.while_loop( cond, body, loop_vars=[ 0, tf.TensorArray(size=self._num_iters, dtype=tf_dtype) ], back_prop=False, parallel_iterations=1) avg_grad = reduce_sum(all_grads.stack(), axis=0) return [avg_grad]
python
def _compute_gradients(self, loss_fn, x, unused_optim_state): """Compute gradient estimates using SPSA.""" # Assumes `x` is a list, containing a [1, H, W, C] image # If static batch dimension is None, tf.reshape to batch size 1 # so that static shape can be inferred assert len(x) == 1 static_x_shape = x[0].get_shape().as_list() if static_x_shape[0] is None: x[0] = tf.reshape(x[0], [1] + static_x_shape[1:]) assert x[0].get_shape().as_list()[0] == 1 x = x[0] x_shape = x.get_shape().as_list() def body(i, grad_array): delta = self._delta delta_x = self._get_delta(x, delta) delta_x = tf.concat([delta_x, -delta_x], axis=0) loss_vals = tf.reshape( loss_fn(x + delta_x), [2 * self._num_samples] + [1] * (len(x_shape) - 1)) avg_grad = reduce_mean(loss_vals * delta_x, axis=0) / delta avg_grad = tf.expand_dims(avg_grad, axis=0) new_grad_array = grad_array.write(i, avg_grad) return i + 1, new_grad_array def cond(i, _): return i < self._num_iters _, all_grads = tf.while_loop( cond, body, loop_vars=[ 0, tf.TensorArray(size=self._num_iters, dtype=tf_dtype) ], back_prop=False, parallel_iterations=1) avg_grad = reduce_sum(all_grads.stack(), axis=0) return [avg_grad]
[ "def", "_compute_gradients", "(", "self", ",", "loss_fn", ",", "x", ",", "unused_optim_state", ")", ":", "# Assumes `x` is a list, containing a [1, H, W, C] image", "# If static batch dimension is None, tf.reshape to batch size 1", "# so that static shape can be inferred", "assert", "len", "(", "x", ")", "==", "1", "static_x_shape", "=", "x", "[", "0", "]", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "if", "static_x_shape", "[", "0", "]", "is", "None", ":", "x", "[", "0", "]", "=", "tf", ".", "reshape", "(", "x", "[", "0", "]", ",", "[", "1", "]", "+", "static_x_shape", "[", "1", ":", "]", ")", "assert", "x", "[", "0", "]", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "[", "0", "]", "==", "1", "x", "=", "x", "[", "0", "]", "x_shape", "=", "x", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "def", "body", "(", "i", ",", "grad_array", ")", ":", "delta", "=", "self", ".", "_delta", "delta_x", "=", "self", ".", "_get_delta", "(", "x", ",", "delta", ")", "delta_x", "=", "tf", ".", "concat", "(", "[", "delta_x", ",", "-", "delta_x", "]", ",", "axis", "=", "0", ")", "loss_vals", "=", "tf", ".", "reshape", "(", "loss_fn", "(", "x", "+", "delta_x", ")", ",", "[", "2", "*", "self", ".", "_num_samples", "]", "+", "[", "1", "]", "*", "(", "len", "(", "x_shape", ")", "-", "1", ")", ")", "avg_grad", "=", "reduce_mean", "(", "loss_vals", "*", "delta_x", ",", "axis", "=", "0", ")", "/", "delta", "avg_grad", "=", "tf", ".", "expand_dims", "(", "avg_grad", ",", "axis", "=", "0", ")", "new_grad_array", "=", "grad_array", ".", "write", "(", "i", ",", "avg_grad", ")", "return", "i", "+", "1", ",", "new_grad_array", "def", "cond", "(", "i", ",", "_", ")", ":", "return", "i", "<", "self", ".", "_num_iters", "_", ",", "all_grads", "=", "tf", ".", "while_loop", "(", "cond", ",", "body", ",", "loop_vars", "=", "[", "0", ",", "tf", ".", "TensorArray", "(", "size", "=", "self", ".", "_num_iters", ",", "dtype", "=", "tf_dtype", ")", "]", ",", "back_prop", "=", "False", ",", "parallel_iterations", "=", "1", ")", "avg_grad", "=", "reduce_sum", "(", "all_grads", ".", "stack", "(", ")", ",", "axis", "=", "0", ")", "return", "[", "avg_grad", "]" ]
Compute gradient estimates using SPSA.
[ "Compute", "gradient", "estimates", "using", "SPSA", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/spsa.py#L404-L441
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/dev_toolkit/run_attacks_and_defenses.py
parse_args
def parse_args(): """Parses command line arguments.""" parser = argparse.ArgumentParser( description='Tool to run attacks and defenses.') parser.add_argument('--attacks_dir', required=True, help='Location of all attacks.') parser.add_argument('--targeted_attacks_dir', required=True, help='Location of all targeted attacks.') parser.add_argument('--defenses_dir', required=True, help='Location of all defenses.') parser.add_argument('--dataset_dir', required=True, help='Location of the dataset.') parser.add_argument('--dataset_metadata', required=True, help='Location of the dataset metadata.') parser.add_argument('--intermediate_results_dir', required=True, help='Directory to store intermediate results.') parser.add_argument('--output_dir', required=True, help=('Output directory.')) parser.add_argument('--epsilon', required=False, type=int, default=16, help='Maximum allowed size of adversarial perturbation') parser.add_argument('--gpu', dest='use_gpu', action='store_true') parser.add_argument('--nogpu', dest='use_gpu', action='store_false') parser.set_defaults(use_gpu=False) parser.add_argument('--save_all_classification', dest='save_all_classification', action='store_true') parser.add_argument('--nosave_all_classification', dest='save_all_classification', action='store_false') parser.set_defaults(save_all_classification=False) return parser.parse_args()
python
def parse_args(): """Parses command line arguments.""" parser = argparse.ArgumentParser( description='Tool to run attacks and defenses.') parser.add_argument('--attacks_dir', required=True, help='Location of all attacks.') parser.add_argument('--targeted_attacks_dir', required=True, help='Location of all targeted attacks.') parser.add_argument('--defenses_dir', required=True, help='Location of all defenses.') parser.add_argument('--dataset_dir', required=True, help='Location of the dataset.') parser.add_argument('--dataset_metadata', required=True, help='Location of the dataset metadata.') parser.add_argument('--intermediate_results_dir', required=True, help='Directory to store intermediate results.') parser.add_argument('--output_dir', required=True, help=('Output directory.')) parser.add_argument('--epsilon', required=False, type=int, default=16, help='Maximum allowed size of adversarial perturbation') parser.add_argument('--gpu', dest='use_gpu', action='store_true') parser.add_argument('--nogpu', dest='use_gpu', action='store_false') parser.set_defaults(use_gpu=False) parser.add_argument('--save_all_classification', dest='save_all_classification', action='store_true') parser.add_argument('--nosave_all_classification', dest='save_all_classification', action='store_false') parser.set_defaults(save_all_classification=False) return parser.parse_args()
[ "def", "parse_args", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Tool to run attacks and defenses.'", ")", "parser", ".", "add_argument", "(", "'--attacks_dir'", ",", "required", "=", "True", ",", "help", "=", "'Location of all attacks.'", ")", "parser", ".", "add_argument", "(", "'--targeted_attacks_dir'", ",", "required", "=", "True", ",", "help", "=", "'Location of all targeted attacks.'", ")", "parser", ".", "add_argument", "(", "'--defenses_dir'", ",", "required", "=", "True", ",", "help", "=", "'Location of all defenses.'", ")", "parser", ".", "add_argument", "(", "'--dataset_dir'", ",", "required", "=", "True", ",", "help", "=", "'Location of the dataset.'", ")", "parser", ".", "add_argument", "(", "'--dataset_metadata'", ",", "required", "=", "True", ",", "help", "=", "'Location of the dataset metadata.'", ")", "parser", ".", "add_argument", "(", "'--intermediate_results_dir'", ",", "required", "=", "True", ",", "help", "=", "'Directory to store intermediate results.'", ")", "parser", ".", "add_argument", "(", "'--output_dir'", ",", "required", "=", "True", ",", "help", "=", "(", "'Output directory.'", ")", ")", "parser", ".", "add_argument", "(", "'--epsilon'", ",", "required", "=", "False", ",", "type", "=", "int", ",", "default", "=", "16", ",", "help", "=", "'Maximum allowed size of adversarial perturbation'", ")", "parser", ".", "add_argument", "(", "'--gpu'", ",", "dest", "=", "'use_gpu'", ",", "action", "=", "'store_true'", ")", "parser", ".", "add_argument", "(", "'--nogpu'", ",", "dest", "=", "'use_gpu'", ",", "action", "=", "'store_false'", ")", "parser", ".", "set_defaults", "(", "use_gpu", "=", "False", ")", "parser", ".", "add_argument", "(", "'--save_all_classification'", ",", "dest", "=", "'save_all_classification'", ",", "action", "=", "'store_true'", ")", "parser", ".", "add_argument", "(", "'--nosave_all_classification'", ",", "dest", "=", "'save_all_classification'", ",", "action", "=", "'store_false'", ")", "parser", ".", "set_defaults", "(", "save_all_classification", "=", "False", ")", "return", "parser", ".", "parse_args", "(", ")" ]
Parses command line arguments.
[ "Parses", "command", "line", "arguments", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/run_attacks_and_defenses.py#L16-L44
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/dev_toolkit/run_attacks_and_defenses.py
read_submissions_from_directory
def read_submissions_from_directory(dirname, use_gpu): """Scans directory and read all submissions. Args: dirname: directory to scan. use_gpu: whether submissions should use GPU. This argument is used to pick proper Docker container for each submission and create instance of Attack or Defense class. Returns: List with submissions (subclasses of Submission class). """ result = [] for sub_dir in os.listdir(dirname): submission_path = os.path.join(dirname, sub_dir) try: if not os.path.isdir(submission_path): continue if not os.path.exists(os.path.join(submission_path, 'metadata.json')): continue with open(os.path.join(submission_path, 'metadata.json')) as f: metadata = json.load(f) if use_gpu and ('container_gpu' in metadata): container = metadata['container_gpu'] else: container = metadata['container'] entry_point = metadata['entry_point'] submission_type = metadata['type'] if submission_type == 'attack' or submission_type == 'targeted_attack': submission = Attack(submission_path, container, entry_point, use_gpu) elif submission_type == 'defense': submission = Defense(submission_path, container, entry_point, use_gpu) else: raise ValueError('Invalid type of submission: %s' % submission_type) result.append(submission) except (IOError, KeyError, ValueError): print('Failed to read submission from directory ', submission_path) return result
python
def read_submissions_from_directory(dirname, use_gpu): """Scans directory and read all submissions. Args: dirname: directory to scan. use_gpu: whether submissions should use GPU. This argument is used to pick proper Docker container for each submission and create instance of Attack or Defense class. Returns: List with submissions (subclasses of Submission class). """ result = [] for sub_dir in os.listdir(dirname): submission_path = os.path.join(dirname, sub_dir) try: if not os.path.isdir(submission_path): continue if not os.path.exists(os.path.join(submission_path, 'metadata.json')): continue with open(os.path.join(submission_path, 'metadata.json')) as f: metadata = json.load(f) if use_gpu and ('container_gpu' in metadata): container = metadata['container_gpu'] else: container = metadata['container'] entry_point = metadata['entry_point'] submission_type = metadata['type'] if submission_type == 'attack' or submission_type == 'targeted_attack': submission = Attack(submission_path, container, entry_point, use_gpu) elif submission_type == 'defense': submission = Defense(submission_path, container, entry_point, use_gpu) else: raise ValueError('Invalid type of submission: %s' % submission_type) result.append(submission) except (IOError, KeyError, ValueError): print('Failed to read submission from directory ', submission_path) return result
[ "def", "read_submissions_from_directory", "(", "dirname", ",", "use_gpu", ")", ":", "result", "=", "[", "]", "for", "sub_dir", "in", "os", ".", "listdir", "(", "dirname", ")", ":", "submission_path", "=", "os", ".", "path", ".", "join", "(", "dirname", ",", "sub_dir", ")", "try", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "submission_path", ")", ":", "continue", "if", "not", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "submission_path", ",", "'metadata.json'", ")", ")", ":", "continue", "with", "open", "(", "os", ".", "path", ".", "join", "(", "submission_path", ",", "'metadata.json'", ")", ")", "as", "f", ":", "metadata", "=", "json", ".", "load", "(", "f", ")", "if", "use_gpu", "and", "(", "'container_gpu'", "in", "metadata", ")", ":", "container", "=", "metadata", "[", "'container_gpu'", "]", "else", ":", "container", "=", "metadata", "[", "'container'", "]", "entry_point", "=", "metadata", "[", "'entry_point'", "]", "submission_type", "=", "metadata", "[", "'type'", "]", "if", "submission_type", "==", "'attack'", "or", "submission_type", "==", "'targeted_attack'", ":", "submission", "=", "Attack", "(", "submission_path", ",", "container", ",", "entry_point", ",", "use_gpu", ")", "elif", "submission_type", "==", "'defense'", ":", "submission", "=", "Defense", "(", "submission_path", ",", "container", ",", "entry_point", ",", "use_gpu", ")", "else", ":", "raise", "ValueError", "(", "'Invalid type of submission: %s'", "%", "submission_type", ")", "result", ".", "append", "(", "submission", ")", "except", "(", "IOError", ",", "KeyError", ",", "ValueError", ")", ":", "print", "(", "'Failed to read submission from directory '", ",", "submission_path", ")", "return", "result" ]
Scans directory and read all submissions. Args: dirname: directory to scan. use_gpu: whether submissions should use GPU. This argument is used to pick proper Docker container for each submission and create instance of Attack or Defense class. Returns: List with submissions (subclasses of Submission class).
[ "Scans", "directory", "and", "read", "all", "submissions", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/run_attacks_and_defenses.py#L121-L158
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/dev_toolkit/run_attacks_and_defenses.py
load_defense_output
def load_defense_output(filename): """Loads output of defense from given file.""" result = {} with open(filename) as f: for row in csv.reader(f): try: image_filename = row[0] if image_filename.endswith('.png') or image_filename.endswith('.jpg'): image_filename = image_filename[:image_filename.rfind('.')] label = int(row[1]) except (IndexError, ValueError): continue result[image_filename] = label return result
python
def load_defense_output(filename): """Loads output of defense from given file.""" result = {} with open(filename) as f: for row in csv.reader(f): try: image_filename = row[0] if image_filename.endswith('.png') or image_filename.endswith('.jpg'): image_filename = image_filename[:image_filename.rfind('.')] label = int(row[1]) except (IndexError, ValueError): continue result[image_filename] = label return result
[ "def", "load_defense_output", "(", "filename", ")", ":", "result", "=", "{", "}", "with", "open", "(", "filename", ")", "as", "f", ":", "for", "row", "in", "csv", ".", "reader", "(", "f", ")", ":", "try", ":", "image_filename", "=", "row", "[", "0", "]", "if", "image_filename", ".", "endswith", "(", "'.png'", ")", "or", "image_filename", ".", "endswith", "(", "'.jpg'", ")", ":", "image_filename", "=", "image_filename", "[", ":", "image_filename", ".", "rfind", "(", "'.'", ")", "]", "label", "=", "int", "(", "row", "[", "1", "]", ")", "except", "(", "IndexError", ",", "ValueError", ")", ":", "continue", "result", "[", "image_filename", "]", "=", "label", "return", "result" ]
Loads output of defense from given file.
[ "Loads", "output", "of", "defense", "from", "given", "file", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/run_attacks_and_defenses.py#L328-L341
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/dev_toolkit/run_attacks_and_defenses.py
compute_and_save_scores_and_ranking
def compute_and_save_scores_and_ranking(attacks_output, defenses_output, dataset_meta, output_dir, save_all_classification=False): """Computes scores and ranking and saves it. Args: attacks_output: output of attacks, instance of AttacksOutput class. defenses_output: outputs of defenses. Dictionary of dictionaries, key in outer dictionary is name of the defense, key of inner dictionary is name of the image, value of inner dictionary is classification label. dataset_meta: dataset metadata, instance of DatasetMetadata class. output_dir: output directory where results will be saved. save_all_classification: If True then classification results of all defenses on all images produces by all attacks will be saved into all_classification.csv file. Useful for debugging. This function saves following files into output directory: accuracy_on_attacks.csv: matrix with number of correctly classified images for each pair of defense and attack. accuracy_on_targeted_attacks.csv: matrix with number of correctly classified images for each pair of defense and targeted attack. hit_target_class.csv: matrix with number of times defense classified image as specified target class for each pair of defense and targeted attack. defense_ranking.csv: ranking and scores of all defenses. attack_ranking.csv: ranking and scores of all attacks. targeted_attack_ranking.csv: ranking and scores of all targeted attacks. all_classification.csv: results of classification of all defenses on all images produced by all attacks. Only saved if save_all_classification argument is True. """ def write_ranking(filename, header, names, scores): """Helper method which saves submissions' scores and names.""" order = np.argsort(scores)[::-1] with open(filename, 'w') as f: writer = csv.writer(f) writer.writerow(header) for idx in order: writer.writerow([names[idx], scores[idx]]) def write_score_matrix(filename, scores, row_names, column_names): """Helper method which saves score matrix.""" result = np.pad(scores, ((1, 0), (1, 0)), 'constant').astype(np.object) result[0, 0] = '' result[1:, 0] = row_names result[0, 1:] = column_names np.savetxt(filename, result, fmt='%s', delimiter=',') attack_names = list(attacks_output.attack_names) attack_names_idx = {name: index for index, name in enumerate(attack_names)} targeted_attack_names = list(attacks_output.targeted_attack_names) targeted_attack_names_idx = {name: index for index, name in enumerate(targeted_attack_names)} defense_names = list(defenses_output.keys()) defense_names_idx = {name: index for index, name in enumerate(defense_names)} # In the matrices below: rows - attacks, columns - defenses. accuracy_on_attacks = np.zeros( (len(attack_names), len(defense_names)), dtype=np.int32) accuracy_on_targeted_attacks = np.zeros( (len(targeted_attack_names), len(defense_names)), dtype=np.int32) hit_target_class = np.zeros( (len(targeted_attack_names), len(defense_names)), dtype=np.int32) for defense_name, defense_result in defenses_output.items(): for image_filename, predicted_label in defense_result.items(): attack_name, is_targeted, image_id = ( attacks_output.image_by_base_filename(image_filename)) true_label = dataset_meta.get_true_label(image_id) defense_idx = defense_names_idx[defense_name] if is_targeted: target_class = dataset_meta.get_target_class(image_id) if true_label == predicted_label: attack_idx = targeted_attack_names_idx[attack_name] accuracy_on_targeted_attacks[attack_idx, defense_idx] += 1 if target_class == predicted_label: attack_idx = targeted_attack_names_idx[attack_name] hit_target_class[attack_idx, defense_idx] += 1 else: if true_label == predicted_label: attack_idx = attack_names_idx[attack_name] accuracy_on_attacks[attack_idx, defense_idx] += 1 # Save matrices. write_score_matrix(os.path.join(output_dir, 'accuracy_on_attacks.csv'), accuracy_on_attacks, attack_names, defense_names) write_score_matrix( os.path.join(output_dir, 'accuracy_on_targeted_attacks.csv'), accuracy_on_targeted_attacks, targeted_attack_names, defense_names) write_score_matrix(os.path.join(output_dir, 'hit_target_class.csv'), hit_target_class, targeted_attack_names, defense_names) # Compute and save scores and ranking of attacks and defenses, # higher scores are better. defense_scores = (np.sum(accuracy_on_attacks, axis=0) + np.sum(accuracy_on_targeted_attacks, axis=0)) attack_scores = (attacks_output.dataset_image_count * len(defenses_output) - np.sum(accuracy_on_attacks, axis=1)) targeted_attack_scores = np.sum(hit_target_class, axis=1) write_ranking(os.path.join(output_dir, 'defense_ranking.csv'), ['DefenseName', 'Score'], defense_names, defense_scores) write_ranking(os.path.join(output_dir, 'attack_ranking.csv'), ['AttackName', 'Score'], attack_names, attack_scores) write_ranking( os.path.join(output_dir, 'targeted_attack_ranking.csv'), ['AttackName', 'Score'], targeted_attack_names, targeted_attack_scores) if save_all_classification: with open(os.path.join(output_dir, 'all_classification.csv'), 'w') as f: writer = csv.writer(f) writer.writerow(['AttackName', 'IsTargeted', 'DefenseName', 'ImageId', 'PredictedLabel', 'TrueLabel', 'TargetClass']) for defense_name, defense_result in defenses_output.items(): for image_filename, predicted_label in defense_result.items(): attack_name, is_targeted, image_id = ( attacks_output.image_by_base_filename(image_filename)) true_label = dataset_meta.get_true_label(image_id) target_class = dataset_meta.get_target_class(image_id) writer.writerow([attack_name, is_targeted, defense_name, image_id, predicted_label, true_label, target_class])
python
def compute_and_save_scores_and_ranking(attacks_output, defenses_output, dataset_meta, output_dir, save_all_classification=False): """Computes scores and ranking and saves it. Args: attacks_output: output of attacks, instance of AttacksOutput class. defenses_output: outputs of defenses. Dictionary of dictionaries, key in outer dictionary is name of the defense, key of inner dictionary is name of the image, value of inner dictionary is classification label. dataset_meta: dataset metadata, instance of DatasetMetadata class. output_dir: output directory where results will be saved. save_all_classification: If True then classification results of all defenses on all images produces by all attacks will be saved into all_classification.csv file. Useful for debugging. This function saves following files into output directory: accuracy_on_attacks.csv: matrix with number of correctly classified images for each pair of defense and attack. accuracy_on_targeted_attacks.csv: matrix with number of correctly classified images for each pair of defense and targeted attack. hit_target_class.csv: matrix with number of times defense classified image as specified target class for each pair of defense and targeted attack. defense_ranking.csv: ranking and scores of all defenses. attack_ranking.csv: ranking and scores of all attacks. targeted_attack_ranking.csv: ranking and scores of all targeted attacks. all_classification.csv: results of classification of all defenses on all images produced by all attacks. Only saved if save_all_classification argument is True. """ def write_ranking(filename, header, names, scores): """Helper method which saves submissions' scores and names.""" order = np.argsort(scores)[::-1] with open(filename, 'w') as f: writer = csv.writer(f) writer.writerow(header) for idx in order: writer.writerow([names[idx], scores[idx]]) def write_score_matrix(filename, scores, row_names, column_names): """Helper method which saves score matrix.""" result = np.pad(scores, ((1, 0), (1, 0)), 'constant').astype(np.object) result[0, 0] = '' result[1:, 0] = row_names result[0, 1:] = column_names np.savetxt(filename, result, fmt='%s', delimiter=',') attack_names = list(attacks_output.attack_names) attack_names_idx = {name: index for index, name in enumerate(attack_names)} targeted_attack_names = list(attacks_output.targeted_attack_names) targeted_attack_names_idx = {name: index for index, name in enumerate(targeted_attack_names)} defense_names = list(defenses_output.keys()) defense_names_idx = {name: index for index, name in enumerate(defense_names)} # In the matrices below: rows - attacks, columns - defenses. accuracy_on_attacks = np.zeros( (len(attack_names), len(defense_names)), dtype=np.int32) accuracy_on_targeted_attacks = np.zeros( (len(targeted_attack_names), len(defense_names)), dtype=np.int32) hit_target_class = np.zeros( (len(targeted_attack_names), len(defense_names)), dtype=np.int32) for defense_name, defense_result in defenses_output.items(): for image_filename, predicted_label in defense_result.items(): attack_name, is_targeted, image_id = ( attacks_output.image_by_base_filename(image_filename)) true_label = dataset_meta.get_true_label(image_id) defense_idx = defense_names_idx[defense_name] if is_targeted: target_class = dataset_meta.get_target_class(image_id) if true_label == predicted_label: attack_idx = targeted_attack_names_idx[attack_name] accuracy_on_targeted_attacks[attack_idx, defense_idx] += 1 if target_class == predicted_label: attack_idx = targeted_attack_names_idx[attack_name] hit_target_class[attack_idx, defense_idx] += 1 else: if true_label == predicted_label: attack_idx = attack_names_idx[attack_name] accuracy_on_attacks[attack_idx, defense_idx] += 1 # Save matrices. write_score_matrix(os.path.join(output_dir, 'accuracy_on_attacks.csv'), accuracy_on_attacks, attack_names, defense_names) write_score_matrix( os.path.join(output_dir, 'accuracy_on_targeted_attacks.csv'), accuracy_on_targeted_attacks, targeted_attack_names, defense_names) write_score_matrix(os.path.join(output_dir, 'hit_target_class.csv'), hit_target_class, targeted_attack_names, defense_names) # Compute and save scores and ranking of attacks and defenses, # higher scores are better. defense_scores = (np.sum(accuracy_on_attacks, axis=0) + np.sum(accuracy_on_targeted_attacks, axis=0)) attack_scores = (attacks_output.dataset_image_count * len(defenses_output) - np.sum(accuracy_on_attacks, axis=1)) targeted_attack_scores = np.sum(hit_target_class, axis=1) write_ranking(os.path.join(output_dir, 'defense_ranking.csv'), ['DefenseName', 'Score'], defense_names, defense_scores) write_ranking(os.path.join(output_dir, 'attack_ranking.csv'), ['AttackName', 'Score'], attack_names, attack_scores) write_ranking( os.path.join(output_dir, 'targeted_attack_ranking.csv'), ['AttackName', 'Score'], targeted_attack_names, targeted_attack_scores) if save_all_classification: with open(os.path.join(output_dir, 'all_classification.csv'), 'w') as f: writer = csv.writer(f) writer.writerow(['AttackName', 'IsTargeted', 'DefenseName', 'ImageId', 'PredictedLabel', 'TrueLabel', 'TargetClass']) for defense_name, defense_result in defenses_output.items(): for image_filename, predicted_label in defense_result.items(): attack_name, is_targeted, image_id = ( attacks_output.image_by_base_filename(image_filename)) true_label = dataset_meta.get_true_label(image_id) target_class = dataset_meta.get_target_class(image_id) writer.writerow([attack_name, is_targeted, defense_name, image_id, predicted_label, true_label, target_class])
[ "def", "compute_and_save_scores_and_ranking", "(", "attacks_output", ",", "defenses_output", ",", "dataset_meta", ",", "output_dir", ",", "save_all_classification", "=", "False", ")", ":", "def", "write_ranking", "(", "filename", ",", "header", ",", "names", ",", "scores", ")", ":", "\"\"\"Helper method which saves submissions' scores and names.\"\"\"", "order", "=", "np", ".", "argsort", "(", "scores", ")", "[", ":", ":", "-", "1", "]", "with", "open", "(", "filename", ",", "'w'", ")", "as", "f", ":", "writer", "=", "csv", ".", "writer", "(", "f", ")", "writer", ".", "writerow", "(", "header", ")", "for", "idx", "in", "order", ":", "writer", ".", "writerow", "(", "[", "names", "[", "idx", "]", ",", "scores", "[", "idx", "]", "]", ")", "def", "write_score_matrix", "(", "filename", ",", "scores", ",", "row_names", ",", "column_names", ")", ":", "\"\"\"Helper method which saves score matrix.\"\"\"", "result", "=", "np", ".", "pad", "(", "scores", ",", "(", "(", "1", ",", "0", ")", ",", "(", "1", ",", "0", ")", ")", ",", "'constant'", ")", ".", "astype", "(", "np", ".", "object", ")", "result", "[", "0", ",", "0", "]", "=", "''", "result", "[", "1", ":", ",", "0", "]", "=", "row_names", "result", "[", "0", ",", "1", ":", "]", "=", "column_names", "np", ".", "savetxt", "(", "filename", ",", "result", ",", "fmt", "=", "'%s'", ",", "delimiter", "=", "','", ")", "attack_names", "=", "list", "(", "attacks_output", ".", "attack_names", ")", "attack_names_idx", "=", "{", "name", ":", "index", "for", "index", ",", "name", "in", "enumerate", "(", "attack_names", ")", "}", "targeted_attack_names", "=", "list", "(", "attacks_output", ".", "targeted_attack_names", ")", "targeted_attack_names_idx", "=", "{", "name", ":", "index", "for", "index", ",", "name", "in", "enumerate", "(", "targeted_attack_names", ")", "}", "defense_names", "=", "list", "(", "defenses_output", ".", "keys", "(", ")", ")", "defense_names_idx", "=", "{", "name", ":", "index", "for", "index", ",", "name", "in", "enumerate", "(", "defense_names", ")", "}", "# In the matrices below: rows - attacks, columns - defenses.", "accuracy_on_attacks", "=", "np", ".", "zeros", "(", "(", "len", "(", "attack_names", ")", ",", "len", "(", "defense_names", ")", ")", ",", "dtype", "=", "np", ".", "int32", ")", "accuracy_on_targeted_attacks", "=", "np", ".", "zeros", "(", "(", "len", "(", "targeted_attack_names", ")", ",", "len", "(", "defense_names", ")", ")", ",", "dtype", "=", "np", ".", "int32", ")", "hit_target_class", "=", "np", ".", "zeros", "(", "(", "len", "(", "targeted_attack_names", ")", ",", "len", "(", "defense_names", ")", ")", ",", "dtype", "=", "np", ".", "int32", ")", "for", "defense_name", ",", "defense_result", "in", "defenses_output", ".", "items", "(", ")", ":", "for", "image_filename", ",", "predicted_label", "in", "defense_result", ".", "items", "(", ")", ":", "attack_name", ",", "is_targeted", ",", "image_id", "=", "(", "attacks_output", ".", "image_by_base_filename", "(", "image_filename", ")", ")", "true_label", "=", "dataset_meta", ".", "get_true_label", "(", "image_id", ")", "defense_idx", "=", "defense_names_idx", "[", "defense_name", "]", "if", "is_targeted", ":", "target_class", "=", "dataset_meta", ".", "get_target_class", "(", "image_id", ")", "if", "true_label", "==", "predicted_label", ":", "attack_idx", "=", "targeted_attack_names_idx", "[", "attack_name", "]", "accuracy_on_targeted_attacks", "[", "attack_idx", ",", "defense_idx", "]", "+=", "1", "if", "target_class", "==", "predicted_label", ":", "attack_idx", "=", "targeted_attack_names_idx", "[", "attack_name", "]", "hit_target_class", "[", "attack_idx", ",", "defense_idx", "]", "+=", "1", "else", ":", "if", "true_label", "==", "predicted_label", ":", "attack_idx", "=", "attack_names_idx", "[", "attack_name", "]", "accuracy_on_attacks", "[", "attack_idx", ",", "defense_idx", "]", "+=", "1", "# Save matrices.", "write_score_matrix", "(", "os", ".", "path", ".", "join", "(", "output_dir", ",", "'accuracy_on_attacks.csv'", ")", ",", "accuracy_on_attacks", ",", "attack_names", ",", "defense_names", ")", "write_score_matrix", "(", "os", ".", "path", ".", "join", "(", "output_dir", ",", "'accuracy_on_targeted_attacks.csv'", ")", ",", "accuracy_on_targeted_attacks", ",", "targeted_attack_names", ",", "defense_names", ")", "write_score_matrix", "(", "os", ".", "path", ".", "join", "(", "output_dir", ",", "'hit_target_class.csv'", ")", ",", "hit_target_class", ",", "targeted_attack_names", ",", "defense_names", ")", "# Compute and save scores and ranking of attacks and defenses,", "# higher scores are better.", "defense_scores", "=", "(", "np", ".", "sum", "(", "accuracy_on_attacks", ",", "axis", "=", "0", ")", "+", "np", ".", "sum", "(", "accuracy_on_targeted_attacks", ",", "axis", "=", "0", ")", ")", "attack_scores", "=", "(", "attacks_output", ".", "dataset_image_count", "*", "len", "(", "defenses_output", ")", "-", "np", ".", "sum", "(", "accuracy_on_attacks", ",", "axis", "=", "1", ")", ")", "targeted_attack_scores", "=", "np", ".", "sum", "(", "hit_target_class", ",", "axis", "=", "1", ")", "write_ranking", "(", "os", ".", "path", ".", "join", "(", "output_dir", ",", "'defense_ranking.csv'", ")", ",", "[", "'DefenseName'", ",", "'Score'", "]", ",", "defense_names", ",", "defense_scores", ")", "write_ranking", "(", "os", ".", "path", ".", "join", "(", "output_dir", ",", "'attack_ranking.csv'", ")", ",", "[", "'AttackName'", ",", "'Score'", "]", ",", "attack_names", ",", "attack_scores", ")", "write_ranking", "(", "os", ".", "path", ".", "join", "(", "output_dir", ",", "'targeted_attack_ranking.csv'", ")", ",", "[", "'AttackName'", ",", "'Score'", "]", ",", "targeted_attack_names", ",", "targeted_attack_scores", ")", "if", "save_all_classification", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "output_dir", ",", "'all_classification.csv'", ")", ",", "'w'", ")", "as", "f", ":", "writer", "=", "csv", ".", "writer", "(", "f", ")", "writer", ".", "writerow", "(", "[", "'AttackName'", ",", "'IsTargeted'", ",", "'DefenseName'", ",", "'ImageId'", ",", "'PredictedLabel'", ",", "'TrueLabel'", ",", "'TargetClass'", "]", ")", "for", "defense_name", ",", "defense_result", "in", "defenses_output", ".", "items", "(", ")", ":", "for", "image_filename", ",", "predicted_label", "in", "defense_result", ".", "items", "(", ")", ":", "attack_name", ",", "is_targeted", ",", "image_id", "=", "(", "attacks_output", ".", "image_by_base_filename", "(", "image_filename", ")", ")", "true_label", "=", "dataset_meta", ".", "get_true_label", "(", "image_id", ")", "target_class", "=", "dataset_meta", ".", "get_target_class", "(", "image_id", ")", "writer", ".", "writerow", "(", "[", "attack_name", ",", "is_targeted", ",", "defense_name", ",", "image_id", ",", "predicted_label", ",", "true_label", ",", "target_class", "]", ")" ]
Computes scores and ranking and saves it. Args: attacks_output: output of attacks, instance of AttacksOutput class. defenses_output: outputs of defenses. Dictionary of dictionaries, key in outer dictionary is name of the defense, key of inner dictionary is name of the image, value of inner dictionary is classification label. dataset_meta: dataset metadata, instance of DatasetMetadata class. output_dir: output directory where results will be saved. save_all_classification: If True then classification results of all defenses on all images produces by all attacks will be saved into all_classification.csv file. Useful for debugging. This function saves following files into output directory: accuracy_on_attacks.csv: matrix with number of correctly classified images for each pair of defense and attack. accuracy_on_targeted_attacks.csv: matrix with number of correctly classified images for each pair of defense and targeted attack. hit_target_class.csv: matrix with number of times defense classified image as specified target class for each pair of defense and targeted attack. defense_ranking.csv: ranking and scores of all defenses. attack_ranking.csv: ranking and scores of all attacks. targeted_attack_ranking.csv: ranking and scores of all targeted attacks. all_classification.csv: results of classification of all defenses on all images produced by all attacks. Only saved if save_all_classification argument is True.
[ "Computes", "scores", "and", "ranking", "and", "saves", "it", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/run_attacks_and_defenses.py#L344-L465
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/dev_toolkit/run_attacks_and_defenses.py
main
def main(): """Run all attacks against all defenses and compute results. """ args = parse_args() attacks_output_dir = os.path.join(args.intermediate_results_dir, 'attacks_output') targeted_attacks_output_dir = os.path.join(args.intermediate_results_dir, 'targeted_attacks_output') defenses_output_dir = os.path.join(args.intermediate_results_dir, 'defenses_output') all_adv_examples_dir = os.path.join(args.intermediate_results_dir, 'all_adv_examples') # Load dataset metadata. dataset_meta = DatasetMetadata(args.dataset_metadata) # Load attacks and defenses. attacks = [ a for a in read_submissions_from_directory(args.attacks_dir, args.use_gpu) if isinstance(a, Attack) ] targeted_attacks = [ a for a in read_submissions_from_directory(args.targeted_attacks_dir, args.use_gpu) if isinstance(a, Attack) ] defenses = [ d for d in read_submissions_from_directory(args.defenses_dir, args.use_gpu) if isinstance(d, Defense) ] print('Found attacks: ', [a.name for a in attacks]) print('Found tageted attacks: ', [a.name for a in targeted_attacks]) print('Found defenses: ', [d.name for d in defenses]) # Prepare subdirectories for intermediate results. os.mkdir(attacks_output_dir) os.mkdir(targeted_attacks_output_dir) os.mkdir(defenses_output_dir) os.mkdir(all_adv_examples_dir) for a in attacks: os.mkdir(os.path.join(attacks_output_dir, a.name)) for a in targeted_attacks: os.mkdir(os.path.join(targeted_attacks_output_dir, a.name)) for d in defenses: os.mkdir(os.path.join(defenses_output_dir, d.name)) # Run all non-targeted attacks. attacks_output = AttacksOutput(args.dataset_dir, attacks_output_dir, targeted_attacks_output_dir, all_adv_examples_dir, args.epsilon) for a in attacks: a.run(args.dataset_dir, os.path.join(attacks_output_dir, a.name), args.epsilon) attacks_output.clip_and_copy_attack_outputs(a.name, False) # Run all targeted attacks. dataset_meta.save_target_classes(os.path.join(args.dataset_dir, 'target_class.csv')) for a in targeted_attacks: a.run(args.dataset_dir, os.path.join(targeted_attacks_output_dir, a.name), args.epsilon) attacks_output.clip_and_copy_attack_outputs(a.name, True) # Run all defenses. defenses_output = {} for d in defenses: d.run(all_adv_examples_dir, os.path.join(defenses_output_dir, d.name)) defenses_output[d.name] = load_defense_output( os.path.join(defenses_output_dir, d.name, 'result.csv')) # Compute and save scoring. compute_and_save_scores_and_ranking(attacks_output, defenses_output, dataset_meta, args.output_dir, args.save_all_classification)
python
def main(): """Run all attacks against all defenses and compute results. """ args = parse_args() attacks_output_dir = os.path.join(args.intermediate_results_dir, 'attacks_output') targeted_attacks_output_dir = os.path.join(args.intermediate_results_dir, 'targeted_attacks_output') defenses_output_dir = os.path.join(args.intermediate_results_dir, 'defenses_output') all_adv_examples_dir = os.path.join(args.intermediate_results_dir, 'all_adv_examples') # Load dataset metadata. dataset_meta = DatasetMetadata(args.dataset_metadata) # Load attacks and defenses. attacks = [ a for a in read_submissions_from_directory(args.attacks_dir, args.use_gpu) if isinstance(a, Attack) ] targeted_attacks = [ a for a in read_submissions_from_directory(args.targeted_attacks_dir, args.use_gpu) if isinstance(a, Attack) ] defenses = [ d for d in read_submissions_from_directory(args.defenses_dir, args.use_gpu) if isinstance(d, Defense) ] print('Found attacks: ', [a.name for a in attacks]) print('Found tageted attacks: ', [a.name for a in targeted_attacks]) print('Found defenses: ', [d.name for d in defenses]) # Prepare subdirectories for intermediate results. os.mkdir(attacks_output_dir) os.mkdir(targeted_attacks_output_dir) os.mkdir(defenses_output_dir) os.mkdir(all_adv_examples_dir) for a in attacks: os.mkdir(os.path.join(attacks_output_dir, a.name)) for a in targeted_attacks: os.mkdir(os.path.join(targeted_attacks_output_dir, a.name)) for d in defenses: os.mkdir(os.path.join(defenses_output_dir, d.name)) # Run all non-targeted attacks. attacks_output = AttacksOutput(args.dataset_dir, attacks_output_dir, targeted_attacks_output_dir, all_adv_examples_dir, args.epsilon) for a in attacks: a.run(args.dataset_dir, os.path.join(attacks_output_dir, a.name), args.epsilon) attacks_output.clip_and_copy_attack_outputs(a.name, False) # Run all targeted attacks. dataset_meta.save_target_classes(os.path.join(args.dataset_dir, 'target_class.csv')) for a in targeted_attacks: a.run(args.dataset_dir, os.path.join(targeted_attacks_output_dir, a.name), args.epsilon) attacks_output.clip_and_copy_attack_outputs(a.name, True) # Run all defenses. defenses_output = {} for d in defenses: d.run(all_adv_examples_dir, os.path.join(defenses_output_dir, d.name)) defenses_output[d.name] = load_defense_output( os.path.join(defenses_output_dir, d.name, 'result.csv')) # Compute and save scoring. compute_and_save_scores_and_ranking(attacks_output, defenses_output, dataset_meta, args.output_dir, args.save_all_classification)
[ "def", "main", "(", ")", ":", "args", "=", "parse_args", "(", ")", "attacks_output_dir", "=", "os", ".", "path", ".", "join", "(", "args", ".", "intermediate_results_dir", ",", "'attacks_output'", ")", "targeted_attacks_output_dir", "=", "os", ".", "path", ".", "join", "(", "args", ".", "intermediate_results_dir", ",", "'targeted_attacks_output'", ")", "defenses_output_dir", "=", "os", ".", "path", ".", "join", "(", "args", ".", "intermediate_results_dir", ",", "'defenses_output'", ")", "all_adv_examples_dir", "=", "os", ".", "path", ".", "join", "(", "args", ".", "intermediate_results_dir", ",", "'all_adv_examples'", ")", "# Load dataset metadata.", "dataset_meta", "=", "DatasetMetadata", "(", "args", ".", "dataset_metadata", ")", "# Load attacks and defenses.", "attacks", "=", "[", "a", "for", "a", "in", "read_submissions_from_directory", "(", "args", ".", "attacks_dir", ",", "args", ".", "use_gpu", ")", "if", "isinstance", "(", "a", ",", "Attack", ")", "]", "targeted_attacks", "=", "[", "a", "for", "a", "in", "read_submissions_from_directory", "(", "args", ".", "targeted_attacks_dir", ",", "args", ".", "use_gpu", ")", "if", "isinstance", "(", "a", ",", "Attack", ")", "]", "defenses", "=", "[", "d", "for", "d", "in", "read_submissions_from_directory", "(", "args", ".", "defenses_dir", ",", "args", ".", "use_gpu", ")", "if", "isinstance", "(", "d", ",", "Defense", ")", "]", "print", "(", "'Found attacks: '", ",", "[", "a", ".", "name", "for", "a", "in", "attacks", "]", ")", "print", "(", "'Found tageted attacks: '", ",", "[", "a", ".", "name", "for", "a", "in", "targeted_attacks", "]", ")", "print", "(", "'Found defenses: '", ",", "[", "d", ".", "name", "for", "d", "in", "defenses", "]", ")", "# Prepare subdirectories for intermediate results.", "os", ".", "mkdir", "(", "attacks_output_dir", ")", "os", ".", "mkdir", "(", "targeted_attacks_output_dir", ")", "os", ".", "mkdir", "(", "defenses_output_dir", ")", "os", ".", "mkdir", "(", "all_adv_examples_dir", ")", "for", "a", "in", "attacks", ":", "os", ".", "mkdir", "(", "os", ".", "path", ".", "join", "(", "attacks_output_dir", ",", "a", ".", "name", ")", ")", "for", "a", "in", "targeted_attacks", ":", "os", ".", "mkdir", "(", "os", ".", "path", ".", "join", "(", "targeted_attacks_output_dir", ",", "a", ".", "name", ")", ")", "for", "d", "in", "defenses", ":", "os", ".", "mkdir", "(", "os", ".", "path", ".", "join", "(", "defenses_output_dir", ",", "d", ".", "name", ")", ")", "# Run all non-targeted attacks.", "attacks_output", "=", "AttacksOutput", "(", "args", ".", "dataset_dir", ",", "attacks_output_dir", ",", "targeted_attacks_output_dir", ",", "all_adv_examples_dir", ",", "args", ".", "epsilon", ")", "for", "a", "in", "attacks", ":", "a", ".", "run", "(", "args", ".", "dataset_dir", ",", "os", ".", "path", ".", "join", "(", "attacks_output_dir", ",", "a", ".", "name", ")", ",", "args", ".", "epsilon", ")", "attacks_output", ".", "clip_and_copy_attack_outputs", "(", "a", ".", "name", ",", "False", ")", "# Run all targeted attacks.", "dataset_meta", ".", "save_target_classes", "(", "os", ".", "path", ".", "join", "(", "args", ".", "dataset_dir", ",", "'target_class.csv'", ")", ")", "for", "a", "in", "targeted_attacks", ":", "a", ".", "run", "(", "args", ".", "dataset_dir", ",", "os", ".", "path", ".", "join", "(", "targeted_attacks_output_dir", ",", "a", ".", "name", ")", ",", "args", ".", "epsilon", ")", "attacks_output", ".", "clip_and_copy_attack_outputs", "(", "a", ".", "name", ",", "True", ")", "# Run all defenses.", "defenses_output", "=", "{", "}", "for", "d", "in", "defenses", ":", "d", ".", "run", "(", "all_adv_examples_dir", ",", "os", ".", "path", ".", "join", "(", "defenses_output_dir", ",", "d", ".", "name", ")", ")", "defenses_output", "[", "d", ".", "name", "]", "=", "load_defense_output", "(", "os", ".", "path", ".", "join", "(", "defenses_output_dir", ",", "d", ".", "name", ",", "'result.csv'", ")", ")", "# Compute and save scoring.", "compute_and_save_scores_and_ranking", "(", "attacks_output", ",", "defenses_output", ",", "dataset_meta", ",", "args", ".", "output_dir", ",", "args", ".", "save_all_classification", ")" ]
Run all attacks against all defenses and compute results.
[ "Run", "all", "attacks", "against", "all", "defenses", "and", "compute", "results", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/run_attacks_and_defenses.py#L468-L547
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/dev_toolkit/run_attacks_and_defenses.py
Attack.run
def run(self, input_dir, output_dir, epsilon): """Runs attack inside Docker. Args: input_dir: directory with input (dataset). output_dir: directory where output (adversarial images) should be written. epsilon: maximum allowed size of adversarial perturbation, should be in range [0, 255]. """ print('Running attack ', self.name) cmd = [self.docker_binary(), 'run', '-v', '{0}:/input_images'.format(input_dir), '-v', '{0}:/output_images'.format(output_dir), '-v', '{0}:/code'.format(self.directory), '-w', '/code', self.container, './' + self.entry_point, '/input_images', '/output_images', str(epsilon)] print(' '.join(cmd)) subprocess.call(cmd)
python
def run(self, input_dir, output_dir, epsilon): """Runs attack inside Docker. Args: input_dir: directory with input (dataset). output_dir: directory where output (adversarial images) should be written. epsilon: maximum allowed size of adversarial perturbation, should be in range [0, 255]. """ print('Running attack ', self.name) cmd = [self.docker_binary(), 'run', '-v', '{0}:/input_images'.format(input_dir), '-v', '{0}:/output_images'.format(output_dir), '-v', '{0}:/code'.format(self.directory), '-w', '/code', self.container, './' + self.entry_point, '/input_images', '/output_images', str(epsilon)] print(' '.join(cmd)) subprocess.call(cmd)
[ "def", "run", "(", "self", ",", "input_dir", ",", "output_dir", ",", "epsilon", ")", ":", "print", "(", "'Running attack '", ",", "self", ".", "name", ")", "cmd", "=", "[", "self", ".", "docker_binary", "(", ")", ",", "'run'", ",", "'-v'", ",", "'{0}:/input_images'", ".", "format", "(", "input_dir", ")", ",", "'-v'", ",", "'{0}:/output_images'", ".", "format", "(", "output_dir", ")", ",", "'-v'", ",", "'{0}:/code'", ".", "format", "(", "self", ".", "directory", ")", ",", "'-w'", ",", "'/code'", ",", "self", ".", "container", ",", "'./'", "+", "self", ".", "entry_point", ",", "'/input_images'", ",", "'/output_images'", ",", "str", "(", "epsilon", ")", "]", "print", "(", "' '", ".", "join", "(", "cmd", ")", ")", "subprocess", ".", "call", "(", "cmd", ")" ]
Runs attack inside Docker. Args: input_dir: directory with input (dataset). output_dir: directory where output (adversarial images) should be written. epsilon: maximum allowed size of adversarial perturbation, should be in range [0, 255].
[ "Runs", "attack", "inside", "Docker", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/run_attacks_and_defenses.py#L73-L94
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/dev_toolkit/run_attacks_and_defenses.py
AttacksOutput._load_dataset_clipping
def _load_dataset_clipping(self, dataset_dir, epsilon): """Helper method which loads dataset and determines clipping range. Args: dataset_dir: location of the dataset. epsilon: maximum allowed size of adversarial perturbation. """ self.dataset_max_clip = {} self.dataset_min_clip = {} self._dataset_image_count = 0 for fname in os.listdir(dataset_dir): if not fname.endswith('.png'): continue image_id = fname[:-4] image = np.array( Image.open(os.path.join(dataset_dir, fname)).convert('RGB')) image = image.astype('int32') self._dataset_image_count += 1 self.dataset_max_clip[image_id] = np.clip(image + epsilon, 0, 255).astype('uint8') self.dataset_min_clip[image_id] = np.clip(image - epsilon, 0, 255).astype('uint8')
python
def _load_dataset_clipping(self, dataset_dir, epsilon): """Helper method which loads dataset and determines clipping range. Args: dataset_dir: location of the dataset. epsilon: maximum allowed size of adversarial perturbation. """ self.dataset_max_clip = {} self.dataset_min_clip = {} self._dataset_image_count = 0 for fname in os.listdir(dataset_dir): if not fname.endswith('.png'): continue image_id = fname[:-4] image = np.array( Image.open(os.path.join(dataset_dir, fname)).convert('RGB')) image = image.astype('int32') self._dataset_image_count += 1 self.dataset_max_clip[image_id] = np.clip(image + epsilon, 0, 255).astype('uint8') self.dataset_min_clip[image_id] = np.clip(image - epsilon, 0, 255).astype('uint8')
[ "def", "_load_dataset_clipping", "(", "self", ",", "dataset_dir", ",", "epsilon", ")", ":", "self", ".", "dataset_max_clip", "=", "{", "}", "self", ".", "dataset_min_clip", "=", "{", "}", "self", ".", "_dataset_image_count", "=", "0", "for", "fname", "in", "os", ".", "listdir", "(", "dataset_dir", ")", ":", "if", "not", "fname", ".", "endswith", "(", "'.png'", ")", ":", "continue", "image_id", "=", "fname", "[", ":", "-", "4", "]", "image", "=", "np", ".", "array", "(", "Image", ".", "open", "(", "os", ".", "path", ".", "join", "(", "dataset_dir", ",", "fname", ")", ")", ".", "convert", "(", "'RGB'", ")", ")", "image", "=", "image", ".", "astype", "(", "'int32'", ")", "self", ".", "_dataset_image_count", "+=", "1", "self", ".", "dataset_max_clip", "[", "image_id", "]", "=", "np", ".", "clip", "(", "image", "+", "epsilon", ",", "0", ",", "255", ")", ".", "astype", "(", "'uint8'", ")", "self", ".", "dataset_min_clip", "[", "image_id", "]", "=", "np", ".", "clip", "(", "image", "-", "epsilon", ",", "0", ",", "255", ")", ".", "astype", "(", "'uint8'", ")" ]
Helper method which loads dataset and determines clipping range. Args: dataset_dir: location of the dataset. epsilon: maximum allowed size of adversarial perturbation.
[ "Helper", "method", "which", "loads", "dataset", "and", "determines", "clipping", "range", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/run_attacks_and_defenses.py#L191-L214
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/dev_toolkit/run_attacks_and_defenses.py
AttacksOutput.clip_and_copy_attack_outputs
def clip_and_copy_attack_outputs(self, attack_name, is_targeted): """Clips results of attack and copy it to directory with all images. Args: attack_name: name of the attack. is_targeted: if True then attack is targeted, otherwise non-targeted. """ if is_targeted: self._targeted_attack_names.add(attack_name) else: self._attack_names.add(attack_name) attack_dir = os.path.join(self.targeted_attacks_output_dir if is_targeted else self.attacks_output_dir, attack_name) for fname in os.listdir(attack_dir): if not (fname.endswith('.png') or fname.endswith('.jpg')): continue image_id = fname[:-4] if image_id not in self.dataset_max_clip: continue image_max_clip = self.dataset_max_clip[image_id] image_min_clip = self.dataset_min_clip[image_id] adversarial_image = np.array( Image.open(os.path.join(attack_dir, fname)).convert('RGB')) clipped_adv_image = np.clip(adversarial_image, image_min_clip, image_max_clip) output_basename = '{0:08d}'.format(self._output_image_idx) self._output_image_idx += 1 self._output_to_attack_mapping[output_basename] = (attack_name, is_targeted, image_id) if is_targeted: self._targeted_attack_image_count += 1 else: self._attack_image_count += 1 Image.fromarray(clipped_adv_image).save( os.path.join(self.all_adv_examples_dir, output_basename + '.png'))
python
def clip_and_copy_attack_outputs(self, attack_name, is_targeted): """Clips results of attack and copy it to directory with all images. Args: attack_name: name of the attack. is_targeted: if True then attack is targeted, otherwise non-targeted. """ if is_targeted: self._targeted_attack_names.add(attack_name) else: self._attack_names.add(attack_name) attack_dir = os.path.join(self.targeted_attacks_output_dir if is_targeted else self.attacks_output_dir, attack_name) for fname in os.listdir(attack_dir): if not (fname.endswith('.png') or fname.endswith('.jpg')): continue image_id = fname[:-4] if image_id not in self.dataset_max_clip: continue image_max_clip = self.dataset_max_clip[image_id] image_min_clip = self.dataset_min_clip[image_id] adversarial_image = np.array( Image.open(os.path.join(attack_dir, fname)).convert('RGB')) clipped_adv_image = np.clip(adversarial_image, image_min_clip, image_max_clip) output_basename = '{0:08d}'.format(self._output_image_idx) self._output_image_idx += 1 self._output_to_attack_mapping[output_basename] = (attack_name, is_targeted, image_id) if is_targeted: self._targeted_attack_image_count += 1 else: self._attack_image_count += 1 Image.fromarray(clipped_adv_image).save( os.path.join(self.all_adv_examples_dir, output_basename + '.png'))
[ "def", "clip_and_copy_attack_outputs", "(", "self", ",", "attack_name", ",", "is_targeted", ")", ":", "if", "is_targeted", ":", "self", ".", "_targeted_attack_names", ".", "add", "(", "attack_name", ")", "else", ":", "self", ".", "_attack_names", ".", "add", "(", "attack_name", ")", "attack_dir", "=", "os", ".", "path", ".", "join", "(", "self", ".", "targeted_attacks_output_dir", "if", "is_targeted", "else", "self", ".", "attacks_output_dir", ",", "attack_name", ")", "for", "fname", "in", "os", ".", "listdir", "(", "attack_dir", ")", ":", "if", "not", "(", "fname", ".", "endswith", "(", "'.png'", ")", "or", "fname", ".", "endswith", "(", "'.jpg'", ")", ")", ":", "continue", "image_id", "=", "fname", "[", ":", "-", "4", "]", "if", "image_id", "not", "in", "self", ".", "dataset_max_clip", ":", "continue", "image_max_clip", "=", "self", ".", "dataset_max_clip", "[", "image_id", "]", "image_min_clip", "=", "self", ".", "dataset_min_clip", "[", "image_id", "]", "adversarial_image", "=", "np", ".", "array", "(", "Image", ".", "open", "(", "os", ".", "path", ".", "join", "(", "attack_dir", ",", "fname", ")", ")", ".", "convert", "(", "'RGB'", ")", ")", "clipped_adv_image", "=", "np", ".", "clip", "(", "adversarial_image", ",", "image_min_clip", ",", "image_max_clip", ")", "output_basename", "=", "'{0:08d}'", ".", "format", "(", "self", ".", "_output_image_idx", ")", "self", ".", "_output_image_idx", "+=", "1", "self", ".", "_output_to_attack_mapping", "[", "output_basename", "]", "=", "(", "attack_name", ",", "is_targeted", ",", "image_id", ")", "if", "is_targeted", ":", "self", ".", "_targeted_attack_image_count", "+=", "1", "else", ":", "self", ".", "_attack_image_count", "+=", "1", "Image", ".", "fromarray", "(", "clipped_adv_image", ")", ".", "save", "(", "os", ".", "path", ".", "join", "(", "self", ".", "all_adv_examples_dir", ",", "output_basename", "+", "'.png'", ")", ")" ]
Clips results of attack and copy it to directory with all images. Args: attack_name: name of the attack. is_targeted: if True then attack is targeted, otherwise non-targeted.
[ "Clips", "results", "of", "attack", "and", "copy", "it", "to", "directory", "with", "all", "images", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/run_attacks_and_defenses.py#L216-L254
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/dev_toolkit/run_attacks_and_defenses.py
DatasetMetadata.save_target_classes
def save_target_classes(self, filename): """Saves target classed for all dataset images into given file.""" with open(filename, 'w') as f: for k, v in self._target_classes.items(): f.write('{0}.png,{1}\n'.format(k, v))
python
def save_target_classes(self, filename): """Saves target classed for all dataset images into given file.""" with open(filename, 'w') as f: for k, v in self._target_classes.items(): f.write('{0}.png,{1}\n'.format(k, v))
[ "def", "save_target_classes", "(", "self", ",", "filename", ")", ":", "with", "open", "(", "filename", ",", "'w'", ")", "as", "f", ":", "for", "k", ",", "v", "in", "self", ".", "_target_classes", ".", "items", "(", ")", ":", "f", ".", "write", "(", "'{0}.png,{1}\\n'", ".", "format", "(", "k", ",", "v", ")", ")" ]
Saves target classed for all dataset images into given file.
[ "Saves", "target", "classed", "for", "all", "dataset", "images", "into", "given", "file", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/run_attacks_and_defenses.py#L321-L325
train
tensorflow/cleverhans
cleverhans/attack_bundling.py
single_run_max_confidence_recipe
def single_run_max_confidence_recipe(sess, model, x, y, nb_classes, eps, clip_min, clip_max, eps_iter, nb_iter, report_path, batch_size=BATCH_SIZE, eps_iter_small=None): """A reasonable attack bundling recipe for a max norm threat model and a defender that uses confidence thresholding. This recipe uses both uniform noise and randomly-initialized PGD targeted attacks. References: https://openreview.net/forum?id=H1g0piA9tQ This version runs each attack (noise, targeted PGD for each class with nb_iter iterations, target PGD for each class with 25X more iterations) just once and then stops. See `basic_max_confidence_recipe` for a version that runs indefinitely. :param sess: tf.Session :param model: cleverhans.model.Model :param x: numpy array containing clean example inputs to attack :param y: numpy array containing true labels :param nb_classes: int, number of classes :param eps: float, maximum size of perturbation (measured by max norm) :param eps_iter: float, step size for one version of PGD attacks (will also run another version with eps_iter_small step size) :param nb_iter: int, number of iterations for the cheaper PGD attacks (will also run another version with 25X more iterations) :param report_path: str, the path that the report will be saved to. :param batch_size: int, the total number of examples to run simultaneously :param eps_iter_small: optional, float. The second version of the PGD attack is run with 25 * nb_iter iterations and eps_iter_small step size. If eps_iter_small is not specified it is set to eps_iter / 25. """ noise_attack = Noise(model, sess) pgd_attack = ProjectedGradientDescent(model, sess) threat_params = {"eps": eps, "clip_min": clip_min, "clip_max": clip_max} noise_attack_config = AttackConfig(noise_attack, threat_params, "noise") attack_configs = [noise_attack_config] pgd_attack_configs = [] pgd_params = copy.copy(threat_params) pgd_params["eps_iter"] = eps_iter pgd_params["nb_iter"] = nb_iter assert batch_size % num_devices == 0 dev_batch_size = batch_size // num_devices ones = tf.ones(dev_batch_size, tf.int32) expensive_pgd = [] if eps_iter_small is None: eps_iter_small = eps_iter / 25. for cls in range(nb_classes): cls_params = copy.copy(pgd_params) cls_params['y_target'] = tf.to_float(tf.one_hot(ones * cls, nb_classes)) cls_attack_config = AttackConfig(pgd_attack, cls_params, "pgd_" + str(cls)) pgd_attack_configs.append(cls_attack_config) expensive_params = copy.copy(cls_params) expensive_params["eps_iter"] = eps_iter_small expensive_params["nb_iter"] *= 25. expensive_config = AttackConfig( pgd_attack, expensive_params, "expensive_pgd_" + str(cls)) expensive_pgd.append(expensive_config) attack_configs = [noise_attack_config] + pgd_attack_configs + expensive_pgd new_work_goal = {config: 1 for config in attack_configs} goals = [MaxConfidence(t=1., new_work_goal=new_work_goal)] bundle_attacks(sess, model, x, y, attack_configs, goals, report_path, attack_batch_size=batch_size, eval_batch_size=batch_size)
python
def single_run_max_confidence_recipe(sess, model, x, y, nb_classes, eps, clip_min, clip_max, eps_iter, nb_iter, report_path, batch_size=BATCH_SIZE, eps_iter_small=None): """A reasonable attack bundling recipe for a max norm threat model and a defender that uses confidence thresholding. This recipe uses both uniform noise and randomly-initialized PGD targeted attacks. References: https://openreview.net/forum?id=H1g0piA9tQ This version runs each attack (noise, targeted PGD for each class with nb_iter iterations, target PGD for each class with 25X more iterations) just once and then stops. See `basic_max_confidence_recipe` for a version that runs indefinitely. :param sess: tf.Session :param model: cleverhans.model.Model :param x: numpy array containing clean example inputs to attack :param y: numpy array containing true labels :param nb_classes: int, number of classes :param eps: float, maximum size of perturbation (measured by max norm) :param eps_iter: float, step size for one version of PGD attacks (will also run another version with eps_iter_small step size) :param nb_iter: int, number of iterations for the cheaper PGD attacks (will also run another version with 25X more iterations) :param report_path: str, the path that the report will be saved to. :param batch_size: int, the total number of examples to run simultaneously :param eps_iter_small: optional, float. The second version of the PGD attack is run with 25 * nb_iter iterations and eps_iter_small step size. If eps_iter_small is not specified it is set to eps_iter / 25. """ noise_attack = Noise(model, sess) pgd_attack = ProjectedGradientDescent(model, sess) threat_params = {"eps": eps, "clip_min": clip_min, "clip_max": clip_max} noise_attack_config = AttackConfig(noise_attack, threat_params, "noise") attack_configs = [noise_attack_config] pgd_attack_configs = [] pgd_params = copy.copy(threat_params) pgd_params["eps_iter"] = eps_iter pgd_params["nb_iter"] = nb_iter assert batch_size % num_devices == 0 dev_batch_size = batch_size // num_devices ones = tf.ones(dev_batch_size, tf.int32) expensive_pgd = [] if eps_iter_small is None: eps_iter_small = eps_iter / 25. for cls in range(nb_classes): cls_params = copy.copy(pgd_params) cls_params['y_target'] = tf.to_float(tf.one_hot(ones * cls, nb_classes)) cls_attack_config = AttackConfig(pgd_attack, cls_params, "pgd_" + str(cls)) pgd_attack_configs.append(cls_attack_config) expensive_params = copy.copy(cls_params) expensive_params["eps_iter"] = eps_iter_small expensive_params["nb_iter"] *= 25. expensive_config = AttackConfig( pgd_attack, expensive_params, "expensive_pgd_" + str(cls)) expensive_pgd.append(expensive_config) attack_configs = [noise_attack_config] + pgd_attack_configs + expensive_pgd new_work_goal = {config: 1 for config in attack_configs} goals = [MaxConfidence(t=1., new_work_goal=new_work_goal)] bundle_attacks(sess, model, x, y, attack_configs, goals, report_path, attack_batch_size=batch_size, eval_batch_size=batch_size)
[ "def", "single_run_max_confidence_recipe", "(", "sess", ",", "model", ",", "x", ",", "y", ",", "nb_classes", ",", "eps", ",", "clip_min", ",", "clip_max", ",", "eps_iter", ",", "nb_iter", ",", "report_path", ",", "batch_size", "=", "BATCH_SIZE", ",", "eps_iter_small", "=", "None", ")", ":", "noise_attack", "=", "Noise", "(", "model", ",", "sess", ")", "pgd_attack", "=", "ProjectedGradientDescent", "(", "model", ",", "sess", ")", "threat_params", "=", "{", "\"eps\"", ":", "eps", ",", "\"clip_min\"", ":", "clip_min", ",", "\"clip_max\"", ":", "clip_max", "}", "noise_attack_config", "=", "AttackConfig", "(", "noise_attack", ",", "threat_params", ",", "\"noise\"", ")", "attack_configs", "=", "[", "noise_attack_config", "]", "pgd_attack_configs", "=", "[", "]", "pgd_params", "=", "copy", ".", "copy", "(", "threat_params", ")", "pgd_params", "[", "\"eps_iter\"", "]", "=", "eps_iter", "pgd_params", "[", "\"nb_iter\"", "]", "=", "nb_iter", "assert", "batch_size", "%", "num_devices", "==", "0", "dev_batch_size", "=", "batch_size", "//", "num_devices", "ones", "=", "tf", ".", "ones", "(", "dev_batch_size", ",", "tf", ".", "int32", ")", "expensive_pgd", "=", "[", "]", "if", "eps_iter_small", "is", "None", ":", "eps_iter_small", "=", "eps_iter", "/", "25.", "for", "cls", "in", "range", "(", "nb_classes", ")", ":", "cls_params", "=", "copy", ".", "copy", "(", "pgd_params", ")", "cls_params", "[", "'y_target'", "]", "=", "tf", ".", "to_float", "(", "tf", ".", "one_hot", "(", "ones", "*", "cls", ",", "nb_classes", ")", ")", "cls_attack_config", "=", "AttackConfig", "(", "pgd_attack", ",", "cls_params", ",", "\"pgd_\"", "+", "str", "(", "cls", ")", ")", "pgd_attack_configs", ".", "append", "(", "cls_attack_config", ")", "expensive_params", "=", "copy", ".", "copy", "(", "cls_params", ")", "expensive_params", "[", "\"eps_iter\"", "]", "=", "eps_iter_small", "expensive_params", "[", "\"nb_iter\"", "]", "*=", "25.", "expensive_config", "=", "AttackConfig", "(", "pgd_attack", ",", "expensive_params", ",", "\"expensive_pgd_\"", "+", "str", "(", "cls", ")", ")", "expensive_pgd", ".", "append", "(", "expensive_config", ")", "attack_configs", "=", "[", "noise_attack_config", "]", "+", "pgd_attack_configs", "+", "expensive_pgd", "new_work_goal", "=", "{", "config", ":", "1", "for", "config", "in", "attack_configs", "}", "goals", "=", "[", "MaxConfidence", "(", "t", "=", "1.", ",", "new_work_goal", "=", "new_work_goal", ")", "]", "bundle_attacks", "(", "sess", ",", "model", ",", "x", ",", "y", ",", "attack_configs", ",", "goals", ",", "report_path", ",", "attack_batch_size", "=", "batch_size", ",", "eval_batch_size", "=", "batch_size", ")" ]
A reasonable attack bundling recipe for a max norm threat model and a defender that uses confidence thresholding. This recipe uses both uniform noise and randomly-initialized PGD targeted attacks. References: https://openreview.net/forum?id=H1g0piA9tQ This version runs each attack (noise, targeted PGD for each class with nb_iter iterations, target PGD for each class with 25X more iterations) just once and then stops. See `basic_max_confidence_recipe` for a version that runs indefinitely. :param sess: tf.Session :param model: cleverhans.model.Model :param x: numpy array containing clean example inputs to attack :param y: numpy array containing true labels :param nb_classes: int, number of classes :param eps: float, maximum size of perturbation (measured by max norm) :param eps_iter: float, step size for one version of PGD attacks (will also run another version with eps_iter_small step size) :param nb_iter: int, number of iterations for the cheaper PGD attacks (will also run another version with 25X more iterations) :param report_path: str, the path that the report will be saved to. :param batch_size: int, the total number of examples to run simultaneously :param eps_iter_small: optional, float. The second version of the PGD attack is run with 25 * nb_iter iterations and eps_iter_small step size. If eps_iter_small is not specified it is set to eps_iter / 25.
[ "A", "reasonable", "attack", "bundling", "recipe", "for", "a", "max", "norm", "threat", "model", "and", "a", "defender", "that", "uses", "confidence", "thresholding", ".", "This", "recipe", "uses", "both", "uniform", "noise", "and", "randomly", "-", "initialized", "PGD", "targeted", "attacks", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attack_bundling.py#L43-L107
train
tensorflow/cleverhans
cleverhans/attack_bundling.py
random_search_max_confidence_recipe
def random_search_max_confidence_recipe(sess, model, x, y, eps, clip_min, clip_max, report_path, batch_size=BATCH_SIZE, num_noise_points=10000): """Max confidence using random search. References: https://openreview.net/forum?id=H1g0piA9tQ Describes the max_confidence procedure used for the bundling in this recipe https://arxiv.org/abs/1802.00420 Describes using random search with 1e5 or more random points to avoid gradient masking. :param sess: tf.Session :param model: cleverhans.model.Model :param x: numpy array containing clean example inputs to attack :param y: numpy array containing true labels :param nb_classes: int, number of classes :param eps: float, maximum size of perturbation (measured by max norm) :param eps_iter: float, step size for one version of PGD attacks (will also run another version with 25X smaller step size) :param nb_iter: int, number of iterations for one version of PGD attacks (will also run another version with 25X more iterations) :param report_path: str, the path that the report will be saved to. :batch_size: int, the total number of examples to run simultaneously """ noise_attack = Noise(model, sess) threat_params = {"eps": eps, "clip_min": clip_min, "clip_max": clip_max} noise_attack_config = AttackConfig(noise_attack, threat_params) attack_configs = [noise_attack_config] assert batch_size % num_devices == 0 new_work_goal = {noise_attack_config: num_noise_points} goals = [MaxConfidence(t=1., new_work_goal=new_work_goal)] bundle_attacks(sess, model, x, y, attack_configs, goals, report_path)
python
def random_search_max_confidence_recipe(sess, model, x, y, eps, clip_min, clip_max, report_path, batch_size=BATCH_SIZE, num_noise_points=10000): """Max confidence using random search. References: https://openreview.net/forum?id=H1g0piA9tQ Describes the max_confidence procedure used for the bundling in this recipe https://arxiv.org/abs/1802.00420 Describes using random search with 1e5 or more random points to avoid gradient masking. :param sess: tf.Session :param model: cleverhans.model.Model :param x: numpy array containing clean example inputs to attack :param y: numpy array containing true labels :param nb_classes: int, number of classes :param eps: float, maximum size of perturbation (measured by max norm) :param eps_iter: float, step size for one version of PGD attacks (will also run another version with 25X smaller step size) :param nb_iter: int, number of iterations for one version of PGD attacks (will also run another version with 25X more iterations) :param report_path: str, the path that the report will be saved to. :batch_size: int, the total number of examples to run simultaneously """ noise_attack = Noise(model, sess) threat_params = {"eps": eps, "clip_min": clip_min, "clip_max": clip_max} noise_attack_config = AttackConfig(noise_attack, threat_params) attack_configs = [noise_attack_config] assert batch_size % num_devices == 0 new_work_goal = {noise_attack_config: num_noise_points} goals = [MaxConfidence(t=1., new_work_goal=new_work_goal)] bundle_attacks(sess, model, x, y, attack_configs, goals, report_path)
[ "def", "random_search_max_confidence_recipe", "(", "sess", ",", "model", ",", "x", ",", "y", ",", "eps", ",", "clip_min", ",", "clip_max", ",", "report_path", ",", "batch_size", "=", "BATCH_SIZE", ",", "num_noise_points", "=", "10000", ")", ":", "noise_attack", "=", "Noise", "(", "model", ",", "sess", ")", "threat_params", "=", "{", "\"eps\"", ":", "eps", ",", "\"clip_min\"", ":", "clip_min", ",", "\"clip_max\"", ":", "clip_max", "}", "noise_attack_config", "=", "AttackConfig", "(", "noise_attack", ",", "threat_params", ")", "attack_configs", "=", "[", "noise_attack_config", "]", "assert", "batch_size", "%", "num_devices", "==", "0", "new_work_goal", "=", "{", "noise_attack_config", ":", "num_noise_points", "}", "goals", "=", "[", "MaxConfidence", "(", "t", "=", "1.", ",", "new_work_goal", "=", "new_work_goal", ")", "]", "bundle_attacks", "(", "sess", ",", "model", ",", "x", ",", "y", ",", "attack_configs", ",", "goals", ",", "report_path", ")" ]
Max confidence using random search. References: https://openreview.net/forum?id=H1g0piA9tQ Describes the max_confidence procedure used for the bundling in this recipe https://arxiv.org/abs/1802.00420 Describes using random search with 1e5 or more random points to avoid gradient masking. :param sess: tf.Session :param model: cleverhans.model.Model :param x: numpy array containing clean example inputs to attack :param y: numpy array containing true labels :param nb_classes: int, number of classes :param eps: float, maximum size of perturbation (measured by max norm) :param eps_iter: float, step size for one version of PGD attacks (will also run another version with 25X smaller step size) :param nb_iter: int, number of iterations for one version of PGD attacks (will also run another version with 25X more iterations) :param report_path: str, the path that the report will be saved to. :batch_size: int, the total number of examples to run simultaneously
[ "Max", "confidence", "using", "random", "search", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attack_bundling.py#L256-L289
train
tensorflow/cleverhans
cleverhans/attack_bundling.py
bundle_attacks
def bundle_attacks(sess, model, x, y, attack_configs, goals, report_path, attack_batch_size=BATCH_SIZE, eval_batch_size=BATCH_SIZE): """ Runs attack bundling. Users of cleverhans may call this function but are more likely to call one of the recipes above. Reference: https://openreview.net/forum?id=H1g0piA9tQ :param sess: tf.session.Session :param model: cleverhans.model.Model :param x: numpy array containing clean example inputs to attack :param y: numpy array containing true labels :param attack_configs: list of AttackConfigs to run :param goals: list of AttackGoals to run The bundler works through the goals in order, until each is satisfied. Some goals may never be satisfied, in which case the bundler will run forever, updating the report on disk as it goes. :param report_path: str, the path the report will be saved to :param attack_batch_size: int, batch size for generating adversarial examples :param eval_batch_size: int, batch size for evaluating the model on clean / adversarial examples :returns: adv_x: The adversarial examples, in the same format as `x` run_counts: dict mapping each AttackConfig to a numpy array reporting how many times that AttackConfig was run on each example """ assert isinstance(sess, tf.Session) assert isinstance(model, Model) assert all(isinstance(attack_config, AttackConfig) for attack_config in attack_configs) assert all(isinstance(goal, AttackGoal) for goal in goals) assert isinstance(report_path, six.string_types) if x.shape[0] != y.shape[0]: raise ValueError("Number of input examples does not match number of labels") # Note: no need to precompile attacks, correctness_and_confidence # caches them run_counts = {} for attack_config in attack_configs: run_counts[attack_config] = np.zeros(x.shape[0], dtype=np.int64) # TODO: make an interface to pass this in if it has already been computed # elsewhere _logger.info("Running on clean data to initialize the report...") packed = correctness_and_confidence(sess, model, x, y, batch_size=eval_batch_size, devices=devices) _logger.info("...done") correctness, confidence = packed _logger.info("Accuracy: " + str(correctness.mean())) report = ConfidenceReport() report['clean'] = ConfidenceReportEntry(correctness, confidence) adv_x = x.copy() for goal in goals: bundle_attacks_with_goal(sess, model, x, y, adv_x, attack_configs, run_counts, goal, report, report_path, attack_batch_size=attack_batch_size, eval_batch_size=eval_batch_size) # Many users will set `goals` to make this run forever, so the return # statement is not the primary way to get information out. return adv_x, run_counts
python
def bundle_attacks(sess, model, x, y, attack_configs, goals, report_path, attack_batch_size=BATCH_SIZE, eval_batch_size=BATCH_SIZE): """ Runs attack bundling. Users of cleverhans may call this function but are more likely to call one of the recipes above. Reference: https://openreview.net/forum?id=H1g0piA9tQ :param sess: tf.session.Session :param model: cleverhans.model.Model :param x: numpy array containing clean example inputs to attack :param y: numpy array containing true labels :param attack_configs: list of AttackConfigs to run :param goals: list of AttackGoals to run The bundler works through the goals in order, until each is satisfied. Some goals may never be satisfied, in which case the bundler will run forever, updating the report on disk as it goes. :param report_path: str, the path the report will be saved to :param attack_batch_size: int, batch size for generating adversarial examples :param eval_batch_size: int, batch size for evaluating the model on clean / adversarial examples :returns: adv_x: The adversarial examples, in the same format as `x` run_counts: dict mapping each AttackConfig to a numpy array reporting how many times that AttackConfig was run on each example """ assert isinstance(sess, tf.Session) assert isinstance(model, Model) assert all(isinstance(attack_config, AttackConfig) for attack_config in attack_configs) assert all(isinstance(goal, AttackGoal) for goal in goals) assert isinstance(report_path, six.string_types) if x.shape[0] != y.shape[0]: raise ValueError("Number of input examples does not match number of labels") # Note: no need to precompile attacks, correctness_and_confidence # caches them run_counts = {} for attack_config in attack_configs: run_counts[attack_config] = np.zeros(x.shape[0], dtype=np.int64) # TODO: make an interface to pass this in if it has already been computed # elsewhere _logger.info("Running on clean data to initialize the report...") packed = correctness_and_confidence(sess, model, x, y, batch_size=eval_batch_size, devices=devices) _logger.info("...done") correctness, confidence = packed _logger.info("Accuracy: " + str(correctness.mean())) report = ConfidenceReport() report['clean'] = ConfidenceReportEntry(correctness, confidence) adv_x = x.copy() for goal in goals: bundle_attacks_with_goal(sess, model, x, y, adv_x, attack_configs, run_counts, goal, report, report_path, attack_batch_size=attack_batch_size, eval_batch_size=eval_batch_size) # Many users will set `goals` to make this run forever, so the return # statement is not the primary way to get information out. return adv_x, run_counts
[ "def", "bundle_attacks", "(", "sess", ",", "model", ",", "x", ",", "y", ",", "attack_configs", ",", "goals", ",", "report_path", ",", "attack_batch_size", "=", "BATCH_SIZE", ",", "eval_batch_size", "=", "BATCH_SIZE", ")", ":", "assert", "isinstance", "(", "sess", ",", "tf", ".", "Session", ")", "assert", "isinstance", "(", "model", ",", "Model", ")", "assert", "all", "(", "isinstance", "(", "attack_config", ",", "AttackConfig", ")", "for", "attack_config", "in", "attack_configs", ")", "assert", "all", "(", "isinstance", "(", "goal", ",", "AttackGoal", ")", "for", "goal", "in", "goals", ")", "assert", "isinstance", "(", "report_path", ",", "six", ".", "string_types", ")", "if", "x", ".", "shape", "[", "0", "]", "!=", "y", ".", "shape", "[", "0", "]", ":", "raise", "ValueError", "(", "\"Number of input examples does not match number of labels\"", ")", "# Note: no need to precompile attacks, correctness_and_confidence", "# caches them", "run_counts", "=", "{", "}", "for", "attack_config", "in", "attack_configs", ":", "run_counts", "[", "attack_config", "]", "=", "np", ".", "zeros", "(", "x", ".", "shape", "[", "0", "]", ",", "dtype", "=", "np", ".", "int64", ")", "# TODO: make an interface to pass this in if it has already been computed", "# elsewhere", "_logger", ".", "info", "(", "\"Running on clean data to initialize the report...\"", ")", "packed", "=", "correctness_and_confidence", "(", "sess", ",", "model", ",", "x", ",", "y", ",", "batch_size", "=", "eval_batch_size", ",", "devices", "=", "devices", ")", "_logger", ".", "info", "(", "\"...done\"", ")", "correctness", ",", "confidence", "=", "packed", "_logger", ".", "info", "(", "\"Accuracy: \"", "+", "str", "(", "correctness", ".", "mean", "(", ")", ")", ")", "report", "=", "ConfidenceReport", "(", ")", "report", "[", "'clean'", "]", "=", "ConfidenceReportEntry", "(", "correctness", ",", "confidence", ")", "adv_x", "=", "x", ".", "copy", "(", ")", "for", "goal", "in", "goals", ":", "bundle_attacks_with_goal", "(", "sess", ",", "model", ",", "x", ",", "y", ",", "adv_x", ",", "attack_configs", ",", "run_counts", ",", "goal", ",", "report", ",", "report_path", ",", "attack_batch_size", "=", "attack_batch_size", ",", "eval_batch_size", "=", "eval_batch_size", ")", "# Many users will set `goals` to make this run forever, so the return", "# statement is not the primary way to get information out.", "return", "adv_x", ",", "run_counts" ]
Runs attack bundling. Users of cleverhans may call this function but are more likely to call one of the recipes above. Reference: https://openreview.net/forum?id=H1g0piA9tQ :param sess: tf.session.Session :param model: cleverhans.model.Model :param x: numpy array containing clean example inputs to attack :param y: numpy array containing true labels :param attack_configs: list of AttackConfigs to run :param goals: list of AttackGoals to run The bundler works through the goals in order, until each is satisfied. Some goals may never be satisfied, in which case the bundler will run forever, updating the report on disk as it goes. :param report_path: str, the path the report will be saved to :param attack_batch_size: int, batch size for generating adversarial examples :param eval_batch_size: int, batch size for evaluating the model on clean / adversarial examples :returns: adv_x: The adversarial examples, in the same format as `x` run_counts: dict mapping each AttackConfig to a numpy array reporting how many times that AttackConfig was run on each example
[ "Runs", "attack", "bundling", ".", "Users", "of", "cleverhans", "may", "call", "this", "function", "but", "are", "more", "likely", "to", "call", "one", "of", "the", "recipes", "above", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attack_bundling.py#L320-L383
train
tensorflow/cleverhans
cleverhans/attack_bundling.py
bundle_attacks_with_goal
def bundle_attacks_with_goal(sess, model, x, y, adv_x, attack_configs, run_counts, goal, report, report_path, attack_batch_size=BATCH_SIZE, eval_batch_size=BATCH_SIZE): """ Runs attack bundling, working on one specific AttackGoal. This function is mostly intended to be called by `bundle_attacks`. Reference: https://openreview.net/forum?id=H1g0piA9tQ :param sess: tf.session.Session :param model: cleverhans.model.Model :param x: numpy array containing clean example inputs to attack :param y: numpy array containing true labels :param adv_x: numpy array containing the adversarial examples made so far by earlier work in the bundling process :param attack_configs: list of AttackConfigs to run :param run_counts: dict mapping AttackConfigs to numpy arrays specifying how many times they have been run on each example :param goal: AttackGoal to run :param report: ConfidenceReport :param report_path: str, the path the report will be saved to :param attack_batch_size: int, batch size for generating adversarial examples :param eval_batch_size: int, batch size for evaluating the model on adversarial examples """ goal.start(run_counts) _logger.info("Running criteria for new goal...") criteria = goal.get_criteria(sess, model, adv_x, y, batch_size=eval_batch_size) assert 'correctness' in criteria _logger.info("Accuracy: " + str(criteria['correctness'].mean())) assert 'confidence' in criteria while not goal.is_satisfied(criteria, run_counts): run_batch_with_goal(sess, model, x, y, adv_x, criteria, attack_configs, run_counts, goal, report, report_path, attack_batch_size=attack_batch_size) # Save after finishing all goals. # The incremental saves run on a timer. This save is needed so that the last # few attacks after the timer don't get discarded report.completed = True save(criteria, report, report_path, adv_x)
python
def bundle_attacks_with_goal(sess, model, x, y, adv_x, attack_configs, run_counts, goal, report, report_path, attack_batch_size=BATCH_SIZE, eval_batch_size=BATCH_SIZE): """ Runs attack bundling, working on one specific AttackGoal. This function is mostly intended to be called by `bundle_attacks`. Reference: https://openreview.net/forum?id=H1g0piA9tQ :param sess: tf.session.Session :param model: cleverhans.model.Model :param x: numpy array containing clean example inputs to attack :param y: numpy array containing true labels :param adv_x: numpy array containing the adversarial examples made so far by earlier work in the bundling process :param attack_configs: list of AttackConfigs to run :param run_counts: dict mapping AttackConfigs to numpy arrays specifying how many times they have been run on each example :param goal: AttackGoal to run :param report: ConfidenceReport :param report_path: str, the path the report will be saved to :param attack_batch_size: int, batch size for generating adversarial examples :param eval_batch_size: int, batch size for evaluating the model on adversarial examples """ goal.start(run_counts) _logger.info("Running criteria for new goal...") criteria = goal.get_criteria(sess, model, adv_x, y, batch_size=eval_batch_size) assert 'correctness' in criteria _logger.info("Accuracy: " + str(criteria['correctness'].mean())) assert 'confidence' in criteria while not goal.is_satisfied(criteria, run_counts): run_batch_with_goal(sess, model, x, y, adv_x, criteria, attack_configs, run_counts, goal, report, report_path, attack_batch_size=attack_batch_size) # Save after finishing all goals. # The incremental saves run on a timer. This save is needed so that the last # few attacks after the timer don't get discarded report.completed = True save(criteria, report, report_path, adv_x)
[ "def", "bundle_attacks_with_goal", "(", "sess", ",", "model", ",", "x", ",", "y", ",", "adv_x", ",", "attack_configs", ",", "run_counts", ",", "goal", ",", "report", ",", "report_path", ",", "attack_batch_size", "=", "BATCH_SIZE", ",", "eval_batch_size", "=", "BATCH_SIZE", ")", ":", "goal", ".", "start", "(", "run_counts", ")", "_logger", ".", "info", "(", "\"Running criteria for new goal...\"", ")", "criteria", "=", "goal", ".", "get_criteria", "(", "sess", ",", "model", ",", "adv_x", ",", "y", ",", "batch_size", "=", "eval_batch_size", ")", "assert", "'correctness'", "in", "criteria", "_logger", ".", "info", "(", "\"Accuracy: \"", "+", "str", "(", "criteria", "[", "'correctness'", "]", ".", "mean", "(", ")", ")", ")", "assert", "'confidence'", "in", "criteria", "while", "not", "goal", ".", "is_satisfied", "(", "criteria", ",", "run_counts", ")", ":", "run_batch_with_goal", "(", "sess", ",", "model", ",", "x", ",", "y", ",", "adv_x", ",", "criteria", ",", "attack_configs", ",", "run_counts", ",", "goal", ",", "report", ",", "report_path", ",", "attack_batch_size", "=", "attack_batch_size", ")", "# Save after finishing all goals.", "# The incremental saves run on a timer. This save is needed so that the last", "# few attacks after the timer don't get discarded", "report", ".", "completed", "=", "True", "save", "(", "criteria", ",", "report", ",", "report_path", ",", "adv_x", ")" ]
Runs attack bundling, working on one specific AttackGoal. This function is mostly intended to be called by `bundle_attacks`. Reference: https://openreview.net/forum?id=H1g0piA9tQ :param sess: tf.session.Session :param model: cleverhans.model.Model :param x: numpy array containing clean example inputs to attack :param y: numpy array containing true labels :param adv_x: numpy array containing the adversarial examples made so far by earlier work in the bundling process :param attack_configs: list of AttackConfigs to run :param run_counts: dict mapping AttackConfigs to numpy arrays specifying how many times they have been run on each example :param goal: AttackGoal to run :param report: ConfidenceReport :param report_path: str, the path the report will be saved to :param attack_batch_size: int, batch size for generating adversarial examples :param eval_batch_size: int, batch size for evaluating the model on adversarial examples
[ "Runs", "attack", "bundling", "working", "on", "one", "specific", "AttackGoal", ".", "This", "function", "is", "mostly", "intended", "to", "be", "called", "by", "bundle_attacks", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attack_bundling.py#L385-L425
train
tensorflow/cleverhans
cleverhans/attack_bundling.py
run_batch_with_goal
def run_batch_with_goal(sess, model, x, y, adv_x_val, criteria, attack_configs, run_counts, goal, report, report_path, attack_batch_size=BATCH_SIZE): """ Runs attack bundling on one batch of data. This function is mostly intended to be called by `bundle_attacks_with_goal`. :param sess: tf.session.Session :param model: cleverhans.model.Model :param x: numpy array containing clean example inputs to attack :param y: numpy array containing true labels :param adv_x_val: numpy array containing the adversarial examples made so far by earlier work in the bundling process :param criteria: dict mapping string names of criteria to numpy arrays with their values for each example (Different AttackGoals track different criteria) :param run_counts: dict mapping AttackConfigs to numpy arrays reporting how many times they have been run on each example :param goal: the AttackGoal to work on :param report: dict, see `bundle_attacks_with_goal` :param report_path: str, path to save the report to """ attack_config = goal.get_attack_config(attack_configs, run_counts, criteria) idxs = goal.request_examples(attack_config, criteria, run_counts, attack_batch_size) x_batch = x[idxs] assert x_batch.shape[0] == attack_batch_size y_batch = y[idxs] assert y_batch.shape[0] == attack_batch_size adv_x_batch = run_attack(sess, model, x_batch, y_batch, attack_config.attack, attack_config.params, attack_batch_size, devices, pass_y=attack_config.pass_y) criteria_batch = goal.get_criteria(sess, model, adv_x_batch, y_batch, batch_size=min(attack_batch_size, BATCH_SIZE)) # This can't be parallelized because some orig examples are copied more # than once into the batch cur_run_counts = run_counts[attack_config] for batch_idx, orig_idx in enumerate(idxs): cur_run_counts[orig_idx] += 1 should_copy = goal.new_wins(criteria, orig_idx, criteria_batch, batch_idx) if should_copy: adv_x_val[orig_idx] = adv_x_batch[batch_idx] for key in criteria: criteria[key][orig_idx] = criteria_batch[key][batch_idx] assert np.allclose(y[orig_idx], y_batch[batch_idx]) report['bundled'] = ConfidenceReportEntry(criteria['correctness'], criteria['confidence']) should_save = False new_time = time.time() if hasattr(report, 'time'): if new_time - report.time > REPORT_TIME_INTERVAL: should_save = True else: should_save = True if should_save: report.time = new_time goal.print_progress(criteria, run_counts) save(criteria, report, report_path, adv_x_val)
python
def run_batch_with_goal(sess, model, x, y, adv_x_val, criteria, attack_configs, run_counts, goal, report, report_path, attack_batch_size=BATCH_SIZE): """ Runs attack bundling on one batch of data. This function is mostly intended to be called by `bundle_attacks_with_goal`. :param sess: tf.session.Session :param model: cleverhans.model.Model :param x: numpy array containing clean example inputs to attack :param y: numpy array containing true labels :param adv_x_val: numpy array containing the adversarial examples made so far by earlier work in the bundling process :param criteria: dict mapping string names of criteria to numpy arrays with their values for each example (Different AttackGoals track different criteria) :param run_counts: dict mapping AttackConfigs to numpy arrays reporting how many times they have been run on each example :param goal: the AttackGoal to work on :param report: dict, see `bundle_attacks_with_goal` :param report_path: str, path to save the report to """ attack_config = goal.get_attack_config(attack_configs, run_counts, criteria) idxs = goal.request_examples(attack_config, criteria, run_counts, attack_batch_size) x_batch = x[idxs] assert x_batch.shape[0] == attack_batch_size y_batch = y[idxs] assert y_batch.shape[0] == attack_batch_size adv_x_batch = run_attack(sess, model, x_batch, y_batch, attack_config.attack, attack_config.params, attack_batch_size, devices, pass_y=attack_config.pass_y) criteria_batch = goal.get_criteria(sess, model, adv_x_batch, y_batch, batch_size=min(attack_batch_size, BATCH_SIZE)) # This can't be parallelized because some orig examples are copied more # than once into the batch cur_run_counts = run_counts[attack_config] for batch_idx, orig_idx in enumerate(idxs): cur_run_counts[orig_idx] += 1 should_copy = goal.new_wins(criteria, orig_idx, criteria_batch, batch_idx) if should_copy: adv_x_val[orig_idx] = adv_x_batch[batch_idx] for key in criteria: criteria[key][orig_idx] = criteria_batch[key][batch_idx] assert np.allclose(y[orig_idx], y_batch[batch_idx]) report['bundled'] = ConfidenceReportEntry(criteria['correctness'], criteria['confidence']) should_save = False new_time = time.time() if hasattr(report, 'time'): if new_time - report.time > REPORT_TIME_INTERVAL: should_save = True else: should_save = True if should_save: report.time = new_time goal.print_progress(criteria, run_counts) save(criteria, report, report_path, adv_x_val)
[ "def", "run_batch_with_goal", "(", "sess", ",", "model", ",", "x", ",", "y", ",", "adv_x_val", ",", "criteria", ",", "attack_configs", ",", "run_counts", ",", "goal", ",", "report", ",", "report_path", ",", "attack_batch_size", "=", "BATCH_SIZE", ")", ":", "attack_config", "=", "goal", ".", "get_attack_config", "(", "attack_configs", ",", "run_counts", ",", "criteria", ")", "idxs", "=", "goal", ".", "request_examples", "(", "attack_config", ",", "criteria", ",", "run_counts", ",", "attack_batch_size", ")", "x_batch", "=", "x", "[", "idxs", "]", "assert", "x_batch", ".", "shape", "[", "0", "]", "==", "attack_batch_size", "y_batch", "=", "y", "[", "idxs", "]", "assert", "y_batch", ".", "shape", "[", "0", "]", "==", "attack_batch_size", "adv_x_batch", "=", "run_attack", "(", "sess", ",", "model", ",", "x_batch", ",", "y_batch", ",", "attack_config", ".", "attack", ",", "attack_config", ".", "params", ",", "attack_batch_size", ",", "devices", ",", "pass_y", "=", "attack_config", ".", "pass_y", ")", "criteria_batch", "=", "goal", ".", "get_criteria", "(", "sess", ",", "model", ",", "adv_x_batch", ",", "y_batch", ",", "batch_size", "=", "min", "(", "attack_batch_size", ",", "BATCH_SIZE", ")", ")", "# This can't be parallelized because some orig examples are copied more", "# than once into the batch", "cur_run_counts", "=", "run_counts", "[", "attack_config", "]", "for", "batch_idx", ",", "orig_idx", "in", "enumerate", "(", "idxs", ")", ":", "cur_run_counts", "[", "orig_idx", "]", "+=", "1", "should_copy", "=", "goal", ".", "new_wins", "(", "criteria", ",", "orig_idx", ",", "criteria_batch", ",", "batch_idx", ")", "if", "should_copy", ":", "adv_x_val", "[", "orig_idx", "]", "=", "adv_x_batch", "[", "batch_idx", "]", "for", "key", "in", "criteria", ":", "criteria", "[", "key", "]", "[", "orig_idx", "]", "=", "criteria_batch", "[", "key", "]", "[", "batch_idx", "]", "assert", "np", ".", "allclose", "(", "y", "[", "orig_idx", "]", ",", "y_batch", "[", "batch_idx", "]", ")", "report", "[", "'bundled'", "]", "=", "ConfidenceReportEntry", "(", "criteria", "[", "'correctness'", "]", ",", "criteria", "[", "'confidence'", "]", ")", "should_save", "=", "False", "new_time", "=", "time", ".", "time", "(", ")", "if", "hasattr", "(", "report", ",", "'time'", ")", ":", "if", "new_time", "-", "report", ".", "time", ">", "REPORT_TIME_INTERVAL", ":", "should_save", "=", "True", "else", ":", "should_save", "=", "True", "if", "should_save", ":", "report", ".", "time", "=", "new_time", "goal", ".", "print_progress", "(", "criteria", ",", "run_counts", ")", "save", "(", "criteria", ",", "report", ",", "report_path", ",", "adv_x_val", ")" ]
Runs attack bundling on one batch of data. This function is mostly intended to be called by `bundle_attacks_with_goal`. :param sess: tf.session.Session :param model: cleverhans.model.Model :param x: numpy array containing clean example inputs to attack :param y: numpy array containing true labels :param adv_x_val: numpy array containing the adversarial examples made so far by earlier work in the bundling process :param criteria: dict mapping string names of criteria to numpy arrays with their values for each example (Different AttackGoals track different criteria) :param run_counts: dict mapping AttackConfigs to numpy arrays reporting how many times they have been run on each example :param goal: the AttackGoal to work on :param report: dict, see `bundle_attacks_with_goal` :param report_path: str, path to save the report to
[ "Runs", "attack", "bundling", "on", "one", "batch", "of", "data", ".", "This", "function", "is", "mostly", "intended", "to", "be", "called", "by", "bundle_attacks_with_goal", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attack_bundling.py#L428-L487
train
tensorflow/cleverhans
cleverhans/attack_bundling.py
save
def save(criteria, report, report_path, adv_x_val): """ Saves the report and adversarial examples. :param criteria: dict, of the form returned by AttackGoal.get_criteria :param report: dict containing a confidence report :param report_path: string, filepath :param adv_x_val: numpy array containing dataset of adversarial examples """ print_stats(criteria['correctness'], criteria['confidence'], 'bundled') print("Saving to " + report_path) serial.save(report_path, report) assert report_path.endswith(".joblib") adv_x_path = report_path[:-len(".joblib")] + "_adv.npy" np.save(adv_x_path, adv_x_val)
python
def save(criteria, report, report_path, adv_x_val): """ Saves the report and adversarial examples. :param criteria: dict, of the form returned by AttackGoal.get_criteria :param report: dict containing a confidence report :param report_path: string, filepath :param adv_x_val: numpy array containing dataset of adversarial examples """ print_stats(criteria['correctness'], criteria['confidence'], 'bundled') print("Saving to " + report_path) serial.save(report_path, report) assert report_path.endswith(".joblib") adv_x_path = report_path[:-len(".joblib")] + "_adv.npy" np.save(adv_x_path, adv_x_val)
[ "def", "save", "(", "criteria", ",", "report", ",", "report_path", ",", "adv_x_val", ")", ":", "print_stats", "(", "criteria", "[", "'correctness'", "]", ",", "criteria", "[", "'confidence'", "]", ",", "'bundled'", ")", "print", "(", "\"Saving to \"", "+", "report_path", ")", "serial", ".", "save", "(", "report_path", ",", "report", ")", "assert", "report_path", ".", "endswith", "(", "\".joblib\"", ")", "adv_x_path", "=", "report_path", "[", ":", "-", "len", "(", "\".joblib\"", ")", "]", "+", "\"_adv.npy\"", "np", ".", "save", "(", "adv_x_path", ",", "adv_x_val", ")" ]
Saves the report and adversarial examples. :param criteria: dict, of the form returned by AttackGoal.get_criteria :param report: dict containing a confidence report :param report_path: string, filepath :param adv_x_val: numpy array containing dataset of adversarial examples
[ "Saves", "the", "report", "and", "adversarial", "examples", ".", ":", "param", "criteria", ":", "dict", "of", "the", "form", "returned", "by", "AttackGoal", ".", "get_criteria", ":", "param", "report", ":", "dict", "containing", "a", "confidence", "report", ":", "param", "report_path", ":", "string", "filepath", ":", "param", "adv_x_val", ":", "numpy", "array", "containing", "dataset", "of", "adversarial", "examples" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attack_bundling.py#L490-L505
train
tensorflow/cleverhans
cleverhans/attack_bundling.py
unfinished_attack_configs
def unfinished_attack_configs(new_work_goal, work_before, run_counts, log=False): """ Returns a list of attack configs that have not yet been run the desired number of times. :param new_work_goal: dict mapping attacks to desired number of times to run :param work_before: dict mapping attacks to number of times they were run before starting this new goal. Should be prefiltered to include only examples that don't already meet the primary goal :param run_counts: dict mapping attacks to total number of times they have ever been run. Should be prefiltered to include only examples that don't already meet the primary goal """ assert isinstance(work_before, dict), work_before for key in work_before: value = work_before[key] assert value.ndim == 1, value.shape if key in run_counts: assert run_counts[key].shape == value.shape attack_configs = [] for attack_config in new_work_goal: done_now = run_counts[attack_config] if log: _logger.info(str(attack_config) + " ave run count: " + str(done_now.mean())) _logger.info(str(attack_config) + " min run count: " + str(done_now.min())) done_before = work_before[attack_config] if log: _logger.info(str(attack_config) + " mean work before: " + str(done_before.mean())) # This is the vector for all examples new = done_now - done_before # The work is only done when it has been done for every example new = new.min() assert isinstance(new, (int, np.int64)), type(new) new_goal = new_work_goal[attack_config] assert isinstance(new_goal, int), type(new_goal) if new < new_goal: if log: _logger.info(str(attack_config) + " has run " + str(new) + " of " + str(new_goal)) attack_configs.append(attack_config) return attack_configs
python
def unfinished_attack_configs(new_work_goal, work_before, run_counts, log=False): """ Returns a list of attack configs that have not yet been run the desired number of times. :param new_work_goal: dict mapping attacks to desired number of times to run :param work_before: dict mapping attacks to number of times they were run before starting this new goal. Should be prefiltered to include only examples that don't already meet the primary goal :param run_counts: dict mapping attacks to total number of times they have ever been run. Should be prefiltered to include only examples that don't already meet the primary goal """ assert isinstance(work_before, dict), work_before for key in work_before: value = work_before[key] assert value.ndim == 1, value.shape if key in run_counts: assert run_counts[key].shape == value.shape attack_configs = [] for attack_config in new_work_goal: done_now = run_counts[attack_config] if log: _logger.info(str(attack_config) + " ave run count: " + str(done_now.mean())) _logger.info(str(attack_config) + " min run count: " + str(done_now.min())) done_before = work_before[attack_config] if log: _logger.info(str(attack_config) + " mean work before: " + str(done_before.mean())) # This is the vector for all examples new = done_now - done_before # The work is only done when it has been done for every example new = new.min() assert isinstance(new, (int, np.int64)), type(new) new_goal = new_work_goal[attack_config] assert isinstance(new_goal, int), type(new_goal) if new < new_goal: if log: _logger.info(str(attack_config) + " has run " + str(new) + " of " + str(new_goal)) attack_configs.append(attack_config) return attack_configs
[ "def", "unfinished_attack_configs", "(", "new_work_goal", ",", "work_before", ",", "run_counts", ",", "log", "=", "False", ")", ":", "assert", "isinstance", "(", "work_before", ",", "dict", ")", ",", "work_before", "for", "key", "in", "work_before", ":", "value", "=", "work_before", "[", "key", "]", "assert", "value", ".", "ndim", "==", "1", ",", "value", ".", "shape", "if", "key", "in", "run_counts", ":", "assert", "run_counts", "[", "key", "]", ".", "shape", "==", "value", ".", "shape", "attack_configs", "=", "[", "]", "for", "attack_config", "in", "new_work_goal", ":", "done_now", "=", "run_counts", "[", "attack_config", "]", "if", "log", ":", "_logger", ".", "info", "(", "str", "(", "attack_config", ")", "+", "\" ave run count: \"", "+", "str", "(", "done_now", ".", "mean", "(", ")", ")", ")", "_logger", ".", "info", "(", "str", "(", "attack_config", ")", "+", "\" min run count: \"", "+", "str", "(", "done_now", ".", "min", "(", ")", ")", ")", "done_before", "=", "work_before", "[", "attack_config", "]", "if", "log", ":", "_logger", ".", "info", "(", "str", "(", "attack_config", ")", "+", "\" mean work before: \"", "+", "str", "(", "done_before", ".", "mean", "(", ")", ")", ")", "# This is the vector for all examples", "new", "=", "done_now", "-", "done_before", "# The work is only done when it has been done for every example", "new", "=", "new", ".", "min", "(", ")", "assert", "isinstance", "(", "new", ",", "(", "int", ",", "np", ".", "int64", ")", ")", ",", "type", "(", "new", ")", "new_goal", "=", "new_work_goal", "[", "attack_config", "]", "assert", "isinstance", "(", "new_goal", ",", "int", ")", ",", "type", "(", "new_goal", ")", "if", "new", "<", "new_goal", ":", "if", "log", ":", "_logger", ".", "info", "(", "str", "(", "attack_config", ")", "+", "\" has run \"", "+", "str", "(", "new", ")", "+", "\" of \"", "+", "str", "(", "new_goal", ")", ")", "attack_configs", ".", "append", "(", "attack_config", ")", "return", "attack_configs" ]
Returns a list of attack configs that have not yet been run the desired number of times. :param new_work_goal: dict mapping attacks to desired number of times to run :param work_before: dict mapping attacks to number of times they were run before starting this new goal. Should be prefiltered to include only examples that don't already meet the primary goal :param run_counts: dict mapping attacks to total number of times they have ever been run. Should be prefiltered to include only examples that don't already meet the primary goal
[ "Returns", "a", "list", "of", "attack", "configs", "that", "have", "not", "yet", "been", "run", "the", "desired", "number", "of", "times", ".", ":", "param", "new_work_goal", ":", "dict", "mapping", "attacks", "to", "desired", "number", "of", "times", "to", "run", ":", "param", "work_before", ":", "dict", "mapping", "attacks", "to", "number", "of", "times", "they", "were", "run", "before", "starting", "this", "new", "goal", ".", "Should", "be", "prefiltered", "to", "include", "only", "examples", "that", "don", "t", "already", "meet", "the", "primary", "goal", ":", "param", "run_counts", ":", "dict", "mapping", "attacks", "to", "total", "number", "of", "times", "they", "have", "ever", "been", "run", ".", "Should", "be", "prefiltered", "to", "include", "only", "examples", "that", "don", "t", "already", "meet", "the", "primary", "goal" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attack_bundling.py#L916-L962
train
tensorflow/cleverhans
cleverhans/attack_bundling.py
bundle_examples_with_goal
def bundle_examples_with_goal(sess, model, adv_x_list, y, goal, report_path, batch_size=BATCH_SIZE): """ A post-processor version of attack bundling, that chooses the strongest example from the output of multiple earlier bundling strategies. :param sess: tf.session.Session :param model: cleverhans.model.Model :param adv_x_list: list of numpy arrays Each entry in the list is the output of a previous bundler; it is an adversarial version of the whole dataset. :param y: numpy array containing true labels :param goal: AttackGoal to use to choose the best version of each adversarial example :param report_path: str, the path the report will be saved to :param batch_size: int, batch size """ # Check the input num_attacks = len(adv_x_list) assert num_attacks > 0 adv_x_0 = adv_x_list[0] assert isinstance(adv_x_0, np.ndarray) assert all(adv_x.shape == adv_x_0.shape for adv_x in adv_x_list) # Allocate the output out = np.zeros_like(adv_x_0) m = adv_x_0.shape[0] # Initialize with negative sentinel values to make sure everything is # written to correctness = -np.ones(m, dtype='int32') confidence = -np.ones(m, dtype='float32') # Gather criteria criteria = [goal.get_criteria(sess, model, adv_x, y, batch_size=batch_size) for adv_x in adv_x_list] assert all('correctness' in c for c in criteria) assert all('confidence' in c for c in criteria) _logger.info("Accuracy on each advx dataset: ") for c in criteria: _logger.info("\t" + str(c['correctness'].mean())) for example_idx in range(m): # Index of the best attack for this example attack_idx = 0 # Find the winner for candidate_idx in range(1, num_attacks): if goal.new_wins(criteria[attack_idx], example_idx, criteria[candidate_idx], example_idx): attack_idx = candidate_idx # Copy the winner into the output out[example_idx] = adv_x_list[attack_idx][example_idx] correctness[example_idx] = criteria[attack_idx]['correctness'][example_idx] confidence[example_idx] = criteria[attack_idx]['confidence'][example_idx] assert correctness.min() >= 0 assert correctness.max() <= 1 assert confidence.min() >= 0. assert confidence.max() <= 1. correctness = correctness.astype('bool') _logger.info("Accuracy on bundled examples: " + str(correctness.mean())) report = ConfidenceReport() report['bundled'] = ConfidenceReportEntry(correctness, confidence) serial.save(report_path, report) assert report_path.endswith('.joblib') adv_x_path = report_path[:-len('.joblib')] + "_adv_x.npy" np.save(adv_x_path, out)
python
def bundle_examples_with_goal(sess, model, adv_x_list, y, goal, report_path, batch_size=BATCH_SIZE): """ A post-processor version of attack bundling, that chooses the strongest example from the output of multiple earlier bundling strategies. :param sess: tf.session.Session :param model: cleverhans.model.Model :param adv_x_list: list of numpy arrays Each entry in the list is the output of a previous bundler; it is an adversarial version of the whole dataset. :param y: numpy array containing true labels :param goal: AttackGoal to use to choose the best version of each adversarial example :param report_path: str, the path the report will be saved to :param batch_size: int, batch size """ # Check the input num_attacks = len(adv_x_list) assert num_attacks > 0 adv_x_0 = adv_x_list[0] assert isinstance(adv_x_0, np.ndarray) assert all(adv_x.shape == adv_x_0.shape for adv_x in adv_x_list) # Allocate the output out = np.zeros_like(adv_x_0) m = adv_x_0.shape[0] # Initialize with negative sentinel values to make sure everything is # written to correctness = -np.ones(m, dtype='int32') confidence = -np.ones(m, dtype='float32') # Gather criteria criteria = [goal.get_criteria(sess, model, adv_x, y, batch_size=batch_size) for adv_x in adv_x_list] assert all('correctness' in c for c in criteria) assert all('confidence' in c for c in criteria) _logger.info("Accuracy on each advx dataset: ") for c in criteria: _logger.info("\t" + str(c['correctness'].mean())) for example_idx in range(m): # Index of the best attack for this example attack_idx = 0 # Find the winner for candidate_idx in range(1, num_attacks): if goal.new_wins(criteria[attack_idx], example_idx, criteria[candidate_idx], example_idx): attack_idx = candidate_idx # Copy the winner into the output out[example_idx] = adv_x_list[attack_idx][example_idx] correctness[example_idx] = criteria[attack_idx]['correctness'][example_idx] confidence[example_idx] = criteria[attack_idx]['confidence'][example_idx] assert correctness.min() >= 0 assert correctness.max() <= 1 assert confidence.min() >= 0. assert confidence.max() <= 1. correctness = correctness.astype('bool') _logger.info("Accuracy on bundled examples: " + str(correctness.mean())) report = ConfidenceReport() report['bundled'] = ConfidenceReportEntry(correctness, confidence) serial.save(report_path, report) assert report_path.endswith('.joblib') adv_x_path = report_path[:-len('.joblib')] + "_adv_x.npy" np.save(adv_x_path, out)
[ "def", "bundle_examples_with_goal", "(", "sess", ",", "model", ",", "adv_x_list", ",", "y", ",", "goal", ",", "report_path", ",", "batch_size", "=", "BATCH_SIZE", ")", ":", "# Check the input", "num_attacks", "=", "len", "(", "adv_x_list", ")", "assert", "num_attacks", ">", "0", "adv_x_0", "=", "adv_x_list", "[", "0", "]", "assert", "isinstance", "(", "adv_x_0", ",", "np", ".", "ndarray", ")", "assert", "all", "(", "adv_x", ".", "shape", "==", "adv_x_0", ".", "shape", "for", "adv_x", "in", "adv_x_list", ")", "# Allocate the output", "out", "=", "np", ".", "zeros_like", "(", "adv_x_0", ")", "m", "=", "adv_x_0", ".", "shape", "[", "0", "]", "# Initialize with negative sentinel values to make sure everything is", "# written to", "correctness", "=", "-", "np", ".", "ones", "(", "m", ",", "dtype", "=", "'int32'", ")", "confidence", "=", "-", "np", ".", "ones", "(", "m", ",", "dtype", "=", "'float32'", ")", "# Gather criteria", "criteria", "=", "[", "goal", ".", "get_criteria", "(", "sess", ",", "model", ",", "adv_x", ",", "y", ",", "batch_size", "=", "batch_size", ")", "for", "adv_x", "in", "adv_x_list", "]", "assert", "all", "(", "'correctness'", "in", "c", "for", "c", "in", "criteria", ")", "assert", "all", "(", "'confidence'", "in", "c", "for", "c", "in", "criteria", ")", "_logger", ".", "info", "(", "\"Accuracy on each advx dataset: \"", ")", "for", "c", "in", "criteria", ":", "_logger", ".", "info", "(", "\"\\t\"", "+", "str", "(", "c", "[", "'correctness'", "]", ".", "mean", "(", ")", ")", ")", "for", "example_idx", "in", "range", "(", "m", ")", ":", "# Index of the best attack for this example", "attack_idx", "=", "0", "# Find the winner", "for", "candidate_idx", "in", "range", "(", "1", ",", "num_attacks", ")", ":", "if", "goal", ".", "new_wins", "(", "criteria", "[", "attack_idx", "]", ",", "example_idx", ",", "criteria", "[", "candidate_idx", "]", ",", "example_idx", ")", ":", "attack_idx", "=", "candidate_idx", "# Copy the winner into the output", "out", "[", "example_idx", "]", "=", "adv_x_list", "[", "attack_idx", "]", "[", "example_idx", "]", "correctness", "[", "example_idx", "]", "=", "criteria", "[", "attack_idx", "]", "[", "'correctness'", "]", "[", "example_idx", "]", "confidence", "[", "example_idx", "]", "=", "criteria", "[", "attack_idx", "]", "[", "'confidence'", "]", "[", "example_idx", "]", "assert", "correctness", ".", "min", "(", ")", ">=", "0", "assert", "correctness", ".", "max", "(", ")", "<=", "1", "assert", "confidence", ".", "min", "(", ")", ">=", "0.", "assert", "confidence", ".", "max", "(", ")", "<=", "1.", "correctness", "=", "correctness", ".", "astype", "(", "'bool'", ")", "_logger", ".", "info", "(", "\"Accuracy on bundled examples: \"", "+", "str", "(", "correctness", ".", "mean", "(", ")", ")", ")", "report", "=", "ConfidenceReport", "(", ")", "report", "[", "'bundled'", "]", "=", "ConfidenceReportEntry", "(", "correctness", ",", "confidence", ")", "serial", ".", "save", "(", "report_path", ",", "report", ")", "assert", "report_path", ".", "endswith", "(", "'.joblib'", ")", "adv_x_path", "=", "report_path", "[", ":", "-", "len", "(", "'.joblib'", ")", "]", "+", "\"_adv_x.npy\"", "np", ".", "save", "(", "adv_x_path", ",", "out", ")" ]
A post-processor version of attack bundling, that chooses the strongest example from the output of multiple earlier bundling strategies. :param sess: tf.session.Session :param model: cleverhans.model.Model :param adv_x_list: list of numpy arrays Each entry in the list is the output of a previous bundler; it is an adversarial version of the whole dataset. :param y: numpy array containing true labels :param goal: AttackGoal to use to choose the best version of each adversarial example :param report_path: str, the path the report will be saved to :param batch_size: int, batch size
[ "A", "post", "-", "processor", "version", "of", "attack", "bundling", "that", "chooses", "the", "strongest", "example", "from", "the", "output", "of", "multiple", "earlier", "bundling", "strategies", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attack_bundling.py#L1044-L1110
train
tensorflow/cleverhans
cleverhans/attack_bundling.py
spsa_max_confidence_recipe
def spsa_max_confidence_recipe(sess, model, x, y, nb_classes, eps, clip_min, clip_max, nb_iter, report_path, spsa_samples=SPSA.DEFAULT_SPSA_SAMPLES, spsa_iters=SPSA.DEFAULT_SPSA_ITERS, eval_batch_size=BATCH_SIZE): """Runs the MaxConfidence attack using SPSA as the underlying optimizer. Even though this runs only one attack, it must be implemented as a bundler because SPSA supports only batch_size=1. The cleverhans.attacks.MaxConfidence attack internally multiplies the batch size by nb_classes, so it can't take SPSA as a base attacker. Insteader, we must bundle batch_size=1 calls using cleverhans.attack_bundling.MaxConfidence. References: https://openreview.net/forum?id=H1g0piA9tQ :param sess: tf.Session :param model: cleverhans.model.Model :param x: numpy array containing clean example inputs to attack :param y: numpy array containing true labels :param nb_classes: int, number of classes :param eps: float, maximum size of perturbation (measured by max norm) :param nb_iter: int, number of iterations for one version of PGD attacks (will also run another version with 25X more iterations) :param report_path: str, the path that the report will be saved to. :param eval_batch_size: int, batch size for evaluation (as opposed to making attacks) """ spsa = SPSA(model, sess) spsa_params = {"eps": eps, "clip_min" : clip_min, "clip_max" : clip_max, "nb_iter": nb_iter, "spsa_samples": spsa_samples, "spsa_iters": spsa_iters} attack_configs = [] dev_batch_size = 1 # The only batch size supported by SPSA batch_size = num_devices ones = tf.ones(dev_batch_size, tf.int32) for cls in range(nb_classes): cls_params = copy.copy(spsa_params) cls_params['y_target'] = tf.to_float(tf.one_hot(ones * cls, nb_classes)) cls_attack_config = AttackConfig(spsa, cls_params, "spsa_" + str(cls)) attack_configs.append(cls_attack_config) new_work_goal = {config: 1 for config in attack_configs} goals = [MaxConfidence(t=1., new_work_goal=new_work_goal)] bundle_attacks(sess, model, x, y, attack_configs, goals, report_path, attack_batch_size=batch_size, eval_batch_size=eval_batch_size)
python
def spsa_max_confidence_recipe(sess, model, x, y, nb_classes, eps, clip_min, clip_max, nb_iter, report_path, spsa_samples=SPSA.DEFAULT_SPSA_SAMPLES, spsa_iters=SPSA.DEFAULT_SPSA_ITERS, eval_batch_size=BATCH_SIZE): """Runs the MaxConfidence attack using SPSA as the underlying optimizer. Even though this runs only one attack, it must be implemented as a bundler because SPSA supports only batch_size=1. The cleverhans.attacks.MaxConfidence attack internally multiplies the batch size by nb_classes, so it can't take SPSA as a base attacker. Insteader, we must bundle batch_size=1 calls using cleverhans.attack_bundling.MaxConfidence. References: https://openreview.net/forum?id=H1g0piA9tQ :param sess: tf.Session :param model: cleverhans.model.Model :param x: numpy array containing clean example inputs to attack :param y: numpy array containing true labels :param nb_classes: int, number of classes :param eps: float, maximum size of perturbation (measured by max norm) :param nb_iter: int, number of iterations for one version of PGD attacks (will also run another version with 25X more iterations) :param report_path: str, the path that the report will be saved to. :param eval_batch_size: int, batch size for evaluation (as opposed to making attacks) """ spsa = SPSA(model, sess) spsa_params = {"eps": eps, "clip_min" : clip_min, "clip_max" : clip_max, "nb_iter": nb_iter, "spsa_samples": spsa_samples, "spsa_iters": spsa_iters} attack_configs = [] dev_batch_size = 1 # The only batch size supported by SPSA batch_size = num_devices ones = tf.ones(dev_batch_size, tf.int32) for cls in range(nb_classes): cls_params = copy.copy(spsa_params) cls_params['y_target'] = tf.to_float(tf.one_hot(ones * cls, nb_classes)) cls_attack_config = AttackConfig(spsa, cls_params, "spsa_" + str(cls)) attack_configs.append(cls_attack_config) new_work_goal = {config: 1 for config in attack_configs} goals = [MaxConfidence(t=1., new_work_goal=new_work_goal)] bundle_attacks(sess, model, x, y, attack_configs, goals, report_path, attack_batch_size=batch_size, eval_batch_size=eval_batch_size)
[ "def", "spsa_max_confidence_recipe", "(", "sess", ",", "model", ",", "x", ",", "y", ",", "nb_classes", ",", "eps", ",", "clip_min", ",", "clip_max", ",", "nb_iter", ",", "report_path", ",", "spsa_samples", "=", "SPSA", ".", "DEFAULT_SPSA_SAMPLES", ",", "spsa_iters", "=", "SPSA", ".", "DEFAULT_SPSA_ITERS", ",", "eval_batch_size", "=", "BATCH_SIZE", ")", ":", "spsa", "=", "SPSA", "(", "model", ",", "sess", ")", "spsa_params", "=", "{", "\"eps\"", ":", "eps", ",", "\"clip_min\"", ":", "clip_min", ",", "\"clip_max\"", ":", "clip_max", ",", "\"nb_iter\"", ":", "nb_iter", ",", "\"spsa_samples\"", ":", "spsa_samples", ",", "\"spsa_iters\"", ":", "spsa_iters", "}", "attack_configs", "=", "[", "]", "dev_batch_size", "=", "1", "# The only batch size supported by SPSA", "batch_size", "=", "num_devices", "ones", "=", "tf", ".", "ones", "(", "dev_batch_size", ",", "tf", ".", "int32", ")", "for", "cls", "in", "range", "(", "nb_classes", ")", ":", "cls_params", "=", "copy", ".", "copy", "(", "spsa_params", ")", "cls_params", "[", "'y_target'", "]", "=", "tf", ".", "to_float", "(", "tf", ".", "one_hot", "(", "ones", "*", "cls", ",", "nb_classes", ")", ")", "cls_attack_config", "=", "AttackConfig", "(", "spsa", ",", "cls_params", ",", "\"spsa_\"", "+", "str", "(", "cls", ")", ")", "attack_configs", ".", "append", "(", "cls_attack_config", ")", "new_work_goal", "=", "{", "config", ":", "1", "for", "config", "in", "attack_configs", "}", "goals", "=", "[", "MaxConfidence", "(", "t", "=", "1.", ",", "new_work_goal", "=", "new_work_goal", ")", "]", "bundle_attacks", "(", "sess", ",", "model", ",", "x", ",", "y", ",", "attack_configs", ",", "goals", ",", "report_path", ",", "attack_batch_size", "=", "batch_size", ",", "eval_batch_size", "=", "eval_batch_size", ")" ]
Runs the MaxConfidence attack using SPSA as the underlying optimizer. Even though this runs only one attack, it must be implemented as a bundler because SPSA supports only batch_size=1. The cleverhans.attacks.MaxConfidence attack internally multiplies the batch size by nb_classes, so it can't take SPSA as a base attacker. Insteader, we must bundle batch_size=1 calls using cleverhans.attack_bundling.MaxConfidence. References: https://openreview.net/forum?id=H1g0piA9tQ :param sess: tf.Session :param model: cleverhans.model.Model :param x: numpy array containing clean example inputs to attack :param y: numpy array containing true labels :param nb_classes: int, number of classes :param eps: float, maximum size of perturbation (measured by max norm) :param nb_iter: int, number of iterations for one version of PGD attacks (will also run another version with 25X more iterations) :param report_path: str, the path that the report will be saved to. :param eval_batch_size: int, batch size for evaluation (as opposed to making attacks)
[ "Runs", "the", "MaxConfidence", "attack", "using", "SPSA", "as", "the", "underlying", "optimizer", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attack_bundling.py#L1112-L1156
train
tensorflow/cleverhans
cleverhans/attack_bundling.py
AttackGoal.get_criteria
def get_criteria(self, sess, model, advx, y, batch_size=BATCH_SIZE): """ Returns a dictionary mapping the name of each criterion to a NumPy array containing the value of that criterion for each adversarial example. Subclasses can add extra criteria by implementing the `extra_criteria` method. :param sess: tf.session.Session :param model: cleverhans.model.Model :param adv_x: numpy array containing the adversarial examples made so far by earlier work in the bundling process :param y: numpy array containing true labels :param batch_size: int, batch size """ names, factory = self.extra_criteria() factory = _CriteriaFactory(model, factory) results = batch_eval_multi_worker(sess, factory, [advx, y], batch_size=batch_size, devices=devices) names = ['correctness', 'confidence'] + names out = dict(safe_zip(names, results)) return out
python
def get_criteria(self, sess, model, advx, y, batch_size=BATCH_SIZE): """ Returns a dictionary mapping the name of each criterion to a NumPy array containing the value of that criterion for each adversarial example. Subclasses can add extra criteria by implementing the `extra_criteria` method. :param sess: tf.session.Session :param model: cleverhans.model.Model :param adv_x: numpy array containing the adversarial examples made so far by earlier work in the bundling process :param y: numpy array containing true labels :param batch_size: int, batch size """ names, factory = self.extra_criteria() factory = _CriteriaFactory(model, factory) results = batch_eval_multi_worker(sess, factory, [advx, y], batch_size=batch_size, devices=devices) names = ['correctness', 'confidence'] + names out = dict(safe_zip(names, results)) return out
[ "def", "get_criteria", "(", "self", ",", "sess", ",", "model", ",", "advx", ",", "y", ",", "batch_size", "=", "BATCH_SIZE", ")", ":", "names", ",", "factory", "=", "self", ".", "extra_criteria", "(", ")", "factory", "=", "_CriteriaFactory", "(", "model", ",", "factory", ")", "results", "=", "batch_eval_multi_worker", "(", "sess", ",", "factory", ",", "[", "advx", ",", "y", "]", ",", "batch_size", "=", "batch_size", ",", "devices", "=", "devices", ")", "names", "=", "[", "'correctness'", ",", "'confidence'", "]", "+", "names", "out", "=", "dict", "(", "safe_zip", "(", "names", ",", "results", ")", ")", "return", "out" ]
Returns a dictionary mapping the name of each criterion to a NumPy array containing the value of that criterion for each adversarial example. Subclasses can add extra criteria by implementing the `extra_criteria` method. :param sess: tf.session.Session :param model: cleverhans.model.Model :param adv_x: numpy array containing the adversarial examples made so far by earlier work in the bundling process :param y: numpy array containing true labels :param batch_size: int, batch size
[ "Returns", "a", "dictionary", "mapping", "the", "name", "of", "each", "criterion", "to", "a", "NumPy", "array", "containing", "the", "value", "of", "that", "criterion", "for", "each", "adversarial", "example", ".", "Subclasses", "can", "add", "extra", "criteria", "by", "implementing", "the", "extra_criteria", "method", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attack_bundling.py#L532-L554
train
tensorflow/cleverhans
cleverhans/attack_bundling.py
AttackGoal.request_examples
def request_examples(self, attack_config, criteria, run_counts, batch_size): """ Returns a numpy array of integer example indices to run in the next batch. """ raise NotImplementedError(str(type(self)) + "needs to implement request_examples")
python
def request_examples(self, attack_config, criteria, run_counts, batch_size): """ Returns a numpy array of integer example indices to run in the next batch. """ raise NotImplementedError(str(type(self)) + "needs to implement request_examples")
[ "def", "request_examples", "(", "self", ",", "attack_config", ",", "criteria", ",", "run_counts", ",", "batch_size", ")", ":", "raise", "NotImplementedError", "(", "str", "(", "type", "(", "self", ")", ")", "+", "\"needs to implement request_examples\"", ")" ]
Returns a numpy array of integer example indices to run in the next batch.
[ "Returns", "a", "numpy", "array", "of", "integer", "example", "indices", "to", "run", "in", "the", "next", "batch", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attack_bundling.py#L563-L568
train
tensorflow/cleverhans
cleverhans/attack_bundling.py
AttackGoal.new_wins
def new_wins(self, orig_criteria, orig_idx, new_criteria, new_idx): """ Returns a bool indicating whether a new adversarial example is better than the pre-existing one for the same clean example. :param orig_criteria: dict mapping names of criteria to their value for each example in the whole dataset :param orig_idx: The position of the pre-existing example within the whole dataset. :param new_criteria: dict, like orig_criteria, but with values only on the latest batch of adversarial examples :param new_idx: The position of the new adversarial example within the batch """ raise NotImplementedError(str(type(self)) + " needs to implement new_wins.")
python
def new_wins(self, orig_criteria, orig_idx, new_criteria, new_idx): """ Returns a bool indicating whether a new adversarial example is better than the pre-existing one for the same clean example. :param orig_criteria: dict mapping names of criteria to their value for each example in the whole dataset :param orig_idx: The position of the pre-existing example within the whole dataset. :param new_criteria: dict, like orig_criteria, but with values only on the latest batch of adversarial examples :param new_idx: The position of the new adversarial example within the batch """ raise NotImplementedError(str(type(self)) + " needs to implement new_wins.")
[ "def", "new_wins", "(", "self", ",", "orig_criteria", ",", "orig_idx", ",", "new_criteria", ",", "new_idx", ")", ":", "raise", "NotImplementedError", "(", "str", "(", "type", "(", "self", ")", ")", "+", "\" needs to implement new_wins.\"", ")" ]
Returns a bool indicating whether a new adversarial example is better than the pre-existing one for the same clean example. :param orig_criteria: dict mapping names of criteria to their value for each example in the whole dataset :param orig_idx: The position of the pre-existing example within the whole dataset. :param new_criteria: dict, like orig_criteria, but with values only on the latest batch of adversarial examples :param new_idx: The position of the new adversarial example within the batch
[ "Returns", "a", "bool", "indicating", "whether", "a", "new", "adversarial", "example", "is", "better", "than", "the", "pre", "-", "existing", "one", "for", "the", "same", "clean", "example", ".", ":", "param", "orig_criteria", ":", "dict", "mapping", "names", "of", "criteria", "to", "their", "value", "for", "each", "example", "in", "the", "whole", "dataset", ":", "param", "orig_idx", ":", "The", "position", "of", "the", "pre", "-", "existing", "example", "within", "the", "whole", "dataset", ".", ":", "param", "new_criteria", ":", "dict", "like", "orig_criteria", "but", "with", "values", "only", "on", "the", "latest", "batch", "of", "adversarial", "examples", ":", "param", "new_idx", ":", "The", "position", "of", "the", "new", "adversarial", "example", "within", "the", "batch" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attack_bundling.py#L593-L607
train
tensorflow/cleverhans
cleverhans/attack_bundling.py
Misclassify.filter
def filter(self, run_counts, criteria): """ Return run counts only for examples that are still correctly classified """ correctness = criteria['correctness'] assert correctness.dtype == np.bool filtered_counts = deep_copy(run_counts) for key in filtered_counts: filtered_counts[key] = filtered_counts[key][correctness] return filtered_counts
python
def filter(self, run_counts, criteria): """ Return run counts only for examples that are still correctly classified """ correctness = criteria['correctness'] assert correctness.dtype == np.bool filtered_counts = deep_copy(run_counts) for key in filtered_counts: filtered_counts[key] = filtered_counts[key][correctness] return filtered_counts
[ "def", "filter", "(", "self", ",", "run_counts", ",", "criteria", ")", ":", "correctness", "=", "criteria", "[", "'correctness'", "]", "assert", "correctness", ".", "dtype", "==", "np", ".", "bool", "filtered_counts", "=", "deep_copy", "(", "run_counts", ")", "for", "key", "in", "filtered_counts", ":", "filtered_counts", "[", "key", "]", "=", "filtered_counts", "[", "key", "]", "[", "correctness", "]", "return", "filtered_counts" ]
Return run counts only for examples that are still correctly classified
[ "Return", "run", "counts", "only", "for", "examples", "that", "are", "still", "correctly", "classified" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attack_bundling.py#L690-L699
train
tensorflow/cleverhans
cleverhans/attack_bundling.py
MaxConfidence.filter
def filter(self, run_counts, criteria): """ Return the counts for only those examples that are below the threshold """ wrong_confidence = criteria['wrong_confidence'] below_t = wrong_confidence <= self.t filtered_counts = deep_copy(run_counts) for key in filtered_counts: filtered_counts[key] = filtered_counts[key][below_t] return filtered_counts
python
def filter(self, run_counts, criteria): """ Return the counts for only those examples that are below the threshold """ wrong_confidence = criteria['wrong_confidence'] below_t = wrong_confidence <= self.t filtered_counts = deep_copy(run_counts) for key in filtered_counts: filtered_counts[key] = filtered_counts[key][below_t] return filtered_counts
[ "def", "filter", "(", "self", ",", "run_counts", ",", "criteria", ")", ":", "wrong_confidence", "=", "criteria", "[", "'wrong_confidence'", "]", "below_t", "=", "wrong_confidence", "<=", "self", ".", "t", "filtered_counts", "=", "deep_copy", "(", "run_counts", ")", "for", "key", "in", "filtered_counts", ":", "filtered_counts", "[", "key", "]", "=", "filtered_counts", "[", "key", "]", "[", "below_t", "]", "return", "filtered_counts" ]
Return the counts for only those examples that are below the threshold
[ "Return", "the", "counts", "for", "only", "those", "examples", "that", "are", "below", "the", "threshold" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attack_bundling.py#L799-L808
train
tensorflow/cleverhans
cleverhans/future/tf2/attacks/projected_gradient_descent.py
projected_gradient_descent
def projected_gradient_descent(model_fn, x, eps, eps_iter, nb_iter, ord, clip_min=None, clip_max=None, y=None, targeted=False, rand_init=None, rand_minmax=0.3, sanity_checks=True): """ This class implements either the Basic Iterative Method (Kurakin et al. 2016) when rand_init is set to 0. or the Madry et al. (2017) method when rand_minmax is larger than 0. Paper link (Kurakin et al. 2016): https://arxiv.org/pdf/1607.02533.pdf Paper link (Madry et al. 2017): https://arxiv.org/pdf/1706.06083.pdf :param model_fn: a callable that takes an input tensor and returns the model logits. :param x: input tensor. :param eps: epsilon (input variation parameter); see https://arxiv.org/abs/1412.6572. :param eps_iter: step size for each attack iteration :param nb_iter: Number of attack iterations. :param ord: Order of the norm (mimics NumPy). Possible values: np.inf, 1 or 2. :param clip_min: (optional) float. Minimum float value for adversarial example components. :param clip_max: (optional) float. Maximum float value for adversarial example components. :param y: (optional) Tensor with true labels. If targeted is true, then provide the target label. Otherwise, only provide this parameter if you'd like to use true labels when crafting adversarial samples. Otherwise, model predictions are used as labels to avoid the "label leaking" effect (explained in this paper: https://arxiv.org/abs/1611.01236). Default is None. :param targeted: (optional) bool. Is the attack targeted or untargeted? Untargeted, the default, will try to make the label incorrect. Targeted will instead try to move in the direction of being more like y. :param sanity_checks: bool, if True, include asserts (Turn them off to use less runtime / memory or for unit tests that intentionally pass strange input) :return: a tensor for the adversarial example """ assert eps_iter <= eps, (eps_iter, eps) if ord == 1: raise NotImplementedError("It's not clear that FGM is a good inner loop" " step for PGD when ord=1, because ord=1 FGM " " changes only one pixel at a time. We need " " to rigorously test a strong ord=1 PGD " "before enabling this feature.") if ord not in [np.inf, 2]: raise ValueError("Norm order must be either np.inf or 2.") asserts = [] # If a data range was specified, check that the input was in that range if clip_min is not None: asserts.append(tf.math.greater_equal(x, clip_min)) if clip_max is not None: asserts.append(tf.math.less_equal(x, clip_max)) # Initialize loop variables if rand_init: rand_minmax = eps eta = tf.random.uniform(x.shape, -rand_minmax, rand_minmax) else: eta = tf.zeros_like(x) # Clip eta eta = clip_eta(eta, ord, eps) adv_x = x + eta if clip_min is not None or clip_max is not None: adv_x = tf.clip_by_value(adv_x, clip_min, clip_max) if y is None: # Using model predictions as ground truth to avoid label leaking y = tf.argmax(model_fn(x), 1) i = 0 while i < nb_iter: adv_x = fast_gradient_method(model_fn, adv_x, eps_iter, ord, clip_min=clip_min, clip_max=clip_max, y=y, targeted=targeted) # Clipping perturbation eta to ord norm ball eta = adv_x - x eta = clip_eta(eta, ord, eps) adv_x = x + eta # Redo the clipping. # FGM already did it, but subtracting and re-adding eta can add some # small numerical error. if clip_min is not None or clip_max is not None: adv_x = tf.clip_by_value(adv_x, clip_min, clip_max) i += 1 asserts.append(eps_iter <= eps) if ord == np.inf and clip_min is not None: # TODO necessary to cast to x.dtype? asserts.append(eps + clip_min <= clip_max) if sanity_checks: assert np.all(asserts) return adv_x
python
def projected_gradient_descent(model_fn, x, eps, eps_iter, nb_iter, ord, clip_min=None, clip_max=None, y=None, targeted=False, rand_init=None, rand_minmax=0.3, sanity_checks=True): """ This class implements either the Basic Iterative Method (Kurakin et al. 2016) when rand_init is set to 0. or the Madry et al. (2017) method when rand_minmax is larger than 0. Paper link (Kurakin et al. 2016): https://arxiv.org/pdf/1607.02533.pdf Paper link (Madry et al. 2017): https://arxiv.org/pdf/1706.06083.pdf :param model_fn: a callable that takes an input tensor and returns the model logits. :param x: input tensor. :param eps: epsilon (input variation parameter); see https://arxiv.org/abs/1412.6572. :param eps_iter: step size for each attack iteration :param nb_iter: Number of attack iterations. :param ord: Order of the norm (mimics NumPy). Possible values: np.inf, 1 or 2. :param clip_min: (optional) float. Minimum float value for adversarial example components. :param clip_max: (optional) float. Maximum float value for adversarial example components. :param y: (optional) Tensor with true labels. If targeted is true, then provide the target label. Otherwise, only provide this parameter if you'd like to use true labels when crafting adversarial samples. Otherwise, model predictions are used as labels to avoid the "label leaking" effect (explained in this paper: https://arxiv.org/abs/1611.01236). Default is None. :param targeted: (optional) bool. Is the attack targeted or untargeted? Untargeted, the default, will try to make the label incorrect. Targeted will instead try to move in the direction of being more like y. :param sanity_checks: bool, if True, include asserts (Turn them off to use less runtime / memory or for unit tests that intentionally pass strange input) :return: a tensor for the adversarial example """ assert eps_iter <= eps, (eps_iter, eps) if ord == 1: raise NotImplementedError("It's not clear that FGM is a good inner loop" " step for PGD when ord=1, because ord=1 FGM " " changes only one pixel at a time. We need " " to rigorously test a strong ord=1 PGD " "before enabling this feature.") if ord not in [np.inf, 2]: raise ValueError("Norm order must be either np.inf or 2.") asserts = [] # If a data range was specified, check that the input was in that range if clip_min is not None: asserts.append(tf.math.greater_equal(x, clip_min)) if clip_max is not None: asserts.append(tf.math.less_equal(x, clip_max)) # Initialize loop variables if rand_init: rand_minmax = eps eta = tf.random.uniform(x.shape, -rand_minmax, rand_minmax) else: eta = tf.zeros_like(x) # Clip eta eta = clip_eta(eta, ord, eps) adv_x = x + eta if clip_min is not None or clip_max is not None: adv_x = tf.clip_by_value(adv_x, clip_min, clip_max) if y is None: # Using model predictions as ground truth to avoid label leaking y = tf.argmax(model_fn(x), 1) i = 0 while i < nb_iter: adv_x = fast_gradient_method(model_fn, adv_x, eps_iter, ord, clip_min=clip_min, clip_max=clip_max, y=y, targeted=targeted) # Clipping perturbation eta to ord norm ball eta = adv_x - x eta = clip_eta(eta, ord, eps) adv_x = x + eta # Redo the clipping. # FGM already did it, but subtracting and re-adding eta can add some # small numerical error. if clip_min is not None or clip_max is not None: adv_x = tf.clip_by_value(adv_x, clip_min, clip_max) i += 1 asserts.append(eps_iter <= eps) if ord == np.inf and clip_min is not None: # TODO necessary to cast to x.dtype? asserts.append(eps + clip_min <= clip_max) if sanity_checks: assert np.all(asserts) return adv_x
[ "def", "projected_gradient_descent", "(", "model_fn", ",", "x", ",", "eps", ",", "eps_iter", ",", "nb_iter", ",", "ord", ",", "clip_min", "=", "None", ",", "clip_max", "=", "None", ",", "y", "=", "None", ",", "targeted", "=", "False", ",", "rand_init", "=", "None", ",", "rand_minmax", "=", "0.3", ",", "sanity_checks", "=", "True", ")", ":", "assert", "eps_iter", "<=", "eps", ",", "(", "eps_iter", ",", "eps", ")", "if", "ord", "==", "1", ":", "raise", "NotImplementedError", "(", "\"It's not clear that FGM is a good inner loop\"", "\" step for PGD when ord=1, because ord=1 FGM \"", "\" changes only one pixel at a time. We need \"", "\" to rigorously test a strong ord=1 PGD \"", "\"before enabling this feature.\"", ")", "if", "ord", "not", "in", "[", "np", ".", "inf", ",", "2", "]", ":", "raise", "ValueError", "(", "\"Norm order must be either np.inf or 2.\"", ")", "asserts", "=", "[", "]", "# If a data range was specified, check that the input was in that range", "if", "clip_min", "is", "not", "None", ":", "asserts", ".", "append", "(", "tf", ".", "math", ".", "greater_equal", "(", "x", ",", "clip_min", ")", ")", "if", "clip_max", "is", "not", "None", ":", "asserts", ".", "append", "(", "tf", ".", "math", ".", "less_equal", "(", "x", ",", "clip_max", ")", ")", "# Initialize loop variables", "if", "rand_init", ":", "rand_minmax", "=", "eps", "eta", "=", "tf", ".", "random", ".", "uniform", "(", "x", ".", "shape", ",", "-", "rand_minmax", ",", "rand_minmax", ")", "else", ":", "eta", "=", "tf", ".", "zeros_like", "(", "x", ")", "# Clip eta", "eta", "=", "clip_eta", "(", "eta", ",", "ord", ",", "eps", ")", "adv_x", "=", "x", "+", "eta", "if", "clip_min", "is", "not", "None", "or", "clip_max", "is", "not", "None", ":", "adv_x", "=", "tf", ".", "clip_by_value", "(", "adv_x", ",", "clip_min", ",", "clip_max", ")", "if", "y", "is", "None", ":", "# Using model predictions as ground truth to avoid label leaking", "y", "=", "tf", ".", "argmax", "(", "model_fn", "(", "x", ")", ",", "1", ")", "i", "=", "0", "while", "i", "<", "nb_iter", ":", "adv_x", "=", "fast_gradient_method", "(", "model_fn", ",", "adv_x", ",", "eps_iter", ",", "ord", ",", "clip_min", "=", "clip_min", ",", "clip_max", "=", "clip_max", ",", "y", "=", "y", ",", "targeted", "=", "targeted", ")", "# Clipping perturbation eta to ord norm ball", "eta", "=", "adv_x", "-", "x", "eta", "=", "clip_eta", "(", "eta", ",", "ord", ",", "eps", ")", "adv_x", "=", "x", "+", "eta", "# Redo the clipping.", "# FGM already did it, but subtracting and re-adding eta can add some", "# small numerical error.", "if", "clip_min", "is", "not", "None", "or", "clip_max", "is", "not", "None", ":", "adv_x", "=", "tf", ".", "clip_by_value", "(", "adv_x", ",", "clip_min", ",", "clip_max", ")", "i", "+=", "1", "asserts", ".", "append", "(", "eps_iter", "<=", "eps", ")", "if", "ord", "==", "np", ".", "inf", "and", "clip_min", "is", "not", "None", ":", "# TODO necessary to cast to x.dtype?", "asserts", ".", "append", "(", "eps", "+", "clip_min", "<=", "clip_max", ")", "if", "sanity_checks", ":", "assert", "np", ".", "all", "(", "asserts", ")", "return", "adv_x" ]
This class implements either the Basic Iterative Method (Kurakin et al. 2016) when rand_init is set to 0. or the Madry et al. (2017) method when rand_minmax is larger than 0. Paper link (Kurakin et al. 2016): https://arxiv.org/pdf/1607.02533.pdf Paper link (Madry et al. 2017): https://arxiv.org/pdf/1706.06083.pdf :param model_fn: a callable that takes an input tensor and returns the model logits. :param x: input tensor. :param eps: epsilon (input variation parameter); see https://arxiv.org/abs/1412.6572. :param eps_iter: step size for each attack iteration :param nb_iter: Number of attack iterations. :param ord: Order of the norm (mimics NumPy). Possible values: np.inf, 1 or 2. :param clip_min: (optional) float. Minimum float value for adversarial example components. :param clip_max: (optional) float. Maximum float value for adversarial example components. :param y: (optional) Tensor with true labels. If targeted is true, then provide the target label. Otherwise, only provide this parameter if you'd like to use true labels when crafting adversarial samples. Otherwise, model predictions are used as labels to avoid the "label leaking" effect (explained in this paper: https://arxiv.org/abs/1611.01236). Default is None. :param targeted: (optional) bool. Is the attack targeted or untargeted? Untargeted, the default, will try to make the label incorrect. Targeted will instead try to move in the direction of being more like y. :param sanity_checks: bool, if True, include asserts (Turn them off to use less runtime / memory or for unit tests that intentionally pass strange input) :return: a tensor for the adversarial example
[ "This", "class", "implements", "either", "the", "Basic", "Iterative", "Method", "(", "Kurakin", "et", "al", ".", "2016", ")", "when", "rand_init", "is", "set", "to", "0", ".", "or", "the", "Madry", "et", "al", ".", "(", "2017", ")", "method", "when", "rand_minmax", "is", "larger", "than", "0", ".", "Paper", "link", "(", "Kurakin", "et", "al", ".", "2016", ")", ":", "https", ":", "//", "arxiv", ".", "org", "/", "pdf", "/", "1607", ".", "02533", ".", "pdf", "Paper", "link", "(", "Madry", "et", "al", ".", "2017", ")", ":", "https", ":", "//", "arxiv", ".", "org", "/", "pdf", "/", "1706", ".", "06083", ".", "pdf", ":", "param", "model_fn", ":", "a", "callable", "that", "takes", "an", "input", "tensor", "and", "returns", "the", "model", "logits", ".", ":", "param", "x", ":", "input", "tensor", ".", ":", "param", "eps", ":", "epsilon", "(", "input", "variation", "parameter", ")", ";", "see", "https", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1412", ".", "6572", ".", ":", "param", "eps_iter", ":", "step", "size", "for", "each", "attack", "iteration", ":", "param", "nb_iter", ":", "Number", "of", "attack", "iterations", ".", ":", "param", "ord", ":", "Order", "of", "the", "norm", "(", "mimics", "NumPy", ")", ".", "Possible", "values", ":", "np", ".", "inf", "1", "or", "2", ".", ":", "param", "clip_min", ":", "(", "optional", ")", "float", ".", "Minimum", "float", "value", "for", "adversarial", "example", "components", ".", ":", "param", "clip_max", ":", "(", "optional", ")", "float", ".", "Maximum", "float", "value", "for", "adversarial", "example", "components", ".", ":", "param", "y", ":", "(", "optional", ")", "Tensor", "with", "true", "labels", ".", "If", "targeted", "is", "true", "then", "provide", "the", "target", "label", ".", "Otherwise", "only", "provide", "this", "parameter", "if", "you", "d", "like", "to", "use", "true", "labels", "when", "crafting", "adversarial", "samples", ".", "Otherwise", "model", "predictions", "are", "used", "as", "labels", "to", "avoid", "the", "label", "leaking", "effect", "(", "explained", "in", "this", "paper", ":", "https", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1611", ".", "01236", ")", ".", "Default", "is", "None", ".", ":", "param", "targeted", ":", "(", "optional", ")", "bool", ".", "Is", "the", "attack", "targeted", "or", "untargeted?", "Untargeted", "the", "default", "will", "try", "to", "make", "the", "label", "incorrect", ".", "Targeted", "will", "instead", "try", "to", "move", "in", "the", "direction", "of", "being", "more", "like", "y", ".", ":", "param", "sanity_checks", ":", "bool", "if", "True", "include", "asserts", "(", "Turn", "them", "off", "to", "use", "less", "runtime", "/", "memory", "or", "for", "unit", "tests", "that", "intentionally", "pass", "strange", "input", ")", ":", "return", ":", "a", "tensor", "for", "the", "adversarial", "example" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/future/tf2/attacks/projected_gradient_descent.py#L10-L100
train
tensorflow/cleverhans
cleverhans/attacks/bapp.py
clip_image
def clip_image(image, clip_min, clip_max): """ Clip an image, or an image batch, with upper and lower threshold. """ return np.minimum(np.maximum(clip_min, image), clip_max)
python
def clip_image(image, clip_min, clip_max): """ Clip an image, or an image batch, with upper and lower threshold. """ return np.minimum(np.maximum(clip_min, image), clip_max)
[ "def", "clip_image", "(", "image", ",", "clip_min", ",", "clip_max", ")", ":", "return", "np", ".", "minimum", "(", "np", ".", "maximum", "(", "clip_min", ",", "image", ")", ",", "clip_max", ")" ]
Clip an image, or an image batch, with upper and lower threshold.
[ "Clip", "an", "image", "or", "an", "image", "batch", "with", "upper", "and", "lower", "threshold", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/bapp.py#L353-L355
train
tensorflow/cleverhans
cleverhans/attacks/bapp.py
compute_distance
def compute_distance(x_ori, x_pert, constraint='l2'): """ Compute the distance between two images. """ if constraint == 'l2': dist = np.linalg.norm(x_ori - x_pert) elif constraint == 'linf': dist = np.max(abs(x_ori - x_pert)) return dist
python
def compute_distance(x_ori, x_pert, constraint='l2'): """ Compute the distance between two images. """ if constraint == 'l2': dist = np.linalg.norm(x_ori - x_pert) elif constraint == 'linf': dist = np.max(abs(x_ori - x_pert)) return dist
[ "def", "compute_distance", "(", "x_ori", ",", "x_pert", ",", "constraint", "=", "'l2'", ")", ":", "if", "constraint", "==", "'l2'", ":", "dist", "=", "np", ".", "linalg", ".", "norm", "(", "x_ori", "-", "x_pert", ")", "elif", "constraint", "==", "'linf'", ":", "dist", "=", "np", ".", "max", "(", "abs", "(", "x_ori", "-", "x_pert", ")", ")", "return", "dist" ]
Compute the distance between two images.
[ "Compute", "the", "distance", "between", "two", "images", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/bapp.py#L358-L364
train
tensorflow/cleverhans
cleverhans/attacks/bapp.py
approximate_gradient
def approximate_gradient(decision_function, sample, num_evals, delta, constraint, shape, clip_min, clip_max): """ Gradient direction estimation """ # Generate random vectors. noise_shape = [num_evals] + list(shape) if constraint == 'l2': rv = np.random.randn(*noise_shape) elif constraint == 'linf': rv = np.random.uniform(low=-1, high=1, size=noise_shape) axis = tuple(range(1, 1 + len(shape))) rv = rv / np.sqrt(np.sum(rv ** 2, axis=axis, keepdims=True)) perturbed = sample + delta * rv perturbed = clip_image(perturbed, clip_min, clip_max) rv = (perturbed - sample) / delta # query the model. decisions = decision_function(perturbed) decision_shape = [len(decisions)] + [1] * len(shape) fval = 2 * decisions.astype(np_dtype).reshape(decision_shape) - 1.0 # Baseline subtraction (when fval differs) if np.mean(fval) == 1.0: # label changes. gradf = np.mean(rv, axis=0) elif np.mean(fval) == -1.0: # label not change. gradf = - np.mean(rv, axis=0) else: fval = fval - np.mean(fval) gradf = np.mean(fval * rv, axis=0) # Get the gradient direction. gradf = gradf / np.linalg.norm(gradf) return gradf
python
def approximate_gradient(decision_function, sample, num_evals, delta, constraint, shape, clip_min, clip_max): """ Gradient direction estimation """ # Generate random vectors. noise_shape = [num_evals] + list(shape) if constraint == 'l2': rv = np.random.randn(*noise_shape) elif constraint == 'linf': rv = np.random.uniform(low=-1, high=1, size=noise_shape) axis = tuple(range(1, 1 + len(shape))) rv = rv / np.sqrt(np.sum(rv ** 2, axis=axis, keepdims=True)) perturbed = sample + delta * rv perturbed = clip_image(perturbed, clip_min, clip_max) rv = (perturbed - sample) / delta # query the model. decisions = decision_function(perturbed) decision_shape = [len(decisions)] + [1] * len(shape) fval = 2 * decisions.astype(np_dtype).reshape(decision_shape) - 1.0 # Baseline subtraction (when fval differs) if np.mean(fval) == 1.0: # label changes. gradf = np.mean(rv, axis=0) elif np.mean(fval) == -1.0: # label not change. gradf = - np.mean(rv, axis=0) else: fval = fval - np.mean(fval) gradf = np.mean(fval * rv, axis=0) # Get the gradient direction. gradf = gradf / np.linalg.norm(gradf) return gradf
[ "def", "approximate_gradient", "(", "decision_function", ",", "sample", ",", "num_evals", ",", "delta", ",", "constraint", ",", "shape", ",", "clip_min", ",", "clip_max", ")", ":", "# Generate random vectors.", "noise_shape", "=", "[", "num_evals", "]", "+", "list", "(", "shape", ")", "if", "constraint", "==", "'l2'", ":", "rv", "=", "np", ".", "random", ".", "randn", "(", "*", "noise_shape", ")", "elif", "constraint", "==", "'linf'", ":", "rv", "=", "np", ".", "random", ".", "uniform", "(", "low", "=", "-", "1", ",", "high", "=", "1", ",", "size", "=", "noise_shape", ")", "axis", "=", "tuple", "(", "range", "(", "1", ",", "1", "+", "len", "(", "shape", ")", ")", ")", "rv", "=", "rv", "/", "np", ".", "sqrt", "(", "np", ".", "sum", "(", "rv", "**", "2", ",", "axis", "=", "axis", ",", "keepdims", "=", "True", ")", ")", "perturbed", "=", "sample", "+", "delta", "*", "rv", "perturbed", "=", "clip_image", "(", "perturbed", ",", "clip_min", ",", "clip_max", ")", "rv", "=", "(", "perturbed", "-", "sample", ")", "/", "delta", "# query the model.", "decisions", "=", "decision_function", "(", "perturbed", ")", "decision_shape", "=", "[", "len", "(", "decisions", ")", "]", "+", "[", "1", "]", "*", "len", "(", "shape", ")", "fval", "=", "2", "*", "decisions", ".", "astype", "(", "np_dtype", ")", ".", "reshape", "(", "decision_shape", ")", "-", "1.0", "# Baseline subtraction (when fval differs)", "if", "np", ".", "mean", "(", "fval", ")", "==", "1.0", ":", "# label changes.", "gradf", "=", "np", ".", "mean", "(", "rv", ",", "axis", "=", "0", ")", "elif", "np", ".", "mean", "(", "fval", ")", "==", "-", "1.0", ":", "# label not change.", "gradf", "=", "-", "np", ".", "mean", "(", "rv", ",", "axis", "=", "0", ")", "else", ":", "fval", "=", "fval", "-", "np", ".", "mean", "(", "fval", ")", "gradf", "=", "np", ".", "mean", "(", "fval", "*", "rv", ",", "axis", "=", "0", ")", "# Get the gradient direction.", "gradf", "=", "gradf", "/", "np", ".", "linalg", ".", "norm", "(", "gradf", ")", "return", "gradf" ]
Gradient direction estimation
[ "Gradient", "direction", "estimation" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/bapp.py#L366-L399
train
tensorflow/cleverhans
cleverhans/attacks/bapp.py
project
def project(original_image, perturbed_images, alphas, shape, constraint): """ Projection onto given l2 / linf balls in a batch. """ alphas_shape = [len(alphas)] + [1] * len(shape) alphas = alphas.reshape(alphas_shape) if constraint == 'l2': projected = (1-alphas) * original_image + alphas * perturbed_images elif constraint == 'linf': projected = clip_image( perturbed_images, original_image - alphas, original_image + alphas ) return projected
python
def project(original_image, perturbed_images, alphas, shape, constraint): """ Projection onto given l2 / linf balls in a batch. """ alphas_shape = [len(alphas)] + [1] * len(shape) alphas = alphas.reshape(alphas_shape) if constraint == 'l2': projected = (1-alphas) * original_image + alphas * perturbed_images elif constraint == 'linf': projected = clip_image( perturbed_images, original_image - alphas, original_image + alphas ) return projected
[ "def", "project", "(", "original_image", ",", "perturbed_images", ",", "alphas", ",", "shape", ",", "constraint", ")", ":", "alphas_shape", "=", "[", "len", "(", "alphas", ")", "]", "+", "[", "1", "]", "*", "len", "(", "shape", ")", "alphas", "=", "alphas", ".", "reshape", "(", "alphas_shape", ")", "if", "constraint", "==", "'l2'", ":", "projected", "=", "(", "1", "-", "alphas", ")", "*", "original_image", "+", "alphas", "*", "perturbed_images", "elif", "constraint", "==", "'linf'", ":", "projected", "=", "clip_image", "(", "perturbed_images", ",", "original_image", "-", "alphas", ",", "original_image", "+", "alphas", ")", "return", "projected" ]
Projection onto given l2 / linf balls in a batch.
[ "Projection", "onto", "given", "l2", "/", "linf", "balls", "in", "a", "batch", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/bapp.py#L402-L414
train
tensorflow/cleverhans
cleverhans/attacks/bapp.py
binary_search_batch
def binary_search_batch(original_image, perturbed_images, decision_function, shape, constraint, theta): """ Binary search to approach the boundary. """ # Compute distance between each of perturbed image and original image. dists_post_update = np.array([ compute_distance( original_image, perturbed_image, constraint ) for perturbed_image in perturbed_images]) # Choose upper thresholds in binary searchs based on constraint. if constraint == 'linf': highs = dists_post_update # Stopping criteria. thresholds = np.minimum(dists_post_update * theta, theta) else: highs = np.ones(len(perturbed_images)) thresholds = theta lows = np.zeros(len(perturbed_images)) while np.max((highs - lows) / thresholds) > 1: # projection to mids. mids = (highs + lows) / 2.0 mid_images = project(original_image, perturbed_images, mids, shape, constraint) # Update highs and lows based on model decisions. decisions = decision_function(mid_images) lows = np.where(decisions == 0, mids, lows) highs = np.where(decisions == 1, mids, highs) out_images = project(original_image, perturbed_images, highs, shape, constraint) # Compute distance of the output image to select the best choice. # (only used when stepsize_search is grid_search.) dists = np.array([ compute_distance( original_image, out_image, constraint ) for out_image in out_images]) idx = np.argmin(dists) dist = dists_post_update[idx] out_image = out_images[idx] return out_image, dist
python
def binary_search_batch(original_image, perturbed_images, decision_function, shape, constraint, theta): """ Binary search to approach the boundary. """ # Compute distance between each of perturbed image and original image. dists_post_update = np.array([ compute_distance( original_image, perturbed_image, constraint ) for perturbed_image in perturbed_images]) # Choose upper thresholds in binary searchs based on constraint. if constraint == 'linf': highs = dists_post_update # Stopping criteria. thresholds = np.minimum(dists_post_update * theta, theta) else: highs = np.ones(len(perturbed_images)) thresholds = theta lows = np.zeros(len(perturbed_images)) while np.max((highs - lows) / thresholds) > 1: # projection to mids. mids = (highs + lows) / 2.0 mid_images = project(original_image, perturbed_images, mids, shape, constraint) # Update highs and lows based on model decisions. decisions = decision_function(mid_images) lows = np.where(decisions == 0, mids, lows) highs = np.where(decisions == 1, mids, highs) out_images = project(original_image, perturbed_images, highs, shape, constraint) # Compute distance of the output image to select the best choice. # (only used when stepsize_search is grid_search.) dists = np.array([ compute_distance( original_image, out_image, constraint ) for out_image in out_images]) idx = np.argmin(dists) dist = dists_post_update[idx] out_image = out_images[idx] return out_image, dist
[ "def", "binary_search_batch", "(", "original_image", ",", "perturbed_images", ",", "decision_function", ",", "shape", ",", "constraint", ",", "theta", ")", ":", "# Compute distance between each of perturbed image and original image.", "dists_post_update", "=", "np", ".", "array", "(", "[", "compute_distance", "(", "original_image", ",", "perturbed_image", ",", "constraint", ")", "for", "perturbed_image", "in", "perturbed_images", "]", ")", "# Choose upper thresholds in binary searchs based on constraint.", "if", "constraint", "==", "'linf'", ":", "highs", "=", "dists_post_update", "# Stopping criteria.", "thresholds", "=", "np", ".", "minimum", "(", "dists_post_update", "*", "theta", ",", "theta", ")", "else", ":", "highs", "=", "np", ".", "ones", "(", "len", "(", "perturbed_images", ")", ")", "thresholds", "=", "theta", "lows", "=", "np", ".", "zeros", "(", "len", "(", "perturbed_images", ")", ")", "while", "np", ".", "max", "(", "(", "highs", "-", "lows", ")", "/", "thresholds", ")", ">", "1", ":", "# projection to mids.", "mids", "=", "(", "highs", "+", "lows", ")", "/", "2.0", "mid_images", "=", "project", "(", "original_image", ",", "perturbed_images", ",", "mids", ",", "shape", ",", "constraint", ")", "# Update highs and lows based on model decisions.", "decisions", "=", "decision_function", "(", "mid_images", ")", "lows", "=", "np", ".", "where", "(", "decisions", "==", "0", ",", "mids", ",", "lows", ")", "highs", "=", "np", ".", "where", "(", "decisions", "==", "1", ",", "mids", ",", "highs", ")", "out_images", "=", "project", "(", "original_image", ",", "perturbed_images", ",", "highs", ",", "shape", ",", "constraint", ")", "# Compute distance of the output image to select the best choice.", "# (only used when stepsize_search is grid_search.)", "dists", "=", "np", ".", "array", "(", "[", "compute_distance", "(", "original_image", ",", "out_image", ",", "constraint", ")", "for", "out_image", "in", "out_images", "]", ")", "idx", "=", "np", ".", "argmin", "(", "dists", ")", "dist", "=", "dists_post_update", "[", "idx", "]", "out_image", "=", "out_images", "[", "idx", "]", "return", "out_image", ",", "dist" ]
Binary search to approach the boundary.
[ "Binary", "search", "to", "approach", "the", "boundary", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/bapp.py#L417-L468
train
tensorflow/cleverhans
cleverhans/attacks/bapp.py
initialize
def initialize(decision_function, sample, shape, clip_min, clip_max): """ Efficient Implementation of BlendedUniformNoiseAttack in Foolbox. """ success = 0 num_evals = 0 # Find a misclassified random noise. while True: random_noise = np.random.uniform(clip_min, clip_max, size=shape) success = decision_function(random_noise[None])[0] if success: break num_evals += 1 message = "Initialization failed! Try to use a misclassified image as `target_image`" assert num_evals < 1e4, message # Binary search to minimize l2 distance to original image. low = 0.0 high = 1.0 while high - low > 0.001: mid = (high + low) / 2.0 blended = (1 - mid) * sample + mid * random_noise success = decision_function(blended[None])[0] if success: high = mid else: low = mid initialization = (1 - high) * sample + high * random_noise return initialization
python
def initialize(decision_function, sample, shape, clip_min, clip_max): """ Efficient Implementation of BlendedUniformNoiseAttack in Foolbox. """ success = 0 num_evals = 0 # Find a misclassified random noise. while True: random_noise = np.random.uniform(clip_min, clip_max, size=shape) success = decision_function(random_noise[None])[0] if success: break num_evals += 1 message = "Initialization failed! Try to use a misclassified image as `target_image`" assert num_evals < 1e4, message # Binary search to minimize l2 distance to original image. low = 0.0 high = 1.0 while high - low > 0.001: mid = (high + low) / 2.0 blended = (1 - mid) * sample + mid * random_noise success = decision_function(blended[None])[0] if success: high = mid else: low = mid initialization = (1 - high) * sample + high * random_noise return initialization
[ "def", "initialize", "(", "decision_function", ",", "sample", ",", "shape", ",", "clip_min", ",", "clip_max", ")", ":", "success", "=", "0", "num_evals", "=", "0", "# Find a misclassified random noise.", "while", "True", ":", "random_noise", "=", "np", ".", "random", ".", "uniform", "(", "clip_min", ",", "clip_max", ",", "size", "=", "shape", ")", "success", "=", "decision_function", "(", "random_noise", "[", "None", "]", ")", "[", "0", "]", "if", "success", ":", "break", "num_evals", "+=", "1", "message", "=", "\"Initialization failed! Try to use a misclassified image as `target_image`\"", "assert", "num_evals", "<", "1e4", ",", "message", "# Binary search to minimize l2 distance to original image.", "low", "=", "0.0", "high", "=", "1.0", "while", "high", "-", "low", ">", "0.001", ":", "mid", "=", "(", "high", "+", "low", ")", "/", "2.0", "blended", "=", "(", "1", "-", "mid", ")", "*", "sample", "+", "mid", "*", "random_noise", "success", "=", "decision_function", "(", "blended", "[", "None", "]", ")", "[", "0", "]", "if", "success", ":", "high", "=", "mid", "else", ":", "low", "=", "mid", "initialization", "=", "(", "1", "-", "high", ")", "*", "sample", "+", "high", "*", "random_noise", "return", "initialization" ]
Efficient Implementation of BlendedUniformNoiseAttack in Foolbox.
[ "Efficient", "Implementation", "of", "BlendedUniformNoiseAttack", "in", "Foolbox", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/bapp.py#L471-L501
train
tensorflow/cleverhans
cleverhans/attacks/bapp.py
geometric_progression_for_stepsize
def geometric_progression_for_stepsize(x, update, dist, decision_function, current_iteration): """ Geometric progression to search for stepsize. Keep decreasing stepsize by half until reaching the desired side of the boundary. """ epsilon = dist / np.sqrt(current_iteration) while True: updated = x + epsilon * update success = decision_function(updated[None])[0] if success: break else: epsilon = epsilon / 2.0 return epsilon
python
def geometric_progression_for_stepsize(x, update, dist, decision_function, current_iteration): """ Geometric progression to search for stepsize. Keep decreasing stepsize by half until reaching the desired side of the boundary. """ epsilon = dist / np.sqrt(current_iteration) while True: updated = x + epsilon * update success = decision_function(updated[None])[0] if success: break else: epsilon = epsilon / 2.0 return epsilon
[ "def", "geometric_progression_for_stepsize", "(", "x", ",", "update", ",", "dist", ",", "decision_function", ",", "current_iteration", ")", ":", "epsilon", "=", "dist", "/", "np", ".", "sqrt", "(", "current_iteration", ")", "while", "True", ":", "updated", "=", "x", "+", "epsilon", "*", "update", "success", "=", "decision_function", "(", "updated", "[", "None", "]", ")", "[", "0", "]", "if", "success", ":", "break", "else", ":", "epsilon", "=", "epsilon", "/", "2.0", "return", "epsilon" ]
Geometric progression to search for stepsize. Keep decreasing stepsize by half until reaching the desired side of the boundary.
[ "Geometric", "progression", "to", "search", "for", "stepsize", ".", "Keep", "decreasing", "stepsize", "by", "half", "until", "reaching", "the", "desired", "side", "of", "the", "boundary", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/bapp.py#L504-L519
train
tensorflow/cleverhans
cleverhans/attacks/bapp.py
select_delta
def select_delta(dist_post_update, current_iteration, clip_max, clip_min, d, theta, constraint): """ Choose the delta at the scale of distance between x and perturbed sample. """ if current_iteration == 1: delta = 0.1 * (clip_max - clip_min) else: if constraint == 'l2': delta = np.sqrt(d) * theta * dist_post_update elif constraint == 'linf': delta = d * theta * dist_post_update return delta
python
def select_delta(dist_post_update, current_iteration, clip_max, clip_min, d, theta, constraint): """ Choose the delta at the scale of distance between x and perturbed sample. """ if current_iteration == 1: delta = 0.1 * (clip_max - clip_min) else: if constraint == 'l2': delta = np.sqrt(d) * theta * dist_post_update elif constraint == 'linf': delta = d * theta * dist_post_update return delta
[ "def", "select_delta", "(", "dist_post_update", ",", "current_iteration", ",", "clip_max", ",", "clip_min", ",", "d", ",", "theta", ",", "constraint", ")", ":", "if", "current_iteration", "==", "1", ":", "delta", "=", "0.1", "*", "(", "clip_max", "-", "clip_min", ")", "else", ":", "if", "constraint", "==", "'l2'", ":", "delta", "=", "np", ".", "sqrt", "(", "d", ")", "*", "theta", "*", "dist_post_update", "elif", "constraint", "==", "'linf'", ":", "delta", "=", "d", "*", "theta", "*", "dist_post_update", "return", "delta" ]
Choose the delta at the scale of distance between x and perturbed sample.
[ "Choose", "the", "delta", "at", "the", "scale", "of", "distance", "between", "x", "and", "perturbed", "sample", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/bapp.py#L522-L536
train
tensorflow/cleverhans
cleverhans/attacks/bapp.py
BoundaryAttackPlusPlus.generate
def generate(self, x, **kwargs): """ Return a tensor that constructs adversarial examples for the given input. Generate uses tf.py_func in order to operate over tensors. :param x: A tensor with the inputs. :param kwargs: See `parse_params` """ self.parse_params(**kwargs) shape = [int(i) for i in x.get_shape().as_list()[1:]] assert self.sess is not None, \ 'Cannot use `generate` when no `sess` was provided' _check_first_dimension(x, 'input') if self.y_target is not None: _check_first_dimension(self.y_target, 'y_target') assert self.image_target is not None, \ 'Require a target image for targeted attack.' _check_first_dimension(self.image_target, 'image_target') # Set shape and d. self.shape = shape self.d = int(np.prod(shape)) # Set binary search threshold. if self.constraint == 'l2': self.theta = self.gamma / np.sqrt(self.d) else: self.theta = self.gamma / self.d # Construct input placeholder and output for decision function. self.input_ph = tf.placeholder( tf_dtype, [None] + list(self.shape), name='input_image') self.logits = self.model.get_logits(self.input_ph) def bapp_wrap(x, target_label, target_image): """ Wrapper to use tensors as input and output. """ return np.array(self._bapp(x, target_label, target_image), dtype=self.np_dtype) if self.y_target is not None: # targeted attack that requires target label and image. wrap = tf.py_func(bapp_wrap, [x[0], self.y_target[0], self.image_target[0]], self.tf_dtype) else: if self.image_target is not None: # untargeted attack with an initialized image. wrap = tf.py_func(lambda x, target_image: bapp_wrap(x, None, target_image), [x[0], self.image_target[0]], self.tf_dtype) else: # untargeted attack without an initialized image. wrap = tf.py_func(lambda x: bapp_wrap(x, None, None), [x[0]], self.tf_dtype) wrap.set_shape(x.get_shape()) return wrap
python
def generate(self, x, **kwargs): """ Return a tensor that constructs adversarial examples for the given input. Generate uses tf.py_func in order to operate over tensors. :param x: A tensor with the inputs. :param kwargs: See `parse_params` """ self.parse_params(**kwargs) shape = [int(i) for i in x.get_shape().as_list()[1:]] assert self.sess is not None, \ 'Cannot use `generate` when no `sess` was provided' _check_first_dimension(x, 'input') if self.y_target is not None: _check_first_dimension(self.y_target, 'y_target') assert self.image_target is not None, \ 'Require a target image for targeted attack.' _check_first_dimension(self.image_target, 'image_target') # Set shape and d. self.shape = shape self.d = int(np.prod(shape)) # Set binary search threshold. if self.constraint == 'l2': self.theta = self.gamma / np.sqrt(self.d) else: self.theta = self.gamma / self.d # Construct input placeholder and output for decision function. self.input_ph = tf.placeholder( tf_dtype, [None] + list(self.shape), name='input_image') self.logits = self.model.get_logits(self.input_ph) def bapp_wrap(x, target_label, target_image): """ Wrapper to use tensors as input and output. """ return np.array(self._bapp(x, target_label, target_image), dtype=self.np_dtype) if self.y_target is not None: # targeted attack that requires target label and image. wrap = tf.py_func(bapp_wrap, [x[0], self.y_target[0], self.image_target[0]], self.tf_dtype) else: if self.image_target is not None: # untargeted attack with an initialized image. wrap = tf.py_func(lambda x, target_image: bapp_wrap(x, None, target_image), [x[0], self.image_target[0]], self.tf_dtype) else: # untargeted attack without an initialized image. wrap = tf.py_func(lambda x: bapp_wrap(x, None, None), [x[0]], self.tf_dtype) wrap.set_shape(x.get_shape()) return wrap
[ "def", "generate", "(", "self", ",", "x", ",", "*", "*", "kwargs", ")", ":", "self", ".", "parse_params", "(", "*", "*", "kwargs", ")", "shape", "=", "[", "int", "(", "i", ")", "for", "i", "in", "x", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "[", "1", ":", "]", "]", "assert", "self", ".", "sess", "is", "not", "None", ",", "'Cannot use `generate` when no `sess` was provided'", "_check_first_dimension", "(", "x", ",", "'input'", ")", "if", "self", ".", "y_target", "is", "not", "None", ":", "_check_first_dimension", "(", "self", ".", "y_target", ",", "'y_target'", ")", "assert", "self", ".", "image_target", "is", "not", "None", ",", "'Require a target image for targeted attack.'", "_check_first_dimension", "(", "self", ".", "image_target", ",", "'image_target'", ")", "# Set shape and d.", "self", ".", "shape", "=", "shape", "self", ".", "d", "=", "int", "(", "np", ".", "prod", "(", "shape", ")", ")", "# Set binary search threshold.", "if", "self", ".", "constraint", "==", "'l2'", ":", "self", ".", "theta", "=", "self", ".", "gamma", "/", "np", ".", "sqrt", "(", "self", ".", "d", ")", "else", ":", "self", ".", "theta", "=", "self", ".", "gamma", "/", "self", ".", "d", "# Construct input placeholder and output for decision function.", "self", ".", "input_ph", "=", "tf", ".", "placeholder", "(", "tf_dtype", ",", "[", "None", "]", "+", "list", "(", "self", ".", "shape", ")", ",", "name", "=", "'input_image'", ")", "self", ".", "logits", "=", "self", ".", "model", ".", "get_logits", "(", "self", ".", "input_ph", ")", "def", "bapp_wrap", "(", "x", ",", "target_label", ",", "target_image", ")", ":", "\"\"\" Wrapper to use tensors as input and output. \"\"\"", "return", "np", ".", "array", "(", "self", ".", "_bapp", "(", "x", ",", "target_label", ",", "target_image", ")", ",", "dtype", "=", "self", ".", "np_dtype", ")", "if", "self", ".", "y_target", "is", "not", "None", ":", "# targeted attack that requires target label and image.", "wrap", "=", "tf", ".", "py_func", "(", "bapp_wrap", ",", "[", "x", "[", "0", "]", ",", "self", ".", "y_target", "[", "0", "]", ",", "self", ".", "image_target", "[", "0", "]", "]", ",", "self", ".", "tf_dtype", ")", "else", ":", "if", "self", ".", "image_target", "is", "not", "None", ":", "# untargeted attack with an initialized image.", "wrap", "=", "tf", ".", "py_func", "(", "lambda", "x", ",", "target_image", ":", "bapp_wrap", "(", "x", ",", "None", ",", "target_image", ")", ",", "[", "x", "[", "0", "]", ",", "self", ".", "image_target", "[", "0", "]", "]", ",", "self", ".", "tf_dtype", ")", "else", ":", "# untargeted attack without an initialized image.", "wrap", "=", "tf", ".", "py_func", "(", "lambda", "x", ":", "bapp_wrap", "(", "x", ",", "None", ",", "None", ")", ",", "[", "x", "[", "0", "]", "]", ",", "self", ".", "tf_dtype", ")", "wrap", ".", "set_shape", "(", "x", ".", "get_shape", "(", ")", ")", "return", "wrap" ]
Return a tensor that constructs adversarial examples for the given input. Generate uses tf.py_func in order to operate over tensors. :param x: A tensor with the inputs. :param kwargs: See `parse_params`
[ "Return", "a", "tensor", "that", "constructs", "adversarial", "examples", "for", "the", "given", "input", ".", "Generate", "uses", "tf", ".", "py_func", "in", "order", "to", "operate", "over", "tensors", ".", ":", "param", "x", ":", "A", "tensor", "with", "the", "inputs", ".", ":", "param", "kwargs", ":", "See", "parse_params" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/bapp.py#L61-L120
train
tensorflow/cleverhans
cleverhans/attacks/bapp.py
BoundaryAttackPlusPlus.generate_np
def generate_np(self, x, **kwargs): """ Generate adversarial images in a for loop. :param y: An array of shape (n, nb_classes) for true labels. :param y_target: An array of shape (n, nb_classes) for target labels. Required for targeted attack. :param image_target: An array of shape (n, **image shape) for initial target images. Required for targeted attack. See parse_params for other kwargs. """ x_adv = [] if 'image_target' in kwargs and kwargs['image_target'] is not None: image_target = np.copy(kwargs['image_target']) else: image_target = None if 'y_target' in kwargs and kwargs['y_target'] is not None: y_target = np.copy(kwargs['y_target']) else: y_target = None for i, x_single in enumerate(x): img = np.expand_dims(x_single, axis=0) if image_target is not None: single_img_target = np.expand_dims(image_target[i], axis=0) kwargs['image_target'] = single_img_target if y_target is not None: single_y_target = np.expand_dims(y_target[i], axis=0) kwargs['y_target'] = single_y_target adv_img = super(BoundaryAttackPlusPlus, self).generate_np(img, **kwargs) x_adv.append(adv_img) return np.concatenate(x_adv, axis=0)
python
def generate_np(self, x, **kwargs): """ Generate adversarial images in a for loop. :param y: An array of shape (n, nb_classes) for true labels. :param y_target: An array of shape (n, nb_classes) for target labels. Required for targeted attack. :param image_target: An array of shape (n, **image shape) for initial target images. Required for targeted attack. See parse_params for other kwargs. """ x_adv = [] if 'image_target' in kwargs and kwargs['image_target'] is not None: image_target = np.copy(kwargs['image_target']) else: image_target = None if 'y_target' in kwargs and kwargs['y_target'] is not None: y_target = np.copy(kwargs['y_target']) else: y_target = None for i, x_single in enumerate(x): img = np.expand_dims(x_single, axis=0) if image_target is not None: single_img_target = np.expand_dims(image_target[i], axis=0) kwargs['image_target'] = single_img_target if y_target is not None: single_y_target = np.expand_dims(y_target[i], axis=0) kwargs['y_target'] = single_y_target adv_img = super(BoundaryAttackPlusPlus, self).generate_np(img, **kwargs) x_adv.append(adv_img) return np.concatenate(x_adv, axis=0)
[ "def", "generate_np", "(", "self", ",", "x", ",", "*", "*", "kwargs", ")", ":", "x_adv", "=", "[", "]", "if", "'image_target'", "in", "kwargs", "and", "kwargs", "[", "'image_target'", "]", "is", "not", "None", ":", "image_target", "=", "np", ".", "copy", "(", "kwargs", "[", "'image_target'", "]", ")", "else", ":", "image_target", "=", "None", "if", "'y_target'", "in", "kwargs", "and", "kwargs", "[", "'y_target'", "]", "is", "not", "None", ":", "y_target", "=", "np", ".", "copy", "(", "kwargs", "[", "'y_target'", "]", ")", "else", ":", "y_target", "=", "None", "for", "i", ",", "x_single", "in", "enumerate", "(", "x", ")", ":", "img", "=", "np", ".", "expand_dims", "(", "x_single", ",", "axis", "=", "0", ")", "if", "image_target", "is", "not", "None", ":", "single_img_target", "=", "np", ".", "expand_dims", "(", "image_target", "[", "i", "]", ",", "axis", "=", "0", ")", "kwargs", "[", "'image_target'", "]", "=", "single_img_target", "if", "y_target", "is", "not", "None", ":", "single_y_target", "=", "np", ".", "expand_dims", "(", "y_target", "[", "i", "]", ",", "axis", "=", "0", ")", "kwargs", "[", "'y_target'", "]", "=", "single_y_target", "adv_img", "=", "super", "(", "BoundaryAttackPlusPlus", ",", "self", ")", ".", "generate_np", "(", "img", ",", "*", "*", "kwargs", ")", "x_adv", ".", "append", "(", "adv_img", ")", "return", "np", ".", "concatenate", "(", "x_adv", ",", "axis", "=", "0", ")" ]
Generate adversarial images in a for loop. :param y: An array of shape (n, nb_classes) for true labels. :param y_target: An array of shape (n, nb_classes) for target labels. Required for targeted attack. :param image_target: An array of shape (n, **image shape) for initial target images. Required for targeted attack. See parse_params for other kwargs.
[ "Generate", "adversarial", "images", "in", "a", "for", "loop", ".", ":", "param", "y", ":", "An", "array", "of", "shape", "(", "n", "nb_classes", ")", "for", "true", "labels", ".", ":", "param", "y_target", ":", "An", "array", "of", "shape", "(", "n", "nb_classes", ")", "for", "target", "labels", ".", "Required", "for", "targeted", "attack", ".", ":", "param", "image_target", ":", "An", "array", "of", "shape", "(", "n", "**", "image", "shape", ")", "for", "initial", "target", "images", ".", "Required", "for", "targeted", "attack", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/bapp.py#L122-L159
train
tensorflow/cleverhans
cleverhans/attacks/bapp.py
BoundaryAttackPlusPlus.parse_params
def parse_params(self, y_target=None, image_target=None, initial_num_evals=100, max_num_evals=10000, stepsize_search='grid_search', num_iterations=64, gamma=0.01, constraint='l2', batch_size=128, verbose=True, clip_min=0, clip_max=1): """ :param y: A tensor of shape (1, nb_classes) for true labels. :param y_target: A tensor of shape (1, nb_classes) for target labels. Required for targeted attack. :param image_target: A tensor of shape (1, **image shape) for initial target images. Required for targeted attack. :param initial_num_evals: initial number of evaluations for gradient estimation. :param max_num_evals: maximum number of evaluations for gradient estimation. :param stepsize_search: How to search for stepsize; choices are 'geometric_progression', 'grid_search'. 'geometric progression' initializes the stepsize by ||x_t - x||_p / sqrt(iteration), and keep decreasing by half until reaching the target side of the boundary. 'grid_search' chooses the optimal epsilon over a grid, in the scale of ||x_t - x||_p. :param num_iterations: The number of iterations. :param gamma: The binary search threshold theta is gamma / sqrt(d) for l2 attack and gamma / d for linf attack. :param constraint: The distance to optimize; choices are 'l2', 'linf'. :param batch_size: batch_size for model prediction. :param verbose: (boolean) Whether distance at each step is printed. :param clip_min: (optional float) Minimum input component value :param clip_max: (optional float) Maximum input component value """ # ignore the y and y_target argument self.y_target = y_target self.image_target = image_target self.initial_num_evals = initial_num_evals self.max_num_evals = max_num_evals self.stepsize_search = stepsize_search self.num_iterations = num_iterations self.gamma = gamma self.constraint = constraint self.batch_size = batch_size self.clip_min = clip_min self.clip_max = clip_max self.verbose = verbose
python
def parse_params(self, y_target=None, image_target=None, initial_num_evals=100, max_num_evals=10000, stepsize_search='grid_search', num_iterations=64, gamma=0.01, constraint='l2', batch_size=128, verbose=True, clip_min=0, clip_max=1): """ :param y: A tensor of shape (1, nb_classes) for true labels. :param y_target: A tensor of shape (1, nb_classes) for target labels. Required for targeted attack. :param image_target: A tensor of shape (1, **image shape) for initial target images. Required for targeted attack. :param initial_num_evals: initial number of evaluations for gradient estimation. :param max_num_evals: maximum number of evaluations for gradient estimation. :param stepsize_search: How to search for stepsize; choices are 'geometric_progression', 'grid_search'. 'geometric progression' initializes the stepsize by ||x_t - x||_p / sqrt(iteration), and keep decreasing by half until reaching the target side of the boundary. 'grid_search' chooses the optimal epsilon over a grid, in the scale of ||x_t - x||_p. :param num_iterations: The number of iterations. :param gamma: The binary search threshold theta is gamma / sqrt(d) for l2 attack and gamma / d for linf attack. :param constraint: The distance to optimize; choices are 'l2', 'linf'. :param batch_size: batch_size for model prediction. :param verbose: (boolean) Whether distance at each step is printed. :param clip_min: (optional float) Minimum input component value :param clip_max: (optional float) Maximum input component value """ # ignore the y and y_target argument self.y_target = y_target self.image_target = image_target self.initial_num_evals = initial_num_evals self.max_num_evals = max_num_evals self.stepsize_search = stepsize_search self.num_iterations = num_iterations self.gamma = gamma self.constraint = constraint self.batch_size = batch_size self.clip_min = clip_min self.clip_max = clip_max self.verbose = verbose
[ "def", "parse_params", "(", "self", ",", "y_target", "=", "None", ",", "image_target", "=", "None", ",", "initial_num_evals", "=", "100", ",", "max_num_evals", "=", "10000", ",", "stepsize_search", "=", "'grid_search'", ",", "num_iterations", "=", "64", ",", "gamma", "=", "0.01", ",", "constraint", "=", "'l2'", ",", "batch_size", "=", "128", ",", "verbose", "=", "True", ",", "clip_min", "=", "0", ",", "clip_max", "=", "1", ")", ":", "# ignore the y and y_target argument", "self", ".", "y_target", "=", "y_target", "self", ".", "image_target", "=", "image_target", "self", ".", "initial_num_evals", "=", "initial_num_evals", "self", ".", "max_num_evals", "=", "max_num_evals", "self", ".", "stepsize_search", "=", "stepsize_search", "self", ".", "num_iterations", "=", "num_iterations", "self", ".", "gamma", "=", "gamma", "self", ".", "constraint", "=", "constraint", "self", ".", "batch_size", "=", "batch_size", "self", ".", "clip_min", "=", "clip_min", "self", ".", "clip_max", "=", "clip_max", "self", ".", "verbose", "=", "verbose" ]
:param y: A tensor of shape (1, nb_classes) for true labels. :param y_target: A tensor of shape (1, nb_classes) for target labels. Required for targeted attack. :param image_target: A tensor of shape (1, **image shape) for initial target images. Required for targeted attack. :param initial_num_evals: initial number of evaluations for gradient estimation. :param max_num_evals: maximum number of evaluations for gradient estimation. :param stepsize_search: How to search for stepsize; choices are 'geometric_progression', 'grid_search'. 'geometric progression' initializes the stepsize by ||x_t - x||_p / sqrt(iteration), and keep decreasing by half until reaching the target side of the boundary. 'grid_search' chooses the optimal epsilon over a grid, in the scale of ||x_t - x||_p. :param num_iterations: The number of iterations. :param gamma: The binary search threshold theta is gamma / sqrt(d) for l2 attack and gamma / d for linf attack. :param constraint: The distance to optimize; choices are 'l2', 'linf'. :param batch_size: batch_size for model prediction. :param verbose: (boolean) Whether distance at each step is printed. :param clip_min: (optional float) Minimum input component value :param clip_max: (optional float) Maximum input component value
[ ":", "param", "y", ":", "A", "tensor", "of", "shape", "(", "1", "nb_classes", ")", "for", "true", "labels", ".", ":", "param", "y_target", ":", "A", "tensor", "of", "shape", "(", "1", "nb_classes", ")", "for", "target", "labels", ".", "Required", "for", "targeted", "attack", ".", ":", "param", "image_target", ":", "A", "tensor", "of", "shape", "(", "1", "**", "image", "shape", ")", "for", "initial", "target", "images", ".", "Required", "for", "targeted", "attack", ".", ":", "param", "initial_num_evals", ":", "initial", "number", "of", "evaluations", "for", "gradient", "estimation", ".", ":", "param", "max_num_evals", ":", "maximum", "number", "of", "evaluations", "for", "gradient", "estimation", ".", ":", "param", "stepsize_search", ":", "How", "to", "search", "for", "stepsize", ";", "choices", "are", "geometric_progression", "grid_search", ".", "geometric", "progression", "initializes", "the", "stepsize", "by", "||x_t", "-", "x||_p", "/", "sqrt", "(", "iteration", ")", "and", "keep", "decreasing", "by", "half", "until", "reaching", "the", "target", "side", "of", "the", "boundary", ".", "grid_search", "chooses", "the", "optimal", "epsilon", "over", "a", "grid", "in", "the", "scale", "of", "||x_t", "-", "x||_p", ".", ":", "param", "num_iterations", ":", "The", "number", "of", "iterations", ".", ":", "param", "gamma", ":", "The", "binary", "search", "threshold", "theta", "is", "gamma", "/", "sqrt", "(", "d", ")", "for", "l2", "attack", "and", "gamma", "/", "d", "for", "linf", "attack", ".", ":", "param", "constraint", ":", "The", "distance", "to", "optimize", ";", "choices", "are", "l2", "linf", ".", ":", "param", "batch_size", ":", "batch_size", "for", "model", "prediction", ".", ":", "param", "verbose", ":", "(", "boolean", ")", "Whether", "distance", "at", "each", "step", "is", "printed", ".", ":", "param", "clip_min", ":", "(", "optional", "float", ")", "Minimum", "input", "component", "value", ":", "param", "clip_max", ":", "(", "optional", "float", ")", "Maximum", "input", "component", "value" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/bapp.py#L161-L213
train
tensorflow/cleverhans
cleverhans/attacks/bapp.py
BoundaryAttackPlusPlus._bapp
def _bapp(self, sample, target_label, target_image): """ Main algorithm for Boundary Attack ++. Return a tensor that constructs adversarial examples for the given input. Generate uses tf.py_func in order to operate over tensors. :param sample: input image. Without the batchsize dimension. :param target_label: integer for targeted attack, None for nontargeted attack. Without the batchsize dimension. :param target_image: an array with the same size as sample, or None. Without the batchsize dimension. Output: perturbed image. """ # Original label required for untargeted attack. if target_label is None: original_label = np.argmax( self.sess.run(self.logits, feed_dict={self.input_ph: sample[None]}) ) else: target_label = np.argmax(target_label) def decision_function(images): """ Decision function output 1 on the desired side of the boundary, 0 otherwise. """ images = clip_image(images, self.clip_min, self.clip_max) prob = [] for i in range(0, len(images), self.batch_size): batch = images[i:i+self.batch_size] prob_i = self.sess.run(self.logits, feed_dict={self.input_ph: batch}) prob.append(prob_i) prob = np.concatenate(prob, axis=0) if target_label is None: return np.argmax(prob, axis=1) != original_label else: return np.argmax(prob, axis=1) == target_label # Initialize. if target_image is None: perturbed = initialize(decision_function, sample, self.shape, self.clip_min, self.clip_max) else: perturbed = target_image # Project the initialization to the boundary. perturbed, dist_post_update = binary_search_batch(sample, np.expand_dims(perturbed, 0), decision_function, self.shape, self.constraint, self.theta) dist = compute_distance(perturbed, sample, self.constraint) for j in np.arange(self.num_iterations): current_iteration = j + 1 # Choose delta. delta = select_delta(dist_post_update, current_iteration, self.clip_max, self.clip_min, self.d, self.theta, self.constraint) # Choose number of evaluations. num_evals = int(min([self.initial_num_evals * np.sqrt(j+1), self.max_num_evals])) # approximate gradient. gradf = approximate_gradient(decision_function, perturbed, num_evals, delta, self.constraint, self.shape, self.clip_min, self.clip_max) if self.constraint == 'linf': update = np.sign(gradf) else: update = gradf # search step size. if self.stepsize_search == 'geometric_progression': # find step size. epsilon = geometric_progression_for_stepsize(perturbed, update, dist, decision_function, current_iteration) # Update the sample. perturbed = clip_image(perturbed + epsilon * update, self.clip_min, self.clip_max) # Binary search to return to the boundary. perturbed, dist_post_update = binary_search_batch(sample, perturbed[None], decision_function, self.shape, self.constraint, self.theta) elif self.stepsize_search == 'grid_search': # Grid search for stepsize. epsilons = np.logspace(-4, 0, num=20, endpoint=True) * dist epsilons_shape = [20] + len(self.shape) * [1] perturbeds = perturbed + epsilons.reshape(epsilons_shape) * update perturbeds = clip_image(perturbeds, self.clip_min, self.clip_max) idx_perturbed = decision_function(perturbeds) if np.sum(idx_perturbed) > 0: # Select the perturbation that yields the minimum distance # after binary search. perturbed, dist_post_update = binary_search_batch(sample, perturbeds[idx_perturbed], decision_function, self.shape, self.constraint, self.theta) # compute new distance. dist = compute_distance(perturbed, sample, self.constraint) if self.verbose: print('iteration: {:d}, {:s} distance {:.4E}'.format( j+1, self.constraint, dist)) perturbed = np.expand_dims(perturbed, 0) return perturbed
python
def _bapp(self, sample, target_label, target_image): """ Main algorithm for Boundary Attack ++. Return a tensor that constructs adversarial examples for the given input. Generate uses tf.py_func in order to operate over tensors. :param sample: input image. Without the batchsize dimension. :param target_label: integer for targeted attack, None for nontargeted attack. Without the batchsize dimension. :param target_image: an array with the same size as sample, or None. Without the batchsize dimension. Output: perturbed image. """ # Original label required for untargeted attack. if target_label is None: original_label = np.argmax( self.sess.run(self.logits, feed_dict={self.input_ph: sample[None]}) ) else: target_label = np.argmax(target_label) def decision_function(images): """ Decision function output 1 on the desired side of the boundary, 0 otherwise. """ images = clip_image(images, self.clip_min, self.clip_max) prob = [] for i in range(0, len(images), self.batch_size): batch = images[i:i+self.batch_size] prob_i = self.sess.run(self.logits, feed_dict={self.input_ph: batch}) prob.append(prob_i) prob = np.concatenate(prob, axis=0) if target_label is None: return np.argmax(prob, axis=1) != original_label else: return np.argmax(prob, axis=1) == target_label # Initialize. if target_image is None: perturbed = initialize(decision_function, sample, self.shape, self.clip_min, self.clip_max) else: perturbed = target_image # Project the initialization to the boundary. perturbed, dist_post_update = binary_search_batch(sample, np.expand_dims(perturbed, 0), decision_function, self.shape, self.constraint, self.theta) dist = compute_distance(perturbed, sample, self.constraint) for j in np.arange(self.num_iterations): current_iteration = j + 1 # Choose delta. delta = select_delta(dist_post_update, current_iteration, self.clip_max, self.clip_min, self.d, self.theta, self.constraint) # Choose number of evaluations. num_evals = int(min([self.initial_num_evals * np.sqrt(j+1), self.max_num_evals])) # approximate gradient. gradf = approximate_gradient(decision_function, perturbed, num_evals, delta, self.constraint, self.shape, self.clip_min, self.clip_max) if self.constraint == 'linf': update = np.sign(gradf) else: update = gradf # search step size. if self.stepsize_search == 'geometric_progression': # find step size. epsilon = geometric_progression_for_stepsize(perturbed, update, dist, decision_function, current_iteration) # Update the sample. perturbed = clip_image(perturbed + epsilon * update, self.clip_min, self.clip_max) # Binary search to return to the boundary. perturbed, dist_post_update = binary_search_batch(sample, perturbed[None], decision_function, self.shape, self.constraint, self.theta) elif self.stepsize_search == 'grid_search': # Grid search for stepsize. epsilons = np.logspace(-4, 0, num=20, endpoint=True) * dist epsilons_shape = [20] + len(self.shape) * [1] perturbeds = perturbed + epsilons.reshape(epsilons_shape) * update perturbeds = clip_image(perturbeds, self.clip_min, self.clip_max) idx_perturbed = decision_function(perturbeds) if np.sum(idx_perturbed) > 0: # Select the perturbation that yields the minimum distance # after binary search. perturbed, dist_post_update = binary_search_batch(sample, perturbeds[idx_perturbed], decision_function, self.shape, self.constraint, self.theta) # compute new distance. dist = compute_distance(perturbed, sample, self.constraint) if self.verbose: print('iteration: {:d}, {:s} distance {:.4E}'.format( j+1, self.constraint, dist)) perturbed = np.expand_dims(perturbed, 0) return perturbed
[ "def", "_bapp", "(", "self", ",", "sample", ",", "target_label", ",", "target_image", ")", ":", "# Original label required for untargeted attack.", "if", "target_label", "is", "None", ":", "original_label", "=", "np", ".", "argmax", "(", "self", ".", "sess", ".", "run", "(", "self", ".", "logits", ",", "feed_dict", "=", "{", "self", ".", "input_ph", ":", "sample", "[", "None", "]", "}", ")", ")", "else", ":", "target_label", "=", "np", ".", "argmax", "(", "target_label", ")", "def", "decision_function", "(", "images", ")", ":", "\"\"\"\n Decision function output 1 on the desired side of the boundary,\n 0 otherwise.\n \"\"\"", "images", "=", "clip_image", "(", "images", ",", "self", ".", "clip_min", ",", "self", ".", "clip_max", ")", "prob", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "images", ")", ",", "self", ".", "batch_size", ")", ":", "batch", "=", "images", "[", "i", ":", "i", "+", "self", ".", "batch_size", "]", "prob_i", "=", "self", ".", "sess", ".", "run", "(", "self", ".", "logits", ",", "feed_dict", "=", "{", "self", ".", "input_ph", ":", "batch", "}", ")", "prob", ".", "append", "(", "prob_i", ")", "prob", "=", "np", ".", "concatenate", "(", "prob", ",", "axis", "=", "0", ")", "if", "target_label", "is", "None", ":", "return", "np", ".", "argmax", "(", "prob", ",", "axis", "=", "1", ")", "!=", "original_label", "else", ":", "return", "np", ".", "argmax", "(", "prob", ",", "axis", "=", "1", ")", "==", "target_label", "# Initialize.", "if", "target_image", "is", "None", ":", "perturbed", "=", "initialize", "(", "decision_function", ",", "sample", ",", "self", ".", "shape", ",", "self", ".", "clip_min", ",", "self", ".", "clip_max", ")", "else", ":", "perturbed", "=", "target_image", "# Project the initialization to the boundary.", "perturbed", ",", "dist_post_update", "=", "binary_search_batch", "(", "sample", ",", "np", ".", "expand_dims", "(", "perturbed", ",", "0", ")", ",", "decision_function", ",", "self", ".", "shape", ",", "self", ".", "constraint", ",", "self", ".", "theta", ")", "dist", "=", "compute_distance", "(", "perturbed", ",", "sample", ",", "self", ".", "constraint", ")", "for", "j", "in", "np", ".", "arange", "(", "self", ".", "num_iterations", ")", ":", "current_iteration", "=", "j", "+", "1", "# Choose delta.", "delta", "=", "select_delta", "(", "dist_post_update", ",", "current_iteration", ",", "self", ".", "clip_max", ",", "self", ".", "clip_min", ",", "self", ".", "d", ",", "self", ".", "theta", ",", "self", ".", "constraint", ")", "# Choose number of evaluations.", "num_evals", "=", "int", "(", "min", "(", "[", "self", ".", "initial_num_evals", "*", "np", ".", "sqrt", "(", "j", "+", "1", ")", ",", "self", ".", "max_num_evals", "]", ")", ")", "# approximate gradient.", "gradf", "=", "approximate_gradient", "(", "decision_function", ",", "perturbed", ",", "num_evals", ",", "delta", ",", "self", ".", "constraint", ",", "self", ".", "shape", ",", "self", ".", "clip_min", ",", "self", ".", "clip_max", ")", "if", "self", ".", "constraint", "==", "'linf'", ":", "update", "=", "np", ".", "sign", "(", "gradf", ")", "else", ":", "update", "=", "gradf", "# search step size.", "if", "self", ".", "stepsize_search", "==", "'geometric_progression'", ":", "# find step size.", "epsilon", "=", "geometric_progression_for_stepsize", "(", "perturbed", ",", "update", ",", "dist", ",", "decision_function", ",", "current_iteration", ")", "# Update the sample.", "perturbed", "=", "clip_image", "(", "perturbed", "+", "epsilon", "*", "update", ",", "self", ".", "clip_min", ",", "self", ".", "clip_max", ")", "# Binary search to return to the boundary.", "perturbed", ",", "dist_post_update", "=", "binary_search_batch", "(", "sample", ",", "perturbed", "[", "None", "]", ",", "decision_function", ",", "self", ".", "shape", ",", "self", ".", "constraint", ",", "self", ".", "theta", ")", "elif", "self", ".", "stepsize_search", "==", "'grid_search'", ":", "# Grid search for stepsize.", "epsilons", "=", "np", ".", "logspace", "(", "-", "4", ",", "0", ",", "num", "=", "20", ",", "endpoint", "=", "True", ")", "*", "dist", "epsilons_shape", "=", "[", "20", "]", "+", "len", "(", "self", ".", "shape", ")", "*", "[", "1", "]", "perturbeds", "=", "perturbed", "+", "epsilons", ".", "reshape", "(", "epsilons_shape", ")", "*", "update", "perturbeds", "=", "clip_image", "(", "perturbeds", ",", "self", ".", "clip_min", ",", "self", ".", "clip_max", ")", "idx_perturbed", "=", "decision_function", "(", "perturbeds", ")", "if", "np", ".", "sum", "(", "idx_perturbed", ")", ">", "0", ":", "# Select the perturbation that yields the minimum distance # after binary search.", "perturbed", ",", "dist_post_update", "=", "binary_search_batch", "(", "sample", ",", "perturbeds", "[", "idx_perturbed", "]", ",", "decision_function", ",", "self", ".", "shape", ",", "self", ".", "constraint", ",", "self", ".", "theta", ")", "# compute new distance.", "dist", "=", "compute_distance", "(", "perturbed", ",", "sample", ",", "self", ".", "constraint", ")", "if", "self", ".", "verbose", ":", "print", "(", "'iteration: {:d}, {:s} distance {:.4E}'", ".", "format", "(", "j", "+", "1", ",", "self", ".", "constraint", ",", "dist", ")", ")", "perturbed", "=", "np", ".", "expand_dims", "(", "perturbed", ",", "0", ")", "return", "perturbed" ]
Main algorithm for Boundary Attack ++. Return a tensor that constructs adversarial examples for the given input. Generate uses tf.py_func in order to operate over tensors. :param sample: input image. Without the batchsize dimension. :param target_label: integer for targeted attack, None for nontargeted attack. Without the batchsize dimension. :param target_image: an array with the same size as sample, or None. Without the batchsize dimension. Output: perturbed image.
[ "Main", "algorithm", "for", "Boundary", "Attack", "++", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/bapp.py#L215-L339
train
tensorflow/cleverhans
cleverhans/attacks/fast_feature_adversaries.py
FastFeatureAdversaries.parse_params
def parse_params(self, layer=None, eps=0.3, eps_iter=0.05, nb_iter=10, ord=np.inf, clip_min=None, clip_max=None, **kwargs): """ Take in a dictionary of parameters and applies attack-specific checks before saving them as attributes. Attack-specific parameters: :param layer: (required str) name of the layer to target. :param eps: (optional float) maximum distortion of adversarial example compared to original input :param eps_iter: (optional float) step size for each attack iteration :param nb_iter: (optional int) Number of attack iterations. :param ord: (optional) Order of the norm (mimics Numpy). Possible values: np.inf, 1 or 2. :param clip_min: (optional float) Minimum input component value :param clip_max: (optional float) Maximum input component value """ # Save attack-specific parameters self.layer = layer self.eps = eps self.eps_iter = eps_iter self.nb_iter = nb_iter self.ord = ord self.clip_min = clip_min self.clip_max = clip_max # Check if order of the norm is acceptable given current implementation if self.ord not in [np.inf, 1, 2]: raise ValueError("Norm order must be either np.inf, 1, or 2.") if len(kwargs.keys()) > 0: warnings.warn("kwargs is unused and will be removed on or after " "2019-04-26.") return True
python
def parse_params(self, layer=None, eps=0.3, eps_iter=0.05, nb_iter=10, ord=np.inf, clip_min=None, clip_max=None, **kwargs): """ Take in a dictionary of parameters and applies attack-specific checks before saving them as attributes. Attack-specific parameters: :param layer: (required str) name of the layer to target. :param eps: (optional float) maximum distortion of adversarial example compared to original input :param eps_iter: (optional float) step size for each attack iteration :param nb_iter: (optional int) Number of attack iterations. :param ord: (optional) Order of the norm (mimics Numpy). Possible values: np.inf, 1 or 2. :param clip_min: (optional float) Minimum input component value :param clip_max: (optional float) Maximum input component value """ # Save attack-specific parameters self.layer = layer self.eps = eps self.eps_iter = eps_iter self.nb_iter = nb_iter self.ord = ord self.clip_min = clip_min self.clip_max = clip_max # Check if order of the norm is acceptable given current implementation if self.ord not in [np.inf, 1, 2]: raise ValueError("Norm order must be either np.inf, 1, or 2.") if len(kwargs.keys()) > 0: warnings.warn("kwargs is unused and will be removed on or after " "2019-04-26.") return True
[ "def", "parse_params", "(", "self", ",", "layer", "=", "None", ",", "eps", "=", "0.3", ",", "eps_iter", "=", "0.05", ",", "nb_iter", "=", "10", ",", "ord", "=", "np", ".", "inf", ",", "clip_min", "=", "None", ",", "clip_max", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Save attack-specific parameters", "self", ".", "layer", "=", "layer", "self", ".", "eps", "=", "eps", "self", ".", "eps_iter", "=", "eps_iter", "self", ".", "nb_iter", "=", "nb_iter", "self", ".", "ord", "=", "ord", "self", ".", "clip_min", "=", "clip_min", "self", ".", "clip_max", "=", "clip_max", "# Check if order of the norm is acceptable given current implementation", "if", "self", ".", "ord", "not", "in", "[", "np", ".", "inf", ",", "1", ",", "2", "]", ":", "raise", "ValueError", "(", "\"Norm order must be either np.inf, 1, or 2.\"", ")", "if", "len", "(", "kwargs", ".", "keys", "(", ")", ")", ">", "0", ":", "warnings", ".", "warn", "(", "\"kwargs is unused and will be removed on or after \"", "\"2019-04-26.\"", ")", "return", "True" ]
Take in a dictionary of parameters and applies attack-specific checks before saving them as attributes. Attack-specific parameters: :param layer: (required str) name of the layer to target. :param eps: (optional float) maximum distortion of adversarial example compared to original input :param eps_iter: (optional float) step size for each attack iteration :param nb_iter: (optional int) Number of attack iterations. :param ord: (optional) Order of the norm (mimics Numpy). Possible values: np.inf, 1 or 2. :param clip_min: (optional float) Minimum input component value :param clip_max: (optional float) Maximum input component value
[ "Take", "in", "a", "dictionary", "of", "parameters", "and", "applies", "attack", "-", "specific", "checks", "before", "saving", "them", "as", "attributes", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/fast_feature_adversaries.py#L44-L86
train
tensorflow/cleverhans
cleverhans/attacks/fast_feature_adversaries.py
FastFeatureAdversaries.attack_single_step
def attack_single_step(self, x, eta, g_feat): """ TensorFlow implementation of the Fast Feature Gradient. This is a single step attack similar to Fast Gradient Method that attacks an internal representation. :param x: the input placeholder :param eta: A tensor the same shape as x that holds the perturbation. :param g_feat: model's internal tensor for guide :return: a tensor for the adversarial example """ adv_x = x + eta a_feat = self.model.fprop(adv_x)[self.layer] # feat.shape = (batch, c) or (batch, w, h, c) axis = list(range(1, len(a_feat.shape))) # Compute loss # This is a targeted attack, hence the negative sign loss = -reduce_sum(tf.square(a_feat - g_feat), axis) # Define gradient of loss wrt input grad, = tf.gradients(loss, adv_x) # Multiply by constant epsilon scaled_signed_grad = self.eps_iter * tf.sign(grad) # Add perturbation to original example to obtain adversarial example adv_x = adv_x + scaled_signed_grad # If clipping is needed, # reset all values outside of [clip_min, clip_max] if (self.clip_min is not None) and (self.clip_max is not None): adv_x = tf.clip_by_value(adv_x, self.clip_min, self.clip_max) adv_x = tf.stop_gradient(adv_x) eta = adv_x - x eta = clip_eta(eta, self.ord, self.eps) return eta
python
def attack_single_step(self, x, eta, g_feat): """ TensorFlow implementation of the Fast Feature Gradient. This is a single step attack similar to Fast Gradient Method that attacks an internal representation. :param x: the input placeholder :param eta: A tensor the same shape as x that holds the perturbation. :param g_feat: model's internal tensor for guide :return: a tensor for the adversarial example """ adv_x = x + eta a_feat = self.model.fprop(adv_x)[self.layer] # feat.shape = (batch, c) or (batch, w, h, c) axis = list(range(1, len(a_feat.shape))) # Compute loss # This is a targeted attack, hence the negative sign loss = -reduce_sum(tf.square(a_feat - g_feat), axis) # Define gradient of loss wrt input grad, = tf.gradients(loss, adv_x) # Multiply by constant epsilon scaled_signed_grad = self.eps_iter * tf.sign(grad) # Add perturbation to original example to obtain adversarial example adv_x = adv_x + scaled_signed_grad # If clipping is needed, # reset all values outside of [clip_min, clip_max] if (self.clip_min is not None) and (self.clip_max is not None): adv_x = tf.clip_by_value(adv_x, self.clip_min, self.clip_max) adv_x = tf.stop_gradient(adv_x) eta = adv_x - x eta = clip_eta(eta, self.ord, self.eps) return eta
[ "def", "attack_single_step", "(", "self", ",", "x", ",", "eta", ",", "g_feat", ")", ":", "adv_x", "=", "x", "+", "eta", "a_feat", "=", "self", ".", "model", ".", "fprop", "(", "adv_x", ")", "[", "self", ".", "layer", "]", "# feat.shape = (batch, c) or (batch, w, h, c)", "axis", "=", "list", "(", "range", "(", "1", ",", "len", "(", "a_feat", ".", "shape", ")", ")", ")", "# Compute loss", "# This is a targeted attack, hence the negative sign", "loss", "=", "-", "reduce_sum", "(", "tf", ".", "square", "(", "a_feat", "-", "g_feat", ")", ",", "axis", ")", "# Define gradient of loss wrt input", "grad", ",", "=", "tf", ".", "gradients", "(", "loss", ",", "adv_x", ")", "# Multiply by constant epsilon", "scaled_signed_grad", "=", "self", ".", "eps_iter", "*", "tf", ".", "sign", "(", "grad", ")", "# Add perturbation to original example to obtain adversarial example", "adv_x", "=", "adv_x", "+", "scaled_signed_grad", "# If clipping is needed,", "# reset all values outside of [clip_min, clip_max]", "if", "(", "self", ".", "clip_min", "is", "not", "None", ")", "and", "(", "self", ".", "clip_max", "is", "not", "None", ")", ":", "adv_x", "=", "tf", ".", "clip_by_value", "(", "adv_x", ",", "self", ".", "clip_min", ",", "self", ".", "clip_max", ")", "adv_x", "=", "tf", ".", "stop_gradient", "(", "adv_x", ")", "eta", "=", "adv_x", "-", "x", "eta", "=", "clip_eta", "(", "eta", ",", "self", ".", "ord", ",", "self", ".", "eps", ")", "return", "eta" ]
TensorFlow implementation of the Fast Feature Gradient. This is a single step attack similar to Fast Gradient Method that attacks an internal representation. :param x: the input placeholder :param eta: A tensor the same shape as x that holds the perturbation. :param g_feat: model's internal tensor for guide :return: a tensor for the adversarial example
[ "TensorFlow", "implementation", "of", "the", "Fast", "Feature", "Gradient", ".", "This", "is", "a", "single", "step", "attack", "similar", "to", "Fast", "Gradient", "Method", "that", "attacks", "an", "internal", "representation", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/fast_feature_adversaries.py#L88-L129
train
tensorflow/cleverhans
cleverhans/attacks/fast_feature_adversaries.py
FastFeatureAdversaries.generate
def generate(self, x, g, **kwargs): """ Generate symbolic graph for adversarial examples and return. :param x: The model's symbolic inputs. :param g: The target value of the symbolic representation :param kwargs: See `parse_params` """ # Parse and save attack-specific parameters assert self.parse_params(**kwargs) g_feat = self.model.fprop(g)[self.layer] # Initialize loop variables eta = tf.random_uniform( tf.shape(x), -self.eps, self.eps, dtype=self.tf_dtype) eta = clip_eta(eta, self.ord, self.eps) def cond(i, _): return tf.less(i, self.nb_iter) def body(i, e): new_eta = self.attack_single_step(x, e, g_feat) return i + 1, new_eta _, eta = tf.while_loop(cond, body, (tf.zeros([]), eta), back_prop=True, maximum_iterations=self.nb_iter) # Define adversarial example (and clip if necessary) adv_x = x + eta if self.clip_min is not None and self.clip_max is not None: adv_x = tf.clip_by_value(adv_x, self.clip_min, self.clip_max) return adv_x
python
def generate(self, x, g, **kwargs): """ Generate symbolic graph for adversarial examples and return. :param x: The model's symbolic inputs. :param g: The target value of the symbolic representation :param kwargs: See `parse_params` """ # Parse and save attack-specific parameters assert self.parse_params(**kwargs) g_feat = self.model.fprop(g)[self.layer] # Initialize loop variables eta = tf.random_uniform( tf.shape(x), -self.eps, self.eps, dtype=self.tf_dtype) eta = clip_eta(eta, self.ord, self.eps) def cond(i, _): return tf.less(i, self.nb_iter) def body(i, e): new_eta = self.attack_single_step(x, e, g_feat) return i + 1, new_eta _, eta = tf.while_loop(cond, body, (tf.zeros([]), eta), back_prop=True, maximum_iterations=self.nb_iter) # Define adversarial example (and clip if necessary) adv_x = x + eta if self.clip_min is not None and self.clip_max is not None: adv_x = tf.clip_by_value(adv_x, self.clip_min, self.clip_max) return adv_x
[ "def", "generate", "(", "self", ",", "x", ",", "g", ",", "*", "*", "kwargs", ")", ":", "# Parse and save attack-specific parameters", "assert", "self", ".", "parse_params", "(", "*", "*", "kwargs", ")", "g_feat", "=", "self", ".", "model", ".", "fprop", "(", "g", ")", "[", "self", ".", "layer", "]", "# Initialize loop variables", "eta", "=", "tf", ".", "random_uniform", "(", "tf", ".", "shape", "(", "x", ")", ",", "-", "self", ".", "eps", ",", "self", ".", "eps", ",", "dtype", "=", "self", ".", "tf_dtype", ")", "eta", "=", "clip_eta", "(", "eta", ",", "self", ".", "ord", ",", "self", ".", "eps", ")", "def", "cond", "(", "i", ",", "_", ")", ":", "return", "tf", ".", "less", "(", "i", ",", "self", ".", "nb_iter", ")", "def", "body", "(", "i", ",", "e", ")", ":", "new_eta", "=", "self", ".", "attack_single_step", "(", "x", ",", "e", ",", "g_feat", ")", "return", "i", "+", "1", ",", "new_eta", "_", ",", "eta", "=", "tf", ".", "while_loop", "(", "cond", ",", "body", ",", "(", "tf", ".", "zeros", "(", "[", "]", ")", ",", "eta", ")", ",", "back_prop", "=", "True", ",", "maximum_iterations", "=", "self", ".", "nb_iter", ")", "# Define adversarial example (and clip if necessary)", "adv_x", "=", "x", "+", "eta", "if", "self", ".", "clip_min", "is", "not", "None", "and", "self", ".", "clip_max", "is", "not", "None", ":", "adv_x", "=", "tf", ".", "clip_by_value", "(", "adv_x", ",", "self", ".", "clip_min", ",", "self", ".", "clip_max", ")", "return", "adv_x" ]
Generate symbolic graph for adversarial examples and return. :param x: The model's symbolic inputs. :param g: The target value of the symbolic representation :param kwargs: See `parse_params`
[ "Generate", "symbolic", "graph", "for", "adversarial", "examples", "and", "return", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/fast_feature_adversaries.py#L131-L165
train
tensorflow/cleverhans
scripts/make_confidence_report_bundled.py
main
def main(argv=None): """ Make a confidence report and save it to disk. """ try: _name_of_script, filepath = argv except ValueError: raise ValueError(argv) print(filepath) make_confidence_report_bundled(filepath=filepath, test_start=FLAGS.test_start, test_end=FLAGS.test_end, which_set=FLAGS.which_set, recipe=FLAGS.recipe, report_path=FLAGS.report_path, batch_size=FLAGS.batch_size)
python
def main(argv=None): """ Make a confidence report and save it to disk. """ try: _name_of_script, filepath = argv except ValueError: raise ValueError(argv) print(filepath) make_confidence_report_bundled(filepath=filepath, test_start=FLAGS.test_start, test_end=FLAGS.test_end, which_set=FLAGS.which_set, recipe=FLAGS.recipe, report_path=FLAGS.report_path, batch_size=FLAGS.batch_size)
[ "def", "main", "(", "argv", "=", "None", ")", ":", "try", ":", "_name_of_script", ",", "filepath", "=", "argv", "except", "ValueError", ":", "raise", "ValueError", "(", "argv", ")", "print", "(", "filepath", ")", "make_confidence_report_bundled", "(", "filepath", "=", "filepath", ",", "test_start", "=", "FLAGS", ".", "test_start", ",", "test_end", "=", "FLAGS", ".", "test_end", ",", "which_set", "=", "FLAGS", ".", "which_set", ",", "recipe", "=", "FLAGS", ".", "recipe", ",", "report_path", "=", "FLAGS", ".", "report_path", ",", "batch_size", "=", "FLAGS", ".", "batch_size", ")" ]
Make a confidence report and save it to disk.
[ "Make", "a", "confidence", "report", "and", "save", "it", "to", "disk", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/scripts/make_confidence_report_bundled.py#L42-L56
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/dev_toolkit/sample_defenses/ens_adv_inception_resnet_v2/inception_resnet_v2.py
block35
def block35(net, scale=1.0, activation_fn=tf.nn.relu, scope=None, reuse=None): """Builds the 35x35 resnet block.""" with tf.variable_scope(scope, 'Block35', [net], reuse=reuse): with tf.variable_scope('Branch_0'): tower_conv = slim.conv2d(net, 32, 1, scope='Conv2d_1x1') with tf.variable_scope('Branch_1'): tower_conv1_0 = slim.conv2d(net, 32, 1, scope='Conv2d_0a_1x1') tower_conv1_1 = slim.conv2d(tower_conv1_0, 32, 3, scope='Conv2d_0b_3x3') with tf.variable_scope('Branch_2'): tower_conv2_0 = slim.conv2d(net, 32, 1, scope='Conv2d_0a_1x1') tower_conv2_1 = slim.conv2d(tower_conv2_0, 48, 3, scope='Conv2d_0b_3x3') tower_conv2_2 = slim.conv2d(tower_conv2_1, 64, 3, scope='Conv2d_0c_3x3') mixed = tf.concat( axis=3, values=[tower_conv, tower_conv1_1, tower_conv2_2]) up = slim.conv2d(mixed, net.get_shape()[3], 1, normalizer_fn=None, activation_fn=None, scope='Conv2d_1x1') net += scale * up if activation_fn: net = activation_fn(net) return net
python
def block35(net, scale=1.0, activation_fn=tf.nn.relu, scope=None, reuse=None): """Builds the 35x35 resnet block.""" with tf.variable_scope(scope, 'Block35', [net], reuse=reuse): with tf.variable_scope('Branch_0'): tower_conv = slim.conv2d(net, 32, 1, scope='Conv2d_1x1') with tf.variable_scope('Branch_1'): tower_conv1_0 = slim.conv2d(net, 32, 1, scope='Conv2d_0a_1x1') tower_conv1_1 = slim.conv2d(tower_conv1_0, 32, 3, scope='Conv2d_0b_3x3') with tf.variable_scope('Branch_2'): tower_conv2_0 = slim.conv2d(net, 32, 1, scope='Conv2d_0a_1x1') tower_conv2_1 = slim.conv2d(tower_conv2_0, 48, 3, scope='Conv2d_0b_3x3') tower_conv2_2 = slim.conv2d(tower_conv2_1, 64, 3, scope='Conv2d_0c_3x3') mixed = tf.concat( axis=3, values=[tower_conv, tower_conv1_1, tower_conv2_2]) up = slim.conv2d(mixed, net.get_shape()[3], 1, normalizer_fn=None, activation_fn=None, scope='Conv2d_1x1') net += scale * up if activation_fn: net = activation_fn(net) return net
[ "def", "block35", "(", "net", ",", "scale", "=", "1.0", ",", "activation_fn", "=", "tf", ".", "nn", ".", "relu", ",", "scope", "=", "None", ",", "reuse", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "scope", ",", "'Block35'", ",", "[", "net", "]", ",", "reuse", "=", "reuse", ")", ":", "with", "tf", ".", "variable_scope", "(", "'Branch_0'", ")", ":", "tower_conv", "=", "slim", ".", "conv2d", "(", "net", ",", "32", ",", "1", ",", "scope", "=", "'Conv2d_1x1'", ")", "with", "tf", ".", "variable_scope", "(", "'Branch_1'", ")", ":", "tower_conv1_0", "=", "slim", ".", "conv2d", "(", "net", ",", "32", ",", "1", ",", "scope", "=", "'Conv2d_0a_1x1'", ")", "tower_conv1_1", "=", "slim", ".", "conv2d", "(", "tower_conv1_0", ",", "32", ",", "3", ",", "scope", "=", "'Conv2d_0b_3x3'", ")", "with", "tf", ".", "variable_scope", "(", "'Branch_2'", ")", ":", "tower_conv2_0", "=", "slim", ".", "conv2d", "(", "net", ",", "32", ",", "1", ",", "scope", "=", "'Conv2d_0a_1x1'", ")", "tower_conv2_1", "=", "slim", ".", "conv2d", "(", "tower_conv2_0", ",", "48", ",", "3", ",", "scope", "=", "'Conv2d_0b_3x3'", ")", "tower_conv2_2", "=", "slim", ".", "conv2d", "(", "tower_conv2_1", ",", "64", ",", "3", ",", "scope", "=", "'Conv2d_0c_3x3'", ")", "mixed", "=", "tf", ".", "concat", "(", "axis", "=", "3", ",", "values", "=", "[", "tower_conv", ",", "tower_conv1_1", ",", "tower_conv2_2", "]", ")", "up", "=", "slim", ".", "conv2d", "(", "mixed", ",", "net", ".", "get_shape", "(", ")", "[", "3", "]", ",", "1", ",", "normalizer_fn", "=", "None", ",", "activation_fn", "=", "None", ",", "scope", "=", "'Conv2d_1x1'", ")", "net", "+=", "scale", "*", "up", "if", "activation_fn", ":", "net", "=", "activation_fn", "(", "net", ")", "return", "net" ]
Builds the 35x35 resnet block.
[ "Builds", "the", "35x35", "resnet", "block", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/sample_defenses/ens_adv_inception_resnet_v2/inception_resnet_v2.py#L35-L54
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/dev_toolkit/sample_defenses/ens_adv_inception_resnet_v2/inception_resnet_v2.py
block17
def block17(net, scale=1.0, activation_fn=tf.nn.relu, scope=None, reuse=None): """Builds the 17x17 resnet block.""" with tf.variable_scope(scope, 'Block17', [net], reuse=reuse): with tf.variable_scope('Branch_0'): tower_conv = slim.conv2d(net, 192, 1, scope='Conv2d_1x1') with tf.variable_scope('Branch_1'): tower_conv1_0 = slim.conv2d(net, 128, 1, scope='Conv2d_0a_1x1') tower_conv1_1 = slim.conv2d(tower_conv1_0, 160, [1, 7], scope='Conv2d_0b_1x7') tower_conv1_2 = slim.conv2d(tower_conv1_1, 192, [7, 1], scope='Conv2d_0c_7x1') mixed = tf.concat(axis=3, values=[tower_conv, tower_conv1_2]) up = slim.conv2d(mixed, net.get_shape()[3], 1, normalizer_fn=None, activation_fn=None, scope='Conv2d_1x1') net += scale * up if activation_fn: net = activation_fn(net) return net
python
def block17(net, scale=1.0, activation_fn=tf.nn.relu, scope=None, reuse=None): """Builds the 17x17 resnet block.""" with tf.variable_scope(scope, 'Block17', [net], reuse=reuse): with tf.variable_scope('Branch_0'): tower_conv = slim.conv2d(net, 192, 1, scope='Conv2d_1x1') with tf.variable_scope('Branch_1'): tower_conv1_0 = slim.conv2d(net, 128, 1, scope='Conv2d_0a_1x1') tower_conv1_1 = slim.conv2d(tower_conv1_0, 160, [1, 7], scope='Conv2d_0b_1x7') tower_conv1_2 = slim.conv2d(tower_conv1_1, 192, [7, 1], scope='Conv2d_0c_7x1') mixed = tf.concat(axis=3, values=[tower_conv, tower_conv1_2]) up = slim.conv2d(mixed, net.get_shape()[3], 1, normalizer_fn=None, activation_fn=None, scope='Conv2d_1x1') net += scale * up if activation_fn: net = activation_fn(net) return net
[ "def", "block17", "(", "net", ",", "scale", "=", "1.0", ",", "activation_fn", "=", "tf", ".", "nn", ".", "relu", ",", "scope", "=", "None", ",", "reuse", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "scope", ",", "'Block17'", ",", "[", "net", "]", ",", "reuse", "=", "reuse", ")", ":", "with", "tf", ".", "variable_scope", "(", "'Branch_0'", ")", ":", "tower_conv", "=", "slim", ".", "conv2d", "(", "net", ",", "192", ",", "1", ",", "scope", "=", "'Conv2d_1x1'", ")", "with", "tf", ".", "variable_scope", "(", "'Branch_1'", ")", ":", "tower_conv1_0", "=", "slim", ".", "conv2d", "(", "net", ",", "128", ",", "1", ",", "scope", "=", "'Conv2d_0a_1x1'", ")", "tower_conv1_1", "=", "slim", ".", "conv2d", "(", "tower_conv1_0", ",", "160", ",", "[", "1", ",", "7", "]", ",", "scope", "=", "'Conv2d_0b_1x7'", ")", "tower_conv1_2", "=", "slim", ".", "conv2d", "(", "tower_conv1_1", ",", "192", ",", "[", "7", ",", "1", "]", ",", "scope", "=", "'Conv2d_0c_7x1'", ")", "mixed", "=", "tf", ".", "concat", "(", "axis", "=", "3", ",", "values", "=", "[", "tower_conv", ",", "tower_conv1_2", "]", ")", "up", "=", "slim", ".", "conv2d", "(", "mixed", ",", "net", ".", "get_shape", "(", ")", "[", "3", "]", ",", "1", ",", "normalizer_fn", "=", "None", ",", "activation_fn", "=", "None", ",", "scope", "=", "'Conv2d_1x1'", ")", "net", "+=", "scale", "*", "up", "if", "activation_fn", ":", "net", "=", "activation_fn", "(", "net", ")", "return", "net" ]
Builds the 17x17 resnet block.
[ "Builds", "the", "17x17", "resnet", "block", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/sample_defenses/ens_adv_inception_resnet_v2/inception_resnet_v2.py#L57-L74
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/dev_toolkit/sample_defenses/ens_adv_inception_resnet_v2/inception_resnet_v2.py
inception_resnet_v2_base
def inception_resnet_v2_base(inputs, final_endpoint='Conv2d_7b_1x1', output_stride=16, align_feature_maps=False, scope=None): """Inception model from http://arxiv.org/abs/1602.07261. Constructs an Inception Resnet v2 network from inputs to the given final endpoint. This method can construct the network up to the final inception block Conv2d_7b_1x1. Args: inputs: a tensor of size [batch_size, height, width, channels]. final_endpoint: specifies the endpoint to construct the network up to. It can be one of ['Conv2d_1a_3x3', 'Conv2d_2a_3x3', 'Conv2d_2b_3x3', 'MaxPool_3a_3x3', 'Conv2d_3b_1x1', 'Conv2d_4a_3x3', 'MaxPool_5a_3x3', 'Mixed_5b', 'Mixed_6a', 'PreAuxLogits', 'Mixed_7a', 'Conv2d_7b_1x1'] output_stride: A scalar that specifies the requested ratio of input to output spatial resolution. Only supports 8 and 16. align_feature_maps: When true, changes all the VALID paddings in the network to SAME padding so that the feature maps are aligned. scope: Optional variable_scope. Returns: tensor_out: output tensor corresponding to the final_endpoint. end_points: a set of activations for external use, for example summaries or losses. Raises: ValueError: if final_endpoint is not set to one of the predefined values, or if the output_stride is not 8 or 16, or if the output_stride is 8 and we request an end point after 'PreAuxLogits'. """ if output_stride != 8 and output_stride != 16: raise ValueError('output_stride must be 8 or 16.') padding = 'SAME' if align_feature_maps else 'VALID' end_points = {} def add_and_check_final(name, net): """ TODO: write this """ end_points[name] = net return name == final_endpoint with tf.variable_scope(scope, 'InceptionResnetV2', [inputs]): with slim.arg_scope([slim.conv2d, slim.max_pool2d, slim.avg_pool2d], stride=1, padding='SAME'): # 149 x 149 x 32 net = slim.conv2d(inputs, 32, 3, stride=2, padding=padding, scope='Conv2d_1a_3x3') if add_and_check_final('Conv2d_1a_3x3', net): return net, end_points # 147 x 147 x 32 net = slim.conv2d(net, 32, 3, padding=padding, scope='Conv2d_2a_3x3') if add_and_check_final('Conv2d_2a_3x3', net): return net, end_points # 147 x 147 x 64 net = slim.conv2d(net, 64, 3, scope='Conv2d_2b_3x3') if add_and_check_final('Conv2d_2b_3x3', net): return net, end_points # 73 x 73 x 64 net = slim.max_pool2d(net, 3, stride=2, padding=padding, scope='MaxPool_3a_3x3') if add_and_check_final('MaxPool_3a_3x3', net): return net, end_points # 73 x 73 x 80 net = slim.conv2d(net, 80, 1, padding=padding, scope='Conv2d_3b_1x1') if add_and_check_final('Conv2d_3b_1x1', net): return net, end_points # 71 x 71 x 192 net = slim.conv2d(net, 192, 3, padding=padding, scope='Conv2d_4a_3x3') if add_and_check_final('Conv2d_4a_3x3', net): return net, end_points # 35 x 35 x 192 net = slim.max_pool2d(net, 3, stride=2, padding=padding, scope='MaxPool_5a_3x3') if add_and_check_final('MaxPool_5a_3x3', net): return net, end_points # 35 x 35 x 320 with tf.variable_scope('Mixed_5b'): with tf.variable_scope('Branch_0'): tower_conv = slim.conv2d(net, 96, 1, scope='Conv2d_1x1') with tf.variable_scope('Branch_1'): tower_conv1_0 = slim.conv2d(net, 48, 1, scope='Conv2d_0a_1x1') tower_conv1_1 = slim.conv2d(tower_conv1_0, 64, 5, scope='Conv2d_0b_5x5') with tf.variable_scope('Branch_2'): tower_conv2_0 = slim.conv2d(net, 64, 1, scope='Conv2d_0a_1x1') tower_conv2_1 = slim.conv2d(tower_conv2_0, 96, 3, scope='Conv2d_0b_3x3') tower_conv2_2 = slim.conv2d(tower_conv2_1, 96, 3, scope='Conv2d_0c_3x3') with tf.variable_scope('Branch_3'): tower_pool = slim.avg_pool2d(net, 3, stride=1, padding='SAME', scope='AvgPool_0a_3x3') tower_pool_1 = slim.conv2d(tower_pool, 64, 1, scope='Conv2d_0b_1x1') net = tf.concat( [tower_conv, tower_conv1_1, tower_conv2_2, tower_pool_1], 3) if add_and_check_final('Mixed_5b', net): return net, end_points # TODO(alemi): Register intermediate endpoints net = slim.repeat(net, 10, block35, scale=0.17) # 17 x 17 x 1088 if output_stride == 8, # 33 x 33 x 1088 if output_stride == 16 use_atrous = output_stride == 8 with tf.variable_scope('Mixed_6a'): with tf.variable_scope('Branch_0'): tower_conv = slim.conv2d(net, 384, 3, stride=1 if use_atrous else 2, padding=padding, scope='Conv2d_1a_3x3') with tf.variable_scope('Branch_1'): tower_conv1_0 = slim.conv2d(net, 256, 1, scope='Conv2d_0a_1x1') tower_conv1_1 = slim.conv2d(tower_conv1_0, 256, 3, scope='Conv2d_0b_3x3') tower_conv1_2 = slim.conv2d(tower_conv1_1, 384, 3, stride=1 if use_atrous else 2, padding=padding, scope='Conv2d_1a_3x3') with tf.variable_scope('Branch_2'): tower_pool = slim.max_pool2d(net, 3, stride=1 if use_atrous else 2, padding=padding, scope='MaxPool_1a_3x3') net = tf.concat([tower_conv, tower_conv1_2, tower_pool], 3) if add_and_check_final('Mixed_6a', net): return net, end_points # TODO(alemi): register intermediate endpoints with slim.arg_scope([slim.conv2d], rate=2 if use_atrous else 1): net = slim.repeat(net, 20, block17, scale=0.10) if add_and_check_final('PreAuxLogits', net): return net, end_points if output_stride == 8: # TODO(gpapan): Properly support output_stride for the rest of the net. raise ValueError('output_stride==8 is only supported up to the ' 'PreAuxlogits end_point for now.') # 8 x 8 x 2080 with tf.variable_scope('Mixed_7a'): with tf.variable_scope('Branch_0'): tower_conv = slim.conv2d(net, 256, 1, scope='Conv2d_0a_1x1') tower_conv_1 = slim.conv2d(tower_conv, 384, 3, stride=2, padding=padding, scope='Conv2d_1a_3x3') with tf.variable_scope('Branch_1'): tower_conv1 = slim.conv2d(net, 256, 1, scope='Conv2d_0a_1x1') tower_conv1_1 = slim.conv2d(tower_conv1, 288, 3, stride=2, padding=padding, scope='Conv2d_1a_3x3') with tf.variable_scope('Branch_2'): tower_conv2 = slim.conv2d(net, 256, 1, scope='Conv2d_0a_1x1') tower_conv2_1 = slim.conv2d(tower_conv2, 288, 3, scope='Conv2d_0b_3x3') tower_conv2_2 = slim.conv2d(tower_conv2_1, 320, 3, stride=2, padding=padding, scope='Conv2d_1a_3x3') with tf.variable_scope('Branch_3'): tower_pool = slim.max_pool2d(net, 3, stride=2, padding=padding, scope='MaxPool_1a_3x3') net = tf.concat( [tower_conv_1, tower_conv1_1, tower_conv2_2, tower_pool], 3) if add_and_check_final('Mixed_7a', net): return net, end_points # TODO(alemi): register intermediate endpoints net = slim.repeat(net, 9, block8, scale=0.20) net = block8(net, activation_fn=None) # 8 x 8 x 1536 net = slim.conv2d(net, 1536, 1, scope='Conv2d_7b_1x1') if add_and_check_final('Conv2d_7b_1x1', net): return net, end_points raise ValueError('final_endpoint (%s) not recognized' % final_endpoint)
python
def inception_resnet_v2_base(inputs, final_endpoint='Conv2d_7b_1x1', output_stride=16, align_feature_maps=False, scope=None): """Inception model from http://arxiv.org/abs/1602.07261. Constructs an Inception Resnet v2 network from inputs to the given final endpoint. This method can construct the network up to the final inception block Conv2d_7b_1x1. Args: inputs: a tensor of size [batch_size, height, width, channels]. final_endpoint: specifies the endpoint to construct the network up to. It can be one of ['Conv2d_1a_3x3', 'Conv2d_2a_3x3', 'Conv2d_2b_3x3', 'MaxPool_3a_3x3', 'Conv2d_3b_1x1', 'Conv2d_4a_3x3', 'MaxPool_5a_3x3', 'Mixed_5b', 'Mixed_6a', 'PreAuxLogits', 'Mixed_7a', 'Conv2d_7b_1x1'] output_stride: A scalar that specifies the requested ratio of input to output spatial resolution. Only supports 8 and 16. align_feature_maps: When true, changes all the VALID paddings in the network to SAME padding so that the feature maps are aligned. scope: Optional variable_scope. Returns: tensor_out: output tensor corresponding to the final_endpoint. end_points: a set of activations for external use, for example summaries or losses. Raises: ValueError: if final_endpoint is not set to one of the predefined values, or if the output_stride is not 8 or 16, or if the output_stride is 8 and we request an end point after 'PreAuxLogits'. """ if output_stride != 8 and output_stride != 16: raise ValueError('output_stride must be 8 or 16.') padding = 'SAME' if align_feature_maps else 'VALID' end_points = {} def add_and_check_final(name, net): """ TODO: write this """ end_points[name] = net return name == final_endpoint with tf.variable_scope(scope, 'InceptionResnetV2', [inputs]): with slim.arg_scope([slim.conv2d, slim.max_pool2d, slim.avg_pool2d], stride=1, padding='SAME'): # 149 x 149 x 32 net = slim.conv2d(inputs, 32, 3, stride=2, padding=padding, scope='Conv2d_1a_3x3') if add_and_check_final('Conv2d_1a_3x3', net): return net, end_points # 147 x 147 x 32 net = slim.conv2d(net, 32, 3, padding=padding, scope='Conv2d_2a_3x3') if add_and_check_final('Conv2d_2a_3x3', net): return net, end_points # 147 x 147 x 64 net = slim.conv2d(net, 64, 3, scope='Conv2d_2b_3x3') if add_and_check_final('Conv2d_2b_3x3', net): return net, end_points # 73 x 73 x 64 net = slim.max_pool2d(net, 3, stride=2, padding=padding, scope='MaxPool_3a_3x3') if add_and_check_final('MaxPool_3a_3x3', net): return net, end_points # 73 x 73 x 80 net = slim.conv2d(net, 80, 1, padding=padding, scope='Conv2d_3b_1x1') if add_and_check_final('Conv2d_3b_1x1', net): return net, end_points # 71 x 71 x 192 net = slim.conv2d(net, 192, 3, padding=padding, scope='Conv2d_4a_3x3') if add_and_check_final('Conv2d_4a_3x3', net): return net, end_points # 35 x 35 x 192 net = slim.max_pool2d(net, 3, stride=2, padding=padding, scope='MaxPool_5a_3x3') if add_and_check_final('MaxPool_5a_3x3', net): return net, end_points # 35 x 35 x 320 with tf.variable_scope('Mixed_5b'): with tf.variable_scope('Branch_0'): tower_conv = slim.conv2d(net, 96, 1, scope='Conv2d_1x1') with tf.variable_scope('Branch_1'): tower_conv1_0 = slim.conv2d(net, 48, 1, scope='Conv2d_0a_1x1') tower_conv1_1 = slim.conv2d(tower_conv1_0, 64, 5, scope='Conv2d_0b_5x5') with tf.variable_scope('Branch_2'): tower_conv2_0 = slim.conv2d(net, 64, 1, scope='Conv2d_0a_1x1') tower_conv2_1 = slim.conv2d(tower_conv2_0, 96, 3, scope='Conv2d_0b_3x3') tower_conv2_2 = slim.conv2d(tower_conv2_1, 96, 3, scope='Conv2d_0c_3x3') with tf.variable_scope('Branch_3'): tower_pool = slim.avg_pool2d(net, 3, stride=1, padding='SAME', scope='AvgPool_0a_3x3') tower_pool_1 = slim.conv2d(tower_pool, 64, 1, scope='Conv2d_0b_1x1') net = tf.concat( [tower_conv, tower_conv1_1, tower_conv2_2, tower_pool_1], 3) if add_and_check_final('Mixed_5b', net): return net, end_points # TODO(alemi): Register intermediate endpoints net = slim.repeat(net, 10, block35, scale=0.17) # 17 x 17 x 1088 if output_stride == 8, # 33 x 33 x 1088 if output_stride == 16 use_atrous = output_stride == 8 with tf.variable_scope('Mixed_6a'): with tf.variable_scope('Branch_0'): tower_conv = slim.conv2d(net, 384, 3, stride=1 if use_atrous else 2, padding=padding, scope='Conv2d_1a_3x3') with tf.variable_scope('Branch_1'): tower_conv1_0 = slim.conv2d(net, 256, 1, scope='Conv2d_0a_1x1') tower_conv1_1 = slim.conv2d(tower_conv1_0, 256, 3, scope='Conv2d_0b_3x3') tower_conv1_2 = slim.conv2d(tower_conv1_1, 384, 3, stride=1 if use_atrous else 2, padding=padding, scope='Conv2d_1a_3x3') with tf.variable_scope('Branch_2'): tower_pool = slim.max_pool2d(net, 3, stride=1 if use_atrous else 2, padding=padding, scope='MaxPool_1a_3x3') net = tf.concat([tower_conv, tower_conv1_2, tower_pool], 3) if add_and_check_final('Mixed_6a', net): return net, end_points # TODO(alemi): register intermediate endpoints with slim.arg_scope([slim.conv2d], rate=2 if use_atrous else 1): net = slim.repeat(net, 20, block17, scale=0.10) if add_and_check_final('PreAuxLogits', net): return net, end_points if output_stride == 8: # TODO(gpapan): Properly support output_stride for the rest of the net. raise ValueError('output_stride==8 is only supported up to the ' 'PreAuxlogits end_point for now.') # 8 x 8 x 2080 with tf.variable_scope('Mixed_7a'): with tf.variable_scope('Branch_0'): tower_conv = slim.conv2d(net, 256, 1, scope='Conv2d_0a_1x1') tower_conv_1 = slim.conv2d(tower_conv, 384, 3, stride=2, padding=padding, scope='Conv2d_1a_3x3') with tf.variable_scope('Branch_1'): tower_conv1 = slim.conv2d(net, 256, 1, scope='Conv2d_0a_1x1') tower_conv1_1 = slim.conv2d(tower_conv1, 288, 3, stride=2, padding=padding, scope='Conv2d_1a_3x3') with tf.variable_scope('Branch_2'): tower_conv2 = slim.conv2d(net, 256, 1, scope='Conv2d_0a_1x1') tower_conv2_1 = slim.conv2d(tower_conv2, 288, 3, scope='Conv2d_0b_3x3') tower_conv2_2 = slim.conv2d(tower_conv2_1, 320, 3, stride=2, padding=padding, scope='Conv2d_1a_3x3') with tf.variable_scope('Branch_3'): tower_pool = slim.max_pool2d(net, 3, stride=2, padding=padding, scope='MaxPool_1a_3x3') net = tf.concat( [tower_conv_1, tower_conv1_1, tower_conv2_2, tower_pool], 3) if add_and_check_final('Mixed_7a', net): return net, end_points # TODO(alemi): register intermediate endpoints net = slim.repeat(net, 9, block8, scale=0.20) net = block8(net, activation_fn=None) # 8 x 8 x 1536 net = slim.conv2d(net, 1536, 1, scope='Conv2d_7b_1x1') if add_and_check_final('Conv2d_7b_1x1', net): return net, end_points raise ValueError('final_endpoint (%s) not recognized' % final_endpoint)
[ "def", "inception_resnet_v2_base", "(", "inputs", ",", "final_endpoint", "=", "'Conv2d_7b_1x1'", ",", "output_stride", "=", "16", ",", "align_feature_maps", "=", "False", ",", "scope", "=", "None", ")", ":", "if", "output_stride", "!=", "8", "and", "output_stride", "!=", "16", ":", "raise", "ValueError", "(", "'output_stride must be 8 or 16.'", ")", "padding", "=", "'SAME'", "if", "align_feature_maps", "else", "'VALID'", "end_points", "=", "{", "}", "def", "add_and_check_final", "(", "name", ",", "net", ")", ":", "\"\"\"\n TODO: write this\n \"\"\"", "end_points", "[", "name", "]", "=", "net", "return", "name", "==", "final_endpoint", "with", "tf", ".", "variable_scope", "(", "scope", ",", "'InceptionResnetV2'", ",", "[", "inputs", "]", ")", ":", "with", "slim", ".", "arg_scope", "(", "[", "slim", ".", "conv2d", ",", "slim", ".", "max_pool2d", ",", "slim", ".", "avg_pool2d", "]", ",", "stride", "=", "1", ",", "padding", "=", "'SAME'", ")", ":", "# 149 x 149 x 32", "net", "=", "slim", ".", "conv2d", "(", "inputs", ",", "32", ",", "3", ",", "stride", "=", "2", ",", "padding", "=", "padding", ",", "scope", "=", "'Conv2d_1a_3x3'", ")", "if", "add_and_check_final", "(", "'Conv2d_1a_3x3'", ",", "net", ")", ":", "return", "net", ",", "end_points", "# 147 x 147 x 32", "net", "=", "slim", ".", "conv2d", "(", "net", ",", "32", ",", "3", ",", "padding", "=", "padding", ",", "scope", "=", "'Conv2d_2a_3x3'", ")", "if", "add_and_check_final", "(", "'Conv2d_2a_3x3'", ",", "net", ")", ":", "return", "net", ",", "end_points", "# 147 x 147 x 64", "net", "=", "slim", ".", "conv2d", "(", "net", ",", "64", ",", "3", ",", "scope", "=", "'Conv2d_2b_3x3'", ")", "if", "add_and_check_final", "(", "'Conv2d_2b_3x3'", ",", "net", ")", ":", "return", "net", ",", "end_points", "# 73 x 73 x 64", "net", "=", "slim", ".", "max_pool2d", "(", "net", ",", "3", ",", "stride", "=", "2", ",", "padding", "=", "padding", ",", "scope", "=", "'MaxPool_3a_3x3'", ")", "if", "add_and_check_final", "(", "'MaxPool_3a_3x3'", ",", "net", ")", ":", "return", "net", ",", "end_points", "# 73 x 73 x 80", "net", "=", "slim", ".", "conv2d", "(", "net", ",", "80", ",", "1", ",", "padding", "=", "padding", ",", "scope", "=", "'Conv2d_3b_1x1'", ")", "if", "add_and_check_final", "(", "'Conv2d_3b_1x1'", ",", "net", ")", ":", "return", "net", ",", "end_points", "# 71 x 71 x 192", "net", "=", "slim", ".", "conv2d", "(", "net", ",", "192", ",", "3", ",", "padding", "=", "padding", ",", "scope", "=", "'Conv2d_4a_3x3'", ")", "if", "add_and_check_final", "(", "'Conv2d_4a_3x3'", ",", "net", ")", ":", "return", "net", ",", "end_points", "# 35 x 35 x 192", "net", "=", "slim", ".", "max_pool2d", "(", "net", ",", "3", ",", "stride", "=", "2", ",", "padding", "=", "padding", ",", "scope", "=", "'MaxPool_5a_3x3'", ")", "if", "add_and_check_final", "(", "'MaxPool_5a_3x3'", ",", "net", ")", ":", "return", "net", ",", "end_points", "# 35 x 35 x 320", "with", "tf", ".", "variable_scope", "(", "'Mixed_5b'", ")", ":", "with", "tf", ".", "variable_scope", "(", "'Branch_0'", ")", ":", "tower_conv", "=", "slim", ".", "conv2d", "(", "net", ",", "96", ",", "1", ",", "scope", "=", "'Conv2d_1x1'", ")", "with", "tf", ".", "variable_scope", "(", "'Branch_1'", ")", ":", "tower_conv1_0", "=", "slim", ".", "conv2d", "(", "net", ",", "48", ",", "1", ",", "scope", "=", "'Conv2d_0a_1x1'", ")", "tower_conv1_1", "=", "slim", ".", "conv2d", "(", "tower_conv1_0", ",", "64", ",", "5", ",", "scope", "=", "'Conv2d_0b_5x5'", ")", "with", "tf", ".", "variable_scope", "(", "'Branch_2'", ")", ":", "tower_conv2_0", "=", "slim", ".", "conv2d", "(", "net", ",", "64", ",", "1", ",", "scope", "=", "'Conv2d_0a_1x1'", ")", "tower_conv2_1", "=", "slim", ".", "conv2d", "(", "tower_conv2_0", ",", "96", ",", "3", ",", "scope", "=", "'Conv2d_0b_3x3'", ")", "tower_conv2_2", "=", "slim", ".", "conv2d", "(", "tower_conv2_1", ",", "96", ",", "3", ",", "scope", "=", "'Conv2d_0c_3x3'", ")", "with", "tf", ".", "variable_scope", "(", "'Branch_3'", ")", ":", "tower_pool", "=", "slim", ".", "avg_pool2d", "(", "net", ",", "3", ",", "stride", "=", "1", ",", "padding", "=", "'SAME'", ",", "scope", "=", "'AvgPool_0a_3x3'", ")", "tower_pool_1", "=", "slim", ".", "conv2d", "(", "tower_pool", ",", "64", ",", "1", ",", "scope", "=", "'Conv2d_0b_1x1'", ")", "net", "=", "tf", ".", "concat", "(", "[", "tower_conv", ",", "tower_conv1_1", ",", "tower_conv2_2", ",", "tower_pool_1", "]", ",", "3", ")", "if", "add_and_check_final", "(", "'Mixed_5b'", ",", "net", ")", ":", "return", "net", ",", "end_points", "# TODO(alemi): Register intermediate endpoints", "net", "=", "slim", ".", "repeat", "(", "net", ",", "10", ",", "block35", ",", "scale", "=", "0.17", ")", "# 17 x 17 x 1088 if output_stride == 8,", "# 33 x 33 x 1088 if output_stride == 16", "use_atrous", "=", "output_stride", "==", "8", "with", "tf", ".", "variable_scope", "(", "'Mixed_6a'", ")", ":", "with", "tf", ".", "variable_scope", "(", "'Branch_0'", ")", ":", "tower_conv", "=", "slim", ".", "conv2d", "(", "net", ",", "384", ",", "3", ",", "stride", "=", "1", "if", "use_atrous", "else", "2", ",", "padding", "=", "padding", ",", "scope", "=", "'Conv2d_1a_3x3'", ")", "with", "tf", ".", "variable_scope", "(", "'Branch_1'", ")", ":", "tower_conv1_0", "=", "slim", ".", "conv2d", "(", "net", ",", "256", ",", "1", ",", "scope", "=", "'Conv2d_0a_1x1'", ")", "tower_conv1_1", "=", "slim", ".", "conv2d", "(", "tower_conv1_0", ",", "256", ",", "3", ",", "scope", "=", "'Conv2d_0b_3x3'", ")", "tower_conv1_2", "=", "slim", ".", "conv2d", "(", "tower_conv1_1", ",", "384", ",", "3", ",", "stride", "=", "1", "if", "use_atrous", "else", "2", ",", "padding", "=", "padding", ",", "scope", "=", "'Conv2d_1a_3x3'", ")", "with", "tf", ".", "variable_scope", "(", "'Branch_2'", ")", ":", "tower_pool", "=", "slim", ".", "max_pool2d", "(", "net", ",", "3", ",", "stride", "=", "1", "if", "use_atrous", "else", "2", ",", "padding", "=", "padding", ",", "scope", "=", "'MaxPool_1a_3x3'", ")", "net", "=", "tf", ".", "concat", "(", "[", "tower_conv", ",", "tower_conv1_2", ",", "tower_pool", "]", ",", "3", ")", "if", "add_and_check_final", "(", "'Mixed_6a'", ",", "net", ")", ":", "return", "net", ",", "end_points", "# TODO(alemi): register intermediate endpoints", "with", "slim", ".", "arg_scope", "(", "[", "slim", ".", "conv2d", "]", ",", "rate", "=", "2", "if", "use_atrous", "else", "1", ")", ":", "net", "=", "slim", ".", "repeat", "(", "net", ",", "20", ",", "block17", ",", "scale", "=", "0.10", ")", "if", "add_and_check_final", "(", "'PreAuxLogits'", ",", "net", ")", ":", "return", "net", ",", "end_points", "if", "output_stride", "==", "8", ":", "# TODO(gpapan): Properly support output_stride for the rest of the net.", "raise", "ValueError", "(", "'output_stride==8 is only supported up to the '", "'PreAuxlogits end_point for now.'", ")", "# 8 x 8 x 2080", "with", "tf", ".", "variable_scope", "(", "'Mixed_7a'", ")", ":", "with", "tf", ".", "variable_scope", "(", "'Branch_0'", ")", ":", "tower_conv", "=", "slim", ".", "conv2d", "(", "net", ",", "256", ",", "1", ",", "scope", "=", "'Conv2d_0a_1x1'", ")", "tower_conv_1", "=", "slim", ".", "conv2d", "(", "tower_conv", ",", "384", ",", "3", ",", "stride", "=", "2", ",", "padding", "=", "padding", ",", "scope", "=", "'Conv2d_1a_3x3'", ")", "with", "tf", ".", "variable_scope", "(", "'Branch_1'", ")", ":", "tower_conv1", "=", "slim", ".", "conv2d", "(", "net", ",", "256", ",", "1", ",", "scope", "=", "'Conv2d_0a_1x1'", ")", "tower_conv1_1", "=", "slim", ".", "conv2d", "(", "tower_conv1", ",", "288", ",", "3", ",", "stride", "=", "2", ",", "padding", "=", "padding", ",", "scope", "=", "'Conv2d_1a_3x3'", ")", "with", "tf", ".", "variable_scope", "(", "'Branch_2'", ")", ":", "tower_conv2", "=", "slim", ".", "conv2d", "(", "net", ",", "256", ",", "1", ",", "scope", "=", "'Conv2d_0a_1x1'", ")", "tower_conv2_1", "=", "slim", ".", "conv2d", "(", "tower_conv2", ",", "288", ",", "3", ",", "scope", "=", "'Conv2d_0b_3x3'", ")", "tower_conv2_2", "=", "slim", ".", "conv2d", "(", "tower_conv2_1", ",", "320", ",", "3", ",", "stride", "=", "2", ",", "padding", "=", "padding", ",", "scope", "=", "'Conv2d_1a_3x3'", ")", "with", "tf", ".", "variable_scope", "(", "'Branch_3'", ")", ":", "tower_pool", "=", "slim", ".", "max_pool2d", "(", "net", ",", "3", ",", "stride", "=", "2", ",", "padding", "=", "padding", ",", "scope", "=", "'MaxPool_1a_3x3'", ")", "net", "=", "tf", ".", "concat", "(", "[", "tower_conv_1", ",", "tower_conv1_1", ",", "tower_conv2_2", ",", "tower_pool", "]", ",", "3", ")", "if", "add_and_check_final", "(", "'Mixed_7a'", ",", "net", ")", ":", "return", "net", ",", "end_points", "# TODO(alemi): register intermediate endpoints", "net", "=", "slim", ".", "repeat", "(", "net", ",", "9", ",", "block8", ",", "scale", "=", "0.20", ")", "net", "=", "block8", "(", "net", ",", "activation_fn", "=", "None", ")", "# 8 x 8 x 1536", "net", "=", "slim", ".", "conv2d", "(", "net", ",", "1536", ",", "1", ",", "scope", "=", "'Conv2d_7b_1x1'", ")", "if", "add_and_check_final", "(", "'Conv2d_7b_1x1'", ",", "net", ")", ":", "return", "net", ",", "end_points", "raise", "ValueError", "(", "'final_endpoint (%s) not recognized'", "%", "final_endpoint", ")" ]
Inception model from http://arxiv.org/abs/1602.07261. Constructs an Inception Resnet v2 network from inputs to the given final endpoint. This method can construct the network up to the final inception block Conv2d_7b_1x1. Args: inputs: a tensor of size [batch_size, height, width, channels]. final_endpoint: specifies the endpoint to construct the network up to. It can be one of ['Conv2d_1a_3x3', 'Conv2d_2a_3x3', 'Conv2d_2b_3x3', 'MaxPool_3a_3x3', 'Conv2d_3b_1x1', 'Conv2d_4a_3x3', 'MaxPool_5a_3x3', 'Mixed_5b', 'Mixed_6a', 'PreAuxLogits', 'Mixed_7a', 'Conv2d_7b_1x1'] output_stride: A scalar that specifies the requested ratio of input to output spatial resolution. Only supports 8 and 16. align_feature_maps: When true, changes all the VALID paddings in the network to SAME padding so that the feature maps are aligned. scope: Optional variable_scope. Returns: tensor_out: output tensor corresponding to the final_endpoint. end_points: a set of activations for external use, for example summaries or losses. Raises: ValueError: if final_endpoint is not set to one of the predefined values, or if the output_stride is not 8 or 16, or if the output_stride is 8 and we request an end point after 'PreAuxLogits'.
[ "Inception", "model", "from", "http", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1602", ".", "07261", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/sample_defenses/ens_adv_inception_resnet_v2/inception_resnet_v2.py#L97-L285
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/dev_toolkit/sample_defenses/ens_adv_inception_resnet_v2/inception_resnet_v2.py
inception_resnet_v2
def inception_resnet_v2(inputs, nb_classes=1001, is_training=True, dropout_keep_prob=0.8, reuse=None, scope='InceptionResnetV2', create_aux_logits=True, num_classes=None): """Creates the Inception Resnet V2 model. Args: inputs: a 4-D tensor of size [batch_size, height, width, 3]. nb_classes: number of predicted classes. is_training: whether is training or not. dropout_keep_prob: float, the fraction to keep before final layer. reuse: whether or not the network and its variables should be reused. To be able to reuse 'scope' must be given. scope: Optional variable_scope. create_aux_logits: Whether to include the auxilliary logits. num_classes: depricated alias for nb_classes Returns: logits: the logits outputs of the model. end_points: the set of end_points from the inception model. """ if num_classes is not None: warnings.warn("`num_classes` is deprecated. Switch to `nb_classes`." " `num_classes` may be removed on or after 2019-04-23.") nb_classes = num_classes del num_classes end_points = {} with tf.variable_scope(scope, 'InceptionResnetV2', [inputs, nb_classes], reuse=reuse) as var_scope: with slim.arg_scope([slim.batch_norm, slim.dropout], is_training=is_training): net, end_points = inception_resnet_v2_base(inputs, scope=var_scope) if create_aux_logits: with tf.variable_scope('AuxLogits'): aux = end_points['PreAuxLogits'] aux = slim.avg_pool2d(aux, 5, stride=3, padding='VALID', scope='Conv2d_1a_3x3') aux = slim.conv2d(aux, 128, 1, scope='Conv2d_1b_1x1') aux = slim.conv2d(aux, 768, aux.get_shape()[1:3], padding='VALID', scope='Conv2d_2a_5x5') aux = slim.flatten(aux) aux = slim.fully_connected(aux, nb_classes, activation_fn=None, scope='Logits') end_points['AuxLogits'] = aux with tf.variable_scope('Logits'): net = slim.avg_pool2d(net, net.get_shape()[1:3], padding='VALID', scope='AvgPool_1a_8x8') net = slim.flatten(net) net = slim.dropout(net, dropout_keep_prob, is_training=is_training, scope='Dropout') end_points['PreLogitsFlatten'] = net logits = slim.fully_connected(net, nb_classes, activation_fn=None, scope='Logits') end_points['Logits'] = logits end_points['Predictions'] = tf.nn.softmax(logits, name='Predictions') return logits, end_points
python
def inception_resnet_v2(inputs, nb_classes=1001, is_training=True, dropout_keep_prob=0.8, reuse=None, scope='InceptionResnetV2', create_aux_logits=True, num_classes=None): """Creates the Inception Resnet V2 model. Args: inputs: a 4-D tensor of size [batch_size, height, width, 3]. nb_classes: number of predicted classes. is_training: whether is training or not. dropout_keep_prob: float, the fraction to keep before final layer. reuse: whether or not the network and its variables should be reused. To be able to reuse 'scope' must be given. scope: Optional variable_scope. create_aux_logits: Whether to include the auxilliary logits. num_classes: depricated alias for nb_classes Returns: logits: the logits outputs of the model. end_points: the set of end_points from the inception model. """ if num_classes is not None: warnings.warn("`num_classes` is deprecated. Switch to `nb_classes`." " `num_classes` may be removed on or after 2019-04-23.") nb_classes = num_classes del num_classes end_points = {} with tf.variable_scope(scope, 'InceptionResnetV2', [inputs, nb_classes], reuse=reuse) as var_scope: with slim.arg_scope([slim.batch_norm, slim.dropout], is_training=is_training): net, end_points = inception_resnet_v2_base(inputs, scope=var_scope) if create_aux_logits: with tf.variable_scope('AuxLogits'): aux = end_points['PreAuxLogits'] aux = slim.avg_pool2d(aux, 5, stride=3, padding='VALID', scope='Conv2d_1a_3x3') aux = slim.conv2d(aux, 128, 1, scope='Conv2d_1b_1x1') aux = slim.conv2d(aux, 768, aux.get_shape()[1:3], padding='VALID', scope='Conv2d_2a_5x5') aux = slim.flatten(aux) aux = slim.fully_connected(aux, nb_classes, activation_fn=None, scope='Logits') end_points['AuxLogits'] = aux with tf.variable_scope('Logits'): net = slim.avg_pool2d(net, net.get_shape()[1:3], padding='VALID', scope='AvgPool_1a_8x8') net = slim.flatten(net) net = slim.dropout(net, dropout_keep_prob, is_training=is_training, scope='Dropout') end_points['PreLogitsFlatten'] = net logits = slim.fully_connected(net, nb_classes, activation_fn=None, scope='Logits') end_points['Logits'] = logits end_points['Predictions'] = tf.nn.softmax(logits, name='Predictions') return logits, end_points
[ "def", "inception_resnet_v2", "(", "inputs", ",", "nb_classes", "=", "1001", ",", "is_training", "=", "True", ",", "dropout_keep_prob", "=", "0.8", ",", "reuse", "=", "None", ",", "scope", "=", "'InceptionResnetV2'", ",", "create_aux_logits", "=", "True", ",", "num_classes", "=", "None", ")", ":", "if", "num_classes", "is", "not", "None", ":", "warnings", ".", "warn", "(", "\"`num_classes` is deprecated. Switch to `nb_classes`.\"", "\" `num_classes` may be removed on or after 2019-04-23.\"", ")", "nb_classes", "=", "num_classes", "del", "num_classes", "end_points", "=", "{", "}", "with", "tf", ".", "variable_scope", "(", "scope", ",", "'InceptionResnetV2'", ",", "[", "inputs", ",", "nb_classes", "]", ",", "reuse", "=", "reuse", ")", "as", "var_scope", ":", "with", "slim", ".", "arg_scope", "(", "[", "slim", ".", "batch_norm", ",", "slim", ".", "dropout", "]", ",", "is_training", "=", "is_training", ")", ":", "net", ",", "end_points", "=", "inception_resnet_v2_base", "(", "inputs", ",", "scope", "=", "var_scope", ")", "if", "create_aux_logits", ":", "with", "tf", ".", "variable_scope", "(", "'AuxLogits'", ")", ":", "aux", "=", "end_points", "[", "'PreAuxLogits'", "]", "aux", "=", "slim", ".", "avg_pool2d", "(", "aux", ",", "5", ",", "stride", "=", "3", ",", "padding", "=", "'VALID'", ",", "scope", "=", "'Conv2d_1a_3x3'", ")", "aux", "=", "slim", ".", "conv2d", "(", "aux", ",", "128", ",", "1", ",", "scope", "=", "'Conv2d_1b_1x1'", ")", "aux", "=", "slim", ".", "conv2d", "(", "aux", ",", "768", ",", "aux", ".", "get_shape", "(", ")", "[", "1", ":", "3", "]", ",", "padding", "=", "'VALID'", ",", "scope", "=", "'Conv2d_2a_5x5'", ")", "aux", "=", "slim", ".", "flatten", "(", "aux", ")", "aux", "=", "slim", ".", "fully_connected", "(", "aux", ",", "nb_classes", ",", "activation_fn", "=", "None", ",", "scope", "=", "'Logits'", ")", "end_points", "[", "'AuxLogits'", "]", "=", "aux", "with", "tf", ".", "variable_scope", "(", "'Logits'", ")", ":", "net", "=", "slim", ".", "avg_pool2d", "(", "net", ",", "net", ".", "get_shape", "(", ")", "[", "1", ":", "3", "]", ",", "padding", "=", "'VALID'", ",", "scope", "=", "'AvgPool_1a_8x8'", ")", "net", "=", "slim", ".", "flatten", "(", "net", ")", "net", "=", "slim", ".", "dropout", "(", "net", ",", "dropout_keep_prob", ",", "is_training", "=", "is_training", ",", "scope", "=", "'Dropout'", ")", "end_points", "[", "'PreLogitsFlatten'", "]", "=", "net", "logits", "=", "slim", ".", "fully_connected", "(", "net", ",", "nb_classes", ",", "activation_fn", "=", "None", ",", "scope", "=", "'Logits'", ")", "end_points", "[", "'Logits'", "]", "=", "logits", "end_points", "[", "'Predictions'", "]", "=", "tf", ".", "nn", ".", "softmax", "(", "logits", ",", "name", "=", "'Predictions'", ")", "return", "logits", ",", "end_points" ]
Creates the Inception Resnet V2 model. Args: inputs: a 4-D tensor of size [batch_size, height, width, 3]. nb_classes: number of predicted classes. is_training: whether is training or not. dropout_keep_prob: float, the fraction to keep before final layer. reuse: whether or not the network and its variables should be reused. To be able to reuse 'scope' must be given. scope: Optional variable_scope. create_aux_logits: Whether to include the auxilliary logits. num_classes: depricated alias for nb_classes Returns: logits: the logits outputs of the model. end_points: the set of end_points from the inception model.
[ "Creates", "the", "Inception", "Resnet", "V2", "model", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/sample_defenses/ens_adv_inception_resnet_v2/inception_resnet_v2.py#L288-L352
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/dev_toolkit/sample_defenses/ens_adv_inception_resnet_v2/inception_resnet_v2.py
inception_resnet_v2_arg_scope
def inception_resnet_v2_arg_scope(weight_decay=0.00004, batch_norm_decay=0.9997, batch_norm_epsilon=0.001): """Returns the scope with the default parameters for inception_resnet_v2. Args: weight_decay: the weight decay for weights variables. batch_norm_decay: decay for the moving average of batch_norm momentums. batch_norm_epsilon: small float added to variance to avoid dividing by zero. Returns: a arg_scope with the parameters needed for inception_resnet_v2. """ # Set weight_decay for weights in conv2d and fully_connected layers. with slim.arg_scope([slim.conv2d, slim.fully_connected], weights_regularizer=slim.l2_regularizer(weight_decay), biases_regularizer=slim.l2_regularizer(weight_decay)): batch_norm_params = { 'decay': batch_norm_decay, 'epsilon': batch_norm_epsilon, } # Set activation_fn and parameters for batch_norm. with slim.arg_scope([slim.conv2d], activation_fn=tf.nn.relu, normalizer_fn=slim.batch_norm, normalizer_params=batch_norm_params) as scope: return scope
python
def inception_resnet_v2_arg_scope(weight_decay=0.00004, batch_norm_decay=0.9997, batch_norm_epsilon=0.001): """Returns the scope with the default parameters for inception_resnet_v2. Args: weight_decay: the weight decay for weights variables. batch_norm_decay: decay for the moving average of batch_norm momentums. batch_norm_epsilon: small float added to variance to avoid dividing by zero. Returns: a arg_scope with the parameters needed for inception_resnet_v2. """ # Set weight_decay for weights in conv2d and fully_connected layers. with slim.arg_scope([slim.conv2d, slim.fully_connected], weights_regularizer=slim.l2_regularizer(weight_decay), biases_regularizer=slim.l2_regularizer(weight_decay)): batch_norm_params = { 'decay': batch_norm_decay, 'epsilon': batch_norm_epsilon, } # Set activation_fn and parameters for batch_norm. with slim.arg_scope([slim.conv2d], activation_fn=tf.nn.relu, normalizer_fn=slim.batch_norm, normalizer_params=batch_norm_params) as scope: return scope
[ "def", "inception_resnet_v2_arg_scope", "(", "weight_decay", "=", "0.00004", ",", "batch_norm_decay", "=", "0.9997", ",", "batch_norm_epsilon", "=", "0.001", ")", ":", "# Set weight_decay for weights in conv2d and fully_connected layers.", "with", "slim", ".", "arg_scope", "(", "[", "slim", ".", "conv2d", ",", "slim", ".", "fully_connected", "]", ",", "weights_regularizer", "=", "slim", ".", "l2_regularizer", "(", "weight_decay", ")", ",", "biases_regularizer", "=", "slim", ".", "l2_regularizer", "(", "weight_decay", ")", ")", ":", "batch_norm_params", "=", "{", "'decay'", ":", "batch_norm_decay", ",", "'epsilon'", ":", "batch_norm_epsilon", ",", "}", "# Set activation_fn and parameters for batch_norm.", "with", "slim", ".", "arg_scope", "(", "[", "slim", ".", "conv2d", "]", ",", "activation_fn", "=", "tf", ".", "nn", ".", "relu", ",", "normalizer_fn", "=", "slim", ".", "batch_norm", ",", "normalizer_params", "=", "batch_norm_params", ")", "as", "scope", ":", "return", "scope" ]
Returns the scope with the default parameters for inception_resnet_v2. Args: weight_decay: the weight decay for weights variables. batch_norm_decay: decay for the moving average of batch_norm momentums. batch_norm_epsilon: small float added to variance to avoid dividing by zero. Returns: a arg_scope with the parameters needed for inception_resnet_v2.
[ "Returns", "the", "scope", "with", "the", "default", "parameters", "for", "inception_resnet_v2", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/sample_defenses/ens_adv_inception_resnet_v2/inception_resnet_v2.py#L358-L384
train
tensorflow/cleverhans
tutorials/future/tf2/mnist_tutorial.py
ld_mnist
def ld_mnist(): """Load training and test data.""" def convert_types(image, label): image = tf.cast(image, tf.float32) image /= 255 return image, label dataset, info = tfds.load('mnist', data_dir='gs://tfds-data/datasets', with_info=True, as_supervised=True) mnist_train, mnist_test = dataset['train'], dataset['test'] mnist_train = mnist_train.map(convert_types).shuffle(10000).batch(128) mnist_test = mnist_test.map(convert_types).batch(128) return EasyDict(train=mnist_train, test=mnist_test)
python
def ld_mnist(): """Load training and test data.""" def convert_types(image, label): image = tf.cast(image, tf.float32) image /= 255 return image, label dataset, info = tfds.load('mnist', data_dir='gs://tfds-data/datasets', with_info=True, as_supervised=True) mnist_train, mnist_test = dataset['train'], dataset['test'] mnist_train = mnist_train.map(convert_types).shuffle(10000).batch(128) mnist_test = mnist_test.map(convert_types).batch(128) return EasyDict(train=mnist_train, test=mnist_test)
[ "def", "ld_mnist", "(", ")", ":", "def", "convert_types", "(", "image", ",", "label", ")", ":", "image", "=", "tf", ".", "cast", "(", "image", ",", "tf", ".", "float32", ")", "image", "/=", "255", "return", "image", ",", "label", "dataset", ",", "info", "=", "tfds", ".", "load", "(", "'mnist'", ",", "data_dir", "=", "'gs://tfds-data/datasets'", ",", "with_info", "=", "True", ",", "as_supervised", "=", "True", ")", "mnist_train", ",", "mnist_test", "=", "dataset", "[", "'train'", "]", ",", "dataset", "[", "'test'", "]", "mnist_train", "=", "mnist_train", ".", "map", "(", "convert_types", ")", ".", "shuffle", "(", "10000", ")", ".", "batch", "(", "128", ")", "mnist_test", "=", "mnist_test", ".", "map", "(", "convert_types", ")", ".", "batch", "(", "128", ")", "return", "EasyDict", "(", "train", "=", "mnist_train", ",", "test", "=", "mnist_test", ")" ]
Load training and test data.
[ "Load", "training", "and", "test", "data", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/tutorials/future/tf2/mnist_tutorial.py#L29-L42
train
tensorflow/cleverhans
cleverhans_tutorials/mnist_tutorial_keras.py
mnist_tutorial
def mnist_tutorial(train_start=0, train_end=60000, test_start=0, test_end=10000, nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE, learning_rate=LEARNING_RATE, testing=False, label_smoothing=0.1): """ MNIST CleverHans tutorial :param train_start: index of first training set example :param train_end: index of last training set example :param test_start: index of first test set example :param test_end: index of last test set example :param nb_epochs: number of epochs to train model :param batch_size: size of training batches :param learning_rate: learning rate for training :param testing: if true, training error is calculated :param label_smoothing: float, amount of label smoothing for cross entropy :return: an AccuracyReport object """ # Object used to keep track of (and return) key accuracies report = AccuracyReport() # Set TF random seed to improve reproducibility tf.set_random_seed(1234) # Force TensorFlow to use single thread to improve reproducibility config = tf.ConfigProto(intra_op_parallelism_threads=1, inter_op_parallelism_threads=1) if keras.backend.image_data_format() != 'channels_last': raise NotImplementedError("this tutorial requires keras to be configured to channels_last format") # Create TF session and set as Keras backend session sess = tf.Session(config=config) keras.backend.set_session(sess) # Get MNIST test data mnist = MNIST(train_start=train_start, train_end=train_end, test_start=test_start, test_end=test_end) x_train, y_train = mnist.get_set('train') x_test, y_test = mnist.get_set('test') # Obtain Image Parameters img_rows, img_cols, nchannels = x_train.shape[1:4] nb_classes = y_train.shape[1] # Label smoothing y_train -= label_smoothing * (y_train - 1. / nb_classes) # Define Keras model model = cnn_model(img_rows=img_rows, img_cols=img_cols, channels=nchannels, nb_filters=64, nb_classes=nb_classes) print("Defined Keras model.") # To be able to call the model in the custom loss, we need to call it once # before, see https://github.com/tensorflow/tensorflow/issues/23769 model(model.input) # Initialize the Fast Gradient Sign Method (FGSM) attack object wrap = KerasModelWrapper(model) fgsm = FastGradientMethod(wrap, sess=sess) fgsm_params = {'eps': 0.3, 'clip_min': 0., 'clip_max': 1.} adv_acc_metric = get_adversarial_acc_metric(model, fgsm, fgsm_params) model.compile( optimizer=keras.optimizers.Adam(learning_rate), loss='categorical_crossentropy', metrics=['accuracy', adv_acc_metric] ) # Train an MNIST model model.fit(x_train, y_train, batch_size=batch_size, epochs=nb_epochs, validation_data=(x_test, y_test), verbose=2) # Evaluate the accuracy on legitimate and adversarial test examples _, acc, adv_acc = model.evaluate(x_test, y_test, batch_size=batch_size, verbose=0) report.clean_train_clean_eval = acc report.clean_train_adv_eval = adv_acc print('Test accuracy on legitimate examples: %0.4f' % acc) print('Test accuracy on adversarial examples: %0.4f\n' % adv_acc) # Calculate training error if testing: _, train_acc, train_adv_acc = model.evaluate(x_train, y_train, batch_size=batch_size, verbose=0) report.train_clean_train_clean_eval = train_acc report.train_clean_train_adv_eval = train_adv_acc print("Repeating the process, using adversarial training") # Redefine Keras model model_2 = cnn_model(img_rows=img_rows, img_cols=img_cols, channels=nchannels, nb_filters=64, nb_classes=nb_classes) model_2(model_2.input) wrap_2 = KerasModelWrapper(model_2) fgsm_2 = FastGradientMethod(wrap_2, sess=sess) # Use a loss function based on legitimate and adversarial examples adv_loss_2 = get_adversarial_loss(model_2, fgsm_2, fgsm_params) adv_acc_metric_2 = get_adversarial_acc_metric(model_2, fgsm_2, fgsm_params) model_2.compile( optimizer=keras.optimizers.Adam(learning_rate), loss=adv_loss_2, metrics=['accuracy', adv_acc_metric_2] ) # Train an MNIST model model_2.fit(x_train, y_train, batch_size=batch_size, epochs=nb_epochs, validation_data=(x_test, y_test), verbose=2) # Evaluate the accuracy on legitimate and adversarial test examples _, acc, adv_acc = model_2.evaluate(x_test, y_test, batch_size=batch_size, verbose=0) report.adv_train_clean_eval = acc report.adv_train_adv_eval = adv_acc print('Test accuracy on legitimate examples: %0.4f' % acc) print('Test accuracy on adversarial examples: %0.4f\n' % adv_acc) # Calculate training error if testing: _, train_acc, train_adv_acc = model_2.evaluate(x_train, y_train, batch_size=batch_size, verbose=0) report.train_adv_train_clean_eval = train_acc report.train_adv_train_adv_eval = train_adv_acc return report
python
def mnist_tutorial(train_start=0, train_end=60000, test_start=0, test_end=10000, nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE, learning_rate=LEARNING_RATE, testing=False, label_smoothing=0.1): """ MNIST CleverHans tutorial :param train_start: index of first training set example :param train_end: index of last training set example :param test_start: index of first test set example :param test_end: index of last test set example :param nb_epochs: number of epochs to train model :param batch_size: size of training batches :param learning_rate: learning rate for training :param testing: if true, training error is calculated :param label_smoothing: float, amount of label smoothing for cross entropy :return: an AccuracyReport object """ # Object used to keep track of (and return) key accuracies report = AccuracyReport() # Set TF random seed to improve reproducibility tf.set_random_seed(1234) # Force TensorFlow to use single thread to improve reproducibility config = tf.ConfigProto(intra_op_parallelism_threads=1, inter_op_parallelism_threads=1) if keras.backend.image_data_format() != 'channels_last': raise NotImplementedError("this tutorial requires keras to be configured to channels_last format") # Create TF session and set as Keras backend session sess = tf.Session(config=config) keras.backend.set_session(sess) # Get MNIST test data mnist = MNIST(train_start=train_start, train_end=train_end, test_start=test_start, test_end=test_end) x_train, y_train = mnist.get_set('train') x_test, y_test = mnist.get_set('test') # Obtain Image Parameters img_rows, img_cols, nchannels = x_train.shape[1:4] nb_classes = y_train.shape[1] # Label smoothing y_train -= label_smoothing * (y_train - 1. / nb_classes) # Define Keras model model = cnn_model(img_rows=img_rows, img_cols=img_cols, channels=nchannels, nb_filters=64, nb_classes=nb_classes) print("Defined Keras model.") # To be able to call the model in the custom loss, we need to call it once # before, see https://github.com/tensorflow/tensorflow/issues/23769 model(model.input) # Initialize the Fast Gradient Sign Method (FGSM) attack object wrap = KerasModelWrapper(model) fgsm = FastGradientMethod(wrap, sess=sess) fgsm_params = {'eps': 0.3, 'clip_min': 0., 'clip_max': 1.} adv_acc_metric = get_adversarial_acc_metric(model, fgsm, fgsm_params) model.compile( optimizer=keras.optimizers.Adam(learning_rate), loss='categorical_crossentropy', metrics=['accuracy', adv_acc_metric] ) # Train an MNIST model model.fit(x_train, y_train, batch_size=batch_size, epochs=nb_epochs, validation_data=(x_test, y_test), verbose=2) # Evaluate the accuracy on legitimate and adversarial test examples _, acc, adv_acc = model.evaluate(x_test, y_test, batch_size=batch_size, verbose=0) report.clean_train_clean_eval = acc report.clean_train_adv_eval = adv_acc print('Test accuracy on legitimate examples: %0.4f' % acc) print('Test accuracy on adversarial examples: %0.4f\n' % adv_acc) # Calculate training error if testing: _, train_acc, train_adv_acc = model.evaluate(x_train, y_train, batch_size=batch_size, verbose=0) report.train_clean_train_clean_eval = train_acc report.train_clean_train_adv_eval = train_adv_acc print("Repeating the process, using adversarial training") # Redefine Keras model model_2 = cnn_model(img_rows=img_rows, img_cols=img_cols, channels=nchannels, nb_filters=64, nb_classes=nb_classes) model_2(model_2.input) wrap_2 = KerasModelWrapper(model_2) fgsm_2 = FastGradientMethod(wrap_2, sess=sess) # Use a loss function based on legitimate and adversarial examples adv_loss_2 = get_adversarial_loss(model_2, fgsm_2, fgsm_params) adv_acc_metric_2 = get_adversarial_acc_metric(model_2, fgsm_2, fgsm_params) model_2.compile( optimizer=keras.optimizers.Adam(learning_rate), loss=adv_loss_2, metrics=['accuracy', adv_acc_metric_2] ) # Train an MNIST model model_2.fit(x_train, y_train, batch_size=batch_size, epochs=nb_epochs, validation_data=(x_test, y_test), verbose=2) # Evaluate the accuracy on legitimate and adversarial test examples _, acc, adv_acc = model_2.evaluate(x_test, y_test, batch_size=batch_size, verbose=0) report.adv_train_clean_eval = acc report.adv_train_adv_eval = adv_acc print('Test accuracy on legitimate examples: %0.4f' % acc) print('Test accuracy on adversarial examples: %0.4f\n' % adv_acc) # Calculate training error if testing: _, train_acc, train_adv_acc = model_2.evaluate(x_train, y_train, batch_size=batch_size, verbose=0) report.train_adv_train_clean_eval = train_acc report.train_adv_train_adv_eval = train_adv_acc return report
[ "def", "mnist_tutorial", "(", "train_start", "=", "0", ",", "train_end", "=", "60000", ",", "test_start", "=", "0", ",", "test_end", "=", "10000", ",", "nb_epochs", "=", "NB_EPOCHS", ",", "batch_size", "=", "BATCH_SIZE", ",", "learning_rate", "=", "LEARNING_RATE", ",", "testing", "=", "False", ",", "label_smoothing", "=", "0.1", ")", ":", "# Object used to keep track of (and return) key accuracies", "report", "=", "AccuracyReport", "(", ")", "# Set TF random seed to improve reproducibility", "tf", ".", "set_random_seed", "(", "1234", ")", "# Force TensorFlow to use single thread to improve reproducibility", "config", "=", "tf", ".", "ConfigProto", "(", "intra_op_parallelism_threads", "=", "1", ",", "inter_op_parallelism_threads", "=", "1", ")", "if", "keras", ".", "backend", ".", "image_data_format", "(", ")", "!=", "'channels_last'", ":", "raise", "NotImplementedError", "(", "\"this tutorial requires keras to be configured to channels_last format\"", ")", "# Create TF session and set as Keras backend session", "sess", "=", "tf", ".", "Session", "(", "config", "=", "config", ")", "keras", ".", "backend", ".", "set_session", "(", "sess", ")", "# Get MNIST test data", "mnist", "=", "MNIST", "(", "train_start", "=", "train_start", ",", "train_end", "=", "train_end", ",", "test_start", "=", "test_start", ",", "test_end", "=", "test_end", ")", "x_train", ",", "y_train", "=", "mnist", ".", "get_set", "(", "'train'", ")", "x_test", ",", "y_test", "=", "mnist", ".", "get_set", "(", "'test'", ")", "# Obtain Image Parameters", "img_rows", ",", "img_cols", ",", "nchannels", "=", "x_train", ".", "shape", "[", "1", ":", "4", "]", "nb_classes", "=", "y_train", ".", "shape", "[", "1", "]", "# Label smoothing", "y_train", "-=", "label_smoothing", "*", "(", "y_train", "-", "1.", "/", "nb_classes", ")", "# Define Keras model", "model", "=", "cnn_model", "(", "img_rows", "=", "img_rows", ",", "img_cols", "=", "img_cols", ",", "channels", "=", "nchannels", ",", "nb_filters", "=", "64", ",", "nb_classes", "=", "nb_classes", ")", "print", "(", "\"Defined Keras model.\"", ")", "# To be able to call the model in the custom loss, we need to call it once", "# before, see https://github.com/tensorflow/tensorflow/issues/23769", "model", "(", "model", ".", "input", ")", "# Initialize the Fast Gradient Sign Method (FGSM) attack object", "wrap", "=", "KerasModelWrapper", "(", "model", ")", "fgsm", "=", "FastGradientMethod", "(", "wrap", ",", "sess", "=", "sess", ")", "fgsm_params", "=", "{", "'eps'", ":", "0.3", ",", "'clip_min'", ":", "0.", ",", "'clip_max'", ":", "1.", "}", "adv_acc_metric", "=", "get_adversarial_acc_metric", "(", "model", ",", "fgsm", ",", "fgsm_params", ")", "model", ".", "compile", "(", "optimizer", "=", "keras", ".", "optimizers", ".", "Adam", "(", "learning_rate", ")", ",", "loss", "=", "'categorical_crossentropy'", ",", "metrics", "=", "[", "'accuracy'", ",", "adv_acc_metric", "]", ")", "# Train an MNIST model", "model", ".", "fit", "(", "x_train", ",", "y_train", ",", "batch_size", "=", "batch_size", ",", "epochs", "=", "nb_epochs", ",", "validation_data", "=", "(", "x_test", ",", "y_test", ")", ",", "verbose", "=", "2", ")", "# Evaluate the accuracy on legitimate and adversarial test examples", "_", ",", "acc", ",", "adv_acc", "=", "model", ".", "evaluate", "(", "x_test", ",", "y_test", ",", "batch_size", "=", "batch_size", ",", "verbose", "=", "0", ")", "report", ".", "clean_train_clean_eval", "=", "acc", "report", ".", "clean_train_adv_eval", "=", "adv_acc", "print", "(", "'Test accuracy on legitimate examples: %0.4f'", "%", "acc", ")", "print", "(", "'Test accuracy on adversarial examples: %0.4f\\n'", "%", "adv_acc", ")", "# Calculate training error", "if", "testing", ":", "_", ",", "train_acc", ",", "train_adv_acc", "=", "model", ".", "evaluate", "(", "x_train", ",", "y_train", ",", "batch_size", "=", "batch_size", ",", "verbose", "=", "0", ")", "report", ".", "train_clean_train_clean_eval", "=", "train_acc", "report", ".", "train_clean_train_adv_eval", "=", "train_adv_acc", "print", "(", "\"Repeating the process, using adversarial training\"", ")", "# Redefine Keras model", "model_2", "=", "cnn_model", "(", "img_rows", "=", "img_rows", ",", "img_cols", "=", "img_cols", ",", "channels", "=", "nchannels", ",", "nb_filters", "=", "64", ",", "nb_classes", "=", "nb_classes", ")", "model_2", "(", "model_2", ".", "input", ")", "wrap_2", "=", "KerasModelWrapper", "(", "model_2", ")", "fgsm_2", "=", "FastGradientMethod", "(", "wrap_2", ",", "sess", "=", "sess", ")", "# Use a loss function based on legitimate and adversarial examples", "adv_loss_2", "=", "get_adversarial_loss", "(", "model_2", ",", "fgsm_2", ",", "fgsm_params", ")", "adv_acc_metric_2", "=", "get_adversarial_acc_metric", "(", "model_2", ",", "fgsm_2", ",", "fgsm_params", ")", "model_2", ".", "compile", "(", "optimizer", "=", "keras", ".", "optimizers", ".", "Adam", "(", "learning_rate", ")", ",", "loss", "=", "adv_loss_2", ",", "metrics", "=", "[", "'accuracy'", ",", "adv_acc_metric_2", "]", ")", "# Train an MNIST model", "model_2", ".", "fit", "(", "x_train", ",", "y_train", ",", "batch_size", "=", "batch_size", ",", "epochs", "=", "nb_epochs", ",", "validation_data", "=", "(", "x_test", ",", "y_test", ")", ",", "verbose", "=", "2", ")", "# Evaluate the accuracy on legitimate and adversarial test examples", "_", ",", "acc", ",", "adv_acc", "=", "model_2", ".", "evaluate", "(", "x_test", ",", "y_test", ",", "batch_size", "=", "batch_size", ",", "verbose", "=", "0", ")", "report", ".", "adv_train_clean_eval", "=", "acc", "report", ".", "adv_train_adv_eval", "=", "adv_acc", "print", "(", "'Test accuracy on legitimate examples: %0.4f'", "%", "acc", ")", "print", "(", "'Test accuracy on adversarial examples: %0.4f\\n'", "%", "adv_acc", ")", "# Calculate training error", "if", "testing", ":", "_", ",", "train_acc", ",", "train_adv_acc", "=", "model_2", ".", "evaluate", "(", "x_train", ",", "y_train", ",", "batch_size", "=", "batch_size", ",", "verbose", "=", "0", ")", "report", ".", "train_adv_train_clean_eval", "=", "train_acc", "report", ".", "train_adv_train_adv_eval", "=", "train_adv_acc", "return", "report" ]
MNIST CleverHans tutorial :param train_start: index of first training set example :param train_end: index of last training set example :param test_start: index of first test set example :param test_end: index of last test set example :param nb_epochs: number of epochs to train model :param batch_size: size of training batches :param learning_rate: learning rate for training :param testing: if true, training error is calculated :param label_smoothing: float, amount of label smoothing for cross entropy :return: an AccuracyReport object
[ "MNIST", "CleverHans", "tutorial", ":", "param", "train_start", ":", "index", "of", "first", "training", "set", "example", ":", "param", "train_end", ":", "index", "of", "last", "training", "set", "example", ":", "param", "test_start", ":", "index", "of", "first", "test", "set", "example", ":", "param", "test_end", ":", "index", "of", "last", "test", "set", "example", ":", "param", "nb_epochs", ":", "number", "of", "epochs", "to", "train", "model", ":", "param", "batch_size", ":", "size", "of", "training", "batches", ":", "param", "learning_rate", ":", "learning", "rate", "for", "training", ":", "param", "testing", ":", "if", "true", "training", "error", "is", "calculated", ":", "param", "label_smoothing", ":", "float", "amount", "of", "label", "smoothing", "for", "cross", "entropy", ":", "return", ":", "an", "AccuracyReport", "object" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans_tutorials/mnist_tutorial_keras.py#L30-L167
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_and_copy_submissions.py
main
def main(args): """Validate all submissions and copy them into place""" random.seed() temp_dir = tempfile.mkdtemp() logging.info('Created temporary directory: %s', temp_dir) validator = SubmissionValidator( source_dir=args.source_dir, target_dir=args.target_dir, temp_dir=temp_dir, do_copy=args.copy, use_gpu=args.use_gpu, containers_file=args.containers_file) validator.run() logging.info('Deleting temporary directory: %s', temp_dir) subprocess.call(['rm', '-rf', temp_dir])
python
def main(args): """Validate all submissions and copy them into place""" random.seed() temp_dir = tempfile.mkdtemp() logging.info('Created temporary directory: %s', temp_dir) validator = SubmissionValidator( source_dir=args.source_dir, target_dir=args.target_dir, temp_dir=temp_dir, do_copy=args.copy, use_gpu=args.use_gpu, containers_file=args.containers_file) validator.run() logging.info('Deleting temporary directory: %s', temp_dir) subprocess.call(['rm', '-rf', temp_dir])
[ "def", "main", "(", "args", ")", ":", "random", ".", "seed", "(", ")", "temp_dir", "=", "tempfile", ".", "mkdtemp", "(", ")", "logging", ".", "info", "(", "'Created temporary directory: %s'", ",", "temp_dir", ")", "validator", "=", "SubmissionValidator", "(", "source_dir", "=", "args", ".", "source_dir", ",", "target_dir", "=", "args", ".", "target_dir", ",", "temp_dir", "=", "temp_dir", ",", "do_copy", "=", "args", ".", "copy", ",", "use_gpu", "=", "args", ".", "use_gpu", ",", "containers_file", "=", "args", ".", "containers_file", ")", "validator", ".", "run", "(", ")", "logging", ".", "info", "(", "'Deleting temporary directory: %s'", ",", "temp_dir", ")", "subprocess", ".", "call", "(", "[", "'rm'", ",", "'-rf'", ",", "temp_dir", "]", ")" ]
Validate all submissions and copy them into place
[ "Validate", "all", "submissions", "and", "copy", "them", "into", "place" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_and_copy_submissions.py#L229-L243
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_and_copy_submissions.py
ValidationStats._update_stat
def _update_stat(self, submission_type, increase_success, increase_fail): """Common method to update submission statistics.""" stat = self.stats.get(submission_type, (0, 0)) stat = (stat[0] + increase_success, stat[1] + increase_fail) self.stats[submission_type] = stat
python
def _update_stat(self, submission_type, increase_success, increase_fail): """Common method to update submission statistics.""" stat = self.stats.get(submission_type, (0, 0)) stat = (stat[0] + increase_success, stat[1] + increase_fail) self.stats[submission_type] = stat
[ "def", "_update_stat", "(", "self", ",", "submission_type", ",", "increase_success", ",", "increase_fail", ")", ":", "stat", "=", "self", ".", "stats", ".", "get", "(", "submission_type", ",", "(", "0", ",", "0", ")", ")", "stat", "=", "(", "stat", "[", "0", "]", "+", "increase_success", ",", "stat", "[", "1", "]", "+", "increase_fail", ")", "self", ".", "stats", "[", "submission_type", "]", "=", "stat" ]
Common method to update submission statistics.
[ "Common", "method", "to", "update", "submission", "statistics", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_and_copy_submissions.py#L64-L68
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_and_copy_submissions.py
ValidationStats.log_stats
def log_stats(self): """Print statistics into log.""" logging.info('Validation statistics: ') for k, v in iteritems(self.stats): logging.info('%s - %d valid out of %d total submissions', k, v[0], v[0] + v[1])
python
def log_stats(self): """Print statistics into log.""" logging.info('Validation statistics: ') for k, v in iteritems(self.stats): logging.info('%s - %d valid out of %d total submissions', k, v[0], v[0] + v[1])
[ "def", "log_stats", "(", "self", ")", ":", "logging", ".", "info", "(", "'Validation statistics: '", ")", "for", "k", ",", "v", "in", "iteritems", "(", "self", ".", "stats", ")", ":", "logging", ".", "info", "(", "'%s - %d valid out of %d total submissions'", ",", "k", ",", "v", "[", "0", "]", ",", "v", "[", "0", "]", "+", "v", "[", "1", "]", ")" ]
Print statistics into log.
[ "Print", "statistics", "into", "log", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_and_copy_submissions.py#L78-L83
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_and_copy_submissions.py
SubmissionValidator.copy_submission_locally
def copy_submission_locally(self, cloud_path): """Copies submission from Google Cloud Storage to local directory. Args: cloud_path: path of the submission in Google Cloud Storage Returns: name of the local file where submission is copied to """ local_path = os.path.join(self.download_dir, os.path.basename(cloud_path)) cmd = ['gsutil', 'cp', cloud_path, local_path] if subprocess.call(cmd) != 0: logging.error('Can\'t copy submission locally') return None return local_path
python
def copy_submission_locally(self, cloud_path): """Copies submission from Google Cloud Storage to local directory. Args: cloud_path: path of the submission in Google Cloud Storage Returns: name of the local file where submission is copied to """ local_path = os.path.join(self.download_dir, os.path.basename(cloud_path)) cmd = ['gsutil', 'cp', cloud_path, local_path] if subprocess.call(cmd) != 0: logging.error('Can\'t copy submission locally') return None return local_path
[ "def", "copy_submission_locally", "(", "self", ",", "cloud_path", ")", ":", "local_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "download_dir", ",", "os", ".", "path", ".", "basename", "(", "cloud_path", ")", ")", "cmd", "=", "[", "'gsutil'", ",", "'cp'", ",", "cloud_path", ",", "local_path", "]", "if", "subprocess", ".", "call", "(", "cmd", ")", "!=", "0", ":", "logging", ".", "error", "(", "'Can\\'t copy submission locally'", ")", "return", "None", "return", "local_path" ]
Copies submission from Google Cloud Storage to local directory. Args: cloud_path: path of the submission in Google Cloud Storage Returns: name of the local file where submission is copied to
[ "Copies", "submission", "from", "Google", "Cloud", "Storage", "to", "local", "directory", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_and_copy_submissions.py#L119-L133
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_and_copy_submissions.py
SubmissionValidator.copy_submission_to_destination
def copy_submission_to_destination(self, src_filename, dst_subdir, submission_id): """Copies submission to target directory. Args: src_filename: source filename of the submission dst_subdir: subdirectory of the target directory where submission should be copied to submission_id: ID of the submission, will be used as a new submission filename (before extension) """ extension = [e for e in ALLOWED_EXTENSIONS if src_filename.endswith(e)] if len(extension) != 1: logging.error('Invalid submission extension: %s', src_filename) return dst_filename = os.path.join(self.target_dir, dst_subdir, submission_id + extension[0]) cmd = ['gsutil', 'cp', src_filename, dst_filename] if subprocess.call(cmd) != 0: logging.error('Can\'t copy submission to destination') else: logging.info('Submission copied to: %s', dst_filename)
python
def copy_submission_to_destination(self, src_filename, dst_subdir, submission_id): """Copies submission to target directory. Args: src_filename: source filename of the submission dst_subdir: subdirectory of the target directory where submission should be copied to submission_id: ID of the submission, will be used as a new submission filename (before extension) """ extension = [e for e in ALLOWED_EXTENSIONS if src_filename.endswith(e)] if len(extension) != 1: logging.error('Invalid submission extension: %s', src_filename) return dst_filename = os.path.join(self.target_dir, dst_subdir, submission_id + extension[0]) cmd = ['gsutil', 'cp', src_filename, dst_filename] if subprocess.call(cmd) != 0: logging.error('Can\'t copy submission to destination') else: logging.info('Submission copied to: %s', dst_filename)
[ "def", "copy_submission_to_destination", "(", "self", ",", "src_filename", ",", "dst_subdir", ",", "submission_id", ")", ":", "extension", "=", "[", "e", "for", "e", "in", "ALLOWED_EXTENSIONS", "if", "src_filename", ".", "endswith", "(", "e", ")", "]", "if", "len", "(", "extension", ")", "!=", "1", ":", "logging", ".", "error", "(", "'Invalid submission extension: %s'", ",", "src_filename", ")", "return", "dst_filename", "=", "os", ".", "path", ".", "join", "(", "self", ".", "target_dir", ",", "dst_subdir", ",", "submission_id", "+", "extension", "[", "0", "]", ")", "cmd", "=", "[", "'gsutil'", ",", "'cp'", ",", "src_filename", ",", "dst_filename", "]", "if", "subprocess", ".", "call", "(", "cmd", ")", "!=", "0", ":", "logging", ".", "error", "(", "'Can\\'t copy submission to destination'", ")", "else", ":", "logging", ".", "info", "(", "'Submission copied to: %s'", ",", "dst_filename", ")" ]
Copies submission to target directory. Args: src_filename: source filename of the submission dst_subdir: subdirectory of the target directory where submission should be copied to submission_id: ID of the submission, will be used as a new submission filename (before extension)
[ "Copies", "submission", "to", "target", "directory", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_and_copy_submissions.py#L135-L157
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_and_copy_submissions.py
SubmissionValidator.validate_and_copy_one_submission
def validate_and_copy_one_submission(self, submission_path): """Validates one submission and copies it to target directory. Args: submission_path: path in Google Cloud Storage of the submission file """ if os.path.exists(self.download_dir): shutil.rmtree(self.download_dir) os.makedirs(self.download_dir) if os.path.exists(self.validate_dir): shutil.rmtree(self.validate_dir) os.makedirs(self.validate_dir) logging.info('\n' + ('#' * 80) + '\n# Processing submission: %s\n' + '#' * 80, submission_path) local_path = self.copy_submission_locally(submission_path) metadata = self.base_validator.validate_submission(local_path) if not metadata: logging.error('Submission "%s" is INVALID', submission_path) self.stats.add_failure() return submission_type = metadata['type'] container_name = metadata['container_gpu'] logging.info('Submission "%s" is VALID', submission_path) self.list_of_containers.add(container_name) self.stats.add_success(submission_type) if self.do_copy: submission_id = '{0:04}'.format(self.cur_submission_idx) self.cur_submission_idx += 1 self.copy_submission_to_destination(submission_path, TYPE_TO_DIR[submission_type], submission_id) self.id_to_path_mapping[submission_id] = submission_path
python
def validate_and_copy_one_submission(self, submission_path): """Validates one submission and copies it to target directory. Args: submission_path: path in Google Cloud Storage of the submission file """ if os.path.exists(self.download_dir): shutil.rmtree(self.download_dir) os.makedirs(self.download_dir) if os.path.exists(self.validate_dir): shutil.rmtree(self.validate_dir) os.makedirs(self.validate_dir) logging.info('\n' + ('#' * 80) + '\n# Processing submission: %s\n' + '#' * 80, submission_path) local_path = self.copy_submission_locally(submission_path) metadata = self.base_validator.validate_submission(local_path) if not metadata: logging.error('Submission "%s" is INVALID', submission_path) self.stats.add_failure() return submission_type = metadata['type'] container_name = metadata['container_gpu'] logging.info('Submission "%s" is VALID', submission_path) self.list_of_containers.add(container_name) self.stats.add_success(submission_type) if self.do_copy: submission_id = '{0:04}'.format(self.cur_submission_idx) self.cur_submission_idx += 1 self.copy_submission_to_destination(submission_path, TYPE_TO_DIR[submission_type], submission_id) self.id_to_path_mapping[submission_id] = submission_path
[ "def", "validate_and_copy_one_submission", "(", "self", ",", "submission_path", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "self", ".", "download_dir", ")", ":", "shutil", ".", "rmtree", "(", "self", ".", "download_dir", ")", "os", ".", "makedirs", "(", "self", ".", "download_dir", ")", "if", "os", ".", "path", ".", "exists", "(", "self", ".", "validate_dir", ")", ":", "shutil", ".", "rmtree", "(", "self", ".", "validate_dir", ")", "os", ".", "makedirs", "(", "self", ".", "validate_dir", ")", "logging", ".", "info", "(", "'\\n'", "+", "(", "'#'", "*", "80", ")", "+", "'\\n# Processing submission: %s\\n'", "+", "'#'", "*", "80", ",", "submission_path", ")", "local_path", "=", "self", ".", "copy_submission_locally", "(", "submission_path", ")", "metadata", "=", "self", ".", "base_validator", ".", "validate_submission", "(", "local_path", ")", "if", "not", "metadata", ":", "logging", ".", "error", "(", "'Submission \"%s\" is INVALID'", ",", "submission_path", ")", "self", ".", "stats", ".", "add_failure", "(", ")", "return", "submission_type", "=", "metadata", "[", "'type'", "]", "container_name", "=", "metadata", "[", "'container_gpu'", "]", "logging", ".", "info", "(", "'Submission \"%s\" is VALID'", ",", "submission_path", ")", "self", ".", "list_of_containers", ".", "add", "(", "container_name", ")", "self", ".", "stats", ".", "add_success", "(", "submission_type", ")", "if", "self", ".", "do_copy", ":", "submission_id", "=", "'{0:04}'", ".", "format", "(", "self", ".", "cur_submission_idx", ")", "self", ".", "cur_submission_idx", "+=", "1", "self", ".", "copy_submission_to_destination", "(", "submission_path", ",", "TYPE_TO_DIR", "[", "submission_type", "]", ",", "submission_id", ")", "self", ".", "id_to_path_mapping", "[", "submission_id", "]", "=", "submission_path" ]
Validates one submission and copies it to target directory. Args: submission_path: path in Google Cloud Storage of the submission file
[ "Validates", "one", "submission", "and", "copies", "it", "to", "target", "directory", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_and_copy_submissions.py#L159-L190
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_and_copy_submissions.py
SubmissionValidator.save_id_to_path_mapping
def save_id_to_path_mapping(self): """Saves mapping from submission IDs to original filenames. This mapping is saved as CSV file into target directory. """ if not self.id_to_path_mapping: return with open(self.local_id_to_path_mapping_file, 'w') as f: writer = csv.writer(f) writer.writerow(['id', 'path']) for k, v in sorted(iteritems(self.id_to_path_mapping)): writer.writerow([k, v]) cmd = ['gsutil', 'cp', self.local_id_to_path_mapping_file, os.path.join(self.target_dir, 'id_to_path_mapping.csv')] if subprocess.call(cmd) != 0: logging.error('Can\'t copy id_to_path_mapping.csv to target directory')
python
def save_id_to_path_mapping(self): """Saves mapping from submission IDs to original filenames. This mapping is saved as CSV file into target directory. """ if not self.id_to_path_mapping: return with open(self.local_id_to_path_mapping_file, 'w') as f: writer = csv.writer(f) writer.writerow(['id', 'path']) for k, v in sorted(iteritems(self.id_to_path_mapping)): writer.writerow([k, v]) cmd = ['gsutil', 'cp', self.local_id_to_path_mapping_file, os.path.join(self.target_dir, 'id_to_path_mapping.csv')] if subprocess.call(cmd) != 0: logging.error('Can\'t copy id_to_path_mapping.csv to target directory')
[ "def", "save_id_to_path_mapping", "(", "self", ")", ":", "if", "not", "self", ".", "id_to_path_mapping", ":", "return", "with", "open", "(", "self", ".", "local_id_to_path_mapping_file", ",", "'w'", ")", "as", "f", ":", "writer", "=", "csv", ".", "writer", "(", "f", ")", "writer", ".", "writerow", "(", "[", "'id'", ",", "'path'", "]", ")", "for", "k", ",", "v", "in", "sorted", "(", "iteritems", "(", "self", ".", "id_to_path_mapping", ")", ")", ":", "writer", ".", "writerow", "(", "[", "k", ",", "v", "]", ")", "cmd", "=", "[", "'gsutil'", ",", "'cp'", ",", "self", ".", "local_id_to_path_mapping_file", ",", "os", ".", "path", ".", "join", "(", "self", ".", "target_dir", ",", "'id_to_path_mapping.csv'", ")", "]", "if", "subprocess", ".", "call", "(", "cmd", ")", "!=", "0", ":", "logging", ".", "error", "(", "'Can\\'t copy id_to_path_mapping.csv to target directory'", ")" ]
Saves mapping from submission IDs to original filenames. This mapping is saved as CSV file into target directory.
[ "Saves", "mapping", "from", "submission", "IDs", "to", "original", "filenames", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_and_copy_submissions.py#L192-L207
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_and_copy_submissions.py
SubmissionValidator.run
def run(self): """Runs validation of all submissions.""" cmd = ['gsutil', 'ls', os.path.join(self.source_dir, '**')] try: files_list = subprocess.check_output(cmd).split('\n') except subprocess.CalledProcessError: logging.error('Can''t read source directory') all_submissions = [ s for s in files_list if s.endswith('.zip') or s.endswith('.tar') or s.endswith('.tar.gz') ] for submission_path in all_submissions: self.validate_and_copy_one_submission(submission_path) self.stats.log_stats() self.save_id_to_path_mapping() if self.containers_file: with open(self.containers_file, 'w') as f: f.write('\n'.join(sorted(self.list_of_containers)))
python
def run(self): """Runs validation of all submissions.""" cmd = ['gsutil', 'ls', os.path.join(self.source_dir, '**')] try: files_list = subprocess.check_output(cmd).split('\n') except subprocess.CalledProcessError: logging.error('Can''t read source directory') all_submissions = [ s for s in files_list if s.endswith('.zip') or s.endswith('.tar') or s.endswith('.tar.gz') ] for submission_path in all_submissions: self.validate_and_copy_one_submission(submission_path) self.stats.log_stats() self.save_id_to_path_mapping() if self.containers_file: with open(self.containers_file, 'w') as f: f.write('\n'.join(sorted(self.list_of_containers)))
[ "def", "run", "(", "self", ")", ":", "cmd", "=", "[", "'gsutil'", ",", "'ls'", ",", "os", ".", "path", ".", "join", "(", "self", ".", "source_dir", ",", "'**'", ")", "]", "try", ":", "files_list", "=", "subprocess", ".", "check_output", "(", "cmd", ")", ".", "split", "(", "'\\n'", ")", "except", "subprocess", ".", "CalledProcessError", ":", "logging", ".", "error", "(", "'Can'", "'t read source directory'", ")", "all_submissions", "=", "[", "s", "for", "s", "in", "files_list", "if", "s", ".", "endswith", "(", "'.zip'", ")", "or", "s", ".", "endswith", "(", "'.tar'", ")", "or", "s", ".", "endswith", "(", "'.tar.gz'", ")", "]", "for", "submission_path", "in", "all_submissions", ":", "self", ".", "validate_and_copy_one_submission", "(", "submission_path", ")", "self", ".", "stats", ".", "log_stats", "(", ")", "self", ".", "save_id_to_path_mapping", "(", ")", "if", "self", ".", "containers_file", ":", "with", "open", "(", "self", ".", "containers_file", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "'\\n'", ".", "join", "(", "sorted", "(", "self", ".", "list_of_containers", ")", ")", ")" ]
Runs validation of all submissions.
[ "Runs", "validation", "of", "all", "submissions", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_and_copy_submissions.py#L209-L226
train
tensorflow/cleverhans
scripts/plot_success_fail_curve.py
main
def main(argv=None): """Takes the path to a directory with reports and renders success fail plots.""" report_paths = argv[1:] fail_names = FLAGS.fail_names.split(',') for report_path in report_paths: plot_report_from_path(report_path, label=report_path, fail_names=fail_names) pyplot.legend() pyplot.xlim(-.01, 1.) pyplot.ylim(0., 1.) pyplot.show()
python
def main(argv=None): """Takes the path to a directory with reports and renders success fail plots.""" report_paths = argv[1:] fail_names = FLAGS.fail_names.split(',') for report_path in report_paths: plot_report_from_path(report_path, label=report_path, fail_names=fail_names) pyplot.legend() pyplot.xlim(-.01, 1.) pyplot.ylim(0., 1.) pyplot.show()
[ "def", "main", "(", "argv", "=", "None", ")", ":", "report_paths", "=", "argv", "[", "1", ":", "]", "fail_names", "=", "FLAGS", ".", "fail_names", ".", "split", "(", "','", ")", "for", "report_path", "in", "report_paths", ":", "plot_report_from_path", "(", "report_path", ",", "label", "=", "report_path", ",", "fail_names", "=", "fail_names", ")", "pyplot", ".", "legend", "(", ")", "pyplot", ".", "xlim", "(", "-", ".01", ",", "1.", ")", "pyplot", ".", "ylim", "(", "0.", ",", "1.", ")", "pyplot", ".", "show", "(", ")" ]
Takes the path to a directory with reports and renders success fail plots.
[ "Takes", "the", "path", "to", "a", "directory", "with", "reports", "and", "renders", "success", "fail", "plots", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/scripts/plot_success_fail_curve.py#L25-L38
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py
is_unclaimed
def is_unclaimed(work): """Returns True if work piece is unclaimed.""" if work['is_completed']: return False cutoff_time = time.time() - MAX_PROCESSING_TIME if (work['claimed_worker_id'] and work['claimed_worker_start_time'] is not None and work['claimed_worker_start_time'] >= cutoff_time): return False return True
python
def is_unclaimed(work): """Returns True if work piece is unclaimed.""" if work['is_completed']: return False cutoff_time = time.time() - MAX_PROCESSING_TIME if (work['claimed_worker_id'] and work['claimed_worker_start_time'] is not None and work['claimed_worker_start_time'] >= cutoff_time): return False return True
[ "def", "is_unclaimed", "(", "work", ")", ":", "if", "work", "[", "'is_completed'", "]", ":", "return", "False", "cutoff_time", "=", "time", ".", "time", "(", ")", "-", "MAX_PROCESSING_TIME", "if", "(", "work", "[", "'claimed_worker_id'", "]", "and", "work", "[", "'claimed_worker_start_time'", "]", "is", "not", "None", "and", "work", "[", "'claimed_worker_start_time'", "]", ">=", "cutoff_time", ")", ":", "return", "False", "return", "True" ]
Returns True if work piece is unclaimed.
[ "Returns", "True", "if", "work", "piece", "is", "unclaimed", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py#L46-L55
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py
WorkPiecesBase.write_all_to_datastore
def write_all_to_datastore(self): """Writes all work pieces into datastore. Each work piece is identified by ID. This method writes/updates only those work pieces which IDs are stored in this class. For examples, if this class has only work pieces with IDs '1' ... '100' and datastore already contains work pieces with IDs '50' ... '200' then this method will create new work pieces with IDs '1' ... '49', update work pieces with IDs '50' ... '100' and keep unchanged work pieces with IDs '101' ... '200'. """ client = self._datastore_client with client.no_transact_batch() as batch: parent_key = client.key(KIND_WORK_TYPE, self._work_type_entity_id) batch.put(client.entity(parent_key)) for work_id, work_val in iteritems(self._work): entity = client.entity(client.key(KIND_WORK, work_id, parent=parent_key)) entity.update(work_val) batch.put(entity)
python
def write_all_to_datastore(self): """Writes all work pieces into datastore. Each work piece is identified by ID. This method writes/updates only those work pieces which IDs are stored in this class. For examples, if this class has only work pieces with IDs '1' ... '100' and datastore already contains work pieces with IDs '50' ... '200' then this method will create new work pieces with IDs '1' ... '49', update work pieces with IDs '50' ... '100' and keep unchanged work pieces with IDs '101' ... '200'. """ client = self._datastore_client with client.no_transact_batch() as batch: parent_key = client.key(KIND_WORK_TYPE, self._work_type_entity_id) batch.put(client.entity(parent_key)) for work_id, work_val in iteritems(self._work): entity = client.entity(client.key(KIND_WORK, work_id, parent=parent_key)) entity.update(work_val) batch.put(entity)
[ "def", "write_all_to_datastore", "(", "self", ")", ":", "client", "=", "self", ".", "_datastore_client", "with", "client", ".", "no_transact_batch", "(", ")", "as", "batch", ":", "parent_key", "=", "client", ".", "key", "(", "KIND_WORK_TYPE", ",", "self", ".", "_work_type_entity_id", ")", "batch", ".", "put", "(", "client", ".", "entity", "(", "parent_key", ")", ")", "for", "work_id", ",", "work_val", "in", "iteritems", "(", "self", ".", "_work", ")", ":", "entity", "=", "client", ".", "entity", "(", "client", ".", "key", "(", "KIND_WORK", ",", "work_id", ",", "parent", "=", "parent_key", ")", ")", "entity", ".", "update", "(", "work_val", ")", "batch", ".", "put", "(", "entity", ")" ]
Writes all work pieces into datastore. Each work piece is identified by ID. This method writes/updates only those work pieces which IDs are stored in this class. For examples, if this class has only work pieces with IDs '1' ... '100' and datastore already contains work pieces with IDs '50' ... '200' then this method will create new work pieces with IDs '1' ... '49', update work pieces with IDs '50' ... '100' and keep unchanged work pieces with IDs '101' ... '200'.
[ "Writes", "all", "work", "pieces", "into", "datastore", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py#L150-L168
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py
WorkPiecesBase.read_all_from_datastore
def read_all_from_datastore(self): """Reads all work pieces from the datastore.""" self._work = {} client = self._datastore_client parent_key = client.key(KIND_WORK_TYPE, self._work_type_entity_id) for entity in client.query_fetch(kind=KIND_WORK, ancestor=parent_key): work_id = entity.key.flat_path[-1] self.work[work_id] = dict(entity)
python
def read_all_from_datastore(self): """Reads all work pieces from the datastore.""" self._work = {} client = self._datastore_client parent_key = client.key(KIND_WORK_TYPE, self._work_type_entity_id) for entity in client.query_fetch(kind=KIND_WORK, ancestor=parent_key): work_id = entity.key.flat_path[-1] self.work[work_id] = dict(entity)
[ "def", "read_all_from_datastore", "(", "self", ")", ":", "self", ".", "_work", "=", "{", "}", "client", "=", "self", ".", "_datastore_client", "parent_key", "=", "client", ".", "key", "(", "KIND_WORK_TYPE", ",", "self", ".", "_work_type_entity_id", ")", "for", "entity", "in", "client", ".", "query_fetch", "(", "kind", "=", "KIND_WORK", ",", "ancestor", "=", "parent_key", ")", ":", "work_id", "=", "entity", ".", "key", ".", "flat_path", "[", "-", "1", "]", "self", ".", "work", "[", "work_id", "]", "=", "dict", "(", "entity", ")" ]
Reads all work pieces from the datastore.
[ "Reads", "all", "work", "pieces", "from", "the", "datastore", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py#L170-L177
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py
WorkPiecesBase._read_undone_shard_from_datastore
def _read_undone_shard_from_datastore(self, shard_id=None): """Reads undone worke pieces which are assigned to shard with given id.""" self._work = {} client = self._datastore_client parent_key = client.key(KIND_WORK_TYPE, self._work_type_entity_id) filters = [('is_completed', '=', False)] if shard_id is not None: filters.append(('shard_id', '=', shard_id)) for entity in client.query_fetch(kind=KIND_WORK, ancestor=parent_key, filters=filters): work_id = entity.key.flat_path[-1] self.work[work_id] = dict(entity) if len(self._work) >= MAX_WORK_RECORDS_READ: break
python
def _read_undone_shard_from_datastore(self, shard_id=None): """Reads undone worke pieces which are assigned to shard with given id.""" self._work = {} client = self._datastore_client parent_key = client.key(KIND_WORK_TYPE, self._work_type_entity_id) filters = [('is_completed', '=', False)] if shard_id is not None: filters.append(('shard_id', '=', shard_id)) for entity in client.query_fetch(kind=KIND_WORK, ancestor=parent_key, filters=filters): work_id = entity.key.flat_path[-1] self.work[work_id] = dict(entity) if len(self._work) >= MAX_WORK_RECORDS_READ: break
[ "def", "_read_undone_shard_from_datastore", "(", "self", ",", "shard_id", "=", "None", ")", ":", "self", ".", "_work", "=", "{", "}", "client", "=", "self", ".", "_datastore_client", "parent_key", "=", "client", ".", "key", "(", "KIND_WORK_TYPE", ",", "self", ".", "_work_type_entity_id", ")", "filters", "=", "[", "(", "'is_completed'", ",", "'='", ",", "False", ")", "]", "if", "shard_id", "is", "not", "None", ":", "filters", ".", "append", "(", "(", "'shard_id'", ",", "'='", ",", "shard_id", ")", ")", "for", "entity", "in", "client", ".", "query_fetch", "(", "kind", "=", "KIND_WORK", ",", "ancestor", "=", "parent_key", ",", "filters", "=", "filters", ")", ":", "work_id", "=", "entity", ".", "key", ".", "flat_path", "[", "-", "1", "]", "self", ".", "work", "[", "work_id", "]", "=", "dict", "(", "entity", ")", "if", "len", "(", "self", ".", "_work", ")", ">=", "MAX_WORK_RECORDS_READ", ":", "break" ]
Reads undone worke pieces which are assigned to shard with given id.
[ "Reads", "undone", "worke", "pieces", "which", "are", "assigned", "to", "shard", "with", "given", "id", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py#L179-L192
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py
WorkPiecesBase.read_undone_from_datastore
def read_undone_from_datastore(self, shard_id=None, num_shards=None): """Reads undone work from the datastore. If shard_id and num_shards are specified then this method will attempt to read undone work for shard with id shard_id. If no undone work was found then it will try to read shard (shard_id+1) and so on until either found shard with undone work or all shards are read. Args: shard_id: Id of the start shard num_shards: total number of shards Returns: id of the shard with undone work which was read. None means that work from all datastore was read. """ if shard_id is not None: shards_list = [(i + shard_id) % num_shards for i in range(num_shards)] else: shards_list = [] shards_list.append(None) for shard in shards_list: self._read_undone_shard_from_datastore(shard) if self._work: return shard return None
python
def read_undone_from_datastore(self, shard_id=None, num_shards=None): """Reads undone work from the datastore. If shard_id and num_shards are specified then this method will attempt to read undone work for shard with id shard_id. If no undone work was found then it will try to read shard (shard_id+1) and so on until either found shard with undone work or all shards are read. Args: shard_id: Id of the start shard num_shards: total number of shards Returns: id of the shard with undone work which was read. None means that work from all datastore was read. """ if shard_id is not None: shards_list = [(i + shard_id) % num_shards for i in range(num_shards)] else: shards_list = [] shards_list.append(None) for shard in shards_list: self._read_undone_shard_from_datastore(shard) if self._work: return shard return None
[ "def", "read_undone_from_datastore", "(", "self", ",", "shard_id", "=", "None", ",", "num_shards", "=", "None", ")", ":", "if", "shard_id", "is", "not", "None", ":", "shards_list", "=", "[", "(", "i", "+", "shard_id", ")", "%", "num_shards", "for", "i", "in", "range", "(", "num_shards", ")", "]", "else", ":", "shards_list", "=", "[", "]", "shards_list", ".", "append", "(", "None", ")", "for", "shard", "in", "shards_list", ":", "self", ".", "_read_undone_shard_from_datastore", "(", "shard", ")", "if", "self", ".", "_work", ":", "return", "shard", "return", "None" ]
Reads undone work from the datastore. If shard_id and num_shards are specified then this method will attempt to read undone work for shard with id shard_id. If no undone work was found then it will try to read shard (shard_id+1) and so on until either found shard with undone work or all shards are read. Args: shard_id: Id of the start shard num_shards: total number of shards Returns: id of the shard with undone work which was read. None means that work from all datastore was read.
[ "Reads", "undone", "work", "from", "the", "datastore", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py#L194-L219
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py
WorkPiecesBase.try_pick_piece_of_work
def try_pick_piece_of_work(self, worker_id, submission_id=None): """Tries pick next unclaimed piece of work to do. Attempt to claim work piece is done using Cloud Datastore transaction, so only one worker can claim any work piece at a time. Args: worker_id: ID of current worker submission_id: if not None then this method will try to pick piece of work for this submission Returns: ID of the claimed work piece """ client = self._datastore_client unclaimed_work_ids = None if submission_id: unclaimed_work_ids = [ k for k, v in iteritems(self.work) if is_unclaimed(v) and (v['submission_id'] == submission_id) ] if not unclaimed_work_ids: unclaimed_work_ids = [k for k, v in iteritems(self.work) if is_unclaimed(v)] if unclaimed_work_ids: next_work_id = random.choice(unclaimed_work_ids) else: return None try: with client.transaction() as transaction: work_key = client.key(KIND_WORK_TYPE, self._work_type_entity_id, KIND_WORK, next_work_id) work_entity = client.get(work_key, transaction=transaction) if not is_unclaimed(work_entity): return None work_entity['claimed_worker_id'] = worker_id work_entity['claimed_worker_start_time'] = get_integer_time() transaction.put(work_entity) except Exception: return None return next_work_id
python
def try_pick_piece_of_work(self, worker_id, submission_id=None): """Tries pick next unclaimed piece of work to do. Attempt to claim work piece is done using Cloud Datastore transaction, so only one worker can claim any work piece at a time. Args: worker_id: ID of current worker submission_id: if not None then this method will try to pick piece of work for this submission Returns: ID of the claimed work piece """ client = self._datastore_client unclaimed_work_ids = None if submission_id: unclaimed_work_ids = [ k for k, v in iteritems(self.work) if is_unclaimed(v) and (v['submission_id'] == submission_id) ] if not unclaimed_work_ids: unclaimed_work_ids = [k for k, v in iteritems(self.work) if is_unclaimed(v)] if unclaimed_work_ids: next_work_id = random.choice(unclaimed_work_ids) else: return None try: with client.transaction() as transaction: work_key = client.key(KIND_WORK_TYPE, self._work_type_entity_id, KIND_WORK, next_work_id) work_entity = client.get(work_key, transaction=transaction) if not is_unclaimed(work_entity): return None work_entity['claimed_worker_id'] = worker_id work_entity['claimed_worker_start_time'] = get_integer_time() transaction.put(work_entity) except Exception: return None return next_work_id
[ "def", "try_pick_piece_of_work", "(", "self", ",", "worker_id", ",", "submission_id", "=", "None", ")", ":", "client", "=", "self", ".", "_datastore_client", "unclaimed_work_ids", "=", "None", "if", "submission_id", ":", "unclaimed_work_ids", "=", "[", "k", "for", "k", ",", "v", "in", "iteritems", "(", "self", ".", "work", ")", "if", "is_unclaimed", "(", "v", ")", "and", "(", "v", "[", "'submission_id'", "]", "==", "submission_id", ")", "]", "if", "not", "unclaimed_work_ids", ":", "unclaimed_work_ids", "=", "[", "k", "for", "k", ",", "v", "in", "iteritems", "(", "self", ".", "work", ")", "if", "is_unclaimed", "(", "v", ")", "]", "if", "unclaimed_work_ids", ":", "next_work_id", "=", "random", ".", "choice", "(", "unclaimed_work_ids", ")", "else", ":", "return", "None", "try", ":", "with", "client", ".", "transaction", "(", ")", "as", "transaction", ":", "work_key", "=", "client", ".", "key", "(", "KIND_WORK_TYPE", ",", "self", ".", "_work_type_entity_id", ",", "KIND_WORK", ",", "next_work_id", ")", "work_entity", "=", "client", ".", "get", "(", "work_key", ",", "transaction", "=", "transaction", ")", "if", "not", "is_unclaimed", "(", "work_entity", ")", ":", "return", "None", "work_entity", "[", "'claimed_worker_id'", "]", "=", "worker_id", "work_entity", "[", "'claimed_worker_start_time'", "]", "=", "get_integer_time", "(", ")", "transaction", ".", "put", "(", "work_entity", ")", "except", "Exception", ":", "return", "None", "return", "next_work_id" ]
Tries pick next unclaimed piece of work to do. Attempt to claim work piece is done using Cloud Datastore transaction, so only one worker can claim any work piece at a time. Args: worker_id: ID of current worker submission_id: if not None then this method will try to pick piece of work for this submission Returns: ID of the claimed work piece
[ "Tries", "pick", "next", "unclaimed", "piece", "of", "work", "to", "do", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py#L221-L261
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py
WorkPiecesBase.update_work_as_completed
def update_work_as_completed(self, worker_id, work_id, other_values=None, error=None): """Updates work piece in datastore as completed. Args: worker_id: ID of the worker which did the work work_id: ID of the work which was done other_values: dictionary with additonal values which should be saved with the work piece error: if not None then error occurred during computation of the work piece. In such case work will be marked as completed with error. Returns: whether work was successfully updated """ client = self._datastore_client try: with client.transaction() as transaction: work_key = client.key(KIND_WORK_TYPE, self._work_type_entity_id, KIND_WORK, work_id) work_entity = client.get(work_key, transaction=transaction) if work_entity['claimed_worker_id'] != worker_id: return False work_entity['is_completed'] = True if other_values: work_entity.update(other_values) if error: work_entity['error'] = text_type(error) transaction.put(work_entity) except Exception: return False return True
python
def update_work_as_completed(self, worker_id, work_id, other_values=None, error=None): """Updates work piece in datastore as completed. Args: worker_id: ID of the worker which did the work work_id: ID of the work which was done other_values: dictionary with additonal values which should be saved with the work piece error: if not None then error occurred during computation of the work piece. In such case work will be marked as completed with error. Returns: whether work was successfully updated """ client = self._datastore_client try: with client.transaction() as transaction: work_key = client.key(KIND_WORK_TYPE, self._work_type_entity_id, KIND_WORK, work_id) work_entity = client.get(work_key, transaction=transaction) if work_entity['claimed_worker_id'] != worker_id: return False work_entity['is_completed'] = True if other_values: work_entity.update(other_values) if error: work_entity['error'] = text_type(error) transaction.put(work_entity) except Exception: return False return True
[ "def", "update_work_as_completed", "(", "self", ",", "worker_id", ",", "work_id", ",", "other_values", "=", "None", ",", "error", "=", "None", ")", ":", "client", "=", "self", ".", "_datastore_client", "try", ":", "with", "client", ".", "transaction", "(", ")", "as", "transaction", ":", "work_key", "=", "client", ".", "key", "(", "KIND_WORK_TYPE", ",", "self", ".", "_work_type_entity_id", ",", "KIND_WORK", ",", "work_id", ")", "work_entity", "=", "client", ".", "get", "(", "work_key", ",", "transaction", "=", "transaction", ")", "if", "work_entity", "[", "'claimed_worker_id'", "]", "!=", "worker_id", ":", "return", "False", "work_entity", "[", "'is_completed'", "]", "=", "True", "if", "other_values", ":", "work_entity", ".", "update", "(", "other_values", ")", "if", "error", ":", "work_entity", "[", "'error'", "]", "=", "text_type", "(", "error", ")", "transaction", ".", "put", "(", "work_entity", ")", "except", "Exception", ":", "return", "False", "return", "True" ]
Updates work piece in datastore as completed. Args: worker_id: ID of the worker which did the work work_id: ID of the work which was done other_values: dictionary with additonal values which should be saved with the work piece error: if not None then error occurred during computation of the work piece. In such case work will be marked as completed with error. Returns: whether work was successfully updated
[ "Updates", "work", "piece", "in", "datastore", "as", "completed", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py#L263-L294
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py
WorkPiecesBase.compute_work_statistics
def compute_work_statistics(self): """Computes statistics from all work pieces stored in this class.""" result = {} for v in itervalues(self.work): submission_id = v['submission_id'] if submission_id not in result: result[submission_id] = { 'completed': 0, 'num_errors': 0, 'error_messages': set(), 'eval_times': [], 'min_eval_time': None, 'max_eval_time': None, 'mean_eval_time': None, 'median_eval_time': None, } if not v['is_completed']: continue result[submission_id]['completed'] += 1 if 'error' in v and v['error']: result[submission_id]['num_errors'] += 1 result[submission_id]['error_messages'].add(v['error']) else: result[submission_id]['eval_times'].append(float(v['elapsed_time'])) for v in itervalues(result): if v['eval_times']: v['min_eval_time'] = np.min(v['eval_times']) v['max_eval_time'] = np.max(v['eval_times']) v['mean_eval_time'] = np.mean(v['eval_times']) v['median_eval_time'] = np.median(v['eval_times']) return result
python
def compute_work_statistics(self): """Computes statistics from all work pieces stored in this class.""" result = {} for v in itervalues(self.work): submission_id = v['submission_id'] if submission_id not in result: result[submission_id] = { 'completed': 0, 'num_errors': 0, 'error_messages': set(), 'eval_times': [], 'min_eval_time': None, 'max_eval_time': None, 'mean_eval_time': None, 'median_eval_time': None, } if not v['is_completed']: continue result[submission_id]['completed'] += 1 if 'error' in v and v['error']: result[submission_id]['num_errors'] += 1 result[submission_id]['error_messages'].add(v['error']) else: result[submission_id]['eval_times'].append(float(v['elapsed_time'])) for v in itervalues(result): if v['eval_times']: v['min_eval_time'] = np.min(v['eval_times']) v['max_eval_time'] = np.max(v['eval_times']) v['mean_eval_time'] = np.mean(v['eval_times']) v['median_eval_time'] = np.median(v['eval_times']) return result
[ "def", "compute_work_statistics", "(", "self", ")", ":", "result", "=", "{", "}", "for", "v", "in", "itervalues", "(", "self", ".", "work", ")", ":", "submission_id", "=", "v", "[", "'submission_id'", "]", "if", "submission_id", "not", "in", "result", ":", "result", "[", "submission_id", "]", "=", "{", "'completed'", ":", "0", ",", "'num_errors'", ":", "0", ",", "'error_messages'", ":", "set", "(", ")", ",", "'eval_times'", ":", "[", "]", ",", "'min_eval_time'", ":", "None", ",", "'max_eval_time'", ":", "None", ",", "'mean_eval_time'", ":", "None", ",", "'median_eval_time'", ":", "None", ",", "}", "if", "not", "v", "[", "'is_completed'", "]", ":", "continue", "result", "[", "submission_id", "]", "[", "'completed'", "]", "+=", "1", "if", "'error'", "in", "v", "and", "v", "[", "'error'", "]", ":", "result", "[", "submission_id", "]", "[", "'num_errors'", "]", "+=", "1", "result", "[", "submission_id", "]", "[", "'error_messages'", "]", ".", "add", "(", "v", "[", "'error'", "]", ")", "else", ":", "result", "[", "submission_id", "]", "[", "'eval_times'", "]", ".", "append", "(", "float", "(", "v", "[", "'elapsed_time'", "]", ")", ")", "for", "v", "in", "itervalues", "(", "result", ")", ":", "if", "v", "[", "'eval_times'", "]", ":", "v", "[", "'min_eval_time'", "]", "=", "np", ".", "min", "(", "v", "[", "'eval_times'", "]", ")", "v", "[", "'max_eval_time'", "]", "=", "np", ".", "max", "(", "v", "[", "'eval_times'", "]", ")", "v", "[", "'mean_eval_time'", "]", "=", "np", ".", "mean", "(", "v", "[", "'eval_times'", "]", ")", "v", "[", "'median_eval_time'", "]", "=", "np", ".", "median", "(", "v", "[", "'eval_times'", "]", ")", "return", "result" ]
Computes statistics from all work pieces stored in this class.
[ "Computes", "statistics", "from", "all", "work", "pieces", "stored", "in", "this", "class", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py#L296-L326
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py
AttackWorkPieces.init_from_adversarial_batches
def init_from_adversarial_batches(self, adv_batches): """Initializes work pieces from adversarial batches. Args: adv_batches: dict with adversarial batches, could be obtained as AversarialBatches.data """ for idx, (adv_batch_id, adv_batch_val) in enumerate(iteritems(adv_batches)): work_id = ATTACK_WORK_ID_PATTERN.format(idx) self.work[work_id] = { 'claimed_worker_id': None, 'claimed_worker_start_time': None, 'is_completed': False, 'error': None, 'elapsed_time': None, 'submission_id': adv_batch_val['submission_id'], 'shard_id': None, 'output_adversarial_batch_id': adv_batch_id, }
python
def init_from_adversarial_batches(self, adv_batches): """Initializes work pieces from adversarial batches. Args: adv_batches: dict with adversarial batches, could be obtained as AversarialBatches.data """ for idx, (adv_batch_id, adv_batch_val) in enumerate(iteritems(adv_batches)): work_id = ATTACK_WORK_ID_PATTERN.format(idx) self.work[work_id] = { 'claimed_worker_id': None, 'claimed_worker_start_time': None, 'is_completed': False, 'error': None, 'elapsed_time': None, 'submission_id': adv_batch_val['submission_id'], 'shard_id': None, 'output_adversarial_batch_id': adv_batch_id, }
[ "def", "init_from_adversarial_batches", "(", "self", ",", "adv_batches", ")", ":", "for", "idx", ",", "(", "adv_batch_id", ",", "adv_batch_val", ")", "in", "enumerate", "(", "iteritems", "(", "adv_batches", ")", ")", ":", "work_id", "=", "ATTACK_WORK_ID_PATTERN", ".", "format", "(", "idx", ")", "self", ".", "work", "[", "work_id", "]", "=", "{", "'claimed_worker_id'", ":", "None", ",", "'claimed_worker_start_time'", ":", "None", ",", "'is_completed'", ":", "False", ",", "'error'", ":", "None", ",", "'elapsed_time'", ":", "None", ",", "'submission_id'", ":", "adv_batch_val", "[", "'submission_id'", "]", ",", "'shard_id'", ":", "None", ",", "'output_adversarial_batch_id'", ":", "adv_batch_id", ",", "}" ]
Initializes work pieces from adversarial batches. Args: adv_batches: dict with adversarial batches, could be obtained as AversarialBatches.data
[ "Initializes", "work", "pieces", "from", "adversarial", "batches", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py#L349-L367
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py
DefenseWorkPieces.init_from_class_batches
def init_from_class_batches(self, class_batches, num_shards=None): """Initializes work pieces from classification batches. Args: class_batches: dict with classification batches, could be obtained as ClassificationBatches.data num_shards: number of shards to split data into, if None then no sharding is done. """ shards_for_submissions = {} shard_idx = 0 for idx, (batch_id, batch_val) in enumerate(iteritems(class_batches)): work_id = DEFENSE_WORK_ID_PATTERN.format(idx) submission_id = batch_val['submission_id'] shard_id = None if num_shards: shard_id = shards_for_submissions.get(submission_id) if shard_id is None: shard_id = shard_idx % num_shards shards_for_submissions[submission_id] = shard_id shard_idx += 1 # Note: defense also might have following fields populated by worker: # stat_correct, stat_error, stat_target_class, stat_num_images self.work[work_id] = { 'claimed_worker_id': None, 'claimed_worker_start_time': None, 'is_completed': False, 'error': None, 'elapsed_time': None, 'submission_id': submission_id, 'shard_id': shard_id, 'output_classification_batch_id': batch_id, }
python
def init_from_class_batches(self, class_batches, num_shards=None): """Initializes work pieces from classification batches. Args: class_batches: dict with classification batches, could be obtained as ClassificationBatches.data num_shards: number of shards to split data into, if None then no sharding is done. """ shards_for_submissions = {} shard_idx = 0 for idx, (batch_id, batch_val) in enumerate(iteritems(class_batches)): work_id = DEFENSE_WORK_ID_PATTERN.format(idx) submission_id = batch_val['submission_id'] shard_id = None if num_shards: shard_id = shards_for_submissions.get(submission_id) if shard_id is None: shard_id = shard_idx % num_shards shards_for_submissions[submission_id] = shard_id shard_idx += 1 # Note: defense also might have following fields populated by worker: # stat_correct, stat_error, stat_target_class, stat_num_images self.work[work_id] = { 'claimed_worker_id': None, 'claimed_worker_start_time': None, 'is_completed': False, 'error': None, 'elapsed_time': None, 'submission_id': submission_id, 'shard_id': shard_id, 'output_classification_batch_id': batch_id, }
[ "def", "init_from_class_batches", "(", "self", ",", "class_batches", ",", "num_shards", "=", "None", ")", ":", "shards_for_submissions", "=", "{", "}", "shard_idx", "=", "0", "for", "idx", ",", "(", "batch_id", ",", "batch_val", ")", "in", "enumerate", "(", "iteritems", "(", "class_batches", ")", ")", ":", "work_id", "=", "DEFENSE_WORK_ID_PATTERN", ".", "format", "(", "idx", ")", "submission_id", "=", "batch_val", "[", "'submission_id'", "]", "shard_id", "=", "None", "if", "num_shards", ":", "shard_id", "=", "shards_for_submissions", ".", "get", "(", "submission_id", ")", "if", "shard_id", "is", "None", ":", "shard_id", "=", "shard_idx", "%", "num_shards", "shards_for_submissions", "[", "submission_id", "]", "=", "shard_id", "shard_idx", "+=", "1", "# Note: defense also might have following fields populated by worker:", "# stat_correct, stat_error, stat_target_class, stat_num_images", "self", ".", "work", "[", "work_id", "]", "=", "{", "'claimed_worker_id'", ":", "None", ",", "'claimed_worker_start_time'", ":", "None", ",", "'is_completed'", ":", "False", ",", "'error'", ":", "None", ",", "'elapsed_time'", ":", "None", ",", "'submission_id'", ":", "submission_id", ",", "'shard_id'", ":", "shard_id", ",", "'output_classification_batch_id'", ":", "batch_id", ",", "}" ]
Initializes work pieces from classification batches. Args: class_batches: dict with classification batches, could be obtained as ClassificationBatches.data num_shards: number of shards to split data into, if None then no sharding is done.
[ "Initializes", "work", "pieces", "from", "classification", "batches", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py#L379-L411
train
tensorflow/cleverhans
scripts/make_confidence_report_bundle_examples.py
main
def main(argv=None): """ Make a confidence report and save it to disk. """ assert len(argv) >= 3 _name_of_script = argv[0] model_filepath = argv[1] adv_x_filepaths = argv[2:] sess = tf.Session() with sess.as_default(): model = serial.load(model_filepath) factory = model.dataset_factory factory.kwargs['train_start'] = FLAGS.train_start factory.kwargs['train_end'] = FLAGS.train_end factory.kwargs['test_start'] = FLAGS.test_start factory.kwargs['test_end'] = FLAGS.test_end dataset = factory() adv_x_list = [np.load(filepath) for filepath in adv_x_filepaths] x, y = dataset.get_set(FLAGS.which_set) for adv_x in adv_x_list: assert adv_x.shape == x.shape, (adv_x.shape, x.shape) # Make sure these were made for the right dataset with right scaling # arguments, etc. assert adv_x.min() >= 0. - dataset.kwargs['center'] * dataset.max_val assert adv_x.max() <= dataset.max_val data_range = dataset.max_val * (1. + dataset.kwargs['center']) if adv_x.max() - adv_x.min() <= .8 * data_range: warnings.warn("Something is weird. Your adversarial examples use " "less than 80% of the data range." "This might mean you generated them for a model with " "inputs in [0, 1] and are now using them for a model " "with inputs in [0, 255] or something like that. " "Or it could be OK if you're evaluating on a very small " "batch.") report_path = FLAGS.report_path if report_path is None: suffix = "_bundled_examples_report.joblib" assert model_filepath.endswith('.joblib') report_path = model_filepath[:-len('.joblib')] + suffix goal = MaxConfidence() bundle_examples_with_goal(sess, model, adv_x_list, y, goal, report_path, batch_size=FLAGS.batch_size)
python
def main(argv=None): """ Make a confidence report and save it to disk. """ assert len(argv) >= 3 _name_of_script = argv[0] model_filepath = argv[1] adv_x_filepaths = argv[2:] sess = tf.Session() with sess.as_default(): model = serial.load(model_filepath) factory = model.dataset_factory factory.kwargs['train_start'] = FLAGS.train_start factory.kwargs['train_end'] = FLAGS.train_end factory.kwargs['test_start'] = FLAGS.test_start factory.kwargs['test_end'] = FLAGS.test_end dataset = factory() adv_x_list = [np.load(filepath) for filepath in adv_x_filepaths] x, y = dataset.get_set(FLAGS.which_set) for adv_x in adv_x_list: assert adv_x.shape == x.shape, (adv_x.shape, x.shape) # Make sure these were made for the right dataset with right scaling # arguments, etc. assert adv_x.min() >= 0. - dataset.kwargs['center'] * dataset.max_val assert adv_x.max() <= dataset.max_val data_range = dataset.max_val * (1. + dataset.kwargs['center']) if adv_x.max() - adv_x.min() <= .8 * data_range: warnings.warn("Something is weird. Your adversarial examples use " "less than 80% of the data range." "This might mean you generated them for a model with " "inputs in [0, 1] and are now using them for a model " "with inputs in [0, 255] or something like that. " "Or it could be OK if you're evaluating on a very small " "batch.") report_path = FLAGS.report_path if report_path is None: suffix = "_bundled_examples_report.joblib" assert model_filepath.endswith('.joblib') report_path = model_filepath[:-len('.joblib')] + suffix goal = MaxConfidence() bundle_examples_with_goal(sess, model, adv_x_list, y, goal, report_path, batch_size=FLAGS.batch_size)
[ "def", "main", "(", "argv", "=", "None", ")", ":", "assert", "len", "(", "argv", ")", ">=", "3", "_name_of_script", "=", "argv", "[", "0", "]", "model_filepath", "=", "argv", "[", "1", "]", "adv_x_filepaths", "=", "argv", "[", "2", ":", "]", "sess", "=", "tf", ".", "Session", "(", ")", "with", "sess", ".", "as_default", "(", ")", ":", "model", "=", "serial", ".", "load", "(", "model_filepath", ")", "factory", "=", "model", ".", "dataset_factory", "factory", ".", "kwargs", "[", "'train_start'", "]", "=", "FLAGS", ".", "train_start", "factory", ".", "kwargs", "[", "'train_end'", "]", "=", "FLAGS", ".", "train_end", "factory", ".", "kwargs", "[", "'test_start'", "]", "=", "FLAGS", ".", "test_start", "factory", ".", "kwargs", "[", "'test_end'", "]", "=", "FLAGS", ".", "test_end", "dataset", "=", "factory", "(", ")", "adv_x_list", "=", "[", "np", ".", "load", "(", "filepath", ")", "for", "filepath", "in", "adv_x_filepaths", "]", "x", ",", "y", "=", "dataset", ".", "get_set", "(", "FLAGS", ".", "which_set", ")", "for", "adv_x", "in", "adv_x_list", ":", "assert", "adv_x", ".", "shape", "==", "x", ".", "shape", ",", "(", "adv_x", ".", "shape", ",", "x", ".", "shape", ")", "# Make sure these were made for the right dataset with right scaling", "# arguments, etc.", "assert", "adv_x", ".", "min", "(", ")", ">=", "0.", "-", "dataset", ".", "kwargs", "[", "'center'", "]", "*", "dataset", ".", "max_val", "assert", "adv_x", ".", "max", "(", ")", "<=", "dataset", ".", "max_val", "data_range", "=", "dataset", ".", "max_val", "*", "(", "1.", "+", "dataset", ".", "kwargs", "[", "'center'", "]", ")", "if", "adv_x", ".", "max", "(", ")", "-", "adv_x", ".", "min", "(", ")", "<=", ".8", "*", "data_range", ":", "warnings", ".", "warn", "(", "\"Something is weird. Your adversarial examples use \"", "\"less than 80% of the data range.\"", "\"This might mean you generated them for a model with \"", "\"inputs in [0, 1] and are now using them for a model \"", "\"with inputs in [0, 255] or something like that. \"", "\"Or it could be OK if you're evaluating on a very small \"", "\"batch.\"", ")", "report_path", "=", "FLAGS", ".", "report_path", "if", "report_path", "is", "None", ":", "suffix", "=", "\"_bundled_examples_report.joblib\"", "assert", "model_filepath", ".", "endswith", "(", "'.joblib'", ")", "report_path", "=", "model_filepath", "[", ":", "-", "len", "(", "'.joblib'", ")", "]", "+", "suffix", "goal", "=", "MaxConfidence", "(", ")", "bundle_examples_with_goal", "(", "sess", ",", "model", ",", "adv_x_list", ",", "y", ",", "goal", ",", "report_path", ",", "batch_size", "=", "FLAGS", ".", "batch_size", ")" ]
Make a confidence report and save it to disk.
[ "Make", "a", "confidence", "report", "and", "save", "it", "to", "disk", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/scripts/make_confidence_report_bundle_examples.py#L48-L95
train
tensorflow/cleverhans
cleverhans/attacks/fast_gradient_method.py
fgm
def fgm(x, logits, y=None, eps=0.3, ord=np.inf, clip_min=None, clip_max=None, targeted=False, sanity_checks=True): """ TensorFlow implementation of the Fast Gradient Method. :param x: the input placeholder :param logits: output of model.get_logits :param y: (optional) A placeholder for the true labels. If targeted is true, then provide the target label. Otherwise, only provide this parameter if you'd like to use true labels when crafting adversarial samples. Otherwise, model predictions are used as labels to avoid the "label leaking" effect (explained in this paper: https://arxiv.org/abs/1611.01236). Default is None. Labels should be one-hot-encoded. :param eps: the epsilon (input variation parameter) :param ord: (optional) Order of the norm (mimics NumPy). Possible values: np.inf, 1 or 2. :param clip_min: Minimum float value for adversarial example components :param clip_max: Maximum float value for adversarial example components :param targeted: Is the attack targeted or untargeted? Untargeted, the default, will try to make the label incorrect. Targeted will instead try to move in the direction of being more like y. :return: a tensor for the adversarial example """ asserts = [] # If a data range was specified, check that the input was in that range if clip_min is not None: asserts.append(utils_tf.assert_greater_equal( x, tf.cast(clip_min, x.dtype))) if clip_max is not None: asserts.append(utils_tf.assert_less_equal(x, tf.cast(clip_max, x.dtype))) # Make sure the caller has not passed probs by accident assert logits.op.type != 'Softmax' if y is None: # Using model predictions as ground truth to avoid label leaking preds_max = reduce_max(logits, 1, keepdims=True) y = tf.to_float(tf.equal(logits, preds_max)) y = tf.stop_gradient(y) y = y / reduce_sum(y, 1, keepdims=True) # Compute loss loss = softmax_cross_entropy_with_logits(labels=y, logits=logits) if targeted: loss = -loss # Define gradient of loss wrt input grad, = tf.gradients(loss, x) optimal_perturbation = optimize_linear(grad, eps, ord) # Add perturbation to original example to obtain adversarial example adv_x = x + optimal_perturbation # If clipping is needed, reset all values outside of [clip_min, clip_max] if (clip_min is not None) or (clip_max is not None): # We don't currently support one-sided clipping assert clip_min is not None and clip_max is not None adv_x = utils_tf.clip_by_value(adv_x, clip_min, clip_max) if sanity_checks: with tf.control_dependencies(asserts): adv_x = tf.identity(adv_x) return adv_x
python
def fgm(x, logits, y=None, eps=0.3, ord=np.inf, clip_min=None, clip_max=None, targeted=False, sanity_checks=True): """ TensorFlow implementation of the Fast Gradient Method. :param x: the input placeholder :param logits: output of model.get_logits :param y: (optional) A placeholder for the true labels. If targeted is true, then provide the target label. Otherwise, only provide this parameter if you'd like to use true labels when crafting adversarial samples. Otherwise, model predictions are used as labels to avoid the "label leaking" effect (explained in this paper: https://arxiv.org/abs/1611.01236). Default is None. Labels should be one-hot-encoded. :param eps: the epsilon (input variation parameter) :param ord: (optional) Order of the norm (mimics NumPy). Possible values: np.inf, 1 or 2. :param clip_min: Minimum float value for adversarial example components :param clip_max: Maximum float value for adversarial example components :param targeted: Is the attack targeted or untargeted? Untargeted, the default, will try to make the label incorrect. Targeted will instead try to move in the direction of being more like y. :return: a tensor for the adversarial example """ asserts = [] # If a data range was specified, check that the input was in that range if clip_min is not None: asserts.append(utils_tf.assert_greater_equal( x, tf.cast(clip_min, x.dtype))) if clip_max is not None: asserts.append(utils_tf.assert_less_equal(x, tf.cast(clip_max, x.dtype))) # Make sure the caller has not passed probs by accident assert logits.op.type != 'Softmax' if y is None: # Using model predictions as ground truth to avoid label leaking preds_max = reduce_max(logits, 1, keepdims=True) y = tf.to_float(tf.equal(logits, preds_max)) y = tf.stop_gradient(y) y = y / reduce_sum(y, 1, keepdims=True) # Compute loss loss = softmax_cross_entropy_with_logits(labels=y, logits=logits) if targeted: loss = -loss # Define gradient of loss wrt input grad, = tf.gradients(loss, x) optimal_perturbation = optimize_linear(grad, eps, ord) # Add perturbation to original example to obtain adversarial example adv_x = x + optimal_perturbation # If clipping is needed, reset all values outside of [clip_min, clip_max] if (clip_min is not None) or (clip_max is not None): # We don't currently support one-sided clipping assert clip_min is not None and clip_max is not None adv_x = utils_tf.clip_by_value(adv_x, clip_min, clip_max) if sanity_checks: with tf.control_dependencies(asserts): adv_x = tf.identity(adv_x) return adv_x
[ "def", "fgm", "(", "x", ",", "logits", ",", "y", "=", "None", ",", "eps", "=", "0.3", ",", "ord", "=", "np", ".", "inf", ",", "clip_min", "=", "None", ",", "clip_max", "=", "None", ",", "targeted", "=", "False", ",", "sanity_checks", "=", "True", ")", ":", "asserts", "=", "[", "]", "# If a data range was specified, check that the input was in that range", "if", "clip_min", "is", "not", "None", ":", "asserts", ".", "append", "(", "utils_tf", ".", "assert_greater_equal", "(", "x", ",", "tf", ".", "cast", "(", "clip_min", ",", "x", ".", "dtype", ")", ")", ")", "if", "clip_max", "is", "not", "None", ":", "asserts", ".", "append", "(", "utils_tf", ".", "assert_less_equal", "(", "x", ",", "tf", ".", "cast", "(", "clip_max", ",", "x", ".", "dtype", ")", ")", ")", "# Make sure the caller has not passed probs by accident", "assert", "logits", ".", "op", ".", "type", "!=", "'Softmax'", "if", "y", "is", "None", ":", "# Using model predictions as ground truth to avoid label leaking", "preds_max", "=", "reduce_max", "(", "logits", ",", "1", ",", "keepdims", "=", "True", ")", "y", "=", "tf", ".", "to_float", "(", "tf", ".", "equal", "(", "logits", ",", "preds_max", ")", ")", "y", "=", "tf", ".", "stop_gradient", "(", "y", ")", "y", "=", "y", "/", "reduce_sum", "(", "y", ",", "1", ",", "keepdims", "=", "True", ")", "# Compute loss", "loss", "=", "softmax_cross_entropy_with_logits", "(", "labels", "=", "y", ",", "logits", "=", "logits", ")", "if", "targeted", ":", "loss", "=", "-", "loss", "# Define gradient of loss wrt input", "grad", ",", "=", "tf", ".", "gradients", "(", "loss", ",", "x", ")", "optimal_perturbation", "=", "optimize_linear", "(", "grad", ",", "eps", ",", "ord", ")", "# Add perturbation to original example to obtain adversarial example", "adv_x", "=", "x", "+", "optimal_perturbation", "# If clipping is needed, reset all values outside of [clip_min, clip_max]", "if", "(", "clip_min", "is", "not", "None", ")", "or", "(", "clip_max", "is", "not", "None", ")", ":", "# We don't currently support one-sided clipping", "assert", "clip_min", "is", "not", "None", "and", "clip_max", "is", "not", "None", "adv_x", "=", "utils_tf", ".", "clip_by_value", "(", "adv_x", ",", "clip_min", ",", "clip_max", ")", "if", "sanity_checks", ":", "with", "tf", ".", "control_dependencies", "(", "asserts", ")", ":", "adv_x", "=", "tf", ".", "identity", "(", "adv_x", ")", "return", "adv_x" ]
TensorFlow implementation of the Fast Gradient Method. :param x: the input placeholder :param logits: output of model.get_logits :param y: (optional) A placeholder for the true labels. If targeted is true, then provide the target label. Otherwise, only provide this parameter if you'd like to use true labels when crafting adversarial samples. Otherwise, model predictions are used as labels to avoid the "label leaking" effect (explained in this paper: https://arxiv.org/abs/1611.01236). Default is None. Labels should be one-hot-encoded. :param eps: the epsilon (input variation parameter) :param ord: (optional) Order of the norm (mimics NumPy). Possible values: np.inf, 1 or 2. :param clip_min: Minimum float value for adversarial example components :param clip_max: Maximum float value for adversarial example components :param targeted: Is the attack targeted or untargeted? Untargeted, the default, will try to make the label incorrect. Targeted will instead try to move in the direction of being more like y. :return: a tensor for the adversarial example
[ "TensorFlow", "implementation", "of", "the", "Fast", "Gradient", "Method", ".", ":", "param", "x", ":", "the", "input", "placeholder", ":", "param", "logits", ":", "output", "of", "model", ".", "get_logits", ":", "param", "y", ":", "(", "optional", ")", "A", "placeholder", "for", "the", "true", "labels", ".", "If", "targeted", "is", "true", "then", "provide", "the", "target", "label", ".", "Otherwise", "only", "provide", "this", "parameter", "if", "you", "d", "like", "to", "use", "true", "labels", "when", "crafting", "adversarial", "samples", ".", "Otherwise", "model", "predictions", "are", "used", "as", "labels", "to", "avoid", "the", "label", "leaking", "effect", "(", "explained", "in", "this", "paper", ":", "https", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1611", ".", "01236", ")", ".", "Default", "is", "None", ".", "Labels", "should", "be", "one", "-", "hot", "-", "encoded", ".", ":", "param", "eps", ":", "the", "epsilon", "(", "input", "variation", "parameter", ")", ":", "param", "ord", ":", "(", "optional", ")", "Order", "of", "the", "norm", "(", "mimics", "NumPy", ")", ".", "Possible", "values", ":", "np", ".", "inf", "1", "or", "2", ".", ":", "param", "clip_min", ":", "Minimum", "float", "value", "for", "adversarial", "example", "components", ":", "param", "clip_max", ":", "Maximum", "float", "value", "for", "adversarial", "example", "components", ":", "param", "targeted", ":", "Is", "the", "attack", "targeted", "or", "untargeted?", "Untargeted", "the", "default", "will", "try", "to", "make", "the", "label", "incorrect", ".", "Targeted", "will", "instead", "try", "to", "move", "in", "the", "direction", "of", "being", "more", "like", "y", ".", ":", "return", ":", "a", "tensor", "for", "the", "adversarial", "example" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/fast_gradient_method.py#L119-L194
train
tensorflow/cleverhans
cleverhans/attacks/fast_gradient_method.py
optimize_linear
def optimize_linear(grad, eps, ord=np.inf): """ Solves for the optimal input to a linear function under a norm constraint. Optimal_perturbation = argmax_{eta, ||eta||_{ord} < eps} dot(eta, grad) :param grad: tf tensor containing a batch of gradients :param eps: float scalar specifying size of constraint region :param ord: int specifying order of norm :returns: tf tensor containing optimal perturbation """ # In Python 2, the `list` call in the following line is redundant / harmless. # In Python 3, the `list` call is needed to convert the iterator returned by `range` into a list. red_ind = list(range(1, len(grad.get_shape()))) avoid_zero_div = 1e-12 if ord == np.inf: # Take sign of gradient optimal_perturbation = tf.sign(grad) # The following line should not change the numerical results. # It applies only because `optimal_perturbation` is the output of # a `sign` op, which has zero derivative anyway. # It should not be applied for the other norms, where the # perturbation has a non-zero derivative. optimal_perturbation = tf.stop_gradient(optimal_perturbation) elif ord == 1: abs_grad = tf.abs(grad) sign = tf.sign(grad) max_abs_grad = tf.reduce_max(abs_grad, red_ind, keepdims=True) tied_for_max = tf.to_float(tf.equal(abs_grad, max_abs_grad)) num_ties = tf.reduce_sum(tied_for_max, red_ind, keepdims=True) optimal_perturbation = sign * tied_for_max / num_ties elif ord == 2: square = tf.maximum(avoid_zero_div, reduce_sum(tf.square(grad), reduction_indices=red_ind, keepdims=True)) optimal_perturbation = grad / tf.sqrt(square) else: raise NotImplementedError("Only L-inf, L1 and L2 norms are " "currently implemented.") # Scale perturbation to be the solution for the norm=eps rather than # norm=1 problem scaled_perturbation = utils_tf.mul(eps, optimal_perturbation) return scaled_perturbation
python
def optimize_linear(grad, eps, ord=np.inf): """ Solves for the optimal input to a linear function under a norm constraint. Optimal_perturbation = argmax_{eta, ||eta||_{ord} < eps} dot(eta, grad) :param grad: tf tensor containing a batch of gradients :param eps: float scalar specifying size of constraint region :param ord: int specifying order of norm :returns: tf tensor containing optimal perturbation """ # In Python 2, the `list` call in the following line is redundant / harmless. # In Python 3, the `list` call is needed to convert the iterator returned by `range` into a list. red_ind = list(range(1, len(grad.get_shape()))) avoid_zero_div = 1e-12 if ord == np.inf: # Take sign of gradient optimal_perturbation = tf.sign(grad) # The following line should not change the numerical results. # It applies only because `optimal_perturbation` is the output of # a `sign` op, which has zero derivative anyway. # It should not be applied for the other norms, where the # perturbation has a non-zero derivative. optimal_perturbation = tf.stop_gradient(optimal_perturbation) elif ord == 1: abs_grad = tf.abs(grad) sign = tf.sign(grad) max_abs_grad = tf.reduce_max(abs_grad, red_ind, keepdims=True) tied_for_max = tf.to_float(tf.equal(abs_grad, max_abs_grad)) num_ties = tf.reduce_sum(tied_for_max, red_ind, keepdims=True) optimal_perturbation = sign * tied_for_max / num_ties elif ord == 2: square = tf.maximum(avoid_zero_div, reduce_sum(tf.square(grad), reduction_indices=red_ind, keepdims=True)) optimal_perturbation = grad / tf.sqrt(square) else: raise NotImplementedError("Only L-inf, L1 and L2 norms are " "currently implemented.") # Scale perturbation to be the solution for the norm=eps rather than # norm=1 problem scaled_perturbation = utils_tf.mul(eps, optimal_perturbation) return scaled_perturbation
[ "def", "optimize_linear", "(", "grad", ",", "eps", ",", "ord", "=", "np", ".", "inf", ")", ":", "# In Python 2, the `list` call in the following line is redundant / harmless.", "# In Python 3, the `list` call is needed to convert the iterator returned by `range` into a list.", "red_ind", "=", "list", "(", "range", "(", "1", ",", "len", "(", "grad", ".", "get_shape", "(", ")", ")", ")", ")", "avoid_zero_div", "=", "1e-12", "if", "ord", "==", "np", ".", "inf", ":", "# Take sign of gradient", "optimal_perturbation", "=", "tf", ".", "sign", "(", "grad", ")", "# The following line should not change the numerical results.", "# It applies only because `optimal_perturbation` is the output of", "# a `sign` op, which has zero derivative anyway.", "# It should not be applied for the other norms, where the", "# perturbation has a non-zero derivative.", "optimal_perturbation", "=", "tf", ".", "stop_gradient", "(", "optimal_perturbation", ")", "elif", "ord", "==", "1", ":", "abs_grad", "=", "tf", ".", "abs", "(", "grad", ")", "sign", "=", "tf", ".", "sign", "(", "grad", ")", "max_abs_grad", "=", "tf", ".", "reduce_max", "(", "abs_grad", ",", "red_ind", ",", "keepdims", "=", "True", ")", "tied_for_max", "=", "tf", ".", "to_float", "(", "tf", ".", "equal", "(", "abs_grad", ",", "max_abs_grad", ")", ")", "num_ties", "=", "tf", ".", "reduce_sum", "(", "tied_for_max", ",", "red_ind", ",", "keepdims", "=", "True", ")", "optimal_perturbation", "=", "sign", "*", "tied_for_max", "/", "num_ties", "elif", "ord", "==", "2", ":", "square", "=", "tf", ".", "maximum", "(", "avoid_zero_div", ",", "reduce_sum", "(", "tf", ".", "square", "(", "grad", ")", ",", "reduction_indices", "=", "red_ind", ",", "keepdims", "=", "True", ")", ")", "optimal_perturbation", "=", "grad", "/", "tf", ".", "sqrt", "(", "square", ")", "else", ":", "raise", "NotImplementedError", "(", "\"Only L-inf, L1 and L2 norms are \"", "\"currently implemented.\"", ")", "# Scale perturbation to be the solution for the norm=eps rather than", "# norm=1 problem", "scaled_perturbation", "=", "utils_tf", ".", "mul", "(", "eps", ",", "optimal_perturbation", ")", "return", "scaled_perturbation" ]
Solves for the optimal input to a linear function under a norm constraint. Optimal_perturbation = argmax_{eta, ||eta||_{ord} < eps} dot(eta, grad) :param grad: tf tensor containing a batch of gradients :param eps: float scalar specifying size of constraint region :param ord: int specifying order of norm :returns: tf tensor containing optimal perturbation
[ "Solves", "for", "the", "optimal", "input", "to", "a", "linear", "function", "under", "a", "norm", "constraint", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/fast_gradient_method.py#L197-L243
train
tensorflow/cleverhans
cleverhans/attacks/fast_gradient_method.py
FastGradientMethod.generate
def generate(self, x, **kwargs): """ Returns the graph for Fast Gradient Method adversarial examples. :param x: The model's symbolic inputs. :param kwargs: See `parse_params` """ # Parse and save attack-specific parameters assert self.parse_params(**kwargs) labels, _nb_classes = self.get_or_guess_labels(x, kwargs) return fgm( x, self.model.get_logits(x), y=labels, eps=self.eps, ord=self.ord, clip_min=self.clip_min, clip_max=self.clip_max, targeted=(self.y_target is not None), sanity_checks=self.sanity_checks)
python
def generate(self, x, **kwargs): """ Returns the graph for Fast Gradient Method adversarial examples. :param x: The model's symbolic inputs. :param kwargs: See `parse_params` """ # Parse and save attack-specific parameters assert self.parse_params(**kwargs) labels, _nb_classes = self.get_or_guess_labels(x, kwargs) return fgm( x, self.model.get_logits(x), y=labels, eps=self.eps, ord=self.ord, clip_min=self.clip_min, clip_max=self.clip_max, targeted=(self.y_target is not None), sanity_checks=self.sanity_checks)
[ "def", "generate", "(", "self", ",", "x", ",", "*", "*", "kwargs", ")", ":", "# Parse and save attack-specific parameters", "assert", "self", ".", "parse_params", "(", "*", "*", "kwargs", ")", "labels", ",", "_nb_classes", "=", "self", ".", "get_or_guess_labels", "(", "x", ",", "kwargs", ")", "return", "fgm", "(", "x", ",", "self", ".", "model", ".", "get_logits", "(", "x", ")", ",", "y", "=", "labels", ",", "eps", "=", "self", ".", "eps", ",", "ord", "=", "self", ".", "ord", ",", "clip_min", "=", "self", ".", "clip_min", ",", "clip_max", "=", "self", ".", "clip_max", ",", "targeted", "=", "(", "self", ".", "y_target", "is", "not", "None", ")", ",", "sanity_checks", "=", "self", ".", "sanity_checks", ")" ]
Returns the graph for Fast Gradient Method adversarial examples. :param x: The model's symbolic inputs. :param kwargs: See `parse_params`
[ "Returns", "the", "graph", "for", "Fast", "Gradient", "Method", "adversarial", "examples", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/fast_gradient_method.py#L40-L61
train
tensorflow/cleverhans
cleverhans/experimental/certification/nn.py
load_network_from_checkpoint
def load_network_from_checkpoint(checkpoint, model_json, input_shape=None): """Function to read the weights from checkpoint based on json description. Args: checkpoint: tensorflow checkpoint with trained model to verify model_json: path of json file with model description of the network list of dictionary items for each layer containing 'type', 'weight_var', 'bias_var' and 'is_transpose' 'type'is one of {'ff', 'ff_relu' or 'conv'}; 'weight_var' is the name of tf variable for weights of layer i; 'bias_var' is the name of tf variable for bias of layer i; 'is_transpose' is set to True if the weights have to be transposed as per convention Note that last layer is always feedforward net_weights: list of numpy matrices of weights of each layer convention: x[i+1] = W[i] x[i] net_biases: list of numpy arrays of biases of each layer net_layer_types: type of each layer ['ff' or 'ff_relu' or 'ff_conv' or 'ff_conv_relu'] 'ff': Simple feedforward layer with no activations 'ff_relu': Simple feedforward layer with ReLU activations 'ff_conv': Convolution layer with no activation 'ff_conv_relu': Convolution layer with ReLU activation Raises: ValueError: If layer_types are invalid or variable names not found in checkpoint """ # Load checkpoint reader = tf.train.load_checkpoint(checkpoint) variable_map = reader.get_variable_to_shape_map() checkpoint_variable_names = variable_map.keys() # Parse JSON file for names with tf.gfile.Open(model_json) as f: list_model_var = json.load(f) net_layer_types = [] net_weights = [] net_biases = [] cnn_params = [] # Checking validity of the input and adding to list for layer_model_var in list_model_var: if layer_model_var['type'] not in {'ff', 'ff_relu', 'conv'}: raise ValueError('Invalid layer type in description') if (layer_model_var['weight_var'] not in checkpoint_variable_names or layer_model_var['bias_var'] not in checkpoint_variable_names): raise ValueError('Variable names not found in checkpoint') net_layer_types.append(layer_model_var['type']) layer_weight = reader.get_tensor(layer_model_var['weight_var']) layer_bias = reader.get_tensor(layer_model_var['bias_var']) # TODO(aditirag): is there a way to automatically check when to transpose # We want weights W such that x^{i+1} = W^i x^i + b^i # Can think of a hack involving matching shapes but if shapes are equal # it can be ambiguous if layer_model_var['type'] in {'ff', 'ff_relu'}: layer_weight = np.transpose(layer_weight) cnn_params.append(None) if layer_model_var['type'] in {'conv'}: if 'stride' not in layer_model_var or 'padding' not in layer_model_var: raise ValueError('Please define stride and padding for conv layers.') cnn_params.append({'stride': layer_model_var['stride'], 'padding': layer_model_var['padding']}) net_weights.append(layer_weight) net_biases.append(np.reshape(layer_bias, (np.size(layer_bias), 1))) return NeuralNetwork(net_weights, net_biases, net_layer_types, input_shape, cnn_params)
python
def load_network_from_checkpoint(checkpoint, model_json, input_shape=None): """Function to read the weights from checkpoint based on json description. Args: checkpoint: tensorflow checkpoint with trained model to verify model_json: path of json file with model description of the network list of dictionary items for each layer containing 'type', 'weight_var', 'bias_var' and 'is_transpose' 'type'is one of {'ff', 'ff_relu' or 'conv'}; 'weight_var' is the name of tf variable for weights of layer i; 'bias_var' is the name of tf variable for bias of layer i; 'is_transpose' is set to True if the weights have to be transposed as per convention Note that last layer is always feedforward net_weights: list of numpy matrices of weights of each layer convention: x[i+1] = W[i] x[i] net_biases: list of numpy arrays of biases of each layer net_layer_types: type of each layer ['ff' or 'ff_relu' or 'ff_conv' or 'ff_conv_relu'] 'ff': Simple feedforward layer with no activations 'ff_relu': Simple feedforward layer with ReLU activations 'ff_conv': Convolution layer with no activation 'ff_conv_relu': Convolution layer with ReLU activation Raises: ValueError: If layer_types are invalid or variable names not found in checkpoint """ # Load checkpoint reader = tf.train.load_checkpoint(checkpoint) variable_map = reader.get_variable_to_shape_map() checkpoint_variable_names = variable_map.keys() # Parse JSON file for names with tf.gfile.Open(model_json) as f: list_model_var = json.load(f) net_layer_types = [] net_weights = [] net_biases = [] cnn_params = [] # Checking validity of the input and adding to list for layer_model_var in list_model_var: if layer_model_var['type'] not in {'ff', 'ff_relu', 'conv'}: raise ValueError('Invalid layer type in description') if (layer_model_var['weight_var'] not in checkpoint_variable_names or layer_model_var['bias_var'] not in checkpoint_variable_names): raise ValueError('Variable names not found in checkpoint') net_layer_types.append(layer_model_var['type']) layer_weight = reader.get_tensor(layer_model_var['weight_var']) layer_bias = reader.get_tensor(layer_model_var['bias_var']) # TODO(aditirag): is there a way to automatically check when to transpose # We want weights W such that x^{i+1} = W^i x^i + b^i # Can think of a hack involving matching shapes but if shapes are equal # it can be ambiguous if layer_model_var['type'] in {'ff', 'ff_relu'}: layer_weight = np.transpose(layer_weight) cnn_params.append(None) if layer_model_var['type'] in {'conv'}: if 'stride' not in layer_model_var or 'padding' not in layer_model_var: raise ValueError('Please define stride and padding for conv layers.') cnn_params.append({'stride': layer_model_var['stride'], 'padding': layer_model_var['padding']}) net_weights.append(layer_weight) net_biases.append(np.reshape(layer_bias, (np.size(layer_bias), 1))) return NeuralNetwork(net_weights, net_biases, net_layer_types, input_shape, cnn_params)
[ "def", "load_network_from_checkpoint", "(", "checkpoint", ",", "model_json", ",", "input_shape", "=", "None", ")", ":", "# Load checkpoint", "reader", "=", "tf", ".", "train", ".", "load_checkpoint", "(", "checkpoint", ")", "variable_map", "=", "reader", ".", "get_variable_to_shape_map", "(", ")", "checkpoint_variable_names", "=", "variable_map", ".", "keys", "(", ")", "# Parse JSON file for names", "with", "tf", ".", "gfile", ".", "Open", "(", "model_json", ")", "as", "f", ":", "list_model_var", "=", "json", ".", "load", "(", "f", ")", "net_layer_types", "=", "[", "]", "net_weights", "=", "[", "]", "net_biases", "=", "[", "]", "cnn_params", "=", "[", "]", "# Checking validity of the input and adding to list", "for", "layer_model_var", "in", "list_model_var", ":", "if", "layer_model_var", "[", "'type'", "]", "not", "in", "{", "'ff'", ",", "'ff_relu'", ",", "'conv'", "}", ":", "raise", "ValueError", "(", "'Invalid layer type in description'", ")", "if", "(", "layer_model_var", "[", "'weight_var'", "]", "not", "in", "checkpoint_variable_names", "or", "layer_model_var", "[", "'bias_var'", "]", "not", "in", "checkpoint_variable_names", ")", ":", "raise", "ValueError", "(", "'Variable names not found in checkpoint'", ")", "net_layer_types", ".", "append", "(", "layer_model_var", "[", "'type'", "]", ")", "layer_weight", "=", "reader", ".", "get_tensor", "(", "layer_model_var", "[", "'weight_var'", "]", ")", "layer_bias", "=", "reader", ".", "get_tensor", "(", "layer_model_var", "[", "'bias_var'", "]", ")", "# TODO(aditirag): is there a way to automatically check when to transpose", "# We want weights W such that x^{i+1} = W^i x^i + b^i", "# Can think of a hack involving matching shapes but if shapes are equal", "# it can be ambiguous", "if", "layer_model_var", "[", "'type'", "]", "in", "{", "'ff'", ",", "'ff_relu'", "}", ":", "layer_weight", "=", "np", ".", "transpose", "(", "layer_weight", ")", "cnn_params", ".", "append", "(", "None", ")", "if", "layer_model_var", "[", "'type'", "]", "in", "{", "'conv'", "}", ":", "if", "'stride'", "not", "in", "layer_model_var", "or", "'padding'", "not", "in", "layer_model_var", ":", "raise", "ValueError", "(", "'Please define stride and padding for conv layers.'", ")", "cnn_params", ".", "append", "(", "{", "'stride'", ":", "layer_model_var", "[", "'stride'", "]", ",", "'padding'", ":", "layer_model_var", "[", "'padding'", "]", "}", ")", "net_weights", ".", "append", "(", "layer_weight", ")", "net_biases", ".", "append", "(", "np", ".", "reshape", "(", "layer_bias", ",", "(", "np", ".", "size", "(", "layer_bias", ")", ",", "1", ")", ")", ")", "return", "NeuralNetwork", "(", "net_weights", ",", "net_biases", ",", "net_layer_types", ",", "input_shape", ",", "cnn_params", ")" ]
Function to read the weights from checkpoint based on json description. Args: checkpoint: tensorflow checkpoint with trained model to verify model_json: path of json file with model description of the network list of dictionary items for each layer containing 'type', 'weight_var', 'bias_var' and 'is_transpose' 'type'is one of {'ff', 'ff_relu' or 'conv'}; 'weight_var' is the name of tf variable for weights of layer i; 'bias_var' is the name of tf variable for bias of layer i; 'is_transpose' is set to True if the weights have to be transposed as per convention Note that last layer is always feedforward net_weights: list of numpy matrices of weights of each layer convention: x[i+1] = W[i] x[i] net_biases: list of numpy arrays of biases of each layer net_layer_types: type of each layer ['ff' or 'ff_relu' or 'ff_conv' or 'ff_conv_relu'] 'ff': Simple feedforward layer with no activations 'ff_relu': Simple feedforward layer with ReLU activations 'ff_conv': Convolution layer with no activation 'ff_conv_relu': Convolution layer with ReLU activation Raises: ValueError: If layer_types are invalid or variable names not found in checkpoint
[ "Function", "to", "read", "the", "weights", "from", "checkpoint", "based", "on", "json", "description", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/nn.py#L161-L226
train
tensorflow/cleverhans
cleverhans/experimental/certification/nn.py
NeuralNetwork.forward_pass
def forward_pass(self, vector, layer_index, is_transpose=False, is_abs=False): """Performs forward pass through the layer weights at layer_index. Args: vector: vector that has to be passed through in forward pass layer_index: index of the layer is_transpose: whether the weights of the layer have to be transposed is_abs: whether to take the absolute value of the weights Returns: tensor that corresponds to the forward pass through the layer Raises: ValueError: if the layer_index is negative or more than num hidden layers """ if(layer_index < 0 or layer_index > self.num_hidden_layers): raise ValueError('Invalid layer index') layer_type = self.layer_types[layer_index] weight = self.weights[layer_index] if is_abs: weight = tf.abs(weight) if is_transpose: vector = tf.reshape(vector, self.output_shapes[layer_index]) else: vector = tf.reshape(vector, self.input_shapes[layer_index]) if layer_type in {'ff', 'ff_relu'}: if is_transpose: weight = tf.transpose(weight) return_vector = tf.matmul(weight, vector) elif layer_type in {'conv', 'conv_relu'}: if is_transpose: return_vector = tf.nn.conv2d_transpose(vector, weight, output_shape=self.input_shapes[layer_index], strides=[1, self.cnn_params[layer_index]['stride'], self.cnn_params[layer_index]['stride'], 1], padding=self.cnn_params[layer_index]['padding']) else: return_vector = tf.nn.conv2d(vector, weight, strides=[1, self.cnn_params[layer_index]['stride'], self.cnn_params[layer_index]['stride'], 1], padding=self.cnn_params[layer_index]['padding']) else: raise NotImplementedError('Unsupported layer type: {0}'.format(layer_type)) if is_transpose: return tf.reshape(return_vector, (self.sizes[layer_index], 1)) return tf.reshape(return_vector, (self.sizes[layer_index + 1], 1))
python
def forward_pass(self, vector, layer_index, is_transpose=False, is_abs=False): """Performs forward pass through the layer weights at layer_index. Args: vector: vector that has to be passed through in forward pass layer_index: index of the layer is_transpose: whether the weights of the layer have to be transposed is_abs: whether to take the absolute value of the weights Returns: tensor that corresponds to the forward pass through the layer Raises: ValueError: if the layer_index is negative or more than num hidden layers """ if(layer_index < 0 or layer_index > self.num_hidden_layers): raise ValueError('Invalid layer index') layer_type = self.layer_types[layer_index] weight = self.weights[layer_index] if is_abs: weight = tf.abs(weight) if is_transpose: vector = tf.reshape(vector, self.output_shapes[layer_index]) else: vector = tf.reshape(vector, self.input_shapes[layer_index]) if layer_type in {'ff', 'ff_relu'}: if is_transpose: weight = tf.transpose(weight) return_vector = tf.matmul(weight, vector) elif layer_type in {'conv', 'conv_relu'}: if is_transpose: return_vector = tf.nn.conv2d_transpose(vector, weight, output_shape=self.input_shapes[layer_index], strides=[1, self.cnn_params[layer_index]['stride'], self.cnn_params[layer_index]['stride'], 1], padding=self.cnn_params[layer_index]['padding']) else: return_vector = tf.nn.conv2d(vector, weight, strides=[1, self.cnn_params[layer_index]['stride'], self.cnn_params[layer_index]['stride'], 1], padding=self.cnn_params[layer_index]['padding']) else: raise NotImplementedError('Unsupported layer type: {0}'.format(layer_type)) if is_transpose: return tf.reshape(return_vector, (self.sizes[layer_index], 1)) return tf.reshape(return_vector, (self.sizes[layer_index + 1], 1))
[ "def", "forward_pass", "(", "self", ",", "vector", ",", "layer_index", ",", "is_transpose", "=", "False", ",", "is_abs", "=", "False", ")", ":", "if", "(", "layer_index", "<", "0", "or", "layer_index", ">", "self", ".", "num_hidden_layers", ")", ":", "raise", "ValueError", "(", "'Invalid layer index'", ")", "layer_type", "=", "self", ".", "layer_types", "[", "layer_index", "]", "weight", "=", "self", ".", "weights", "[", "layer_index", "]", "if", "is_abs", ":", "weight", "=", "tf", ".", "abs", "(", "weight", ")", "if", "is_transpose", ":", "vector", "=", "tf", ".", "reshape", "(", "vector", ",", "self", ".", "output_shapes", "[", "layer_index", "]", ")", "else", ":", "vector", "=", "tf", ".", "reshape", "(", "vector", ",", "self", ".", "input_shapes", "[", "layer_index", "]", ")", "if", "layer_type", "in", "{", "'ff'", ",", "'ff_relu'", "}", ":", "if", "is_transpose", ":", "weight", "=", "tf", ".", "transpose", "(", "weight", ")", "return_vector", "=", "tf", ".", "matmul", "(", "weight", ",", "vector", ")", "elif", "layer_type", "in", "{", "'conv'", ",", "'conv_relu'", "}", ":", "if", "is_transpose", ":", "return_vector", "=", "tf", ".", "nn", ".", "conv2d_transpose", "(", "vector", ",", "weight", ",", "output_shape", "=", "self", ".", "input_shapes", "[", "layer_index", "]", ",", "strides", "=", "[", "1", ",", "self", ".", "cnn_params", "[", "layer_index", "]", "[", "'stride'", "]", ",", "self", ".", "cnn_params", "[", "layer_index", "]", "[", "'stride'", "]", ",", "1", "]", ",", "padding", "=", "self", ".", "cnn_params", "[", "layer_index", "]", "[", "'padding'", "]", ")", "else", ":", "return_vector", "=", "tf", ".", "nn", ".", "conv2d", "(", "vector", ",", "weight", ",", "strides", "=", "[", "1", ",", "self", ".", "cnn_params", "[", "layer_index", "]", "[", "'stride'", "]", ",", "self", ".", "cnn_params", "[", "layer_index", "]", "[", "'stride'", "]", ",", "1", "]", ",", "padding", "=", "self", ".", "cnn_params", "[", "layer_index", "]", "[", "'padding'", "]", ")", "else", ":", "raise", "NotImplementedError", "(", "'Unsupported layer type: {0}'", ".", "format", "(", "layer_type", ")", ")", "if", "is_transpose", ":", "return", "tf", ".", "reshape", "(", "return_vector", ",", "(", "self", ".", "sizes", "[", "layer_index", "]", ",", "1", ")", ")", "return", "tf", ".", "reshape", "(", "return_vector", ",", "(", "self", ".", "sizes", "[", "layer_index", "+", "1", "]", ",", "1", ")", ")" ]
Performs forward pass through the layer weights at layer_index. Args: vector: vector that has to be passed through in forward pass layer_index: index of the layer is_transpose: whether the weights of the layer have to be transposed is_abs: whether to take the absolute value of the weights Returns: tensor that corresponds to the forward pass through the layer Raises: ValueError: if the layer_index is negative or more than num hidden layers
[ "Performs", "forward", "pass", "through", "the", "layer", "weights", "at", "layer_index", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/nn.py#L111-L159
train
tensorflow/cleverhans
cleverhans/devtools/version.py
dev_version
def dev_version(): """ Returns a hexdigest of all the python files in the module. """ md5_hash = hashlib.md5() py_files = sorted(list_files(suffix=".py")) if not py_files: return '' for filename in py_files: with open(filename, 'rb') as fobj: content = fobj.read() md5_hash.update(content) return md5_hash.hexdigest()
python
def dev_version(): """ Returns a hexdigest of all the python files in the module. """ md5_hash = hashlib.md5() py_files = sorted(list_files(suffix=".py")) if not py_files: return '' for filename in py_files: with open(filename, 'rb') as fobj: content = fobj.read() md5_hash.update(content) return md5_hash.hexdigest()
[ "def", "dev_version", "(", ")", ":", "md5_hash", "=", "hashlib", ".", "md5", "(", ")", "py_files", "=", "sorted", "(", "list_files", "(", "suffix", "=", "\".py\"", ")", ")", "if", "not", "py_files", ":", "return", "''", "for", "filename", "in", "py_files", ":", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "fobj", ":", "content", "=", "fobj", ".", "read", "(", ")", "md5_hash", ".", "update", "(", "content", ")", "return", "md5_hash", ".", "hexdigest", "(", ")" ]
Returns a hexdigest of all the python files in the module.
[ "Returns", "a", "hexdigest", "of", "all", "the", "python", "files", "in", "the", "module", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/devtools/version.py#L11-L24
train
tensorflow/cleverhans
scripts/print_report.py
current
def current(report): """ The current implementation of report printing. :param report: ConfidenceReport """ if hasattr(report, "completed"): if report.completed: print("Report completed") else: print("REPORT NOT COMPLETED") else: warnings.warn("This report does not indicate whether it is completed. Support for reports without a `completed`" "field may be dropped on or after 2019-05-11.") for key in report: covered = report[key].confidence > 0.5 wrong = 1. - report[key].correctness failure_rate = (covered * wrong).mean() print(key, 'failure rate at t=.5', failure_rate) print(key, 'accuracy at t=0', report[key].correctness.mean())
python
def current(report): """ The current implementation of report printing. :param report: ConfidenceReport """ if hasattr(report, "completed"): if report.completed: print("Report completed") else: print("REPORT NOT COMPLETED") else: warnings.warn("This report does not indicate whether it is completed. Support for reports without a `completed`" "field may be dropped on or after 2019-05-11.") for key in report: covered = report[key].confidence > 0.5 wrong = 1. - report[key].correctness failure_rate = (covered * wrong).mean() print(key, 'failure rate at t=.5', failure_rate) print(key, 'accuracy at t=0', report[key].correctness.mean())
[ "def", "current", "(", "report", ")", ":", "if", "hasattr", "(", "report", ",", "\"completed\"", ")", ":", "if", "report", ".", "completed", ":", "print", "(", "\"Report completed\"", ")", "else", ":", "print", "(", "\"REPORT NOT COMPLETED\"", ")", "else", ":", "warnings", ".", "warn", "(", "\"This report does not indicate whether it is completed. Support for reports without a `completed`\"", "\"field may be dropped on or after 2019-05-11.\"", ")", "for", "key", "in", "report", ":", "covered", "=", "report", "[", "key", "]", ".", "confidence", ">", "0.5", "wrong", "=", "1.", "-", "report", "[", "key", "]", ".", "correctness", "failure_rate", "=", "(", "covered", "*", "wrong", ")", ".", "mean", "(", ")", "print", "(", "key", ",", "'failure rate at t=.5'", ",", "failure_rate", ")", "print", "(", "key", ",", "'accuracy at t=0'", ",", "report", "[", "key", "]", ".", "correctness", ".", "mean", "(", ")", ")" ]
The current implementation of report printing. :param report: ConfidenceReport
[ "The", "current", "implementation", "of", "report", "printing", ".", ":", "param", "report", ":", "ConfidenceReport" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/scripts/print_report.py#L23-L41
train
tensorflow/cleverhans
scripts/print_report.py
deprecated
def deprecated(report): """ The deprecated implementation of report printing. :param report: dict """ warnings.warn("Printing dict-based reports is deprecated. This function " "is included only to support a private development branch " "and may be removed without warning.") for key in report: confidence_name = 'confidence' correctness_name = 'correctness' if confidence_name not in report[key]: confidence_name = 'all_probs' correctness_name = 'correctness_mask' warnings.warn("'all_probs' is used only to temporarily support " "the private development branch. This name can be " "removed at any time without warning.") covered = report[key][confidence_name] > 0.5 wrong = 1. - report[key][correctness_name] failure_rate = (covered * wrong).mean() print(key, 'failure rate at t=.5', failure_rate) print(key, 'accuracy at t=0', report[key][correctness_name].mean())
python
def deprecated(report): """ The deprecated implementation of report printing. :param report: dict """ warnings.warn("Printing dict-based reports is deprecated. This function " "is included only to support a private development branch " "and may be removed without warning.") for key in report: confidence_name = 'confidence' correctness_name = 'correctness' if confidence_name not in report[key]: confidence_name = 'all_probs' correctness_name = 'correctness_mask' warnings.warn("'all_probs' is used only to temporarily support " "the private development branch. This name can be " "removed at any time without warning.") covered = report[key][confidence_name] > 0.5 wrong = 1. - report[key][correctness_name] failure_rate = (covered * wrong).mean() print(key, 'failure rate at t=.5', failure_rate) print(key, 'accuracy at t=0', report[key][correctness_name].mean())
[ "def", "deprecated", "(", "report", ")", ":", "warnings", ".", "warn", "(", "\"Printing dict-based reports is deprecated. This function \"", "\"is included only to support a private development branch \"", "\"and may be removed without warning.\"", ")", "for", "key", "in", "report", ":", "confidence_name", "=", "'confidence'", "correctness_name", "=", "'correctness'", "if", "confidence_name", "not", "in", "report", "[", "key", "]", ":", "confidence_name", "=", "'all_probs'", "correctness_name", "=", "'correctness_mask'", "warnings", ".", "warn", "(", "\"'all_probs' is used only to temporarily support \"", "\"the private development branch. This name can be \"", "\"removed at any time without warning.\"", ")", "covered", "=", "report", "[", "key", "]", "[", "confidence_name", "]", ">", "0.5", "wrong", "=", "1.", "-", "report", "[", "key", "]", "[", "correctness_name", "]", "failure_rate", "=", "(", "covered", "*", "wrong", ")", ".", "mean", "(", ")", "print", "(", "key", ",", "'failure rate at t=.5'", ",", "failure_rate", ")", "print", "(", "key", ",", "'accuracy at t=0'", ",", "report", "[", "key", "]", "[", "correctness_name", "]", ".", "mean", "(", ")", ")" ]
The deprecated implementation of report printing. :param report: dict
[ "The", "deprecated", "implementation", "of", "report", "printing", ".", ":", "param", "report", ":", "dict" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/scripts/print_report.py#L43-L65
train
tensorflow/cleverhans
cleverhans/model_zoo/soft_nearest_neighbor_loss/SNNL_regularized_train.py
SNNL_example
def SNNL_example(train_start=0, train_end=60000, test_start=0, test_end=10000, nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE, learning_rate=LEARNING_RATE, nb_filters=NB_FILTERS, SNNL_factor=SNNL_FACTOR, output_dir=OUTPUT_DIR): """ A simple model trained to minimize Cross Entropy and Maximize Soft Nearest Neighbor Loss at each internal layer. This outputs a TSNE of the sign of the adversarial gradients of a trained model. A model with a negative SNNL_factor will show little or no class clusters, while a model with a 0 SNNL_factor will have class clusters in the adversarial gradient direction. :param train_start: index of first training set example :param train_end: index of last training set example :param test_start: index of first test set example :param test_end: index of last test set example :param nb_epochs: number of epochs to train model :param batch_size: size of training batches :param learning_rate: learning rate for training :param SNNL_factor: multiplier for Soft Nearest Neighbor Loss :return: an AccuracyReport object """ # Object used to keep track of (and return) key accuracies report = AccuracyReport() # Set TF random seed to improve reproducibility tf.set_random_seed(1234) # Set logging level to see debug information set_log_level(logging.DEBUG) # Create TF session sess = tf.Session() # Get MNIST data mnist = MNIST(train_start=train_start, train_end=train_end, test_start=test_start, test_end=test_end) x_train, y_train = mnist.get_set('train') x_test, y_test = mnist.get_set('test') # Use Image Parameters img_rows, img_cols, nchannels = x_train.shape[1:4] nb_classes = y_train.shape[1] # Define input TF placeholder x = tf.placeholder(tf.float32, shape=(None, img_rows, img_cols, nchannels)) y = tf.placeholder(tf.float32, shape=(None, nb_classes)) # Train an MNIST model train_params = { 'nb_epochs': nb_epochs, 'batch_size': batch_size, 'learning_rate': learning_rate } eval_params = {'batch_size': batch_size} rng = np.random.RandomState([2017, 8, 30]) def do_eval(preds, x_set, y_set, report_key): acc = model_eval(sess, x, y, preds, x_set, y_set, args=eval_params) setattr(report, report_key, acc) print('Test accuracy on legitimate examples: %0.4f' % (acc)) model = ModelBasicCNN('model', nb_classes, nb_filters) preds = model.get_logits(x) cross_entropy_loss = CrossEntropy(model) if not SNNL_factor: loss = cross_entropy_loss else: loss = SNNLCrossEntropy(model, factor=SNNL_factor, optimize_temperature=False) def evaluate(): do_eval(preds, x_test, y_test, 'clean_train_clean_eval') train(sess, loss, x_train, y_train, evaluate=evaluate, args=train_params, rng=rng, var_list=model.get_params()) do_eval(preds, x_train, y_train, 'train_clean_train_clean_eval') def imscatter(points, images, ax=None, zoom=1, cmap="hot"): if ax is None: ax = plt.gca() artists = [] i = 0 if not isinstance(cmap, list): cmap = [cmap] * len(points) for x0, y0 in points: transformed = (images[i] - np.min(images[i])) / \ (np.max(images[i]) - np.min(images[i])) im = OffsetImage(transformed[:, :, 0], zoom=zoom, cmap=cmap[i]) ab = AnnotationBbox(im, (x0, y0), xycoords='data', frameon=False) artists.append(ax.add_artist(ab)) i += 1 ax.update_datalim(np.column_stack(np.transpose(points))) ax.autoscale() ax.get_xaxis().set_ticks([]) ax.get_yaxis().set_ticks([]) return artists adv_grads = tf.sign(tf.gradients(cross_entropy_loss.fprop(x, y), x)) feed_dict = {x: x_test[:batch_size], y: y_test[:batch_size]} adv_grads_val = sess.run(adv_grads, feed_dict=feed_dict) adv_grads_val = np.reshape(adv_grads_val, (batch_size, img_rows * img_cols)) X_embedded = TSNE(n_components=2, verbose=0).fit_transform(adv_grads_val) plt.figure(num=None, figsize=(50, 50), dpi=40, facecolor='w', edgecolor='k') plt.title("TSNE of Sign of Adv Gradients, SNNLCrossEntropy Model, factor:" + str(FLAGS.SNNL_factor), fontsize=42) imscatter(X_embedded, x_test[:batch_size], zoom=2, cmap="Purples") plt.savefig(output_dir + 'adversarial_gradients_SNNL_factor_' + str(SNNL_factor) + '.png')
python
def SNNL_example(train_start=0, train_end=60000, test_start=0, test_end=10000, nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE, learning_rate=LEARNING_RATE, nb_filters=NB_FILTERS, SNNL_factor=SNNL_FACTOR, output_dir=OUTPUT_DIR): """ A simple model trained to minimize Cross Entropy and Maximize Soft Nearest Neighbor Loss at each internal layer. This outputs a TSNE of the sign of the adversarial gradients of a trained model. A model with a negative SNNL_factor will show little or no class clusters, while a model with a 0 SNNL_factor will have class clusters in the adversarial gradient direction. :param train_start: index of first training set example :param train_end: index of last training set example :param test_start: index of first test set example :param test_end: index of last test set example :param nb_epochs: number of epochs to train model :param batch_size: size of training batches :param learning_rate: learning rate for training :param SNNL_factor: multiplier for Soft Nearest Neighbor Loss :return: an AccuracyReport object """ # Object used to keep track of (and return) key accuracies report = AccuracyReport() # Set TF random seed to improve reproducibility tf.set_random_seed(1234) # Set logging level to see debug information set_log_level(logging.DEBUG) # Create TF session sess = tf.Session() # Get MNIST data mnist = MNIST(train_start=train_start, train_end=train_end, test_start=test_start, test_end=test_end) x_train, y_train = mnist.get_set('train') x_test, y_test = mnist.get_set('test') # Use Image Parameters img_rows, img_cols, nchannels = x_train.shape[1:4] nb_classes = y_train.shape[1] # Define input TF placeholder x = tf.placeholder(tf.float32, shape=(None, img_rows, img_cols, nchannels)) y = tf.placeholder(tf.float32, shape=(None, nb_classes)) # Train an MNIST model train_params = { 'nb_epochs': nb_epochs, 'batch_size': batch_size, 'learning_rate': learning_rate } eval_params = {'batch_size': batch_size} rng = np.random.RandomState([2017, 8, 30]) def do_eval(preds, x_set, y_set, report_key): acc = model_eval(sess, x, y, preds, x_set, y_set, args=eval_params) setattr(report, report_key, acc) print('Test accuracy on legitimate examples: %0.4f' % (acc)) model = ModelBasicCNN('model', nb_classes, nb_filters) preds = model.get_logits(x) cross_entropy_loss = CrossEntropy(model) if not SNNL_factor: loss = cross_entropy_loss else: loss = SNNLCrossEntropy(model, factor=SNNL_factor, optimize_temperature=False) def evaluate(): do_eval(preds, x_test, y_test, 'clean_train_clean_eval') train(sess, loss, x_train, y_train, evaluate=evaluate, args=train_params, rng=rng, var_list=model.get_params()) do_eval(preds, x_train, y_train, 'train_clean_train_clean_eval') def imscatter(points, images, ax=None, zoom=1, cmap="hot"): if ax is None: ax = plt.gca() artists = [] i = 0 if not isinstance(cmap, list): cmap = [cmap] * len(points) for x0, y0 in points: transformed = (images[i] - np.min(images[i])) / \ (np.max(images[i]) - np.min(images[i])) im = OffsetImage(transformed[:, :, 0], zoom=zoom, cmap=cmap[i]) ab = AnnotationBbox(im, (x0, y0), xycoords='data', frameon=False) artists.append(ax.add_artist(ab)) i += 1 ax.update_datalim(np.column_stack(np.transpose(points))) ax.autoscale() ax.get_xaxis().set_ticks([]) ax.get_yaxis().set_ticks([]) return artists adv_grads = tf.sign(tf.gradients(cross_entropy_loss.fprop(x, y), x)) feed_dict = {x: x_test[:batch_size], y: y_test[:batch_size]} adv_grads_val = sess.run(adv_grads, feed_dict=feed_dict) adv_grads_val = np.reshape(adv_grads_val, (batch_size, img_rows * img_cols)) X_embedded = TSNE(n_components=2, verbose=0).fit_transform(adv_grads_val) plt.figure(num=None, figsize=(50, 50), dpi=40, facecolor='w', edgecolor='k') plt.title("TSNE of Sign of Adv Gradients, SNNLCrossEntropy Model, factor:" + str(FLAGS.SNNL_factor), fontsize=42) imscatter(X_embedded, x_test[:batch_size], zoom=2, cmap="Purples") plt.savefig(output_dir + 'adversarial_gradients_SNNL_factor_' + str(SNNL_factor) + '.png')
[ "def", "SNNL_example", "(", "train_start", "=", "0", ",", "train_end", "=", "60000", ",", "test_start", "=", "0", ",", "test_end", "=", "10000", ",", "nb_epochs", "=", "NB_EPOCHS", ",", "batch_size", "=", "BATCH_SIZE", ",", "learning_rate", "=", "LEARNING_RATE", ",", "nb_filters", "=", "NB_FILTERS", ",", "SNNL_factor", "=", "SNNL_FACTOR", ",", "output_dir", "=", "OUTPUT_DIR", ")", ":", "# Object used to keep track of (and return) key accuracies", "report", "=", "AccuracyReport", "(", ")", "# Set TF random seed to improve reproducibility", "tf", ".", "set_random_seed", "(", "1234", ")", "# Set logging level to see debug information", "set_log_level", "(", "logging", ".", "DEBUG", ")", "# Create TF session", "sess", "=", "tf", ".", "Session", "(", ")", "# Get MNIST data", "mnist", "=", "MNIST", "(", "train_start", "=", "train_start", ",", "train_end", "=", "train_end", ",", "test_start", "=", "test_start", ",", "test_end", "=", "test_end", ")", "x_train", ",", "y_train", "=", "mnist", ".", "get_set", "(", "'train'", ")", "x_test", ",", "y_test", "=", "mnist", ".", "get_set", "(", "'test'", ")", "# Use Image Parameters", "img_rows", ",", "img_cols", ",", "nchannels", "=", "x_train", ".", "shape", "[", "1", ":", "4", "]", "nb_classes", "=", "y_train", ".", "shape", "[", "1", "]", "# Define input TF placeholder", "x", "=", "tf", ".", "placeholder", "(", "tf", ".", "float32", ",", "shape", "=", "(", "None", ",", "img_rows", ",", "img_cols", ",", "nchannels", ")", ")", "y", "=", "tf", ".", "placeholder", "(", "tf", ".", "float32", ",", "shape", "=", "(", "None", ",", "nb_classes", ")", ")", "# Train an MNIST model", "train_params", "=", "{", "'nb_epochs'", ":", "nb_epochs", ",", "'batch_size'", ":", "batch_size", ",", "'learning_rate'", ":", "learning_rate", "}", "eval_params", "=", "{", "'batch_size'", ":", "batch_size", "}", "rng", "=", "np", ".", "random", ".", "RandomState", "(", "[", "2017", ",", "8", ",", "30", "]", ")", "def", "do_eval", "(", "preds", ",", "x_set", ",", "y_set", ",", "report_key", ")", ":", "acc", "=", "model_eval", "(", "sess", ",", "x", ",", "y", ",", "preds", ",", "x_set", ",", "y_set", ",", "args", "=", "eval_params", ")", "setattr", "(", "report", ",", "report_key", ",", "acc", ")", "print", "(", "'Test accuracy on legitimate examples: %0.4f'", "%", "(", "acc", ")", ")", "model", "=", "ModelBasicCNN", "(", "'model'", ",", "nb_classes", ",", "nb_filters", ")", "preds", "=", "model", ".", "get_logits", "(", "x", ")", "cross_entropy_loss", "=", "CrossEntropy", "(", "model", ")", "if", "not", "SNNL_factor", ":", "loss", "=", "cross_entropy_loss", "else", ":", "loss", "=", "SNNLCrossEntropy", "(", "model", ",", "factor", "=", "SNNL_factor", ",", "optimize_temperature", "=", "False", ")", "def", "evaluate", "(", ")", ":", "do_eval", "(", "preds", ",", "x_test", ",", "y_test", ",", "'clean_train_clean_eval'", ")", "train", "(", "sess", ",", "loss", ",", "x_train", ",", "y_train", ",", "evaluate", "=", "evaluate", ",", "args", "=", "train_params", ",", "rng", "=", "rng", ",", "var_list", "=", "model", ".", "get_params", "(", ")", ")", "do_eval", "(", "preds", ",", "x_train", ",", "y_train", ",", "'train_clean_train_clean_eval'", ")", "def", "imscatter", "(", "points", ",", "images", ",", "ax", "=", "None", ",", "zoom", "=", "1", ",", "cmap", "=", "\"hot\"", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", "(", ")", "artists", "=", "[", "]", "i", "=", "0", "if", "not", "isinstance", "(", "cmap", ",", "list", ")", ":", "cmap", "=", "[", "cmap", "]", "*", "len", "(", "points", ")", "for", "x0", ",", "y0", "in", "points", ":", "transformed", "=", "(", "images", "[", "i", "]", "-", "np", ".", "min", "(", "images", "[", "i", "]", ")", ")", "/", "(", "np", ".", "max", "(", "images", "[", "i", "]", ")", "-", "np", ".", "min", "(", "images", "[", "i", "]", ")", ")", "im", "=", "OffsetImage", "(", "transformed", "[", ":", ",", ":", ",", "0", "]", ",", "zoom", "=", "zoom", ",", "cmap", "=", "cmap", "[", "i", "]", ")", "ab", "=", "AnnotationBbox", "(", "im", ",", "(", "x0", ",", "y0", ")", ",", "xycoords", "=", "'data'", ",", "frameon", "=", "False", ")", "artists", ".", "append", "(", "ax", ".", "add_artist", "(", "ab", ")", ")", "i", "+=", "1", "ax", ".", "update_datalim", "(", "np", ".", "column_stack", "(", "np", ".", "transpose", "(", "points", ")", ")", ")", "ax", ".", "autoscale", "(", ")", "ax", ".", "get_xaxis", "(", ")", ".", "set_ticks", "(", "[", "]", ")", "ax", ".", "get_yaxis", "(", ")", ".", "set_ticks", "(", "[", "]", ")", "return", "artists", "adv_grads", "=", "tf", ".", "sign", "(", "tf", ".", "gradients", "(", "cross_entropy_loss", ".", "fprop", "(", "x", ",", "y", ")", ",", "x", ")", ")", "feed_dict", "=", "{", "x", ":", "x_test", "[", ":", "batch_size", "]", ",", "y", ":", "y_test", "[", ":", "batch_size", "]", "}", "adv_grads_val", "=", "sess", ".", "run", "(", "adv_grads", ",", "feed_dict", "=", "feed_dict", ")", "adv_grads_val", "=", "np", ".", "reshape", "(", "adv_grads_val", ",", "(", "batch_size", ",", "img_rows", "*", "img_cols", ")", ")", "X_embedded", "=", "TSNE", "(", "n_components", "=", "2", ",", "verbose", "=", "0", ")", ".", "fit_transform", "(", "adv_grads_val", ")", "plt", ".", "figure", "(", "num", "=", "None", ",", "figsize", "=", "(", "50", ",", "50", ")", ",", "dpi", "=", "40", ",", "facecolor", "=", "'w'", ",", "edgecolor", "=", "'k'", ")", "plt", ".", "title", "(", "\"TSNE of Sign of Adv Gradients, SNNLCrossEntropy Model, factor:\"", "+", "str", "(", "FLAGS", ".", "SNNL_factor", ")", ",", "fontsize", "=", "42", ")", "imscatter", "(", "X_embedded", ",", "x_test", "[", ":", "batch_size", "]", ",", "zoom", "=", "2", ",", "cmap", "=", "\"Purples\"", ")", "plt", ".", "savefig", "(", "output_dir", "+", "'adversarial_gradients_SNNL_factor_'", "+", "str", "(", "SNNL_factor", ")", "+", "'.png'", ")" ]
A simple model trained to minimize Cross Entropy and Maximize Soft Nearest Neighbor Loss at each internal layer. This outputs a TSNE of the sign of the adversarial gradients of a trained model. A model with a negative SNNL_factor will show little or no class clusters, while a model with a 0 SNNL_factor will have class clusters in the adversarial gradient direction. :param train_start: index of first training set example :param train_end: index of last training set example :param test_start: index of first test set example :param test_end: index of last test set example :param nb_epochs: number of epochs to train model :param batch_size: size of training batches :param learning_rate: learning rate for training :param SNNL_factor: multiplier for Soft Nearest Neighbor Loss :return: an AccuracyReport object
[ "A", "simple", "model", "trained", "to", "minimize", "Cross", "Entropy", "and", "Maximize", "Soft", "Nearest", "Neighbor", "Loss", "at", "each", "internal", "layer", ".", "This", "outputs", "a", "TSNE", "of", "the", "sign", "of", "the", "adversarial", "gradients", "of", "a", "trained", "model", ".", "A", "model", "with", "a", "negative", "SNNL_factor", "will", "show", "little", "or", "no", "class", "clusters", "while", "a", "model", "with", "a", "0", "SNNL_factor", "will", "have", "class", "clusters", "in", "the", "adversarial", "gradient", "direction", ".", ":", "param", "train_start", ":", "index", "of", "first", "training", "set", "example", ":", "param", "train_end", ":", "index", "of", "last", "training", "set", "example", ":", "param", "test_start", ":", "index", "of", "first", "test", "set", "example", ":", "param", "test_end", ":", "index", "of", "last", "test", "set", "example", ":", "param", "nb_epochs", ":", "number", "of", "epochs", "to", "train", "model", ":", "param", "batch_size", ":", "size", "of", "training", "batches", ":", "param", "learning_rate", ":", "learning", "rate", "for", "training", ":", "param", "SNNL_factor", ":", "multiplier", "for", "Soft", "Nearest", "Neighbor", "Loss", ":", "return", ":", "an", "AccuracyReport", "object" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model_zoo/soft_nearest_neighbor_loss/SNNL_regularized_train.py#L37-L149
train
tensorflow/cleverhans
cleverhans/attacks/projected_gradient_descent.py
ProjectedGradientDescent.generate
def generate(self, x, **kwargs): """ Generate symbolic graph for adversarial examples and return. :param x: The model's symbolic inputs. :param kwargs: See `parse_params` """ # Parse and save attack-specific parameters assert self.parse_params(**kwargs) asserts = [] # If a data range was specified, check that the input was in that range if self.clip_min is not None: asserts.append(utils_tf.assert_greater_equal(x, tf.cast(self.clip_min, x.dtype))) if self.clip_max is not None: asserts.append(utils_tf.assert_less_equal(x, tf.cast(self.clip_max, x.dtype))) # Initialize loop variables if self.rand_init: eta = tf.random_uniform(tf.shape(x), tf.cast(-self.rand_minmax, x.dtype), tf.cast(self.rand_minmax, x.dtype), dtype=x.dtype) else: eta = tf.zeros(tf.shape(x)) # Clip eta eta = clip_eta(eta, self.ord, self.eps) adv_x = x + eta if self.clip_min is not None or self.clip_max is not None: adv_x = utils_tf.clip_by_value(adv_x, self.clip_min, self.clip_max) if self.y_target is not None: y = self.y_target targeted = True elif self.y is not None: y = self.y targeted = False else: model_preds = self.model.get_probs(x) preds_max = tf.reduce_max(model_preds, 1, keepdims=True) y = tf.to_float(tf.equal(model_preds, preds_max)) y = tf.stop_gradient(y) targeted = False del model_preds y_kwarg = 'y_target' if targeted else 'y' fgm_params = { 'eps': self.eps_iter, y_kwarg: y, 'ord': self.ord, 'clip_min': self.clip_min, 'clip_max': self.clip_max } if self.ord == 1: raise NotImplementedError("It's not clear that FGM is a good inner loop" " step for PGD when ord=1, because ord=1 FGM " " changes only one pixel at a time. We need " " to rigorously test a strong ord=1 PGD " "before enabling this feature.") # Use getattr() to avoid errors in eager execution attacks FGM = self.FGM_CLASS( self.model, sess=getattr(self, 'sess', None), dtypestr=self.dtypestr) def cond(i, _): """Iterate until requested number of iterations is completed""" return tf.less(i, self.nb_iter) def body(i, adv_x): """Do a projected gradient step""" adv_x = FGM.generate(adv_x, **fgm_params) # Clipping perturbation eta to self.ord norm ball eta = adv_x - x eta = clip_eta(eta, self.ord, self.eps) adv_x = x + eta # Redo the clipping. # FGM already did it, but subtracting and re-adding eta can add some # small numerical error. if self.clip_min is not None or self.clip_max is not None: adv_x = utils_tf.clip_by_value(adv_x, self.clip_min, self.clip_max) return i + 1, adv_x _, adv_x = tf.while_loop(cond, body, (tf.zeros([]), adv_x), back_prop=True, maximum_iterations=self.nb_iter) # Asserts run only on CPU. # When multi-GPU eval code tries to force all PGD ops onto GPU, this # can cause an error. common_dtype = tf.float32 asserts.append(utils_tf.assert_less_equal(tf.cast(self.eps_iter, dtype=common_dtype), tf.cast(self.eps, dtype=common_dtype))) if self.ord == np.inf and self.clip_min is not None: # The 1e-6 is needed to compensate for numerical error. # Without the 1e-6 this fails when e.g. eps=.2, clip_min=.5, # clip_max=.7 asserts.append(utils_tf.assert_less_equal(tf.cast(self.eps, x.dtype), 1e-6 + tf.cast(self.clip_max, x.dtype) - tf.cast(self.clip_min, x.dtype))) if self.sanity_checks: with tf.control_dependencies(asserts): adv_x = tf.identity(adv_x) return adv_x
python
def generate(self, x, **kwargs): """ Generate symbolic graph for adversarial examples and return. :param x: The model's symbolic inputs. :param kwargs: See `parse_params` """ # Parse and save attack-specific parameters assert self.parse_params(**kwargs) asserts = [] # If a data range was specified, check that the input was in that range if self.clip_min is not None: asserts.append(utils_tf.assert_greater_equal(x, tf.cast(self.clip_min, x.dtype))) if self.clip_max is not None: asserts.append(utils_tf.assert_less_equal(x, tf.cast(self.clip_max, x.dtype))) # Initialize loop variables if self.rand_init: eta = tf.random_uniform(tf.shape(x), tf.cast(-self.rand_minmax, x.dtype), tf.cast(self.rand_minmax, x.dtype), dtype=x.dtype) else: eta = tf.zeros(tf.shape(x)) # Clip eta eta = clip_eta(eta, self.ord, self.eps) adv_x = x + eta if self.clip_min is not None or self.clip_max is not None: adv_x = utils_tf.clip_by_value(adv_x, self.clip_min, self.clip_max) if self.y_target is not None: y = self.y_target targeted = True elif self.y is not None: y = self.y targeted = False else: model_preds = self.model.get_probs(x) preds_max = tf.reduce_max(model_preds, 1, keepdims=True) y = tf.to_float(tf.equal(model_preds, preds_max)) y = tf.stop_gradient(y) targeted = False del model_preds y_kwarg = 'y_target' if targeted else 'y' fgm_params = { 'eps': self.eps_iter, y_kwarg: y, 'ord': self.ord, 'clip_min': self.clip_min, 'clip_max': self.clip_max } if self.ord == 1: raise NotImplementedError("It's not clear that FGM is a good inner loop" " step for PGD when ord=1, because ord=1 FGM " " changes only one pixel at a time. We need " " to rigorously test a strong ord=1 PGD " "before enabling this feature.") # Use getattr() to avoid errors in eager execution attacks FGM = self.FGM_CLASS( self.model, sess=getattr(self, 'sess', None), dtypestr=self.dtypestr) def cond(i, _): """Iterate until requested number of iterations is completed""" return tf.less(i, self.nb_iter) def body(i, adv_x): """Do a projected gradient step""" adv_x = FGM.generate(adv_x, **fgm_params) # Clipping perturbation eta to self.ord norm ball eta = adv_x - x eta = clip_eta(eta, self.ord, self.eps) adv_x = x + eta # Redo the clipping. # FGM already did it, but subtracting and re-adding eta can add some # small numerical error. if self.clip_min is not None or self.clip_max is not None: adv_x = utils_tf.clip_by_value(adv_x, self.clip_min, self.clip_max) return i + 1, adv_x _, adv_x = tf.while_loop(cond, body, (tf.zeros([]), adv_x), back_prop=True, maximum_iterations=self.nb_iter) # Asserts run only on CPU. # When multi-GPU eval code tries to force all PGD ops onto GPU, this # can cause an error. common_dtype = tf.float32 asserts.append(utils_tf.assert_less_equal(tf.cast(self.eps_iter, dtype=common_dtype), tf.cast(self.eps, dtype=common_dtype))) if self.ord == np.inf and self.clip_min is not None: # The 1e-6 is needed to compensate for numerical error. # Without the 1e-6 this fails when e.g. eps=.2, clip_min=.5, # clip_max=.7 asserts.append(utils_tf.assert_less_equal(tf.cast(self.eps, x.dtype), 1e-6 + tf.cast(self.clip_max, x.dtype) - tf.cast(self.clip_min, x.dtype))) if self.sanity_checks: with tf.control_dependencies(asserts): adv_x = tf.identity(adv_x) return adv_x
[ "def", "generate", "(", "self", ",", "x", ",", "*", "*", "kwargs", ")", ":", "# Parse and save attack-specific parameters", "assert", "self", ".", "parse_params", "(", "*", "*", "kwargs", ")", "asserts", "=", "[", "]", "# If a data range was specified, check that the input was in that range", "if", "self", ".", "clip_min", "is", "not", "None", ":", "asserts", ".", "append", "(", "utils_tf", ".", "assert_greater_equal", "(", "x", ",", "tf", ".", "cast", "(", "self", ".", "clip_min", ",", "x", ".", "dtype", ")", ")", ")", "if", "self", ".", "clip_max", "is", "not", "None", ":", "asserts", ".", "append", "(", "utils_tf", ".", "assert_less_equal", "(", "x", ",", "tf", ".", "cast", "(", "self", ".", "clip_max", ",", "x", ".", "dtype", ")", ")", ")", "# Initialize loop variables", "if", "self", ".", "rand_init", ":", "eta", "=", "tf", ".", "random_uniform", "(", "tf", ".", "shape", "(", "x", ")", ",", "tf", ".", "cast", "(", "-", "self", ".", "rand_minmax", ",", "x", ".", "dtype", ")", ",", "tf", ".", "cast", "(", "self", ".", "rand_minmax", ",", "x", ".", "dtype", ")", ",", "dtype", "=", "x", ".", "dtype", ")", "else", ":", "eta", "=", "tf", ".", "zeros", "(", "tf", ".", "shape", "(", "x", ")", ")", "# Clip eta", "eta", "=", "clip_eta", "(", "eta", ",", "self", ".", "ord", ",", "self", ".", "eps", ")", "adv_x", "=", "x", "+", "eta", "if", "self", ".", "clip_min", "is", "not", "None", "or", "self", ".", "clip_max", "is", "not", "None", ":", "adv_x", "=", "utils_tf", ".", "clip_by_value", "(", "adv_x", ",", "self", ".", "clip_min", ",", "self", ".", "clip_max", ")", "if", "self", ".", "y_target", "is", "not", "None", ":", "y", "=", "self", ".", "y_target", "targeted", "=", "True", "elif", "self", ".", "y", "is", "not", "None", ":", "y", "=", "self", ".", "y", "targeted", "=", "False", "else", ":", "model_preds", "=", "self", ".", "model", ".", "get_probs", "(", "x", ")", "preds_max", "=", "tf", ".", "reduce_max", "(", "model_preds", ",", "1", ",", "keepdims", "=", "True", ")", "y", "=", "tf", ".", "to_float", "(", "tf", ".", "equal", "(", "model_preds", ",", "preds_max", ")", ")", "y", "=", "tf", ".", "stop_gradient", "(", "y", ")", "targeted", "=", "False", "del", "model_preds", "y_kwarg", "=", "'y_target'", "if", "targeted", "else", "'y'", "fgm_params", "=", "{", "'eps'", ":", "self", ".", "eps_iter", ",", "y_kwarg", ":", "y", ",", "'ord'", ":", "self", ".", "ord", ",", "'clip_min'", ":", "self", ".", "clip_min", ",", "'clip_max'", ":", "self", ".", "clip_max", "}", "if", "self", ".", "ord", "==", "1", ":", "raise", "NotImplementedError", "(", "\"It's not clear that FGM is a good inner loop\"", "\" step for PGD when ord=1, because ord=1 FGM \"", "\" changes only one pixel at a time. We need \"", "\" to rigorously test a strong ord=1 PGD \"", "\"before enabling this feature.\"", ")", "# Use getattr() to avoid errors in eager execution attacks", "FGM", "=", "self", ".", "FGM_CLASS", "(", "self", ".", "model", ",", "sess", "=", "getattr", "(", "self", ",", "'sess'", ",", "None", ")", ",", "dtypestr", "=", "self", ".", "dtypestr", ")", "def", "cond", "(", "i", ",", "_", ")", ":", "\"\"\"Iterate until requested number of iterations is completed\"\"\"", "return", "tf", ".", "less", "(", "i", ",", "self", ".", "nb_iter", ")", "def", "body", "(", "i", ",", "adv_x", ")", ":", "\"\"\"Do a projected gradient step\"\"\"", "adv_x", "=", "FGM", ".", "generate", "(", "adv_x", ",", "*", "*", "fgm_params", ")", "# Clipping perturbation eta to self.ord norm ball", "eta", "=", "adv_x", "-", "x", "eta", "=", "clip_eta", "(", "eta", ",", "self", ".", "ord", ",", "self", ".", "eps", ")", "adv_x", "=", "x", "+", "eta", "# Redo the clipping.", "# FGM already did it, but subtracting and re-adding eta can add some", "# small numerical error.", "if", "self", ".", "clip_min", "is", "not", "None", "or", "self", ".", "clip_max", "is", "not", "None", ":", "adv_x", "=", "utils_tf", ".", "clip_by_value", "(", "adv_x", ",", "self", ".", "clip_min", ",", "self", ".", "clip_max", ")", "return", "i", "+", "1", ",", "adv_x", "_", ",", "adv_x", "=", "tf", ".", "while_loop", "(", "cond", ",", "body", ",", "(", "tf", ".", "zeros", "(", "[", "]", ")", ",", "adv_x", ")", ",", "back_prop", "=", "True", ",", "maximum_iterations", "=", "self", ".", "nb_iter", ")", "# Asserts run only on CPU.", "# When multi-GPU eval code tries to force all PGD ops onto GPU, this", "# can cause an error.", "common_dtype", "=", "tf", ".", "float32", "asserts", ".", "append", "(", "utils_tf", ".", "assert_less_equal", "(", "tf", ".", "cast", "(", "self", ".", "eps_iter", ",", "dtype", "=", "common_dtype", ")", ",", "tf", ".", "cast", "(", "self", ".", "eps", ",", "dtype", "=", "common_dtype", ")", ")", ")", "if", "self", ".", "ord", "==", "np", ".", "inf", "and", "self", ".", "clip_min", "is", "not", "None", ":", "# The 1e-6 is needed to compensate for numerical error.", "# Without the 1e-6 this fails when e.g. eps=.2, clip_min=.5,", "# clip_max=.7", "asserts", ".", "append", "(", "utils_tf", ".", "assert_less_equal", "(", "tf", ".", "cast", "(", "self", ".", "eps", ",", "x", ".", "dtype", ")", ",", "1e-6", "+", "tf", ".", "cast", "(", "self", ".", "clip_max", ",", "x", ".", "dtype", ")", "-", "tf", ".", "cast", "(", "self", ".", "clip_min", ",", "x", ".", "dtype", ")", ")", ")", "if", "self", ".", "sanity_checks", ":", "with", "tf", ".", "control_dependencies", "(", "asserts", ")", ":", "adv_x", "=", "tf", ".", "identity", "(", "adv_x", ")", "return", "adv_x" ]
Generate symbolic graph for adversarial examples and return. :param x: The model's symbolic inputs. :param kwargs: See `parse_params`
[ "Generate", "symbolic", "graph", "for", "adversarial", "examples", "and", "return", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/projected_gradient_descent.py#L48-L166
train
tensorflow/cleverhans
cleverhans/attacks/projected_gradient_descent.py
ProjectedGradientDescent.parse_params
def parse_params(self, eps=0.3, eps_iter=0.05, nb_iter=10, y=None, ord=np.inf, clip_min=None, clip_max=None, y_target=None, rand_init=None, rand_minmax=0.3, sanity_checks=True, **kwargs): """ Take in a dictionary of parameters and applies attack-specific checks before saving them as attributes. Attack-specific parameters: :param eps: (optional float) maximum distortion of adversarial example compared to original input :param eps_iter: (optional float) step size for each attack iteration :param nb_iter: (optional int) Number of attack iterations. :param y: (optional) A tensor with the true labels. :param y_target: (optional) A tensor with the labels to target. Leave y_target=None if y is also set. Labels should be one-hot-encoded. :param ord: (optional) Order of the norm (mimics Numpy). Possible values: np.inf, 1 or 2. :param clip_min: (optional float) Minimum input component value :param clip_max: (optional float) Maximum input component value :param sanity_checks: bool Insert tf asserts checking values (Some tests need to run with no sanity checks because the tests intentionally configure the attack strangely) """ # Save attack-specific parameters self.eps = eps if rand_init is None: rand_init = self.default_rand_init self.rand_init = rand_init if self.rand_init: self.rand_minmax = eps else: self.rand_minmax = 0. self.eps_iter = eps_iter self.nb_iter = nb_iter self.y = y self.y_target = y_target self.ord = ord self.clip_min = clip_min self.clip_max = clip_max if isinstance(eps, float) and isinstance(eps_iter, float): # If these are both known at compile time, we can check before anything # is run. If they are tf, we can't check them yet. assert eps_iter <= eps, (eps_iter, eps) if self.y is not None and self.y_target is not None: raise ValueError("Must not set both y and y_target") # Check if order of the norm is acceptable given current implementation if self.ord not in [np.inf, 1, 2]: raise ValueError("Norm order must be either np.inf, 1, or 2.") self.sanity_checks = sanity_checks if len(kwargs.keys()) > 0: warnings.warn("kwargs is unused and will be removed on or after " "2019-04-26.") return True
python
def parse_params(self, eps=0.3, eps_iter=0.05, nb_iter=10, y=None, ord=np.inf, clip_min=None, clip_max=None, y_target=None, rand_init=None, rand_minmax=0.3, sanity_checks=True, **kwargs): """ Take in a dictionary of parameters and applies attack-specific checks before saving them as attributes. Attack-specific parameters: :param eps: (optional float) maximum distortion of adversarial example compared to original input :param eps_iter: (optional float) step size for each attack iteration :param nb_iter: (optional int) Number of attack iterations. :param y: (optional) A tensor with the true labels. :param y_target: (optional) A tensor with the labels to target. Leave y_target=None if y is also set. Labels should be one-hot-encoded. :param ord: (optional) Order of the norm (mimics Numpy). Possible values: np.inf, 1 or 2. :param clip_min: (optional float) Minimum input component value :param clip_max: (optional float) Maximum input component value :param sanity_checks: bool Insert tf asserts checking values (Some tests need to run with no sanity checks because the tests intentionally configure the attack strangely) """ # Save attack-specific parameters self.eps = eps if rand_init is None: rand_init = self.default_rand_init self.rand_init = rand_init if self.rand_init: self.rand_minmax = eps else: self.rand_minmax = 0. self.eps_iter = eps_iter self.nb_iter = nb_iter self.y = y self.y_target = y_target self.ord = ord self.clip_min = clip_min self.clip_max = clip_max if isinstance(eps, float) and isinstance(eps_iter, float): # If these are both known at compile time, we can check before anything # is run. If they are tf, we can't check them yet. assert eps_iter <= eps, (eps_iter, eps) if self.y is not None and self.y_target is not None: raise ValueError("Must not set both y and y_target") # Check if order of the norm is acceptable given current implementation if self.ord not in [np.inf, 1, 2]: raise ValueError("Norm order must be either np.inf, 1, or 2.") self.sanity_checks = sanity_checks if len(kwargs.keys()) > 0: warnings.warn("kwargs is unused and will be removed on or after " "2019-04-26.") return True
[ "def", "parse_params", "(", "self", ",", "eps", "=", "0.3", ",", "eps_iter", "=", "0.05", ",", "nb_iter", "=", "10", ",", "y", "=", "None", ",", "ord", "=", "np", ".", "inf", ",", "clip_min", "=", "None", ",", "clip_max", "=", "None", ",", "y_target", "=", "None", ",", "rand_init", "=", "None", ",", "rand_minmax", "=", "0.3", ",", "sanity_checks", "=", "True", ",", "*", "*", "kwargs", ")", ":", "# Save attack-specific parameters", "self", ".", "eps", "=", "eps", "if", "rand_init", "is", "None", ":", "rand_init", "=", "self", ".", "default_rand_init", "self", ".", "rand_init", "=", "rand_init", "if", "self", ".", "rand_init", ":", "self", ".", "rand_minmax", "=", "eps", "else", ":", "self", ".", "rand_minmax", "=", "0.", "self", ".", "eps_iter", "=", "eps_iter", "self", ".", "nb_iter", "=", "nb_iter", "self", ".", "y", "=", "y", "self", ".", "y_target", "=", "y_target", "self", ".", "ord", "=", "ord", "self", ".", "clip_min", "=", "clip_min", "self", ".", "clip_max", "=", "clip_max", "if", "isinstance", "(", "eps", ",", "float", ")", "and", "isinstance", "(", "eps_iter", ",", "float", ")", ":", "# If these are both known at compile time, we can check before anything", "# is run. If they are tf, we can't check them yet.", "assert", "eps_iter", "<=", "eps", ",", "(", "eps_iter", ",", "eps", ")", "if", "self", ".", "y", "is", "not", "None", "and", "self", ".", "y_target", "is", "not", "None", ":", "raise", "ValueError", "(", "\"Must not set both y and y_target\"", ")", "# Check if order of the norm is acceptable given current implementation", "if", "self", ".", "ord", "not", "in", "[", "np", ".", "inf", ",", "1", ",", "2", "]", ":", "raise", "ValueError", "(", "\"Norm order must be either np.inf, 1, or 2.\"", ")", "self", ".", "sanity_checks", "=", "sanity_checks", "if", "len", "(", "kwargs", ".", "keys", "(", ")", ")", ">", "0", ":", "warnings", ".", "warn", "(", "\"kwargs is unused and will be removed on or after \"", "\"2019-04-26.\"", ")", "return", "True" ]
Take in a dictionary of parameters and applies attack-specific checks before saving them as attributes. Attack-specific parameters: :param eps: (optional float) maximum distortion of adversarial example compared to original input :param eps_iter: (optional float) step size for each attack iteration :param nb_iter: (optional int) Number of attack iterations. :param y: (optional) A tensor with the true labels. :param y_target: (optional) A tensor with the labels to target. Leave y_target=None if y is also set. Labels should be one-hot-encoded. :param ord: (optional) Order of the norm (mimics Numpy). Possible values: np.inf, 1 or 2. :param clip_min: (optional float) Minimum input component value :param clip_max: (optional float) Maximum input component value :param sanity_checks: bool Insert tf asserts checking values (Some tests need to run with no sanity checks because the tests intentionally configure the attack strangely)
[ "Take", "in", "a", "dictionary", "of", "parameters", "and", "applies", "attack", "-", "specific", "checks", "before", "saving", "them", "as", "attributes", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/projected_gradient_descent.py#L168-L237
train