partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
train
avg_grads
Calculate the average gradient for each shared variable across all towers. Note that this function provides a synchronization point across all towers. Args: tower_grads: List of lists of (gradient, variable) tuples. The outer list is over individual gradients. The inner list is over the gradient c...
cleverhans/train.py
def avg_grads(tower_grads): """Calculate the average gradient for each shared variable across all towers. Note that this function provides a synchronization point across all towers. Args: tower_grads: List of lists of (gradient, variable) tuples. The outer list is over individual gradients. The inner ...
def avg_grads(tower_grads): """Calculate the average gradient for each shared variable across all towers. Note that this function provides a synchronization point across all towers. Args: tower_grads: List of lists of (gradient, variable) tuples. The outer list is over individual gradients. The inner ...
[ "Calculate", "the", "average", "gradient", "for", "each", "shared", "variable", "across", "all", "towers", ".", "Note", "that", "this", "function", "provides", "a", "synchronization", "point", "across", "all", "towers", ".", "Args", ":", "tower_grads", ":", "L...
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/train.py#L277-L309
[ "def", "avg_grads", "(", "tower_grads", ")", ":", "if", "len", "(", "tower_grads", ")", "==", "1", ":", "return", "tower_grads", "[", "0", "]", "average_grads", "=", "[", "]", "for", "grad_and_vars", "in", "zip", "(", "*", "tower_grads", ")", ":", "# N...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
create_adv_by_name
Creates the symbolic graph of an adversarial example given the name of an attack. Simplifies creating the symbolic graph of an attack by defining dataset-specific parameters. Dataset-specific default parameters are used unless a different value is given in kwargs. :param model: an object of Model class :pa...
examples/multigpu_advtrain/evaluator.py
def create_adv_by_name(model, x, attack_type, sess, dataset, y=None, **kwargs): """ Creates the symbolic graph of an adversarial example given the name of an attack. Simplifies creating the symbolic graph of an attack by defining dataset-specific parameters. Dataset-specific default parameters are used unless...
def create_adv_by_name(model, x, attack_type, sess, dataset, y=None, **kwargs): """ Creates the symbolic graph of an adversarial example given the name of an attack. Simplifies creating the symbolic graph of an attack by defining dataset-specific parameters. Dataset-specific default parameters are used unless...
[ "Creates", "the", "symbolic", "graph", "of", "an", "adversarial", "example", "given", "the", "name", "of", "an", "attack", ".", "Simplifies", "creating", "the", "symbolic", "graph", "of", "an", "attack", "by", "defining", "dataset", "-", "specific", "parameter...
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/evaluator.py#L16-L66
[ "def", "create_adv_by_name", "(", "model", ",", "x", ",", "attack_type", ",", "sess", ",", "dataset", ",", "y", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# TODO: black box attacks", "attack_names", "=", "{", "'FGSM'", ":", "FastGradientMethod", ",", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
Evaluator.log_value
Log values to standard output and Tensorflow summary. :param tag: summary tag. :param val: (required float or numpy array) value to be logged. :param desc: (optional) additional description to be printed.
examples/multigpu_advtrain/evaluator.py
def log_value(self, tag, val, desc=''): """ Log values to standard output and Tensorflow summary. :param tag: summary tag. :param val: (required float or numpy array) value to be logged. :param desc: (optional) additional description to be printed. """ logging.info('%s (%s): %.4f' % (desc, ...
def log_value(self, tag, val, desc=''): """ Log values to standard output and Tensorflow summary. :param tag: summary tag. :param val: (required float or numpy array) value to be logged. :param desc: (optional) additional description to be printed. """ logging.info('%s (%s): %.4f' % (desc, ...
[ "Log", "values", "to", "standard", "output", "and", "Tensorflow", "summary", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/evaluator.py#L127-L136
[ "def", "log_value", "(", "self", ",", "tag", ",", "val", ",", "desc", "=", "''", ")", ":", "logging", ".", "info", "(", "'%s (%s): %.4f'", "%", "(", "desc", ",", "tag", ",", "val", ")", ")", "self", ".", "summary", ".", "value", ".", "add", "(", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
Evaluator.eval_advs
Evaluate the accuracy of the model on adversarial examples :param x: symbolic input to model. :param y: symbolic variable for the label. :param preds_adv: symbolic variable for the prediction on an adversarial example. :param X_test: NumPy array of test set inputs. :param Y_te...
examples/multigpu_advtrain/evaluator.py
def eval_advs(self, x, y, preds_adv, X_test, Y_test, att_type): """ Evaluate the accuracy of the model on adversarial examples :param x: symbolic input to model. :param y: symbolic variable for the label. :param preds_adv: symbolic variable for the prediction on an adversarial...
def eval_advs(self, x, y, preds_adv, X_test, Y_test, att_type): """ Evaluate the accuracy of the model on adversarial examples :param x: symbolic input to model. :param y: symbolic variable for the label. :param preds_adv: symbolic variable for the prediction on an adversarial...
[ "Evaluate", "the", "accuracy", "of", "the", "model", "on", "adversarial", "examples" ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/evaluator.py#L138-L159
[ "def", "eval_advs", "(", "self", ",", "x", ",", "y", ",", "preds_adv", ",", "X_test", ",", "Y_test", ",", "att_type", ")", ":", "end", "=", "(", "len", "(", "X_test", ")", "//", "self", ".", "batch_size", ")", "*", "self", ".", "batch_size", "if", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
Evaluator.eval_multi
Run the evaluation on multiple attacks.
examples/multigpu_advtrain/evaluator.py
def eval_multi(self, inc_epoch=True): """ Run the evaluation on multiple attacks. """ sess = self.sess preds = self.preds x = self.x_pre y = self.y X_train = self.X_train Y_train = self.Y_train X_test = self.X_test Y_test = self.Y_test writer = self.writer self.summa...
def eval_multi(self, inc_epoch=True): """ Run the evaluation on multiple attacks. """ sess = self.sess preds = self.preds x = self.x_pre y = self.y X_train = self.X_train Y_train = self.Y_train X_test = self.X_test Y_test = self.Y_test writer = self.writer self.summa...
[ "Run", "the", "evaluation", "on", "multiple", "attacks", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/evaluator.py#L161-L215
[ "def", "eval_multi", "(", "self", ",", "inc_epoch", "=", "True", ")", ":", "sess", "=", "self", ".", "sess", "preds", "=", "self", ".", "preds", "x", "=", "self", ".", "x_pre", "y", "=", "self", ".", "y", "X_train", "=", "self", ".", "X_train", "...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
run_canary
Runs some code that will crash if the GPUs / GPU driver are suffering from a common bug. This helps to prevent contaminating results in the rest of the library with incorrect calculations.
cleverhans/canary.py
def run_canary(): """ Runs some code that will crash if the GPUs / GPU driver are suffering from a common bug. This helps to prevent contaminating results in the rest of the library with incorrect calculations. """ # Note: please do not edit this function unless you have access to a machine # with GPUs s...
def run_canary(): """ Runs some code that will crash if the GPUs / GPU driver are suffering from a common bug. This helps to prevent contaminating results in the rest of the library with incorrect calculations. """ # Note: please do not edit this function unless you have access to a machine # with GPUs s...
[ "Runs", "some", "code", "that", "will", "crash", "if", "the", "GPUs", "/", "GPU", "driver", "are", "suffering", "from", "a", "common", "bug", ".", "This", "helps", "to", "prevent", "contaminating", "results", "in", "the", "rest", "of", "the", "library", ...
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/canary.py#L13-L72
[ "def", "run_canary", "(", ")", ":", "# Note: please do not edit this function unless you have access to a machine", "# with GPUs suffering from the bug and can verify that the canary still", "# crashes after your edits. Due to the transient nature of the GPU bug it is", "# not possible to unit test ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
_wrap
Wraps a callable `f` in a function that warns that the function is deprecated.
cleverhans/compat.py
def _wrap(f): """ Wraps a callable `f` in a function that warns that the function is deprecated. """ def wrapper(*args, **kwargs): """ Issues a deprecation warning and passes through the arguments. """ warnings.warn(str(f) + " is deprecated. Switch to calling the equivalent function in tensorflo...
def _wrap(f): """ Wraps a callable `f` in a function that warns that the function is deprecated. """ def wrapper(*args, **kwargs): """ Issues a deprecation warning and passes through the arguments. """ warnings.warn(str(f) + " is deprecated. Switch to calling the equivalent function in tensorflo...
[ "Wraps", "a", "callable", "f", "in", "a", "function", "that", "warns", "that", "the", "function", "is", "deprecated", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/compat.py#L14-L26
[ "def", "_wrap", "(", "f", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"\n Issues a deprecation warning and passes through the arguments.\n \"\"\"", "warnings", ".", "warn", "(", "str", "(", "f", ")", "+", "\" is d...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
reduce_function
This function used to be needed to support tf 1.4 and early, but support for tf 1.4 and earlier is now dropped. :param op_func: expects the function to handle eg: tf.reduce_sum. :param input_tensor: The tensor to reduce. Should have numeric type. :param axis: The dimensions to reduce. If None (the default), ...
cleverhans/compat.py
def reduce_function(op_func, input_tensor, axis=None, keepdims=None, name=None, reduction_indices=None): """ This function used to be needed to support tf 1.4 and early, but support for tf 1.4 and earlier is now dropped. :param op_func: expects the function to handle eg: tf.reduce_sum. :para...
def reduce_function(op_func, input_tensor, axis=None, keepdims=None, name=None, reduction_indices=None): """ This function used to be needed to support tf 1.4 and early, but support for tf 1.4 and earlier is now dropped. :param op_func: expects the function to handle eg: tf.reduce_sum. :para...
[ "This", "function", "used", "to", "be", "needed", "to", "support", "tf", "1", ".", "4", "and", "early", "but", "support", "for", "tf", "1", ".", "4", "and", "earlier", "is", "now", "dropped", ".", ":", "param", "op_func", ":", "expects", "the", "func...
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/compat.py#L35-L54
[ "def", "reduce_function", "(", "op_func", ",", "input_tensor", ",", "axis", "=", "None", ",", "keepdims", "=", "None", ",", "name", "=", "None", ",", "reduction_indices", "=", "None", ")", ":", "warnings", ".", "warn", "(", "\"`reduce_function` is deprecated a...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
softmax_cross_entropy_with_logits
Wrapper around tf.nn.softmax_cross_entropy_with_logits_v2 to handle deprecated warning
cleverhans/compat.py
def softmax_cross_entropy_with_logits(sentinel=None, labels=None, logits=None, dim=-1): """ Wrapper around tf.nn.softmax_cross_entropy_with_logits_v2 to handle deprecated warning """ # Make sure t...
def softmax_cross_entropy_with_logits(sentinel=None, labels=None, logits=None, dim=-1): """ Wrapper around tf.nn.softmax_cross_entropy_with_logits_v2 to handle deprecated warning """ # Make sure t...
[ "Wrapper", "around", "tf", ".", "nn", ".", "softmax_cross_entropy_with_logits_v2", "to", "handle", "deprecated", "warning" ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/compat.py#L56-L81
[ "def", "softmax_cross_entropy_with_logits", "(", "sentinel", "=", "None", ",", "labels", "=", "None", ",", "logits", "=", "None", ",", "dim", "=", "-", "1", ")", ":", "# Make sure that all arguments were passed as named arguments.", "if", "sentinel", "is", "not", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
enforce_epsilon_and_compute_hash
Enforces size of perturbation on images, and compute hashes for all images. Args: dataset_batch_dir: directory with the images of specific dataset batch adv_dir: directory with generated adversarial images output_dir: directory where to copy result epsilon: size of perturbation Returns: dictio...
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/dataset_helper.py
def enforce_epsilon_and_compute_hash(dataset_batch_dir, adv_dir, output_dir, epsilon): """Enforces size of perturbation on images, and compute hashes for all images. Args: dataset_batch_dir: directory with the images of specific dataset batch adv_dir: directory with gen...
def enforce_epsilon_and_compute_hash(dataset_batch_dir, adv_dir, output_dir, epsilon): """Enforces size of perturbation on images, and compute hashes for all images. Args: dataset_batch_dir: directory with the images of specific dataset batch adv_dir: directory with gen...
[ "Enforces", "size", "of", "perturbation", "on", "images", "and", "compute", "hashes", "for", "all", "images", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/dataset_helper.py#L81-L124
[ "def", "enforce_epsilon_and_compute_hash", "(", "dataset_batch_dir", ",", "adv_dir", ",", "output_dir", ",", "epsilon", ")", ":", "dataset_images", "=", "[", "f", "for", "f", "in", "os", ".", "listdir", "(", "dataset_batch_dir", ")", "if", "f", ".", "endswith"...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
download_dataset
Downloads dataset, organize it by batches and rename images. Args: storage_client: instance of the CompetitionStorageClient image_batches: subclass of ImageBatchesBase with data about images target_dir: target directory, should exist and be empty local_dataset_copy: directory with local dataset copy,...
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/dataset_helper.py
def download_dataset(storage_client, image_batches, target_dir, local_dataset_copy=None): """Downloads dataset, organize it by batches and rename images. Args: storage_client: instance of the CompetitionStorageClient image_batches: subclass of ImageBatchesBase with data about images ...
def download_dataset(storage_client, image_batches, target_dir, local_dataset_copy=None): """Downloads dataset, organize it by batches and rename images. Args: storage_client: instance of the CompetitionStorageClient image_batches: subclass of ImageBatchesBase with data about images ...
[ "Downloads", "dataset", "organize", "it", "by", "batches", "and", "rename", "images", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/dataset_helper.py#L127-L159
[ "def", "download_dataset", "(", "storage_client", ",", "image_batches", ",", "target_dir", ",", "local_dataset_copy", "=", "None", ")", ":", "for", "batch_id", ",", "batch_value", "in", "iteritems", "(", "image_batches", ".", "data", ")", ":", "batch_dir", "=", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
DatasetMetadata.save_target_classes_for_batch
Saves file with target class for given dataset batch. Args: filename: output filename image_batches: instance of ImageBatchesBase with dataset batches batch_id: dataset batch ID
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/dataset_helper.py
def save_target_classes_for_batch(self, filename, image_batches, batch_id): """Saves file with target class for given dataset batch. Args: filename: output filename image_batches: instance of...
def save_target_classes_for_batch(self, filename, image_batches, batch_id): """Saves file with target class for given dataset batch. Args: filename: output filename image_batches: instance of...
[ "Saves", "file", "with", "target", "class", "for", "given", "dataset", "batch", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/dataset_helper.py#L63-L78
[ "def", "save_target_classes_for_batch", "(", "self", ",", "filename", ",", "image_batches", ",", "batch_id", ")", ":", "images", "=", "image_batches", ".", "data", "[", "batch_id", "]", "[", "'images'", "]", "with", "open", "(", "filename", ",", "'w'", ")", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
Optimization.tf_min_eig_vec
Function for min eigen vector using tf's full eigen decomposition.
cleverhans/experimental/certification/optimization.py
def tf_min_eig_vec(self): """Function for min eigen vector using tf's full eigen decomposition.""" # Full eigen decomposition requires the explicit psd matrix M _, matrix_m = self.dual_object.get_full_psd_matrix() [eig_vals, eig_vectors] = tf.self_adjoint_eig(matrix_m) index = tf.argmin(eig_vals) ...
def tf_min_eig_vec(self): """Function for min eigen vector using tf's full eigen decomposition.""" # Full eigen decomposition requires the explicit psd matrix M _, matrix_m = self.dual_object.get_full_psd_matrix() [eig_vals, eig_vectors] = tf.self_adjoint_eig(matrix_m) index = tf.argmin(eig_vals) ...
[ "Function", "for", "min", "eigen", "vector", "using", "tf", "s", "full", "eigen", "decomposition", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/optimization.py#L56-L63
[ "def", "tf_min_eig_vec", "(", "self", ")", ":", "# Full eigen decomposition requires the explicit psd matrix M", "_", ",", "matrix_m", "=", "self", ".", "dual_object", ".", "get_full_psd_matrix", "(", ")", "[", "eig_vals", ",", "eig_vectors", "]", "=", "tf", ".", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
Optimization.tf_smooth_eig_vec
Function that returns smoothed version of min eigen vector.
cleverhans/experimental/certification/optimization.py
def tf_smooth_eig_vec(self): """Function that returns smoothed version of min eigen vector.""" _, matrix_m = self.dual_object.get_full_psd_matrix() # Easier to think in terms of max so negating the matrix [eig_vals, eig_vectors] = tf.self_adjoint_eig(-matrix_m) exp_eig_vals = tf.exp(tf.divide(eig_va...
def tf_smooth_eig_vec(self): """Function that returns smoothed version of min eigen vector.""" _, matrix_m = self.dual_object.get_full_psd_matrix() # Easier to think in terms of max so negating the matrix [eig_vals, eig_vectors] = tf.self_adjoint_eig(-matrix_m) exp_eig_vals = tf.exp(tf.divide(eig_va...
[ "Function", "that", "returns", "smoothed", "version", "of", "min", "eigen", "vector", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/optimization.py#L65-L79
[ "def", "tf_smooth_eig_vec", "(", "self", ")", ":", "_", ",", "matrix_m", "=", "self", ".", "dual_object", ".", "get_full_psd_matrix", "(", ")", "# Easier to think in terms of max so negating the matrix", "[", "eig_vals", ",", "eig_vectors", "]", "=", "tf", ".", "s...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
Optimization.get_min_eig_vec_proxy
Computes the min eigen value and corresponding vector of matrix M. Args: use_tf_eig: Whether to use tf's default full eigen decomposition Returns: eig_vec: Minimum absolute eigen value eig_val: Corresponding eigen vector
cleverhans/experimental/certification/optimization.py
def get_min_eig_vec_proxy(self, use_tf_eig=False): """Computes the min eigen value and corresponding vector of matrix M. Args: use_tf_eig: Whether to use tf's default full eigen decomposition Returns: eig_vec: Minimum absolute eigen value eig_val: Corresponding eigen vector """ if...
def get_min_eig_vec_proxy(self, use_tf_eig=False): """Computes the min eigen value and corresponding vector of matrix M. Args: use_tf_eig: Whether to use tf's default full eigen decomposition Returns: eig_vec: Minimum absolute eigen value eig_val: Corresponding eigen vector """ if...
[ "Computes", "the", "min", "eigen", "value", "and", "corresponding", "vector", "of", "matrix", "M", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/optimization.py#L81-L109
[ "def", "get_min_eig_vec_proxy", "(", "self", ",", "use_tf_eig", "=", "False", ")", ":", "if", "use_tf_eig", ":", "# If smoothness parameter is too small, essentially no smoothing", "# Just output the eigen vector corresponding to min", "return", "tf", ".", "cond", "(", "self"...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
Optimization.get_scipy_eig_vec
Computes scipy estimate of min eigenvalue for matrix M. Returns: eig_vec: Minimum absolute eigen value eig_val: Corresponding eigen vector
cleverhans/experimental/certification/optimization.py
def get_scipy_eig_vec(self): """Computes scipy estimate of min eigenvalue for matrix M. Returns: eig_vec: Minimum absolute eigen value eig_val: Corresponding eigen vector """ if not self.params['has_conv']: matrix_m = self.sess.run(self.dual_object.matrix_m) min_eig_vec_val, est...
def get_scipy_eig_vec(self): """Computes scipy estimate of min eigenvalue for matrix M. Returns: eig_vec: Minimum absolute eigen value eig_val: Corresponding eigen vector """ if not self.params['has_conv']: matrix_m = self.sess.run(self.dual_object.matrix_m) min_eig_vec_val, est...
[ "Computes", "scipy", "estimate", "of", "min", "eigenvalue", "for", "matrix", "M", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/optimization.py#L111-L138
[ "def", "get_scipy_eig_vec", "(", "self", ")", ":", "if", "not", "self", ".", "params", "[", "'has_conv'", "]", ":", "matrix_m", "=", "self", ".", "sess", ".", "run", "(", "self", ".", "dual_object", ".", "matrix_m", ")", "min_eig_vec_val", ",", "estimate...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
Optimization.prepare_for_optimization
Create tensorflow op for running one step of descent.
cleverhans/experimental/certification/optimization.py
def prepare_for_optimization(self): """Create tensorflow op for running one step of descent.""" if self.params['eig_type'] == 'TF': self.eig_vec_estimate = self.get_min_eig_vec_proxy() elif self.params['eig_type'] == 'LZS': self.eig_vec_estimate = self.dual_object.m_min_vec else: self....
def prepare_for_optimization(self): """Create tensorflow op for running one step of descent.""" if self.params['eig_type'] == 'TF': self.eig_vec_estimate = self.get_min_eig_vec_proxy() elif self.params['eig_type'] == 'LZS': self.eig_vec_estimate = self.dual_object.m_min_vec else: self....
[ "Create", "tensorflow", "op", "for", "running", "one", "step", "of", "descent", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/optimization.py#L140-L212
[ "def", "prepare_for_optimization", "(", "self", ")", ":", "if", "self", ".", "params", "[", "'eig_type'", "]", "==", "'TF'", ":", "self", ".", "eig_vec_estimate", "=", "self", ".", "get_min_eig_vec_proxy", "(", ")", "elif", "self", ".", "params", "[", "'ei...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
Optimization.run_one_step
Run one step of gradient descent for optimization. Args: eig_init_vec_val: Start value for eigen value computations eig_num_iter_val: Number of iterations to run for eigen computations smooth_val: Value of smoothness parameter penalty_val: Value of penalty for the current step learnin...
cleverhans/experimental/certification/optimization.py
def run_one_step(self, eig_init_vec_val, eig_num_iter_val, smooth_val, penalty_val, learning_rate_val): """Run one step of gradient descent for optimization. Args: eig_init_vec_val: Start value for eigen value computations eig_num_iter_val: Number of iterations to run for eigen c...
def run_one_step(self, eig_init_vec_val, eig_num_iter_val, smooth_val, penalty_val, learning_rate_val): """Run one step of gradient descent for optimization. Args: eig_init_vec_val: Start value for eigen value computations eig_num_iter_val: Number of iterations to run for eigen c...
[ "Run", "one", "step", "of", "gradient", "descent", "for", "optimization", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/optimization.py#L214-L296
[ "def", "run_one_step", "(", "self", ",", "eig_init_vec_val", ",", "eig_num_iter_val", ",", "smooth_val", ",", "penalty_val", ",", "learning_rate_val", ")", ":", "# Running step", "step_feed_dict", "=", "{", "self", ".", "eig_init_vec_placeholder", ":", "eig_init_vec_v...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
Optimization.run_optimization
Run the optimization, call run_one_step with suitable placeholders. Returns: True if certificate is found False otherwise
cleverhans/experimental/certification/optimization.py
def run_optimization(self): """Run the optimization, call run_one_step with suitable placeholders. Returns: True if certificate is found False otherwise """ penalty_val = self.params['init_penalty'] # Don't use smoothing initially - very inaccurate for large dimension self.smooth_on...
def run_optimization(self): """Run the optimization, call run_one_step with suitable placeholders. Returns: True if certificate is found False otherwise """ penalty_val = self.params['init_penalty'] # Don't use smoothing initially - very inaccurate for large dimension self.smooth_on...
[ "Run", "the", "optimization", "call", "run_one_step", "with", "suitable", "placeholders", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/optimization.py#L298-L347
[ "def", "run_optimization", "(", "self", ")", ":", "penalty_val", "=", "self", ".", "params", "[", "'init_penalty'", "]", "# Don't use smoothing initially - very inaccurate for large dimension", "self", ".", "smooth_on", "=", "False", "smooth_val", "=", "0", "learning_ra...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
load_target_class
Loads target classes.
examples/nips17_adversarial_competition/dev_toolkit/sample_targeted_attacks/iter_target_class/attack_iter_target_class.py
def load_target_class(input_dir): """Loads target classes.""" with tf.gfile.Open(os.path.join(input_dir, 'target_class.csv')) as f: return {row[0]: int(row[1]) for row in csv.reader(f) if len(row) >= 2}
def load_target_class(input_dir): """Loads target classes.""" with tf.gfile.Open(os.path.join(input_dir, 'target_class.csv')) as f: return {row[0]: int(row[1]) for row in csv.reader(f) if len(row) >= 2}
[ "Loads", "target", "classes", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/sample_targeted_attacks/iter_target_class/attack_iter_target_class.py#L53-L56
[ "def", "load_target_class", "(", "input_dir", ")", ":", "with", "tf", ".", "gfile", ".", "Open", "(", "os", ".", "path", ".", "join", "(", "input_dir", ",", "'target_class.csv'", ")", ")", "as", "f", ":", "return", "{", "row", "[", "0", "]", ":", "...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
save_images
Saves images to the output directory. Args: images: array with minibatch of images filenames: list of filenames without path If number of file names in this list less than number of images in the minibatch then only first len(filenames) images will be saved. output_dir: directory where to sav...
examples/nips17_adversarial_competition/dev_toolkit/sample_targeted_attacks/iter_target_class/attack_iter_target_class.py
def save_images(images, filenames, output_dir): """Saves images to the output directory. Args: images: array with minibatch of images filenames: list of filenames without path If number of file names in this list less than number of images in the minibatch then only first len(filenames) images ...
def save_images(images, filenames, output_dir): """Saves images to the output directory. Args: images: array with minibatch of images filenames: list of filenames without path If number of file names in this list less than number of images in the minibatch then only first len(filenames) images ...
[ "Saves", "images", "to", "the", "output", "directory", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/sample_targeted_attacks/iter_target_class/attack_iter_target_class.py#L92-L106
[ "def", "save_images", "(", "images", ",", "filenames", ",", "output_dir", ")", ":", "for", "i", ",", "filename", "in", "enumerate", "(", "filenames", ")", ":", "# Images for inception classifier are normalized to be in [-1, 1] interval,", "# so rescale them back to [0, 1]."...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
main
Run the sample attack
examples/nips17_adversarial_competition/dev_toolkit/sample_targeted_attacks/iter_target_class/attack_iter_target_class.py
def main(_): """Run the sample attack""" # Images for inception classifier are normalized to be in [-1, 1] interval, # eps is a difference between pixels so it should be in [0, 2] interval. # Renormalizing epsilon from [0, 255] to [0, 2]. eps = 2.0 * FLAGS.max_epsilon / 255.0 alpha = 2.0 * FLAGS.iter_alpha ...
def main(_): """Run the sample attack""" # Images for inception classifier are normalized to be in [-1, 1] interval, # eps is a difference between pixels so it should be in [0, 2] interval. # Renormalizing epsilon from [0, 255] to [0, 2]. eps = 2.0 * FLAGS.max_epsilon / 255.0 alpha = 2.0 * FLAGS.iter_alpha ...
[ "Run", "the", "sample", "attack" ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/sample_targeted_attacks/iter_target_class/attack_iter_target_class.py#L109-L171
[ "def", "main", "(", "_", ")", ":", "# Images for inception classifier are normalized to be in [-1, 1] interval,", "# eps is a difference between pixels so it should be in [0, 2] interval.", "# Renormalizing epsilon from [0, 255] to [0, 2].", "eps", "=", "2.0", "*", "FLAGS", ".", "max_e...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
deepfool_batch
Applies DeepFool to a batch of inputs :param sess: TF session :param x: The input placeholder :param pred: The model's sorted symbolic output of logits, only the top nb_candidate classes are contained :param logits: The model's unnormalized output tensor (the input to the softmax...
cleverhans/attacks/deep_fool.py
def deepfool_batch(sess, x, pred, logits, grads, X, nb_candidate, overshoot, max_iter, clip_min, clip_max, nb_c...
def deepfool_batch(sess, x, pred, logits, grads, X, nb_candidate, overshoot, max_iter, clip_min, clip_max, nb_c...
[ "Applies", "DeepFool", "to", "a", "batch", "of", "inputs", ":", "param", "sess", ":", "TF", "session", ":", "param", "x", ":", "The", "input", "placeholder", ":", "param", "pred", ":", "The", "model", "s", "sorted", "symbolic", "output", "of", "logits", ...
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/deep_fool.py#L115-L165
[ "def", "deepfool_batch", "(", "sess", ",", "x", ",", "pred", ",", "logits", ",", "grads", ",", "X", ",", "nb_candidate", ",", "overshoot", ",", "max_iter", ",", "clip_min", ",", "clip_max", ",", "nb_classes", ",", "feed", "=", "None", ")", ":", "X_adv"...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
deepfool_attack
TensorFlow implementation of DeepFool. Paper link: see https://arxiv.org/pdf/1511.04599.pdf :param sess: TF session :param x: The input placeholder :param predictions: The model's sorted symbolic output of logits, only the top nb_candidate classes are contained :param logits: The model's ...
cleverhans/attacks/deep_fool.py
def deepfool_attack(sess, x, predictions, logits, grads, sample, nb_candidate, overshoot, max_iter, clip_min, clip_max, ...
def deepfool_attack(sess, x, predictions, logits, grads, sample, nb_candidate, overshoot, max_iter, clip_min, clip_max, ...
[ "TensorFlow", "implementation", "of", "DeepFool", ".", "Paper", "link", ":", "see", "https", ":", "//", "arxiv", ".", "org", "/", "pdf", "/", "1511", ".", "04599", ".", "pdf", ":", "param", "sess", ":", "TF", "session", ":", "param", "x", ":", "The",...
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/deep_fool.py#L168-L252
[ "def", "deepfool_attack", "(", "sess", ",", "x", ",", "predictions", ",", "logits", ",", "grads", ",", "sample", ",", "nb_candidate", ",", "overshoot", ",", "max_iter", ",", "clip_min", ",", "clip_max", ",", "feed", "=", "None", ")", ":", "adv_x", "=", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
DeepFool.generate
Generate symbolic graph for adversarial examples and return. :param x: The model's symbolic inputs. :param kwargs: See `parse_params`
cleverhans/attacks/deep_fool.py
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` """ assert self.sess is not None, \ 'Cannot use `generate` when no `sess` was provided' from cleverhans.utils_tf...
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` """ assert self.sess is not None, \ 'Cannot use `generate` when no `sess` was provided' from cleverhans.utils_tf...
[ "Generate", "symbolic", "graph", "for", "adversarial", "examples", "and", "return", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/deep_fool.py#L48-L83
[ "def", "generate", "(", "self", ",", "x", ",", "*", "*", "kwargs", ")", ":", "assert", "self", ".", "sess", "is", "not", "None", ",", "'Cannot use `generate` when no `sess` was provided'", "from", "cleverhans", ".", "utils_tf", "import", "jacobian_graph", "# Par...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
DeepFool.parse_params
:param nb_candidate: The number of classes to test against, i.e., deepfool only consider nb_candidate classes when attacking(thus accelerate speed). The nb_candidate classes are chosen according to the prediction confide...
cleverhans/attacks/deep_fool.py
def parse_params(self, nb_candidate=10, overshoot=0.02, max_iter=50, clip_min=0., clip_max=1., **kwargs): """ :param nb_candidate: The number of classes to test against, i.e., ...
def parse_params(self, nb_candidate=10, overshoot=0.02, max_iter=50, clip_min=0., clip_max=1., **kwargs): """ :param nb_candidate: The number of classes to test against, i.e., ...
[ ":", "param", "nb_candidate", ":", "The", "number", "of", "classes", "to", "test", "against", "i", ".", "e", ".", "deepfool", "only", "consider", "nb_candidate", "classes", "when", "attacking", "(", "thus", "accelerate", "speed", ")", ".", "The", "nb_candida...
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/deep_fool.py#L85-L112
[ "def", "parse_params", "(", "self", ",", "nb_candidate", "=", "10", ",", "overshoot", "=", "0.02", ",", "max_iter", "=", "50", ",", "clip_min", "=", "0.", ",", "clip_max", "=", "1.", ",", "*", "*", "kwargs", ")", ":", "self", ".", "nb_candidate", "="...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
_py_func_with_gradient
PyFunc defined as given by Tensorflow :param func: Custom Function :param inp: Function Inputs :param Tout: Ouput Type of out Custom Function :param stateful: Calculate Gradients when stateful is True :param name: Name of the PyFunction :param grad: Custom Gradient Function :return:
cleverhans/utils_pytorch.py
def _py_func_with_gradient(func, inp, Tout, stateful=True, name=None, grad_func=None): """ PyFunc defined as given by Tensorflow :param func: Custom Function :param inp: Function Inputs :param Tout: Ouput Type of out Custom Function :param stateful: Calculate Gradients when statef...
def _py_func_with_gradient(func, inp, Tout, stateful=True, name=None, grad_func=None): """ PyFunc defined as given by Tensorflow :param func: Custom Function :param inp: Function Inputs :param Tout: Ouput Type of out Custom Function :param stateful: Calculate Gradients when statef...
[ "PyFunc", "defined", "as", "given", "by", "Tensorflow", ":", "param", "func", ":", "Custom", "Function", ":", "param", "inp", ":", "Function", "Inputs", ":", "param", "Tout", ":", "Ouput", "Type", "of", "out", "Custom", "Function", ":", "param", "stateful"...
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_pytorch.py#L14-L38
[ "def", "_py_func_with_gradient", "(", "func", ",", "inp", ",", "Tout", ",", "stateful", "=", "True", ",", "name", "=", "None", ",", "grad_func", "=", "None", ")", ":", "# Generate random name in order to avoid conflicts with inbuilt names", "rnd_name", "=", "'PyFunc...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
convert_pytorch_model_to_tf
Convert a pytorch model into a tensorflow op that allows backprop :param model: A pytorch nn.Module object :param out_dims: The number of output dimensions (classes) for the model :return: A model function that maps an input (tf.Tensor) to the output of the model (tf.Tensor)
cleverhans/utils_pytorch.py
def convert_pytorch_model_to_tf(model, out_dims=None): """ Convert a pytorch model into a tensorflow op that allows backprop :param model: A pytorch nn.Module object :param out_dims: The number of output dimensions (classes) for the model :return: A model function that maps an input (tf.Tensor) to the outpu...
def convert_pytorch_model_to_tf(model, out_dims=None): """ Convert a pytorch model into a tensorflow op that allows backprop :param model: A pytorch nn.Module object :param out_dims: The number of output dimensions (classes) for the model :return: A model function that maps an input (tf.Tensor) to the outpu...
[ "Convert", "a", "pytorch", "model", "into", "a", "tensorflow", "op", "that", "allows", "backprop", ":", "param", "model", ":", "A", "pytorch", "nn", ".", "Module", "object", ":", "param", "out_dims", ":", "The", "number", "of", "output", "dimensions", "(",...
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_pytorch.py#L41-L94
[ "def", "convert_pytorch_model_to_tf", "(", "model", ",", "out_dims", "=", "None", ")", ":", "warnings", ".", "warn", "(", "\"convert_pytorch_model_to_tf is deprecated, switch to\"", "+", "\" dedicated PyTorch support provided by CleverHans v4.\"", ")", "torch_state", "=", "{"...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
clip_eta
PyTorch implementation of the clip_eta in utils_tf. :param eta: Tensor :param ord: np.inf, 1, or 2 :param eps: float
cleverhans/utils_pytorch.py
def clip_eta(eta, ord, eps): """ PyTorch implementation of the clip_eta in utils_tf. :param eta: Tensor :param ord: np.inf, 1, or 2 :param eps: float """ if ord not in [np.inf, 1, 2]: raise ValueError('ord must be np.inf, 1, or 2.') avoid_zero_div = torch.tensor(1e-12, dtype=eta.dtype, device=eta....
def clip_eta(eta, ord, eps): """ PyTorch implementation of the clip_eta in utils_tf. :param eta: Tensor :param ord: np.inf, 1, or 2 :param eps: float """ if ord not in [np.inf, 1, 2]: raise ValueError('ord must be np.inf, 1, or 2.') avoid_zero_div = torch.tensor(1e-12, dtype=eta.dtype, device=eta....
[ "PyTorch", "implementation", "of", "the", "clip_eta", "in", "utils_tf", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_pytorch.py#L97-L130
[ "def", "clip_eta", "(", "eta", ",", "ord", ",", "eps", ")", ":", "if", "ord", "not", "in", "[", "np", ".", "inf", ",", "1", ",", "2", "]", ":", "raise", "ValueError", "(", "'ord must be np.inf, 1, or 2.'", ")", "avoid_zero_div", "=", "torch", ".", "t...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
get_or_guess_labels
Get the label to use in generating an adversarial example for x. The kwargs are fed directly from the kwargs of the attack. If 'y' is in kwargs, then assume it's an untargeted attack and use that as the label. If 'y_target' is in kwargs and is not none, then assume it's a targeted attack and use that as the l...
cleverhans/utils_pytorch.py
def get_or_guess_labels(model, x, **kwargs): """ Get the label to use in generating an adversarial example for x. The kwargs are fed directly from the kwargs of the attack. If 'y' is in kwargs, then assume it's an untargeted attack and use that as the label. If 'y_target' is in kwargs and is not none, then ...
def get_or_guess_labels(model, x, **kwargs): """ Get the label to use in generating an adversarial example for x. The kwargs are fed directly from the kwargs of the attack. If 'y' is in kwargs, then assume it's an untargeted attack and use that as the label. If 'y_target' is in kwargs and is not none, then ...
[ "Get", "the", "label", "to", "use", "in", "generating", "an", "adversarial", "example", "for", "x", ".", "The", "kwargs", "are", "fed", "directly", "from", "the", "kwargs", "of", "the", "attack", ".", "If", "y", "is", "in", "kwargs", "then", "assume", ...
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_pytorch.py#L132-L156
[ "def", "get_or_guess_labels", "(", "model", ",", "x", ",", "*", "*", "kwargs", ")", ":", "if", "'y'", "in", "kwargs", "and", "'y_target'", "in", "kwargs", ":", "raise", "ValueError", "(", "\"Can not set both 'y' and 'y_target'.\"", ")", "if", "'y'", "in", "k...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
optimize_linear
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: Tensor, shape (N, d_1, ...). Batch of gradients :param eps: float. Scalar specifying size of constraint region :param ord: np.inf, 1, or 2. Order of n...
cleverhans/utils_pytorch.py
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: Tensor, shape (N, d_1, ...). Batch of gradients :param eps: float. Scalar specifying size of constra...
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: Tensor, shape (N, d_1, ...). Batch of gradients :param eps: float. Scalar specifying size of constra...
[ "Solves", "for", "the", "optimal", "input", "to", "a", "linear", "function", "under", "a", "norm", "constraint", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_pytorch.py#L159-L213
[ "def", "optimize_linear", "(", "grad", ",", "eps", ",", "ord", "=", "np", ".", "inf", ")", ":", "red_ind", "=", "list", "(", "range", "(", "1", ",", "len", "(", "grad", ".", "size", "(", ")", ")", ")", ")", "avoid_zero_div", "=", "torch", ".", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
ElasticNetMethod.parse_params
:param y: (optional) A tensor with the true labels for an untargeted attack. If None (and y_target is None) then use the original labels the classifier assigns. :param y_target: (optional) A tensor with the target labels for a targeted attack. :param beta: Trades off L2...
cleverhans/attacks/elastic_net_method.py
def parse_params(self, y=None, y_target=None, beta=1e-2, decision_rule='EN', batch_size=1, confidence=0, learning_rate=1e-2, binary_search_steps=9, m...
def parse_params(self, y=None, y_target=None, beta=1e-2, decision_rule='EN', batch_size=1, confidence=0, learning_rate=1e-2, binary_search_steps=9, m...
[ ":", "param", "y", ":", "(", "optional", ")", "A", "tensor", "with", "the", "true", "labels", "for", "an", "untargeted", "attack", ".", "If", "None", "(", "and", "y_target", "is", "None", ")", "then", "use", "the", "original", "labels", "the", "classif...
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/elastic_net_method.py#L91-L162
[ "def", "parse_params", "(", "self", ",", "y", "=", "None", ",", "y_target", "=", "None", ",", "beta", "=", "1e-2", ",", "decision_rule", "=", "'EN'", ",", "batch_size", "=", "1", ",", "confidence", "=", "0", ",", "learning_rate", "=", "1e-2", ",", "b...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
EAD.attack
Perform the EAD attack on the given instance for the given targets. If self.targeted is true, then the targets represents the target labels If self.targeted is false, then targets are the original class labels
cleverhans/attacks/elastic_net_method.py
def attack(self, imgs, targets): """ Perform the EAD attack on the given instance for the given targets. If self.targeted is true, then the targets represents the target labels If self.targeted is false, then targets are the original class labels """ batch_size = self.batch_size r = [] ...
def attack(self, imgs, targets): """ Perform the EAD attack on the given instance for the given targets. If self.targeted is true, then the targets represents the target labels If self.targeted is false, then targets are the original class labels """ batch_size = self.batch_size r = [] ...
[ "Perform", "the", "EAD", "attack", "on", "the", "given", "instance", "for", "the", "given", "targets", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/elastic_net_method.py#L374-L404
[ "def", "attack", "(", "self", ",", "imgs", ",", "targets", ")", ":", "batch_size", "=", "self", ".", "batch_size", "r", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "imgs", ")", "//", "batch_size", ")", ":", "_logger", "."...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
print_in_box
Prints `text` surrounded by a box made of *s
examples/nips17_adversarial_competition/dev_toolkit/validation_tool/validate_submission.py
def print_in_box(text): """ Prints `text` surrounded by a box made of *s """ print('') print('*' * (len(text) + 6)) print('** ' + text + ' **') print('*' * (len(text) + 6)) print('')
def print_in_box(text): """ Prints `text` surrounded by a box made of *s """ print('') print('*' * (len(text) + 6)) print('** ' + text + ' **') print('*' * (len(text) + 6)) print('')
[ "Prints", "text", "surrounded", "by", "a", "box", "made", "of", "*", "s" ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/validation_tool/validate_submission.py#L30-L38
[ "def", "print_in_box", "(", "text", ")", ":", "print", "(", "''", ")", "print", "(", "'*'", "*", "(", "len", "(", "text", ")", "+", "6", ")", ")", "print", "(", "'** '", "+", "text", "+", "' **'", ")", "print", "(", "'*'", "*", "(", "len", "(...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
main
Validates the submission.
examples/nips17_adversarial_competition/dev_toolkit/validation_tool/validate_submission.py
def main(args): """ Validates the submission. """ print_in_box('Validating submission ' + args.submission_filename) random.seed() temp_dir = args.temp_dir delete_temp_dir = False if not temp_dir: temp_dir = tempfile.mkdtemp() logging.info('Created temporary directory: %s', temp_dir) delete_t...
def main(args): """ Validates the submission. """ print_in_box('Validating submission ' + args.submission_filename) random.seed() temp_dir = args.temp_dir delete_temp_dir = False if not temp_dir: temp_dir = tempfile.mkdtemp() logging.info('Created temporary directory: %s', temp_dir) delete_t...
[ "Validates", "the", "submission", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/validation_tool/validate_submission.py#L41-L62
[ "def", "main", "(", "args", ")", ":", "print_in_box", "(", "'Validating submission '", "+", "args", ".", "submission_filename", ")", "random", ".", "seed", "(", ")", "temp_dir", "=", "args", ".", "temp_dir", "delete_temp_dir", "=", "False", "if", "not", "tem...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
main
Make a confidence report and save it to disk.
scripts/make_confidence_report.py
def main(argv=None): """ Make a confidence report and save it to disk. """ try: _name_of_script, filepath = argv except ValueError: raise ValueError(argv) make_confidence_report(filepath=filepath, test_start=FLAGS.test_start, test_end=FLAGS.test_end, which_set=FLAGS.which_se...
def main(argv=None): """ Make a confidence report and save it to disk. """ try: _name_of_script, filepath = argv except ValueError: raise ValueError(argv) make_confidence_report(filepath=filepath, test_start=FLAGS.test_start, test_end=FLAGS.test_end, which_set=FLAGS.which_se...
[ "Make", "a", "confidence", "report", "and", "save", "it", "to", "disk", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/scripts/make_confidence_report.py#L56-L71
[ "def", "main", "(", "argv", "=", "None", ")", ":", "try", ":", "_name_of_script", ",", "filepath", "=", "argv", "except", "ValueError", ":", "raise", "ValueError", "(", "argv", ")", "make_confidence_report", "(", "filepath", "=", "filepath", ",", "test_start...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
make_confidence_report_spsa
Load a saved model, gather its predictions, and save a confidence report. This function works by running a single MaxConfidence attack on each example, using SPSA as the underyling optimizer. This is not intended to be a strong generic attack. It is intended to be a test to uncover gradient masking. :param...
scripts/make_confidence_report_spsa.py
def make_confidence_report_spsa(filepath, train_start=TRAIN_START, train_end=TRAIN_END, test_start=TEST_START, test_end=TEST_END, batch_size=BATCH_SIZE, which_set=WHICH_SET, report_path=REPORT...
def make_confidence_report_spsa(filepath, train_start=TRAIN_START, train_end=TRAIN_END, test_start=TEST_START, test_end=TEST_END, batch_size=BATCH_SIZE, which_set=WHICH_SET, report_path=REPORT...
[ "Load", "a", "saved", "model", "gather", "its", "predictions", "and", "save", "a", "confidence", "report", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/scripts/make_confidence_report_spsa.py#L56-L133
[ "def", "make_confidence_report_spsa", "(", "filepath", ",", "train_start", "=", "TRAIN_START", ",", "train_end", "=", "TRAIN_END", ",", "test_start", "=", "TEST_START", ",", "test_end", "=", "TEST_END", ",", "batch_size", "=", "BATCH_SIZE", ",", "which_set", "=", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
main
Make a confidence report and save it to disk.
scripts/make_confidence_report_spsa.py
def main(argv=None): """ Make a confidence report and save it to disk. """ try: _name_of_script, filepath = argv except ValueError: raise ValueError(argv) make_confidence_report_spsa(filepath=filepath, test_start=FLAGS.test_start, test_end=FLAGS.test_end, ...
def main(argv=None): """ Make a confidence report and save it to disk. """ try: _name_of_script, filepath = argv except ValueError: raise ValueError(argv) make_confidence_report_spsa(filepath=filepath, test_start=FLAGS.test_start, test_end=FLAGS.test_end, ...
[ "Make", "a", "confidence", "report", "and", "save", "it", "to", "disk", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/scripts/make_confidence_report_spsa.py#L135-L150
[ "def", "main", "(", "argv", "=", "None", ")", ":", "try", ":", "_name_of_script", ",", "filepath", "=", "argv", "except", "ValueError", ":", "raise", "ValueError", "(", "argv", ")", "make_confidence_report_spsa", "(", "filepath", "=", "filepath", ",", "test_...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
MadryEtAlMultiGPU.attack
This method creates a symoblic graph of the MadryEtAl attack on multiple GPUs. The graph is created on the first n GPUs. Stop gradient is needed to get the speed-up. This prevents us from being able to back-prop through the attack. :param x: A tensor with the input image. :param y_p: Ground truth ...
examples/multigpu_advtrain/attacks_multigpu.py
def attack(self, x, y_p, **kwargs): """ This method creates a symoblic graph of the MadryEtAl attack on multiple GPUs. The graph is created on the first n GPUs. Stop gradient is needed to get the speed-up. This prevents us from being able to back-prop through the attack. :param x: A tensor wit...
def attack(self, x, y_p, **kwargs): """ This method creates a symoblic graph of the MadryEtAl attack on multiple GPUs. The graph is created on the first n GPUs. Stop gradient is needed to get the speed-up. This prevents us from being able to back-prop through the attack. :param x: A tensor wit...
[ "This", "method", "creates", "a", "symoblic", "graph", "of", "the", "MadryEtAl", "attack", "on", "multiple", "GPUs", ".", "The", "graph", "is", "created", "on", "the", "first", "n", "GPUs", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/attacks_multigpu.py#L42-L106
[ "def", "attack", "(", "self", ",", "x", ",", "y_p", ",", "*", "*", "kwargs", ")", ":", "inputs", "=", "[", "]", "outputs", "=", "[", "]", "# Create the initial random perturbation", "device_name", "=", "'/gpu:0'", "self", ".", "model", ".", "set_device", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
MadryEtAlMultiGPU.generate_np
Facilitates testing this attack.
examples/multigpu_advtrain/attacks_multigpu.py
def generate_np(self, x_val, **kwargs): """ Facilitates testing this attack. """ _, feedable, _feedable_types, hash_key = self.construct_variables(kwargs) if hash_key not in self.graphs: with tf.variable_scope(None, 'attack_%d' % len(self.graphs)): # x is a special placeholder we alwa...
def generate_np(self, x_val, **kwargs): """ Facilitates testing this attack. """ _, feedable, _feedable_types, hash_key = self.construct_variables(kwargs) if hash_key not in self.graphs: with tf.variable_scope(None, 'attack_%d' % len(self.graphs)): # x is a special placeholder we alwa...
[ "Facilitates", "testing", "this", "attack", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/attacks_multigpu.py#L108-L134
[ "def", "generate_np", "(", "self", ",", "x_val", ",", "*", "*", "kwargs", ")", ":", "_", ",", "feedable", ",", "_feedable_types", ",", "hash_key", "=", "self", ".", "construct_variables", "(", "kwargs", ")", "if", "hash_key", "not", "in", "self", ".", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
MadryEtAlMultiGPU.parse_params
Take in a dictionary of parameters and applies attack-specific checks before saving them as attributes. Attack-specific parameters: :param ngpu: (required int) the number of GPUs available. :param kwargs: A dictionary of parameters for MadryEtAl attack.
examples/multigpu_advtrain/attacks_multigpu.py
def parse_params(self, ngpu=1, **kwargs): """ Take in a dictionary of parameters and applies attack-specific checks before saving them as attributes. Attack-specific parameters: :param ngpu: (required int) the number of GPUs available. :param kwargs: A dictionary of parameters for MadryEtAl att...
def parse_params(self, ngpu=1, **kwargs): """ Take in a dictionary of parameters and applies attack-specific checks before saving them as attributes. Attack-specific parameters: :param ngpu: (required int) the number of GPUs available. :param kwargs: A dictionary of parameters for MadryEtAl att...
[ "Take", "in", "a", "dictionary", "of", "parameters", "and", "applies", "attack", "-", "specific", "checks", "before", "saving", "them", "as", "attributes", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/attacks_multigpu.py#L136-L149
[ "def", "parse_params", "(", "self", ",", "ngpu", "=", "1", ",", "*", "*", "kwargs", ")", ":", "return_status", "=", "super", "(", "MadryEtAlMultiGPU", ",", "self", ")", ".", "parse_params", "(", "*", "*", "kwargs", ")", "self", ".", "ngpu", "=", "ngp...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
accuracy
Compute the accuracy of a TF model on some data :param sess: TF session to use when training the graph :param model: cleverhans.model.Model instance :param x: numpy array containing input examples (e.g. MNIST().x_test ) :param y: numpy array containing example labels (e.g. MNIST().y_test ) :param batch_size: ...
cleverhans/evaluation.py
def accuracy(sess, model, x, y, batch_size=None, devices=None, feed=None, attack=None, attack_params=None): """ Compute the accuracy of a TF model on some data :param sess: TF session to use when training the graph :param model: cleverhans.model.Model instance :param x: numpy array containing inp...
def accuracy(sess, model, x, y, batch_size=None, devices=None, feed=None, attack=None, attack_params=None): """ Compute the accuracy of a TF model on some data :param sess: TF session to use when training the graph :param model: cleverhans.model.Model instance :param x: numpy array containing inp...
[ "Compute", "the", "accuracy", "of", "a", "TF", "model", "on", "some", "data", ":", "param", "sess", ":", "TF", "session", "to", "use", "when", "training", "the", "graph", ":", "param", "model", ":", "cleverhans", ".", "model", ".", "Model", "instance", ...
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/evaluation.py#L18-L60
[ "def", "accuracy", "(", "sess", ",", "model", ",", "x", ",", "y", ",", "batch_size", "=", "None", ",", "devices", "=", "None", ",", "feed", "=", "None", ",", "attack", "=", "None", ",", "attack_params", "=", "None", ")", ":", "_check_x", "(", "x", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
class_and_confidence
Return the model's classification of the input data, and the confidence (probability) assigned to each example. :param sess: tf.Session :param model: cleverhans.model.Model :param x: numpy array containing input examples (e.g. MNIST().x_test ) :param y: numpy array containing true labels (Needed only if u...
cleverhans/evaluation.py
def class_and_confidence(sess, model, x, y=None, batch_size=None, devices=None, feed=None, attack=None, attack_params=None): """ Return the model's classification of the input data, and the confidence (probability) assigned to each example. :param sess: tf.Sessi...
def class_and_confidence(sess, model, x, y=None, batch_size=None, devices=None, feed=None, attack=None, attack_params=None): """ Return the model's classification of the input data, and the confidence (probability) assigned to each example. :param sess: tf.Sessi...
[ "Return", "the", "model", "s", "classification", "of", "the", "input", "data", "and", "the", "confidence", "(", "probability", ")", "assigned", "to", "each", "example", ".", ":", "param", "sess", ":", "tf", ".", "Session", ":", "param", "model", ":", "cl...
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/evaluation.py#L63-L126
[ "def", "class_and_confidence", "(", "sess", ",", "model", ",", "x", ",", "y", "=", "None", ",", "batch_size", "=", "None", ",", "devices", "=", "None", ",", "feed", "=", "None", ",", "attack", "=", "None", ",", "attack_params", "=", "None", ")", ":",...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
correctness_and_confidence
Report whether the model is correct and its confidence on each example in a dataset. :param sess: tf.Session :param model: cleverhans.model.Model :param x: numpy array containing input examples (e.g. MNIST().x_test ) :param y: numpy array containing example labels (e.g. MNIST().y_test ) :param batch_size: N...
cleverhans/evaluation.py
def correctness_and_confidence(sess, model, x, y, batch_size=None, devices=None, feed=None, attack=None, attack_params=None): """ Report whether the model is correct and its confidence on each example in a dataset. :param sess: tf.Session :param mo...
def correctness_and_confidence(sess, model, x, y, batch_size=None, devices=None, feed=None, attack=None, attack_params=None): """ Report whether the model is correct and its confidence on each example in a dataset. :param sess: tf.Session :param mo...
[ "Report", "whether", "the", "model", "is", "correct", "and", "its", "confidence", "on", "each", "example", "in", "a", "dataset", ".", ":", "param", "sess", ":", "tf", ".", "Session", ":", "param", "model", ":", "cleverhans", ".", "model", ".", "Model", ...
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/evaluation.py#L129-L188
[ "def", "correctness_and_confidence", "(", "sess", ",", "model", ",", "x", ",", "y", ",", "batch_size", "=", "None", ",", "devices", "=", "None", ",", "feed", "=", "None", ",", "attack", "=", "None", ",", "attack_params", "=", "None", ")", ":", "_check_...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
run_attack
Run attack on every example in a dataset. :param sess: tf.Session :param model: cleverhans.model.Model :param x: numpy array containing input examples (e.g. MNIST().x_test ) :param y: numpy array containing example labels (e.g. MNIST().y_test ) :param attack: cleverhans.attack.Attack :param attack_params: d...
cleverhans/evaluation.py
def run_attack(sess, model, x, y, attack, attack_params, batch_size=None, devices=None, feed=None, pass_y=False): """ Run attack on every example in a dataset. :param sess: tf.Session :param model: cleverhans.model.Model :param x: numpy array containing input examples (e.g. MNIST().x_test ) :...
def run_attack(sess, model, x, y, attack, attack_params, batch_size=None, devices=None, feed=None, pass_y=False): """ Run attack on every example in a dataset. :param sess: tf.Session :param model: cleverhans.model.Model :param x: numpy array containing input examples (e.g. MNIST().x_test ) :...
[ "Run", "attack", "on", "every", "example", "in", "a", "dataset", ".", ":", "param", "sess", ":", "tf", ".", "Session", ":", "param", "model", ":", "cleverhans", ".", "model", ".", "Model", ":", "param", "x", ":", "numpy", "array", "containing", "input"...
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/evaluation.py#L191-L228
[ "def", "run_attack", "(", "sess", ",", "model", ",", "x", ",", "y", ",", "attack", ",", "attack_params", ",", "batch_size", "=", "None", ",", "devices", "=", "None", ",", "feed", "=", "None", ",", "pass_y", "=", "False", ")", ":", "_check_x", "(", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
batch_eval_multi_worker
Generic computation engine for evaluating an expression across a whole dataset, divided into batches. This function assumes that the work can be parallelized with one worker device handling one batch of data. If you need multiple devices per batch, use `batch_eval`. The tensorflow graph for multiple workers...
cleverhans/evaluation.py
def batch_eval_multi_worker(sess, graph_factory, numpy_inputs, batch_size=None, devices=None, feed=None): """ Generic computation engine for evaluating an expression across a whole dataset, divided into batches. This function assumes that the work can be parallelized with one worker...
def batch_eval_multi_worker(sess, graph_factory, numpy_inputs, batch_size=None, devices=None, feed=None): """ Generic computation engine for evaluating an expression across a whole dataset, divided into batches. This function assumes that the work can be parallelized with one worker...
[ "Generic", "computation", "engine", "for", "evaluating", "an", "expression", "across", "a", "whole", "dataset", "divided", "into", "batches", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/evaluation.py#L231-L411
[ "def", "batch_eval_multi_worker", "(", "sess", ",", "graph_factory", ",", "numpy_inputs", ",", "batch_size", "=", "None", ",", "devices", "=", "None", ",", "feed", "=", "None", ")", ":", "canary", ".", "run_canary", "(", ")", "global", "_batch_eval_multi_worke...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
batch_eval
A helper function that computes a tensor on numpy inputs by batches. This version uses exactly the tensorflow graph constructed by the caller, so the caller can place specific ops on specific devices to implement model parallelism. Most users probably prefer `batch_eval_multi_worker` which maps a single-devic...
cleverhans/evaluation.py
def batch_eval(sess, tf_inputs, tf_outputs, numpy_inputs, batch_size=None, feed=None, args=None): """ A helper function that computes a tensor on numpy inputs by batches. This version uses exactly the tensorflow graph constructed by the caller, so the caller can place specific ops ...
def batch_eval(sess, tf_inputs, tf_outputs, numpy_inputs, batch_size=None, feed=None, args=None): """ A helper function that computes a tensor on numpy inputs by batches. This version uses exactly the tensorflow graph constructed by the caller, so the caller can place specific ops ...
[ "A", "helper", "function", "that", "computes", "a", "tensor", "on", "numpy", "inputs", "by", "batches", ".", "This", "version", "uses", "exactly", "the", "tensorflow", "graph", "constructed", "by", "the", "caller", "so", "the", "caller", "can", "place", "spe...
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/evaluation.py#L414-L488
[ "def", "batch_eval", "(", "sess", ",", "tf_inputs", ",", "tf_outputs", ",", "numpy_inputs", ",", "batch_size", "=", "None", ",", "feed", "=", "None", ",", "args", "=", "None", ")", ":", "if", "args", "is", "not", "None", ":", "warnings", ".", "warn", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
_check_y
Makes sure a `y` argument is a vliad numpy dataset.
cleverhans/evaluation.py
def _check_y(y): """ Makes sure a `y` argument is a vliad numpy dataset. """ if not isinstance(y, np.ndarray): raise TypeError("y must be numpy array. Typically y contains " "the entire test set labels. Got " + str(y) + " of type " + str(type(y)))
def _check_y(y): """ Makes sure a `y` argument is a vliad numpy dataset. """ if not isinstance(y, np.ndarray): raise TypeError("y must be numpy array. Typically y contains " "the entire test set labels. Got " + str(y) + " of type " + str(type(y)))
[ "Makes", "sure", "a", "y", "argument", "is", "a", "vliad", "numpy", "dataset", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/evaluation.py#L726-L732
[ "def", "_check_y", "(", "y", ")", ":", "if", "not", "isinstance", "(", "y", ",", "np", ".", "ndarray", ")", ":", "raise", "TypeError", "(", "\"y must be numpy array. Typically y contains \"", "\"the entire test set labels. Got \"", "+", "str", "(", "y", ")", "+"...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
load_images
Read png images from input directory in batches. Args: input_dir: input directory batch_shape: shape of minibatch array, i.e. [batch_size, height, width, 3] Yields: filenames: list file names without path of each image Length of this list could be less than batch_size, in this case only fi...
examples/nips17_adversarial_competition/dev_toolkit/sample_attacks/noop/attack_noop.py
def load_images(input_dir, batch_shape): """Read png images from input directory in batches. Args: input_dir: input directory batch_shape: shape of minibatch array, i.e. [batch_size, height, width, 3] Yields: filenames: list file names without path of each image Length of this list could be le...
def load_images(input_dir, batch_shape): """Read png images from input directory in batches. Args: input_dir: input directory batch_shape: shape of minibatch array, i.e. [batch_size, height, width, 3] Yields: filenames: list file names without path of each image Length of this list could be le...
[ "Read", "png", "images", "from", "input", "directory", "in", "batches", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/sample_attacks/noop/attack_noop.py#L40-L68
[ "def", "load_images", "(", "input_dir", ",", "batch_shape", ")", ":", "images", "=", "np", ".", "zeros", "(", "batch_shape", ")", "filenames", "=", "[", "]", "idx", "=", "0", "batch_size", "=", "batch_shape", "[", "0", "]", "for", "filepath", "in", "tf...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
main
Run the sample attack
examples/nips17_adversarial_competition/dev_toolkit/sample_attacks/noop/attack_noop.py
def main(_): """Run the sample attack""" batch_shape = [FLAGS.batch_size, FLAGS.image_height, FLAGS.image_width, 3] for filenames, images in load_images(FLAGS.input_dir, batch_shape): save_images(images, filenames, FLAGS.output_dir)
def main(_): """Run the sample attack""" batch_shape = [FLAGS.batch_size, FLAGS.image_height, FLAGS.image_width, 3] for filenames, images in load_images(FLAGS.input_dir, batch_shape): save_images(images, filenames, FLAGS.output_dir)
[ "Run", "the", "sample", "attack" ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/sample_attacks/noop/attack_noop.py#L86-L90
[ "def", "main", "(", "_", ")", ":", "batch_shape", "=", "[", "FLAGS", ".", "batch_size", ",", "FLAGS", ".", "image_height", ",", "FLAGS", ".", "image_width", ",", "3", "]", "for", "filenames", ",", "images", "in", "load_images", "(", "FLAGS", ".", "inpu...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
preprocess_batch
Creates a preprocessing graph for a batch given a function that processes a single image. :param images_batch: A tensor for an image batch. :param preproc_func: (optional function) A function that takes in a tensor and returns a preprocessed input.
examples/multigpu_advtrain/utils.py
def preprocess_batch(images_batch, preproc_func=None): """ Creates a preprocessing graph for a batch given a function that processes a single image. :param images_batch: A tensor for an image batch. :param preproc_func: (optional function) A function that takes in a tensor and returns a preprocessed in...
def preprocess_batch(images_batch, preproc_func=None): """ Creates a preprocessing graph for a batch given a function that processes a single image. :param images_batch: A tensor for an image batch. :param preproc_func: (optional function) A function that takes in a tensor and returns a preprocessed in...
[ "Creates", "a", "preprocessing", "graph", "for", "a", "batch", "given", "a", "function", "that", "processes", "a", "single", "image", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/utils.py#L5-L25
[ "def", "preprocess_batch", "(", "images_batch", ",", "preproc_func", "=", "None", ")", ":", "if", "preproc_func", "is", "None", ":", "return", "images_batch", "with", "tf", ".", "variable_scope", "(", "'preprocess'", ")", ":", "images_list", "=", "tf", ".", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
Model.get_logits
:param x: A symbolic representation (Tensor) of the network input :return: A symbolic representation (Tensor) of the output logits (i.e., the values fed as inputs to the softmax layer).
cleverhans/model.py
def get_logits(self, x, **kwargs): """ :param x: A symbolic representation (Tensor) of the network input :return: A symbolic representation (Tensor) of the output logits (i.e., the values fed as inputs to the softmax layer). """ outputs = self.fprop(x, **kwargs) if self.O_LOGITS in outputs: ...
def get_logits(self, x, **kwargs): """ :param x: A symbolic representation (Tensor) of the network input :return: A symbolic representation (Tensor) of the output logits (i.e., the values fed as inputs to the softmax layer). """ outputs = self.fprop(x, **kwargs) if self.O_LOGITS in outputs: ...
[ ":", "param", "x", ":", "A", "symbolic", "representation", "(", "Tensor", ")", "of", "the", "network", "input", ":", "return", ":", "A", "symbolic", "representation", "(", "Tensor", ")", "of", "the", "output", "logits", "(", "i", ".", "e", ".", "the", ...
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model.py#L59-L70
[ "def", "get_logits", "(", "self", ",", "x", ",", "*", "*", "kwargs", ")", ":", "outputs", "=", "self", ".", "fprop", "(", "x", ",", "*", "*", "kwargs", ")", "if", "self", ".", "O_LOGITS", "in", "outputs", ":", "return", "outputs", "[", "self", "....
97488e215760547b81afc53f5e5de8ba7da5bd98
train
Model.get_predicted_class
:param x: A symbolic representation (Tensor) of the network input :return: A symbolic representation (Tensor) of the predicted label
cleverhans/model.py
def get_predicted_class(self, x, **kwargs): """ :param x: A symbolic representation (Tensor) of the network input :return: A symbolic representation (Tensor) of the predicted label """ return tf.argmax(self.get_logits(x, **kwargs), axis=1)
def get_predicted_class(self, x, **kwargs): """ :param x: A symbolic representation (Tensor) of the network input :return: A symbolic representation (Tensor) of the predicted label """ return tf.argmax(self.get_logits(x, **kwargs), axis=1)
[ ":", "param", "x", ":", "A", "symbolic", "representation", "(", "Tensor", ")", "of", "the", "network", "input", ":", "return", ":", "A", "symbolic", "representation", "(", "Tensor", ")", "of", "the", "predicted", "label" ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model.py#L72-L77
[ "def", "get_predicted_class", "(", "self", ",", "x", ",", "*", "*", "kwargs", ")", ":", "return", "tf", ".", "argmax", "(", "self", ".", "get_logits", "(", "x", ",", "*", "*", "kwargs", ")", ",", "axis", "=", "1", ")" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
train
Model.get_probs
:param x: A symbolic representation (Tensor) of the network input :return: A symbolic representation (Tensor) of the output probabilities (i.e., the output values produced by the softmax layer).
cleverhans/model.py
def get_probs(self, x, **kwargs): """ :param x: A symbolic representation (Tensor) of the network input :return: A symbolic representation (Tensor) of the output probabilities (i.e., the output values produced by the softmax layer). """ d = self.fprop(x, **kwargs) if self.O_PROBS in d: ...
def get_probs(self, x, **kwargs): """ :param x: A symbolic representation (Tensor) of the network input :return: A symbolic representation (Tensor) of the output probabilities (i.e., the output values produced by the softmax layer). """ d = self.fprop(x, **kwargs) if self.O_PROBS in d: ...
[ ":", "param", "x", ":", "A", "symbolic", "representation", "(", "Tensor", ")", "of", "the", "network", "input", ":", "return", ":", "A", "symbolic", "representation", "(", "Tensor", ")", "of", "the", "output", "probabilities", "(", "i", ".", "e", ".", ...
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model.py#L79-L100
[ "def", "get_probs", "(", "self", ",", "x", ",", "*", "*", "kwargs", ")", ":", "d", "=", "self", ".", "fprop", "(", "x", ",", "*", "*", "kwargs", ")", "if", "self", ".", "O_PROBS", "in", "d", ":", "output", "=", "d", "[", "self", ".", "O_PROBS...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
Model.get_params
Provides access to the model's parameters. :return: A list of all Variables defining the model parameters.
cleverhans/model.py
def get_params(self): """ Provides access to the model's parameters. :return: A list of all Variables defining the model parameters. """ if hasattr(self, 'params'): return list(self.params) # Catch eager execution and assert function overload. try: if tf.executing_eagerly(): ...
def get_params(self): """ Provides access to the model's parameters. :return: A list of all Variables defining the model parameters. """ if hasattr(self, 'params'): return list(self.params) # Catch eager execution and assert function overload. try: if tf.executing_eagerly(): ...
[ "Provides", "access", "to", "the", "model", "s", "parameters", ".", ":", "return", ":", "A", "list", "of", "all", "Variables", "defining", "the", "model", "parameters", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model.py#L111-L150
[ "def", "get_params", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "'params'", ")", ":", "return", "list", "(", "self", ".", "params", ")", "# Catch eager execution and assert function overload.", "try", ":", "if", "tf", ".", "executing_eagerly", "...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
Model.make_params
Create all Variables to be returned later by get_params. By default this is a no-op. Models that need their fprop to be called for their params to be created can set `needs_dummy_fprop=True` in the constructor.
cleverhans/model.py
def make_params(self): """ Create all Variables to be returned later by get_params. By default this is a no-op. Models that need their fprop to be called for their params to be created can set `needs_dummy_fprop=True` in the constructor. """ if self.needs_dummy_fprop: if hasattr(self,...
def make_params(self): """ Create all Variables to be returned later by get_params. By default this is a no-op. Models that need their fprop to be called for their params to be created can set `needs_dummy_fprop=True` in the constructor. """ if self.needs_dummy_fprop: if hasattr(self,...
[ "Create", "all", "Variables", "to", "be", "returned", "later", "by", "get_params", ".", "By", "default", "this", "is", "a", "no", "-", "op", ".", "Models", "that", "need", "their", "fprop", "to", "be", "called", "for", "their", "params", "to", "be", "c...
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model.py#L152-L164
[ "def", "make_params", "(", "self", ")", ":", "if", "self", ".", "needs_dummy_fprop", ":", "if", "hasattr", "(", "self", ",", "\"_dummy_input\"", ")", ":", "return", "self", ".", "_dummy_input", "=", "self", ".", "make_input_placeholder", "(", ")", "self", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
Model.get_layer
Return a layer output. :param x: tensor, the input to the network. :param layer: str, the name of the layer to compute. :param **kwargs: dict, extra optional params to pass to self.fprop. :return: the content of layer `layer`
cleverhans/model.py
def get_layer(self, x, layer, **kwargs): """Return a layer output. :param x: tensor, the input to the network. :param layer: str, the name of the layer to compute. :param **kwargs: dict, extra optional params to pass to self.fprop. :return: the content of layer `layer` """ return self.fprop(...
def get_layer(self, x, layer, **kwargs): """Return a layer output. :param x: tensor, the input to the network. :param layer: str, the name of the layer to compute. :param **kwargs: dict, extra optional params to pass to self.fprop. :return: the content of layer `layer` """ return self.fprop(...
[ "Return", "a", "layer", "output", ".", ":", "param", "x", ":", "tensor", "the", "input", "to", "the", "network", ".", ":", "param", "layer", ":", "str", "the", "name", "of", "the", "layer", "to", "compute", ".", ":", "param", "**", "kwargs", ":", "...
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model.py#L170-L177
[ "def", "get_layer", "(", "self", ",", "x", ",", "layer", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "fprop", "(", "x", ",", "*", "*", "kwargs", ")", "[", "layer", "]" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
train
plot_reliability_diagram
Takes in confidence values for predictions and correct labels for the data, plots a reliability diagram. :param confidence: nb_samples x nb_classes (e.g., output of softmax) :param labels: vector of nb_samples :param filepath: where to save the diagram :return:
cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py
def plot_reliability_diagram(confidence, labels, filepath): """ Takes in confidence values for predictions and correct labels for the data, plots a reliability diagram. :param confidence: nb_samples x nb_classes (e.g., output of softmax) :param labels: vector of nb_samples :param filepath: where to save the...
def plot_reliability_diagram(confidence, labels, filepath): """ Takes in confidence values for predictions and correct labels for the data, plots a reliability diagram. :param confidence: nb_samples x nb_classes (e.g., output of softmax) :param labels: vector of nb_samples :param filepath: where to save the...
[ "Takes", "in", "confidence", "values", "for", "predictions", "and", "correct", "labels", "for", "the", "data", "plots", "a", "reliability", "diagram", ".", ":", "param", "confidence", ":", "nb_samples", "x", "nb_classes", "(", "e", ".", "g", ".", "output", ...
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py#L266-L333
[ "def", "plot_reliability_diagram", "(", "confidence", ",", "labels", ",", "filepath", ")", ":", "assert", "len", "(", "confidence", ".", "shape", ")", "==", "2", "assert", "len", "(", "labels", ".", "shape", ")", "==", "1", "assert", "confidence", ".", "...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
DkNNModel.init_lsh
Initializes locality-sensitive hashing with FALCONN to find nearest neighbors in training data.
cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py
def init_lsh(self): """ Initializes locality-sensitive hashing with FALCONN to find nearest neighbors in training data. """ self.query_objects = { } # contains the object that can be queried to find nearest neighbors at each layer. # mean of training data representation per layer (that needs to...
def init_lsh(self): """ Initializes locality-sensitive hashing with FALCONN to find nearest neighbors in training data. """ self.query_objects = { } # contains the object that can be queried to find nearest neighbors at each layer. # mean of training data representation per layer (that needs to...
[ "Initializes", "locality", "-", "sensitive", "hashing", "with", "FALCONN", "to", "find", "nearest", "neighbors", "in", "training", "data", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py#L88-L132
[ "def", "init_lsh", "(", "self", ")", ":", "self", ".", "query_objects", "=", "{", "}", "# contains the object that can be queried to find nearest neighbors at each layer.", "# mean of training data representation per layer (that needs to be substracted before LSH).", "self", ".", "ce...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
DkNNModel.find_train_knns
Given a data_activation dictionary that contains a np array with activations for each layer, find the knns in the training data.
cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py
def find_train_knns(self, data_activations): """ Given a data_activation dictionary that contains a np array with activations for each layer, find the knns in the training data. """ knns_ind = {} knns_labels = {} for layer in self.layers: # Pre-process representations of data to norma...
def find_train_knns(self, data_activations): """ Given a data_activation dictionary that contains a np array with activations for each layer, find the knns in the training data. """ knns_ind = {} knns_labels = {} for layer in self.layers: # Pre-process representations of data to norma...
[ "Given", "a", "data_activation", "dictionary", "that", "contains", "a", "np", "array", "with", "activations", "for", "each", "layer", "find", "the", "knns", "in", "the", "training", "data", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py#L134-L168
[ "def", "find_train_knns", "(", "self", ",", "data_activations", ")", ":", "knns_ind", "=", "{", "}", "knns_labels", "=", "{", "}", "for", "layer", "in", "self", ".", "layers", ":", "# Pre-process representations of data to normalize and remove training data mean.", "d...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
DkNNModel.nonconformity
Given an dictionary of nb_data x nb_classes dimension, compute the nonconformity of each candidate label for each data point: i.e. the number of knns whose label is different from the candidate label.
cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py
def nonconformity(self, knns_labels): """ Given an dictionary of nb_data x nb_classes dimension, compute the nonconformity of each candidate label for each data point: i.e. the number of knns whose label is different from the candidate label. """ nb_data = knns_labels[self.layers[0]].shape[0] ...
def nonconformity(self, knns_labels): """ Given an dictionary of nb_data x nb_classes dimension, compute the nonconformity of each candidate label for each data point: i.e. the number of knns whose label is different from the candidate label. """ nb_data = knns_labels[self.layers[0]].shape[0] ...
[ "Given", "an", "dictionary", "of", "nb_data", "x", "nb_classes", "dimension", "compute", "the", "nonconformity", "of", "each", "candidate", "label", "for", "each", "data", "point", ":", "i", ".", "e", ".", "the", "number", "of", "knns", "whose", "label", "...
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py#L170-L190
[ "def", "nonconformity", "(", "self", ",", "knns_labels", ")", ":", "nb_data", "=", "knns_labels", "[", "self", ".", "layers", "[", "0", "]", "]", ".", "shape", "[", "0", "]", "knns_not_in_class", "=", "np", ".", "zeros", "(", "(", "nb_data", ",", "se...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
DkNNModel.preds_conf_cred
Given an array of nb_data x nb_classes dimensions, use conformal prediction to compute the DkNN's prediction, confidence and credibility.
cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py
def preds_conf_cred(self, knns_not_in_class): """ Given an array of nb_data x nb_classes dimensions, use conformal prediction to compute the DkNN's prediction, confidence and credibility. """ nb_data = knns_not_in_class.shape[0] preds_knn = np.zeros(nb_data, dtype=np.int32) confs = np.zeros(...
def preds_conf_cred(self, knns_not_in_class): """ Given an array of nb_data x nb_classes dimensions, use conformal prediction to compute the DkNN's prediction, confidence and credibility. """ nb_data = knns_not_in_class.shape[0] preds_knn = np.zeros(nb_data, dtype=np.int32) confs = np.zeros(...
[ "Given", "an", "array", "of", "nb_data", "x", "nb_classes", "dimensions", "use", "conformal", "prediction", "to", "compute", "the", "DkNN", "s", "prediction", "confidence", "and", "credibility", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py#L192-L214
[ "def", "preds_conf_cred", "(", "self", ",", "knns_not_in_class", ")", ":", "nb_data", "=", "knns_not_in_class", ".", "shape", "[", "0", "]", "preds_knn", "=", "np", ".", "zeros", "(", "nb_data", ",", "dtype", "=", "np", ".", "int32", ")", "confs", "=", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
DkNNModel.fprop_np
Performs a forward pass through the DkNN on an numpy array of data.
cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py
def fprop_np(self, data_np): """ Performs a forward pass through the DkNN on an numpy array of data. """ if not self.calibrated: raise ValueError( "DkNN needs to be calibrated by calling DkNNModel.calibrate method once before inferring.") data_activations = self.get_activations(data_...
def fprop_np(self, data_np): """ Performs a forward pass through the DkNN on an numpy array of data. """ if not self.calibrated: raise ValueError( "DkNN needs to be calibrated by calling DkNNModel.calibrate method once before inferring.") data_activations = self.get_activations(data_...
[ "Performs", "a", "forward", "pass", "through", "the", "DkNN", "on", "an", "numpy", "array", "of", "data", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py#L216-L227
[ "def", "fprop_np", "(", "self", ",", "data_np", ")", ":", "if", "not", "self", ".", "calibrated", ":", "raise", "ValueError", "(", "\"DkNN needs to be calibrated by calling DkNNModel.calibrate method once before inferring.\"", ")", "data_activations", "=", "self", ".", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
DkNNModel.fprop
Performs a forward pass through the DkNN on a TF tensor by wrapping the fprop_np method.
cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py
def fprop(self, x): """ Performs a forward pass through the DkNN on a TF tensor by wrapping the fprop_np method. """ logits = tf.py_func(self.fprop_np, [x], tf.float32) return {self.O_LOGITS: logits}
def fprop(self, x): """ Performs a forward pass through the DkNN on a TF tensor by wrapping the fprop_np method. """ logits = tf.py_func(self.fprop_np, [x], tf.float32) return {self.O_LOGITS: logits}
[ "Performs", "a", "forward", "pass", "through", "the", "DkNN", "on", "a", "TF", "tensor", "by", "wrapping", "the", "fprop_np", "method", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py#L229-L235
[ "def", "fprop", "(", "self", ",", "x", ")", ":", "logits", "=", "tf", ".", "py_func", "(", "self", ".", "fprop_np", ",", "[", "x", "]", ",", "tf", ".", "float32", ")", "return", "{", "self", ".", "O_LOGITS", ":", "logits", "}" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
train
DkNNModel.calibrate
Runs the DkNN on holdout data to calibrate the credibility metric. :param cali_data: np array of calibration data. :param cali_labels: np vector of calibration labels.
cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py
def calibrate(self, cali_data, cali_labels): """ Runs the DkNN on holdout data to calibrate the credibility metric. :param cali_data: np array of calibration data. :param cali_labels: np vector of calibration labels. """ self.nb_cali = cali_labels.shape[0] self.cali_activations = self.get_ac...
def calibrate(self, cali_data, cali_labels): """ Runs the DkNN on holdout data to calibrate the credibility metric. :param cali_data: np array of calibration data. :param cali_labels: np vector of calibration labels. """ self.nb_cali = cali_labels.shape[0] self.cali_activations = self.get_ac...
[ "Runs", "the", "DkNN", "on", "holdout", "data", "to", "calibrate", "the", "credibility", "metric", ".", ":", "param", "cali_data", ":", "np", "array", "of", "calibration", "data", ".", ":", "param", "cali_labels", ":", "np", "vector", "of", "calibration", ...
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py#L237-L263
[ "def", "calibrate", "(", "self", ",", "cali_data", ",", "cali_labels", ")", ":", "self", ".", "nb_cali", "=", "cali_labels", ".", "shape", "[", "0", "]", "self", ".", "cali_activations", "=", "self", ".", "get_activations", "(", "cali_data", ")", "self", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
mnist_tutorial
MNIST cleverhans tutorial :param nb_epochs: number of epochs to train model :param batch_size: size of training batches :param learning_rate: learning rate for training :return: an AccuracyReport object
cleverhans_tutorials/mnist_tutorial_pytorch.py
def mnist_tutorial(nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE, train_end=-1, test_end=-1, learning_rate=LEARNING_RATE): """ MNIST cleverhans tutorial :param nb_epochs: number of epochs to train model :param batch_size: size of training batches :param learning_rate: learning rate for trainin...
def mnist_tutorial(nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE, train_end=-1, test_end=-1, learning_rate=LEARNING_RATE): """ MNIST cleverhans tutorial :param nb_epochs: number of epochs to train model :param batch_size: size of training batches :param learning_rate: learning rate for trainin...
[ "MNIST", "cleverhans", "tutorial", ":", "param", "nb_epochs", ":", "number", "of", "epochs", "to", "train", "model", ":", "param", "batch_size", ":", "size", "of", "training", "batches", ":", "param", "learning_rate", ":", "learning", "rate", "for", "training"...
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans_tutorials/mnist_tutorial_pytorch.py#L68-L170
[ "def", "mnist_tutorial", "(", "nb_epochs", "=", "NB_EPOCHS", ",", "batch_size", "=", "BATCH_SIZE", ",", "train_end", "=", "-", "1", ",", "test_end", "=", "-", "1", ",", "learning_rate", "=", "LEARNING_RATE", ")", ":", "# Train a pytorch MNIST model", "torch_mode...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
apply_perturbations
TensorFlow implementation for apply perturbations to input features based on salency maps :param i: index of first selected feature :param j: index of second selected feature :param X: a matrix containing our input features for our sample :param increase: boolean; true if we are increasing pixels, false other...
cleverhans/attacks_tf.py
def apply_perturbations(i, j, X, increase, theta, clip_min, clip_max): """ TensorFlow implementation for apply perturbations to input features based on salency maps :param i: index of first selected feature :param j: index of second selected feature :param X: a matrix containing our input features for our s...
def apply_perturbations(i, j, X, increase, theta, clip_min, clip_max): """ TensorFlow implementation for apply perturbations to input features based on salency maps :param i: index of first selected feature :param j: index of second selected feature :param X: a matrix containing our input features for our s...
[ "TensorFlow", "implementation", "for", "apply", "perturbations", "to", "input", "features", "based", "on", "salency", "maps", ":", "param", "i", ":", "index", "of", "first", "selected", "feature", ":", "param", "j", ":", "index", "of", "second", "selected", ...
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks_tf.py#L55-L79
[ "def", "apply_perturbations", "(", "i", ",", "j", ",", "X", ",", "increase", ",", "theta", ",", "clip_min", ",", "clip_max", ")", ":", "warnings", ".", "warn", "(", "\"This function is dead code and will be removed on or after 2019-07-18\"", ")", "# perturb our input ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
saliency_map
TensorFlow implementation for computing saliency maps :param grads_target: a matrix containing forward derivatives for the target class :param grads_other: a matrix where every element is the sum of forward derivatives over all non-target classes at that index :param s...
cleverhans/attacks_tf.py
def saliency_map(grads_target, grads_other, search_domain, increase): """ TensorFlow implementation for computing saliency maps :param grads_target: a matrix containing forward derivatives for the target class :param grads_other: a matrix where every element is the sum of forward ...
def saliency_map(grads_target, grads_other, search_domain, increase): """ TensorFlow implementation for computing saliency maps :param grads_target: a matrix containing forward derivatives for the target class :param grads_other: a matrix where every element is the sum of forward ...
[ "TensorFlow", "implementation", "for", "computing", "saliency", "maps", ":", "param", "grads_target", ":", "a", "matrix", "containing", "forward", "derivatives", "for", "the", "target", "class", ":", "param", "grads_other", ":", "a", "matrix", "where", "every", ...
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks_tf.py#L82-L130
[ "def", "saliency_map", "(", "grads_target", ",", "grads_other", ",", "search_domain", ",", "increase", ")", ":", "warnings", ".", "warn", "(", "\"This function is dead code and will be removed on or after 2019-07-18\"", ")", "# Compute the size of the input (the number of feature...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
jacobian
TensorFlow implementation of the foward derivative / Jacobian :param x: the input placeholder :param grads: the list of TF gradients returned by jacobian_graph() :param target: the target misclassification class :param X: numpy array with sample input :param nb_features: the number of features in the input ...
cleverhans/attacks_tf.py
def jacobian(sess, x, grads, target, X, nb_features, nb_classes, feed=None): """ TensorFlow implementation of the foward derivative / Jacobian :param x: the input placeholder :param grads: the list of TF gradients returned by jacobian_graph() :param target: the target misclassification class :param X: numpy...
def jacobian(sess, x, grads, target, X, nb_features, nb_classes, feed=None): """ TensorFlow implementation of the foward derivative / Jacobian :param x: the input placeholder :param grads: the list of TF gradients returned by jacobian_graph() :param target: the target misclassification class :param X: numpy...
[ "TensorFlow", "implementation", "of", "the", "foward", "derivative", "/", "Jacobian", ":", "param", "x", ":", "the", "input", "placeholder", ":", "param", "grads", ":", "the", "list", "of", "TF", "gradients", "returned", "by", "jacobian_graph", "()", ":", "p...
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks_tf.py#L133-L164
[ "def", "jacobian", "(", "sess", ",", "x", ",", "grads", ",", "target", ",", "X", ",", "nb_features", ",", "nb_classes", ",", "feed", "=", "None", ")", ":", "warnings", ".", "warn", "(", "\"This function is dead code and will be removed on or after 2019-07-18\"", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
projected_gradient_descent
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.p...
cleverhans/future/torch/attacks/projected_gradient_descent.py
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...
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...
[ "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", ...
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/future/torch/attacks/projected_gradient_descent.py#L9-L100
[ "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", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
_batch_norm
Batch normalization.
cleverhans/model_zoo/madry_lab_challenges/cifar10_model.py
def _batch_norm(name, x): """Batch normalization.""" with tf.name_scope(name): return tf.contrib.layers.batch_norm( inputs=x, decay=.9, center=True, scale=True, activation_fn=None, updates_collections=None, is_training=False)
def _batch_norm(name, x): """Batch normalization.""" with tf.name_scope(name): return tf.contrib.layers.batch_norm( inputs=x, decay=.9, center=True, scale=True, activation_fn=None, updates_collections=None, is_training=False)
[ "Batch", "normalization", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model_zoo/madry_lab_challenges/cifar10_model.py#L224-L234
[ "def", "_batch_norm", "(", "name", ",", "x", ")", ":", "with", "tf", ".", "name_scope", "(", "name", ")", ":", "return", "tf", ".", "contrib", ".", "layers", ".", "batch_norm", "(", "inputs", "=", "x", ",", "decay", "=", ".9", ",", "center", "=", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
_residual
Residual unit with 2 sub layers.
cleverhans/model_zoo/madry_lab_challenges/cifar10_model.py
def _residual(x, in_filter, out_filter, stride, activate_before_residual=False): """Residual unit with 2 sub layers.""" if activate_before_residual: with tf.variable_scope('shared_activation'): x = _batch_norm('init_bn', x) x = _relu(x, 0.1) orig_x = x else: with tf.variabl...
def _residual(x, in_filter, out_filter, stride, activate_before_residual=False): """Residual unit with 2 sub layers.""" if activate_before_residual: with tf.variable_scope('shared_activation'): x = _batch_norm('init_bn', x) x = _relu(x, 0.1) orig_x = x else: with tf.variabl...
[ "Residual", "unit", "with", "2", "sub", "layers", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model_zoo/madry_lab_challenges/cifar10_model.py#L237-L269
[ "def", "_residual", "(", "x", ",", "in_filter", ",", "out_filter", ",", "stride", ",", "activate_before_residual", "=", "False", ")", ":", "if", "activate_before_residual", ":", "with", "tf", ".", "variable_scope", "(", "'shared_activation'", ")", ":", "x", "=...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
_decay
L2 weight decay loss.
cleverhans/model_zoo/madry_lab_challenges/cifar10_model.py
def _decay(): """L2 weight decay loss.""" costs = [] for var in tf.trainable_variables(): if var.op.name.find('DW') > 0: costs.append(tf.nn.l2_loss(var)) return tf.add_n(costs)
def _decay(): """L2 weight decay loss.""" costs = [] for var in tf.trainable_variables(): if var.op.name.find('DW') > 0: costs.append(tf.nn.l2_loss(var)) return tf.add_n(costs)
[ "L2", "weight", "decay", "loss", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model_zoo/madry_lab_challenges/cifar10_model.py#L272-L278
[ "def", "_decay", "(", ")", ":", "costs", "=", "[", "]", "for", "var", "in", "tf", ".", "trainable_variables", "(", ")", ":", "if", "var", ".", "op", ".", "name", ".", "find", "(", "'DW'", ")", ">", "0", ":", "costs", ".", "append", "(", "tf", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
_relu
Relu, with optional leaky support.
cleverhans/model_zoo/madry_lab_challenges/cifar10_model.py
def _relu(x, leakiness=0.0): """Relu, with optional leaky support.""" return tf.where(tf.less(x, 0.0), leakiness * x, x, name='leaky_relu')
def _relu(x, leakiness=0.0): """Relu, with optional leaky support.""" return tf.where(tf.less(x, 0.0), leakiness * x, x, name='leaky_relu')
[ "Relu", "with", "optional", "leaky", "support", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model_zoo/madry_lab_challenges/cifar10_model.py#L292-L294
[ "def", "_relu", "(", "x", ",", "leakiness", "=", "0.0", ")", ":", "return", "tf", ".", "where", "(", "tf", ".", "less", "(", "x", ",", "0.0", ")", ",", "leakiness", "*", "x", ",", "x", ",", "name", "=", "'leaky_relu'", ")" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
train
Input.set_input_shape
Build the core model within the graph.
cleverhans/model_zoo/madry_lab_challenges/cifar10_model.py
def set_input_shape(self, input_shape): batch_size, rows, cols, input_channels = input_shape # assert self.mode == 'train' or self.mode == 'eval' """Build the core model within the graph.""" input_shape = list(input_shape) input_shape[0] = 1 dummy_batch = tf.zeros(input_shape) dummy_output =...
def set_input_shape(self, input_shape): batch_size, rows, cols, input_channels = input_shape # assert self.mode == 'train' or self.mode == 'eval' """Build the core model within the graph.""" input_shape = list(input_shape) input_shape[0] = 1 dummy_batch = tf.zeros(input_shape) dummy_output =...
[ "Build", "the", "core", "model", "within", "the", "graph", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model_zoo/madry_lab_challenges/cifar10_model.py#L118-L128
[ "def", "set_input_shape", "(", "self", ",", "input_shape", ")", ":", "batch_size", ",", "rows", ",", "cols", ",", "input_channels", "=", "input_shape", "# assert self.mode == 'train' or self.mode == 'eval'", "input_shape", "=", "list", "(", "input_shape", ")", "input_...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
DualFormulation.create_projected_dual
Function to create variables for the projected dual object. Function that projects the input dual variables onto the feasible set. Returns: projected_dual: Feasible dual solution corresponding to current dual
cleverhans/experimental/certification/dual_formulation.py
def create_projected_dual(self): """Function to create variables for the projected dual object. Function that projects the input dual variables onto the feasible set. Returns: projected_dual: Feasible dual solution corresponding to current dual """ # TODO: consider whether we can use shallow c...
def create_projected_dual(self): """Function to create variables for the projected dual object. Function that projects the input dual variables onto the feasible set. Returns: projected_dual: Feasible dual solution corresponding to current dual """ # TODO: consider whether we can use shallow c...
[ "Function", "to", "create", "variables", "for", "the", "projected", "dual", "object", ".", "Function", "that", "projects", "the", "input", "dual", "variables", "onto", "the", "feasible", "set", ".", "Returns", ":", "projected_dual", ":", "Feasible", "dual", "s...
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/dual_formulation.py#L159-L203
[ "def", "create_projected_dual", "(", "self", ")", ":", "# TODO: consider whether we can use shallow copy of the lists without", "# using tf.identity", "projected_nu", "=", "tf", ".", "placeholder", "(", "tf", ".", "float32", ",", "shape", "=", "[", "]", ")", "min_eig_h"...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
DualFormulation.construct_lanczos_params
Computes matrices T and V using the Lanczos algorithm. Args: k: number of iterations and dimensionality of the tridiagonal matrix Returns: eig_vec: eigen vector corresponding to min eigenvalue
cleverhans/experimental/certification/dual_formulation.py
def construct_lanczos_params(self): """Computes matrices T and V using the Lanczos algorithm. Args: k: number of iterations and dimensionality of the tridiagonal matrix Returns: eig_vec: eigen vector corresponding to min eigenvalue """ # Using autograph to automatically handle # the...
def construct_lanczos_params(self): """Computes matrices T and V using the Lanczos algorithm. Args: k: number of iterations and dimensionality of the tridiagonal matrix Returns: eig_vec: eigen vector corresponding to min eigenvalue """ # Using autograph to automatically handle # the...
[ "Computes", "matrices", "T", "and", "V", "using", "the", "Lanczos", "algorithm", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/dual_formulation.py#L205-L247
[ "def", "construct_lanczos_params", "(", "self", ")", ":", "# Using autograph to automatically handle", "# the control flow of minimum_eigen_vector", "self", ".", "min_eigen_vec", "=", "autograph", ".", "to_graph", "(", "utils", ".", "tf_lanczos_smallest_eigval", ")", "def", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
DualFormulation.set_differentiable_objective
Function that constructs minimization objective from dual variables.
cleverhans/experimental/certification/dual_formulation.py
def set_differentiable_objective(self): """Function that constructs minimization objective from dual variables.""" # Checking if graphs are already created if self.vector_g is not None: return # Computing the scalar term bias_sum = 0 for i in range(0, self.nn_params.num_hidden_layers): ...
def set_differentiable_objective(self): """Function that constructs minimization objective from dual variables.""" # Checking if graphs are already created if self.vector_g is not None: return # Computing the scalar term bias_sum = 0 for i in range(0, self.nn_params.num_hidden_layers): ...
[ "Function", "that", "constructs", "minimization", "objective", "from", "dual", "variables", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/dual_formulation.py#L249-L298
[ "def", "set_differentiable_objective", "(", "self", ")", ":", "# Checking if graphs are already created", "if", "self", ".", "vector_g", "is", "not", "None", ":", "return", "# Computing the scalar term", "bias_sum", "=", "0", "for", "i", "in", "range", "(", "0", "...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
DualFormulation.get_h_product
Function that provides matrix product interface with PSD matrix. Args: vector: the vector to be multiplied with matrix H Returns: result_product: Matrix product of H and vector
cleverhans/experimental/certification/dual_formulation.py
def get_h_product(self, vector, dtype=None): """Function that provides matrix product interface with PSD matrix. Args: vector: the vector to be multiplied with matrix H Returns: result_product: Matrix product of H and vector """ # Computing the product of matrix_h with beta (input vect...
def get_h_product(self, vector, dtype=None): """Function that provides matrix product interface with PSD matrix. Args: vector: the vector to be multiplied with matrix H Returns: result_product: Matrix product of H and vector """ # Computing the product of matrix_h with beta (input vect...
[ "Function", "that", "provides", "matrix", "product", "interface", "with", "PSD", "matrix", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/dual_formulation.py#L300-L350
[ "def", "get_h_product", "(", "self", ",", "vector", ",", "dtype", "=", "None", ")", ":", "# Computing the product of matrix_h with beta (input vector)", "# At first layer, h is simply diagonal", "if", "dtype", "is", "None", ":", "dtype", "=", "self", ".", "nn_dtype", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
DualFormulation.get_psd_product
Function that provides matrix product interface with PSD matrix. Args: vector: the vector to be multiplied with matrix M Returns: result_product: Matrix product of M and vector
cleverhans/experimental/certification/dual_formulation.py
def get_psd_product(self, vector, dtype=None): """Function that provides matrix product interface with PSD matrix. Args: vector: the vector to be multiplied with matrix M Returns: result_product: Matrix product of M and vector """ # For convenience, think of x as [\alpha, \beta] if...
def get_psd_product(self, vector, dtype=None): """Function that provides matrix product interface with PSD matrix. Args: vector: the vector to be multiplied with matrix M Returns: result_product: Matrix product of M and vector """ # For convenience, think of x as [\alpha, \beta] if...
[ "Function", "that", "provides", "matrix", "product", "interface", "with", "PSD", "matrix", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/dual_formulation.py#L352-L378
[ "def", "get_psd_product", "(", "self", ",", "vector", ",", "dtype", "=", "None", ")", ":", "# For convenience, think of x as [\\alpha, \\beta]", "if", "dtype", "is", "None", ":", "dtype", "=", "self", ".", "nn_dtype", "vector", "=", "tf", ".", "cast", "(", "...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
DualFormulation.get_full_psd_matrix
Function that returns the tf graph corresponding to the entire matrix M. Returns: matrix_h: unrolled version of tf matrix corresponding to H matrix_m: unrolled tf matrix corresponding to M
cleverhans/experimental/certification/dual_formulation.py
def get_full_psd_matrix(self): """Function that returns the tf graph corresponding to the entire matrix M. Returns: matrix_h: unrolled version of tf matrix corresponding to H matrix_m: unrolled tf matrix corresponding to M """ if self.matrix_m is not None: return self.matrix_h, self.m...
def get_full_psd_matrix(self): """Function that returns the tf graph corresponding to the entire matrix M. Returns: matrix_h: unrolled version of tf matrix corresponding to H matrix_m: unrolled tf matrix corresponding to M """ if self.matrix_m is not None: return self.matrix_h, self.m...
[ "Function", "that", "returns", "the", "tf", "graph", "corresponding", "to", "the", "entire", "matrix", "M", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/dual_formulation.py#L380-L423
[ "def", "get_full_psd_matrix", "(", "self", ")", ":", "if", "self", ".", "matrix_m", "is", "not", "None", ":", "return", "self", ".", "matrix_h", ",", "self", ".", "matrix_m", "# Computing the matrix term", "h_columns", "=", "[", "]", "for", "i", "in", "ran...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
DualFormulation.make_m_psd
Run binary search to find a value for nu that makes M PSD Args: original_nu: starting value of nu to do binary search on feed_dictionary: dictionary of updated lambda variables to feed into M Returns: new_nu: new value of nu
cleverhans/experimental/certification/dual_formulation.py
def make_m_psd(self, original_nu, feed_dictionary): """Run binary search to find a value for nu that makes M PSD Args: original_nu: starting value of nu to do binary search on feed_dictionary: dictionary of updated lambda variables to feed into M Returns: new_nu: new value of nu """ ...
def make_m_psd(self, original_nu, feed_dictionary): """Run binary search to find a value for nu that makes M PSD Args: original_nu: starting value of nu to do binary search on feed_dictionary: dictionary of updated lambda variables to feed into M Returns: new_nu: new value of nu """ ...
[ "Run", "binary", "search", "to", "find", "a", "value", "for", "nu", "that", "makes", "M", "PSD", "Args", ":", "original_nu", ":", "starting", "value", "of", "nu", "to", "do", "binary", "search", "on", "feed_dictionary", ":", "dictionary", "of", "updated", ...
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/dual_formulation.py#L425-L462
[ "def", "make_m_psd", "(", "self", ",", "original_nu", ",", "feed_dictionary", ")", ":", "feed_dict", "=", "feed_dictionary", ".", "copy", "(", ")", "_", ",", "min_eig_val_m", "=", "self", ".", "get_lanczos_eig", "(", "compute_m", "=", "True", ",", "feed_dict...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
DualFormulation.get_lanczos_eig
Computes the min eigen value and corresponding vector of matrix M or H using the Lanczos algorithm. Args: compute_m: boolean to determine whether we should compute eig val/vec for M or for H. True for M; False for H. feed_dict: dictionary mapping from TF placeholders to values (optional) ...
cleverhans/experimental/certification/dual_formulation.py
def get_lanczos_eig(self, compute_m=True, feed_dict=None): """Computes the min eigen value and corresponding vector of matrix M or H using the Lanczos algorithm. Args: compute_m: boolean to determine whether we should compute eig val/vec for M or for H. True for M; False for H. feed_dict...
def get_lanczos_eig(self, compute_m=True, feed_dict=None): """Computes the min eigen value and corresponding vector of matrix M or H using the Lanczos algorithm. Args: compute_m: boolean to determine whether we should compute eig val/vec for M or for H. True for M; False for H. feed_dict...
[ "Computes", "the", "min", "eigen", "value", "and", "corresponding", "vector", "of", "matrix", "M", "or", "H", "using", "the", "Lanczos", "algorithm", ".", "Args", ":", "compute_m", ":", "boolean", "to", "determine", "whether", "we", "should", "compute", "eig...
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/dual_formulation.py#L464-L481
[ "def", "get_lanczos_eig", "(", "self", ",", "compute_m", "=", "True", ",", "feed_dict", "=", "None", ")", ":", "if", "compute_m", ":", "min_eig", ",", "min_vec", "=", "self", ".", "sess", ".", "run", "(", "[", "self", ".", "m_min_eig", ",", "self", "...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
DualFormulation.compute_certificate
Function to compute the certificate based either current value or dual variables loaded from dual folder
cleverhans/experimental/certification/dual_formulation.py
def compute_certificate(self, current_step, feed_dictionary): """ Function to compute the certificate based either current value or dual variables loaded from dual folder """ feed_dict = feed_dictionary.copy() nu = feed_dict[self.nu] second_term = self.make_m_psd(nu, feed_dict) tf.logging.info('...
def compute_certificate(self, current_step, feed_dictionary): """ Function to compute the certificate based either current value or dual variables loaded from dual folder """ feed_dict = feed_dictionary.copy() nu = feed_dict[self.nu] second_term = self.make_m_psd(nu, feed_dict) tf.logging.info('...
[ "Function", "to", "compute", "the", "certificate", "based", "either", "current", "value", "or", "dual", "variables", "loaded", "from", "dual", "folder" ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/dual_formulation.py#L483-L521
[ "def", "compute_certificate", "(", "self", ",", "current_step", ",", "feed_dictionary", ")", ":", "feed_dict", "=", "feed_dictionary", ".", "copy", "(", ")", "nu", "=", "feed_dict", "[", "self", ".", "nu", "]", "second_term", "=", "self", ".", "make_m_psd", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
SpatialTransformationMethod.generate
Generate symbolic graph for adversarial examples and return. :param x: The model's symbolic inputs. :param kwargs: See `parse_params`
cleverhans/attacks/spatial_transformation_method.py
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) from cleverhans.attacks_tf import...
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) from cleverhans.attacks_tf import...
[ "Generate", "symbolic", "graph", "for", "adversarial", "examples", "and", "return", ".", ":", "param", "x", ":", "The", "model", "s", "symbolic", "inputs", ".", ":", "param", "kwargs", ":", "See", "parse_params" ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/spatial_transformation_method.py#L31-L52
[ "def", "generate", "(", "self", ",", "x", ",", "*", "*", "kwargs", ")", ":", "# Parse and save attack-specific parameters", "assert", "self", ".", "parse_params", "(", "*", "*", "kwargs", ")", "from", "cleverhans", ".", "attacks_tf", "import", "spm", "labels",...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
SpatialTransformationMethod.parse_params
Take in a dictionary of parameters and applies attack-specific checks before saving them as attributes. :param n_samples: (optional) The number of transformations sampled to construct the attack. Set it to None to run full grid attack. :param dx_min: (optional flo...
cleverhans/attacks/spatial_transformation_method.py
def parse_params(self, n_samples=None, dx_min=-0.1, dx_max=0.1, n_dxs=2, dy_min=-0.1, dy_max=0.1, n_dys=2, angle_min=-30, angle_max=30, ...
def parse_params(self, n_samples=None, dx_min=-0.1, dx_max=0.1, n_dxs=2, dy_min=-0.1, dy_max=0.1, n_dys=2, angle_min=-30, angle_max=30, ...
[ "Take", "in", "a", "dictionary", "of", "parameters", "and", "applies", "attack", "-", "specific", "checks", "before", "saving", "them", "as", "attributes", ".", ":", "param", "n_samples", ":", "(", "optional", ")", "The", "number", "of", "transformations", "...
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/spatial_transformation_method.py#L54-L106
[ "def", "parse_params", "(", "self", ",", "n_samples", "=", "None", ",", "dx_min", "=", "-", "0.1", ",", "dx_max", "=", "0.1", ",", "n_dxs", "=", "2", ",", "dy_min", "=", "-", "0.1", ",", "dy_max", "=", "0.1", ",", "n_dys", "=", "2", ",", "angle_m...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
conv_2d
Defines the right convolutional layer according to the version of Keras that is installed. :param filters: (required integer) the dimensionality of the output space (i.e. the number output of filters in the convolution) :param kernel_shape: (required tuple or list of 2 integers...
cleverhans/utils_keras.py
def conv_2d(filters, kernel_shape, strides, padding, input_shape=None): """ Defines the right convolutional layer according to the version of Keras that is installed. :param filters: (required integer) the dimensionality of the output space (i.e. the number output of filters in the ...
def conv_2d(filters, kernel_shape, strides, padding, input_shape=None): """ Defines the right convolutional layer according to the version of Keras that is installed. :param filters: (required integer) the dimensionality of the output space (i.e. the number output of filters in the ...
[ "Defines", "the", "right", "convolutional", "layer", "according", "to", "the", "version", "of", "Keras", "that", "is", "installed", ".", ":", "param", "filters", ":", "(", "required", "integer", ")", "the", "dimensionality", "of", "the", "output", "space", "...
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_keras.py#L19-L44
[ "def", "conv_2d", "(", "filters", ",", "kernel_shape", ",", "strides", ",", "padding", ",", "input_shape", "=", "None", ")", ":", "if", "input_shape", "is", "not", "None", ":", "return", "Conv2D", "(", "filters", "=", "filters", ",", "kernel_size", "=", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
cnn_model
Defines a CNN model using Keras sequential model :param logits: If set to False, returns a Keras model, otherwise will also return logits tensor :param input_ph: The TensorFlow tensor for the input (needed if returning logits) ("ph" stands for placeholder but it...
cleverhans/utils_keras.py
def cnn_model(logits=False, input_ph=None, img_rows=28, img_cols=28, channels=1, nb_filters=64, nb_classes=10): """ Defines a CNN model using Keras sequential model :param logits: If set to False, returns a Keras model, otherwise will also return logits tensor :param input_ph: Th...
def cnn_model(logits=False, input_ph=None, img_rows=28, img_cols=28, channels=1, nb_filters=64, nb_classes=10): """ Defines a CNN model using Keras sequential model :param logits: If set to False, returns a Keras model, otherwise will also return logits tensor :param input_ph: Th...
[ "Defines", "a", "CNN", "model", "using", "Keras", "sequential", "model", ":", "param", "logits", ":", "If", "set", "to", "False", "returns", "a", "Keras", "model", "otherwise", "will", "also", "return", "logits", "tensor", ":", "param", "input_ph", ":", "T...
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_keras.py#L47-L93
[ "def", "cnn_model", "(", "logits", "=", "False", ",", "input_ph", "=", "None", ",", "img_rows", "=", "28", ",", "img_cols", "=", "28", ",", "channels", "=", "1", ",", "nb_filters", "=", "64", ",", "nb_classes", "=", "10", ")", ":", "model", "=", "S...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
KerasModelWrapper._get_softmax_name
Looks for the name of the softmax layer. :return: Softmax layer name
cleverhans/utils_keras.py
def _get_softmax_name(self): """ Looks for the name of the softmax layer. :return: Softmax layer name """ for layer in self.model.layers: cfg = layer.get_config() if 'activation' in cfg and cfg['activation'] == 'softmax': return layer.name raise Exception("No softmax layers ...
def _get_softmax_name(self): """ Looks for the name of the softmax layer. :return: Softmax layer name """ for layer in self.model.layers: cfg = layer.get_config() if 'activation' in cfg and cfg['activation'] == 'softmax': return layer.name raise Exception("No softmax layers ...
[ "Looks", "for", "the", "name", "of", "the", "softmax", "layer", ".", ":", "return", ":", "Softmax", "layer", "name" ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_keras.py#L117-L127
[ "def", "_get_softmax_name", "(", "self", ")", ":", "for", "layer", "in", "self", ".", "model", ".", "layers", ":", "cfg", "=", "layer", ".", "get_config", "(", ")", "if", "'activation'", "in", "cfg", "and", "cfg", "[", "'activation'", "]", "==", "'soft...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
KerasModelWrapper._get_abstract_layer_name
Looks for the name of abstracted layer. Usually these layers appears when model is stacked. :return: List of abstracted layers
cleverhans/utils_keras.py
def _get_abstract_layer_name(self): """ Looks for the name of abstracted layer. Usually these layers appears when model is stacked. :return: List of abstracted layers """ abstract_layers = [] for layer in self.model.layers: if 'layers' in layer.get_config(): abstract_layers.app...
def _get_abstract_layer_name(self): """ Looks for the name of abstracted layer. Usually these layers appears when model is stacked. :return: List of abstracted layers """ abstract_layers = [] for layer in self.model.layers: if 'layers' in layer.get_config(): abstract_layers.app...
[ "Looks", "for", "the", "name", "of", "abstracted", "layer", ".", "Usually", "these", "layers", "appears", "when", "model", "is", "stacked", ".", ":", "return", ":", "List", "of", "abstracted", "layers" ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_keras.py#L129-L140
[ "def", "_get_abstract_layer_name", "(", "self", ")", ":", "abstract_layers", "=", "[", "]", "for", "layer", "in", "self", ".", "model", ".", "layers", ":", "if", "'layers'", "in", "layer", ".", "get_config", "(", ")", ":", "abstract_layers", ".", "append",...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
KerasModelWrapper._get_logits_name
Looks for the name of the layer producing the logits. :return: name of layer producing the logits
cleverhans/utils_keras.py
def _get_logits_name(self): """ Looks for the name of the layer producing the logits. :return: name of layer producing the logits """ softmax_name = self._get_softmax_name() softmax_layer = self.model.get_layer(softmax_name) if not isinstance(softmax_layer, Activation): # In this case...
def _get_logits_name(self): """ Looks for the name of the layer producing the logits. :return: name of layer producing the logits """ softmax_name = self._get_softmax_name() softmax_layer = self.model.get_layer(softmax_name) if not isinstance(softmax_layer, Activation): # In this case...
[ "Looks", "for", "the", "name", "of", "the", "layer", "producing", "the", "logits", ".", ":", "return", ":", "name", "of", "layer", "producing", "the", "logits" ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_keras.py#L142-L161
[ "def", "_get_logits_name", "(", "self", ")", ":", "softmax_name", "=", "self", ".", "_get_softmax_name", "(", ")", "softmax_layer", "=", "self", ".", "model", ".", "get_layer", "(", "softmax_name", ")", "if", "not", "isinstance", "(", "softmax_layer", ",", "...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
KerasModelWrapper.get_logits
:param x: A symbolic representation of the network input. :return: A symbolic representation of the logits
cleverhans/utils_keras.py
def get_logits(self, x): """ :param x: A symbolic representation of the network input. :return: A symbolic representation of the logits """ logits_name = self._get_logits_name() logits_layer = self.get_layer(x, logits_name) # Need to deal with the case where softmax is part of the # log...
def get_logits(self, x): """ :param x: A symbolic representation of the network input. :return: A symbolic representation of the logits """ logits_name = self._get_logits_name() logits_layer = self.get_layer(x, logits_name) # Need to deal with the case where softmax is part of the # log...
[ ":", "param", "x", ":", "A", "symbolic", "representation", "of", "the", "network", "input", ".", ":", "return", ":", "A", "symbolic", "representation", "of", "the", "logits" ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_keras.py#L163-L179
[ "def", "get_logits", "(", "self", ",", "x", ")", ":", "logits_name", "=", "self", ".", "_get_logits_name", "(", ")", "logits_layer", "=", "self", ".", "get_layer", "(", "x", ",", "logits_name", ")", "# Need to deal with the case where softmax is part of the", "# l...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
KerasModelWrapper.get_probs
:param x: A symbolic representation of the network input. :return: A symbolic representation of the probs
cleverhans/utils_keras.py
def get_probs(self, x): """ :param x: A symbolic representation of the network input. :return: A symbolic representation of the probs """ name = self._get_softmax_name() return self.get_layer(x, name)
def get_probs(self, x): """ :param x: A symbolic representation of the network input. :return: A symbolic representation of the probs """ name = self._get_softmax_name() return self.get_layer(x, name)
[ ":", "param", "x", ":", "A", "symbolic", "representation", "of", "the", "network", "input", ".", ":", "return", ":", "A", "symbolic", "representation", "of", "the", "probs" ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_keras.py#L181-L188
[ "def", "get_probs", "(", "self", ",", "x", ")", ":", "name", "=", "self", ".", "_get_softmax_name", "(", ")", "return", "self", ".", "get_layer", "(", "x", ",", "name", ")" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
train
KerasModelWrapper.get_layer_names
:return: Names of all the layers kept by Keras
cleverhans/utils_keras.py
def get_layer_names(self): """ :return: Names of all the layers kept by Keras """ layer_names = [x.name for x in self.model.layers] return layer_names
def get_layer_names(self): """ :return: Names of all the layers kept by Keras """ layer_names = [x.name for x in self.model.layers] return layer_names
[ ":", "return", ":", "Names", "of", "all", "the", "layers", "kept", "by", "Keras" ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_keras.py#L190-L195
[ "def", "get_layer_names", "(", "self", ")", ":", "layer_names", "=", "[", "x", ".", "name", "for", "x", "in", "self", ".", "model", ".", "layers", "]", "return", "layer_names" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
train
KerasModelWrapper.fprop
Exposes all the layers of the model returned by get_layer_names. :param x: A symbolic representation of the network input :return: A dictionary mapping layer names to the symbolic representation of their output.
cleverhans/utils_keras.py
def fprop(self, x): """ Exposes all the layers of the model returned by get_layer_names. :param x: A symbolic representation of the network input :return: A dictionary mapping layer names to the symbolic representation of their output. """ if self.keras_model is None: # Get t...
def fprop(self, x): """ Exposes all the layers of the model returned by get_layer_names. :param x: A symbolic representation of the network input :return: A dictionary mapping layer names to the symbolic representation of their output. """ if self.keras_model is None: # Get t...
[ "Exposes", "all", "the", "layers", "of", "the", "model", "returned", "by", "get_layer_names", ".", ":", "param", "x", ":", "A", "symbolic", "representation", "of", "the", "network", "input", ":", "return", ":", "A", "dictionary", "mapping", "layer", "names",...
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_keras.py#L197-L238
[ "def", "fprop", "(", "self", ",", "x", ")", ":", "if", "self", ".", "keras_model", "is", "None", ":", "# Get the input layer", "new_input", "=", "self", ".", "model", ".", "get_input_at", "(", "0", ")", "# Make a new model that returns each of the layers as output...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
KerasModelWrapper.get_layer
Expose the hidden features of a model given a layer name. :param x: A symbolic representation of the network input :param layer: The name of the hidden layer to return features at. :return: A symbolic representation of the hidden features :raise: NoSuchLayerError if `layer` is not in the model.
cleverhans/utils_keras.py
def get_layer(self, x, layer): """ Expose the hidden features of a model given a layer name. :param x: A symbolic representation of the network input :param layer: The name of the hidden layer to return features at. :return: A symbolic representation of the hidden features :raise: NoSuchLayerErr...
def get_layer(self, x, layer): """ Expose the hidden features of a model given a layer name. :param x: A symbolic representation of the network input :param layer: The name of the hidden layer to return features at. :return: A symbolic representation of the hidden features :raise: NoSuchLayerErr...
[ "Expose", "the", "hidden", "features", "of", "a", "model", "given", "a", "layer", "name", ".", ":", "param", "x", ":", "A", "symbolic", "representation", "of", "the", "network", "input", ":", "param", "layer", ":", "The", "name", "of", "the", "hidden", ...
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_keras.py#L240-L254
[ "def", "get_layer", "(", "self", ",", "x", ",", "layer", ")", ":", "# Return the symbolic representation for this layer.", "output", "=", "self", ".", "fprop", "(", "x", ")", "try", ":", "requested", "=", "output", "[", "layer", "]", "except", "KeyError", ":...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
get_extract_command_template
Returns extraction command based on the filename extension.
examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_submission_lib.py
def get_extract_command_template(filename): """Returns extraction command based on the filename extension.""" for k, v in iteritems(EXTRACT_COMMAND): if filename.endswith(k): return v return None
def get_extract_command_template(filename): """Returns extraction command based on the filename extension.""" for k, v in iteritems(EXTRACT_COMMAND): if filename.endswith(k): return v return None
[ "Returns", "extraction", "command", "based", "on", "the", "filename", "extension", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_submission_lib.py#L45-L50
[ "def", "get_extract_command_template", "(", "filename", ")", ":", "for", "k", ",", "v", "in", "iteritems", "(", "EXTRACT_COMMAND", ")", ":", "if", "filename", ".", "endswith", "(", "k", ")", ":", "return", "v", "return", "None" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
train
shell_call
Calls shell command with parameter substitution. Args: command: command to run as a list of tokens **kwargs: dirctionary with substitutions Returns: whether command was successful, i.e. returned 0 status code Example of usage: shell_call(['cp', '${A}', '${B}'], A='src_file', B='dst_file') wil...
examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_submission_lib.py
def shell_call(command, **kwargs): """Calls shell command with parameter substitution. Args: command: command to run as a list of tokens **kwargs: dirctionary with substitutions Returns: whether command was successful, i.e. returned 0 status code Example of usage: shell_call(['cp', '${A}', '$...
def shell_call(command, **kwargs): """Calls shell command with parameter substitution. Args: command: command to run as a list of tokens **kwargs: dirctionary with substitutions Returns: whether command was successful, i.e. returned 0 status code Example of usage: shell_call(['cp', '${A}', '$...
[ "Calls", "shell", "command", "with", "parameter", "substitution", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_submission_lib.py#L53-L75
[ "def", "shell_call", "(", "command", ",", "*", "*", "kwargs", ")", ":", "command", "=", "list", "(", "command", ")", "for", "i", "in", "range", "(", "len", "(", "command", ")", ")", ":", "m", "=", "CMD_VARIABLE_RE", ".", "match", "(", "command", "[...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
make_directory_writable
Makes directory readable and writable by everybody. Args: dirname: name of the directory Returns: True if operation was successfull If you run something inside Docker container and it writes files, then these files will be written as root user with restricted permissions. So to be able to read/modi...
examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_submission_lib.py
def make_directory_writable(dirname): """Makes directory readable and writable by everybody. Args: dirname: name of the directory Returns: True if operation was successfull If you run something inside Docker container and it writes files, then these files will be written as root user with restricte...
def make_directory_writable(dirname): """Makes directory readable and writable by everybody. Args: dirname: name of the directory Returns: True if operation was successfull If you run something inside Docker container and it writes files, then these files will be written as root user with restricte...
[ "Makes", "directory", "readable", "and", "writable", "by", "everybody", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_submission_lib.py#L78-L98
[ "def", "make_directory_writable", "(", "dirname", ")", ":", "retval", "=", "shell_call", "(", "[", "'docker'", ",", "'run'", ",", "'-v'", ",", "'{0}:/output_dir'", ".", "format", "(", "dirname", ")", ",", "'busybox:1.27.2'", ",", "'chmod'", ",", "'-R'", ",",...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
SubmissionValidator._prepare_temp_dir
Cleans up and prepare temporary directory.
examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_submission_lib.py
def _prepare_temp_dir(self): """Cleans up and prepare temporary directory.""" if not shell_call(['sudo', 'rm', '-rf', os.path.join(self._temp_dir, '*')]): logging.error('Failed to cleanup temporary directory.') sys.exit(1) # NOTE: we do not create self._extracted_submission_dir # this is int...
def _prepare_temp_dir(self): """Cleans up and prepare temporary directory.""" if not shell_call(['sudo', 'rm', '-rf', os.path.join(self._temp_dir, '*')]): logging.error('Failed to cleanup temporary directory.') sys.exit(1) # NOTE: we do not create self._extracted_submission_dir # this is int...
[ "Cleans", "up", "and", "prepare", "temporary", "directory", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_submission_lib.py#L134-L146
[ "def", "_prepare_temp_dir", "(", "self", ")", ":", "if", "not", "shell_call", "(", "[", "'sudo'", ",", "'rm'", ",", "'-rf'", ",", "os", ".", "path", ".", "join", "(", "self", ".", "_temp_dir", ",", "'*'", ")", "]", ")", ":", "logging", ".", "error"...
97488e215760547b81afc53f5e5de8ba7da5bd98