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
load_defense_output
Loads output of defense from given file.
examples/nips17_adversarial_competition/dev_toolkit/run_attacks_and_defenses.py
def load_defense_output(filename): """Loads output of defense from given file.""" result = {} with open(filename) as f: for row in csv.reader(f): try: image_filename = row[0] if image_filename.endswith('.png') or image_filename.endswith('.jpg'): image_filename = image_filename[...
def load_defense_output(filename): """Loads output of defense from given file.""" result = {} with open(filename) as f: for row in csv.reader(f): try: image_filename = row[0] if image_filename.endswith('.png') or image_filename.endswith('.jpg'): image_filename = image_filename[...
[ "Loads", "output", "of", "defense", "from", "given", "file", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/run_attacks_and_defenses.py#L328-L341
[ "def", "load_defense_output", "(", "filename", ")", ":", "result", "=", "{", "}", "with", "open", "(", "filename", ")", "as", "f", ":", "for", "row", "in", "csv", ".", "reader", "(", "f", ")", ":", "try", ":", "image_filename", "=", "row", "[", "0"...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
compute_and_save_scores_and_ranking
Computes scores and ranking and saves it. Args: attacks_output: output of attacks, instance of AttacksOutput class. defenses_output: outputs of defenses. Dictionary of dictionaries, key in outer dictionary is name of the defense, key of inner dictionary is name of the image, value of inner dictio...
examples/nips17_adversarial_competition/dev_toolkit/run_attacks_and_defenses.py
def compute_and_save_scores_and_ranking(attacks_output, defenses_output, dataset_meta, output_dir, save_all_classification=False): """Computes scores and rank...
def compute_and_save_scores_and_ranking(attacks_output, defenses_output, dataset_meta, output_dir, save_all_classification=False): """Computes scores and rank...
[ "Computes", "scores", "and", "ranking", "and", "saves", "it", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/run_attacks_and_defenses.py#L344-L465
[ "def", "compute_and_save_scores_and_ranking", "(", "attacks_output", ",", "defenses_output", ",", "dataset_meta", ",", "output_dir", ",", "save_all_classification", "=", "False", ")", ":", "def", "write_ranking", "(", "filename", ",", "header", ",", "names", ",", "s...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
main
Run all attacks against all defenses and compute results.
examples/nips17_adversarial_competition/dev_toolkit/run_attacks_and_defenses.py
def main(): """Run all attacks against all defenses and compute results. """ args = parse_args() attacks_output_dir = os.path.join(args.intermediate_results_dir, 'attacks_output') targeted_attacks_output_dir = os.path.join(args.intermediate_results_dir, ...
def main(): """Run all attacks against all defenses and compute results. """ args = parse_args() attacks_output_dir = os.path.join(args.intermediate_results_dir, 'attacks_output') targeted_attacks_output_dir = os.path.join(args.intermediate_results_dir, ...
[ "Run", "all", "attacks", "against", "all", "defenses", "and", "compute", "results", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/run_attacks_and_defenses.py#L468-L547
[ "def", "main", "(", ")", ":", "args", "=", "parse_args", "(", ")", "attacks_output_dir", "=", "os", ".", "path", ".", "join", "(", "args", ".", "intermediate_results_dir", ",", "'attacks_output'", ")", "targeted_attacks_output_dir", "=", "os", ".", "path", "...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
Attack.run
Runs attack inside Docker. Args: input_dir: directory with input (dataset). output_dir: directory where output (adversarial images) should be written. epsilon: maximum allowed size of adversarial perturbation, should be in range [0, 255].
examples/nips17_adversarial_competition/dev_toolkit/run_attacks_and_defenses.py
def run(self, input_dir, output_dir, epsilon): """Runs attack inside Docker. Args: input_dir: directory with input (dataset). output_dir: directory where output (adversarial images) should be written. epsilon: maximum allowed size of adversarial perturbation, should be in range [0, 25...
def run(self, input_dir, output_dir, epsilon): """Runs attack inside Docker. Args: input_dir: directory with input (dataset). output_dir: directory where output (adversarial images) should be written. epsilon: maximum allowed size of adversarial perturbation, should be in range [0, 25...
[ "Runs", "attack", "inside", "Docker", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/run_attacks_and_defenses.py#L73-L94
[ "def", "run", "(", "self", ",", "input_dir", ",", "output_dir", ",", "epsilon", ")", ":", "print", "(", "'Running attack '", ",", "self", ".", "name", ")", "cmd", "=", "[", "self", ".", "docker_binary", "(", ")", ",", "'run'", ",", "'-v'", ",", "'{0}...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
AttacksOutput._load_dataset_clipping
Helper method which loads dataset and determines clipping range. Args: dataset_dir: location of the dataset. epsilon: maximum allowed size of adversarial perturbation.
examples/nips17_adversarial_competition/dev_toolkit/run_attacks_and_defenses.py
def _load_dataset_clipping(self, dataset_dir, epsilon): """Helper method which loads dataset and determines clipping range. Args: dataset_dir: location of the dataset. epsilon: maximum allowed size of adversarial perturbation. """ self.dataset_max_clip = {} self.dataset_min_clip = {} ...
def _load_dataset_clipping(self, dataset_dir, epsilon): """Helper method which loads dataset and determines clipping range. Args: dataset_dir: location of the dataset. epsilon: maximum allowed size of adversarial perturbation. """ self.dataset_max_clip = {} self.dataset_min_clip = {} ...
[ "Helper", "method", "which", "loads", "dataset", "and", "determines", "clipping", "range", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/run_attacks_and_defenses.py#L191-L214
[ "def", "_load_dataset_clipping", "(", "self", ",", "dataset_dir", ",", "epsilon", ")", ":", "self", ".", "dataset_max_clip", "=", "{", "}", "self", ".", "dataset_min_clip", "=", "{", "}", "self", ".", "_dataset_image_count", "=", "0", "for", "fname", "in", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
AttacksOutput.clip_and_copy_attack_outputs
Clips results of attack and copy it to directory with all images. Args: attack_name: name of the attack. is_targeted: if True then attack is targeted, otherwise non-targeted.
examples/nips17_adversarial_competition/dev_toolkit/run_attacks_and_defenses.py
def clip_and_copy_attack_outputs(self, attack_name, is_targeted): """Clips results of attack and copy it to directory with all images. Args: attack_name: name of the attack. is_targeted: if True then attack is targeted, otherwise non-targeted. """ if is_targeted: self._targeted_attack...
def clip_and_copy_attack_outputs(self, attack_name, is_targeted): """Clips results of attack and copy it to directory with all images. Args: attack_name: name of the attack. is_targeted: if True then attack is targeted, otherwise non-targeted. """ if is_targeted: self._targeted_attack...
[ "Clips", "results", "of", "attack", "and", "copy", "it", "to", "directory", "with", "all", "images", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/run_attacks_and_defenses.py#L216-L254
[ "def", "clip_and_copy_attack_outputs", "(", "self", ",", "attack_name", ",", "is_targeted", ")", ":", "if", "is_targeted", ":", "self", ".", "_targeted_attack_names", ".", "add", "(", "attack_name", ")", "else", ":", "self", ".", "_attack_names", ".", "add", "...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
DatasetMetadata.save_target_classes
Saves target classed for all dataset images into given file.
examples/nips17_adversarial_competition/dev_toolkit/run_attacks_and_defenses.py
def save_target_classes(self, filename): """Saves target classed for all dataset images into given file.""" with open(filename, 'w') as f: for k, v in self._target_classes.items(): f.write('{0}.png,{1}\n'.format(k, v))
def save_target_classes(self, filename): """Saves target classed for all dataset images into given file.""" with open(filename, 'w') as f: for k, v in self._target_classes.items(): f.write('{0}.png,{1}\n'.format(k, v))
[ "Saves", "target", "classed", "for", "all", "dataset", "images", "into", "given", "file", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/run_attacks_and_defenses.py#L321-L325
[ "def", "save_target_classes", "(", "self", ",", "filename", ")", ":", "with", "open", "(", "filename", ",", "'w'", ")", "as", "f", ":", "for", "k", ",", "v", "in", "self", ".", "_target_classes", ".", "items", "(", ")", ":", "f", ".", "write", "(",...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
single_run_max_confidence_recipe
A reasonable attack bundling recipe for a max norm threat model and a defender that uses confidence thresholding. This recipe uses both uniform noise and randomly-initialized PGD targeted attacks. References: https://openreview.net/forum?id=H1g0piA9tQ This version runs each attack (noise, targeted PGD for e...
cleverhans/attack_bundling.py
def single_run_max_confidence_recipe(sess, model, x, y, nb_classes, eps, clip_min, clip_max, eps_iter, nb_iter, report_path, batch_size=BATCH_SIZE, eps_iter_small=None): ...
def single_run_max_confidence_recipe(sess, model, x, y, nb_classes, eps, clip_min, clip_max, eps_iter, nb_iter, report_path, batch_size=BATCH_SIZE, eps_iter_small=None): ...
[ "A", "reasonable", "attack", "bundling", "recipe", "for", "a", "max", "norm", "threat", "model", "and", "a", "defender", "that", "uses", "confidence", "thresholding", ".", "This", "recipe", "uses", "both", "uniform", "noise", "and", "randomly", "-", "initializ...
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attack_bundling.py#L43-L107
[ "def", "single_run_max_confidence_recipe", "(", "sess", ",", "model", ",", "x", ",", "y", ",", "nb_classes", ",", "eps", ",", "clip_min", ",", "clip_max", ",", "eps_iter", ",", "nb_iter", ",", "report_path", ",", "batch_size", "=", "BATCH_SIZE", ",", "eps_it...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
random_search_max_confidence_recipe
Max confidence using random search. References: https://openreview.net/forum?id=H1g0piA9tQ Describes the max_confidence procedure used for the bundling in this recipe https://arxiv.org/abs/1802.00420 Describes using random search with 1e5 or more random points to avoid gradient masking. :param ses...
cleverhans/attack_bundling.py
def random_search_max_confidence_recipe(sess, model, x, y, eps, clip_min, clip_max, report_path, batch_size=BATCH_SIZE, num_noise_points=10000): """Max confidence using random search. References:...
def random_search_max_confidence_recipe(sess, model, x, y, eps, clip_min, clip_max, report_path, batch_size=BATCH_SIZE, num_noise_points=10000): """Max confidence using random search. References:...
[ "Max", "confidence", "using", "random", "search", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attack_bundling.py#L256-L289
[ "def", "random_search_max_confidence_recipe", "(", "sess", ",", "model", ",", "x", ",", "y", ",", "eps", ",", "clip_min", ",", "clip_max", ",", "report_path", ",", "batch_size", "=", "BATCH_SIZE", ",", "num_noise_points", "=", "10000", ")", ":", "noise_attack"...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
bundle_attacks
Runs attack bundling. Users of cleverhans may call this function but are more likely to call one of the recipes above. Reference: https://openreview.net/forum?id=H1g0piA9tQ :param sess: tf.session.Session :param model: cleverhans.model.Model :param x: numpy array containing clean example inputs to attack ...
cleverhans/attack_bundling.py
def bundle_attacks(sess, model, x, y, attack_configs, goals, report_path, attack_batch_size=BATCH_SIZE, eval_batch_size=BATCH_SIZE): """ Runs attack bundling. Users of cleverhans may call this function but are more likely to call one of the recipes above. Reference: https://openreview.net/...
def bundle_attacks(sess, model, x, y, attack_configs, goals, report_path, attack_batch_size=BATCH_SIZE, eval_batch_size=BATCH_SIZE): """ Runs attack bundling. Users of cleverhans may call this function but are more likely to call one of the recipes above. Reference: https://openreview.net/...
[ "Runs", "attack", "bundling", ".", "Users", "of", "cleverhans", "may", "call", "this", "function", "but", "are", "more", "likely", "to", "call", "one", "of", "the", "recipes", "above", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attack_bundling.py#L320-L383
[ "def", "bundle_attacks", "(", "sess", ",", "model", ",", "x", ",", "y", ",", "attack_configs", ",", "goals", ",", "report_path", ",", "attack_batch_size", "=", "BATCH_SIZE", ",", "eval_batch_size", "=", "BATCH_SIZE", ")", ":", "assert", "isinstance", "(", "s...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
bundle_attacks_with_goal
Runs attack bundling, working on one specific AttackGoal. This function is mostly intended to be called by `bundle_attacks`. Reference: https://openreview.net/forum?id=H1g0piA9tQ :param sess: tf.session.Session :param model: cleverhans.model.Model :param x: numpy array containing clean example inputs to att...
cleverhans/attack_bundling.py
def bundle_attacks_with_goal(sess, model, x, y, adv_x, attack_configs, run_counts, goal, report, report_path, attack_batch_size=BATCH_SIZE, eval_batch_size=BATCH_SIZE): """ Runs attack bundling, working on one specific AttackGoal...
def bundle_attacks_with_goal(sess, model, x, y, adv_x, attack_configs, run_counts, goal, report, report_path, attack_batch_size=BATCH_SIZE, eval_batch_size=BATCH_SIZE): """ Runs attack bundling, working on one specific AttackGoal...
[ "Runs", "attack", "bundling", "working", "on", "one", "specific", "AttackGoal", ".", "This", "function", "is", "mostly", "intended", "to", "be", "called", "by", "bundle_attacks", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attack_bundling.py#L385-L425
[ "def", "bundle_attacks_with_goal", "(", "sess", ",", "model", ",", "x", ",", "y", ",", "adv_x", ",", "attack_configs", ",", "run_counts", ",", "goal", ",", "report", ",", "report_path", ",", "attack_batch_size", "=", "BATCH_SIZE", ",", "eval_batch_size", "=", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
run_batch_with_goal
Runs attack bundling on one batch of data. This function is mostly intended to be called by `bundle_attacks_with_goal`. :param sess: tf.session.Session :param model: cleverhans.model.Model :param x: numpy array containing clean example inputs to attack :param y: numpy array containing true labels :param ...
cleverhans/attack_bundling.py
def run_batch_with_goal(sess, model, x, y, adv_x_val, criteria, attack_configs, run_counts, goal, report, report_path, attack_batch_size=BATCH_SIZE): """ Runs attack bundling on one batch of data. This function is mostly intended to be called by `bundle_attacks_wi...
def run_batch_with_goal(sess, model, x, y, adv_x_val, criteria, attack_configs, run_counts, goal, report, report_path, attack_batch_size=BATCH_SIZE): """ Runs attack bundling on one batch of data. This function is mostly intended to be called by `bundle_attacks_wi...
[ "Runs", "attack", "bundling", "on", "one", "batch", "of", "data", ".", "This", "function", "is", "mostly", "intended", "to", "be", "called", "by", "bundle_attacks_with_goal", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attack_bundling.py#L428-L487
[ "def", "run_batch_with_goal", "(", "sess", ",", "model", ",", "x", ",", "y", ",", "adv_x_val", ",", "criteria", ",", "attack_configs", ",", "run_counts", ",", "goal", ",", "report", ",", "report_path", ",", "attack_batch_size", "=", "BATCH_SIZE", ")", ":", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
save
Saves the report and adversarial examples. :param criteria: dict, of the form returned by AttackGoal.get_criteria :param report: dict containing a confidence report :param report_path: string, filepath :param adv_x_val: numpy array containing dataset of adversarial examples
cleverhans/attack_bundling.py
def save(criteria, report, report_path, adv_x_val): """ Saves the report and adversarial examples. :param criteria: dict, of the form returned by AttackGoal.get_criteria :param report: dict containing a confidence report :param report_path: string, filepath :param adv_x_val: numpy array containing dataset o...
def save(criteria, report, report_path, adv_x_val): """ Saves the report and adversarial examples. :param criteria: dict, of the form returned by AttackGoal.get_criteria :param report: dict containing a confidence report :param report_path: string, filepath :param adv_x_val: numpy array containing dataset o...
[ "Saves", "the", "report", "and", "adversarial", "examples", ".", ":", "param", "criteria", ":", "dict", "of", "the", "form", "returned", "by", "AttackGoal", ".", "get_criteria", ":", "param", "report", ":", "dict", "containing", "a", "confidence", "report", ...
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attack_bundling.py#L490-L505
[ "def", "save", "(", "criteria", ",", "report", ",", "report_path", ",", "adv_x_val", ")", ":", "print_stats", "(", "criteria", "[", "'correctness'", "]", ",", "criteria", "[", "'confidence'", "]", ",", "'bundled'", ")", "print", "(", "\"Saving to \"", "+", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
unfinished_attack_configs
Returns a list of attack configs that have not yet been run the desired number of times. :param new_work_goal: dict mapping attacks to desired number of times to run :param work_before: dict mapping attacks to number of times they were run before starting this new goal. Should be prefiltered to include only ...
cleverhans/attack_bundling.py
def unfinished_attack_configs(new_work_goal, work_before, run_counts, log=False): """ Returns a list of attack configs that have not yet been run the desired number of times. :param new_work_goal: dict mapping attacks to desired number of times to run :param work_before: dict map...
def unfinished_attack_configs(new_work_goal, work_before, run_counts, log=False): """ Returns a list of attack configs that have not yet been run the desired number of times. :param new_work_goal: dict mapping attacks to desired number of times to run :param work_before: dict map...
[ "Returns", "a", "list", "of", "attack", "configs", "that", "have", "not", "yet", "been", "run", "the", "desired", "number", "of", "times", ".", ":", "param", "new_work_goal", ":", "dict", "mapping", "attacks", "to", "desired", "number", "of", "times", "to"...
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attack_bundling.py#L916-L962
[ "def", "unfinished_attack_configs", "(", "new_work_goal", ",", "work_before", ",", "run_counts", ",", "log", "=", "False", ")", ":", "assert", "isinstance", "(", "work_before", ",", "dict", ")", ",", "work_before", "for", "key", "in", "work_before", ":", "valu...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
bundle_examples_with_goal
A post-processor version of attack bundling, that chooses the strongest example from the output of multiple earlier bundling strategies. :param sess: tf.session.Session :param model: cleverhans.model.Model :param adv_x_list: list of numpy arrays Each entry in the list is the output of a previous bundler; i...
cleverhans/attack_bundling.py
def bundle_examples_with_goal(sess, model, adv_x_list, y, goal, report_path, batch_size=BATCH_SIZE): """ A post-processor version of attack bundling, that chooses the strongest example from the output of multiple earlier bundling strategies. :param sess: tf.session.Session :para...
def bundle_examples_with_goal(sess, model, adv_x_list, y, goal, report_path, batch_size=BATCH_SIZE): """ A post-processor version of attack bundling, that chooses the strongest example from the output of multiple earlier bundling strategies. :param sess: tf.session.Session :para...
[ "A", "post", "-", "processor", "version", "of", "attack", "bundling", "that", "chooses", "the", "strongest", "example", "from", "the", "output", "of", "multiple", "earlier", "bundling", "strategies", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attack_bundling.py#L1044-L1110
[ "def", "bundle_examples_with_goal", "(", "sess", ",", "model", ",", "adv_x_list", ",", "y", ",", "goal", ",", "report_path", ",", "batch_size", "=", "BATCH_SIZE", ")", ":", "# Check the input", "num_attacks", "=", "len", "(", "adv_x_list", ")", "assert", "num_...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
spsa_max_confidence_recipe
Runs the MaxConfidence attack using SPSA as the underlying optimizer. Even though this runs only one attack, it must be implemented as a bundler because SPSA supports only batch_size=1. The cleverhans.attacks.MaxConfidence attack internally multiplies the batch size by nb_classes, so it can't take SPSA as a ba...
cleverhans/attack_bundling.py
def spsa_max_confidence_recipe(sess, model, x, y, nb_classes, eps, clip_min, clip_max, nb_iter, report_path, spsa_samples=SPSA.DEFAULT_SPSA_SAMPLES, spsa_iters=SPSA.DEFAULT_SPSA_ITERS, ...
def spsa_max_confidence_recipe(sess, model, x, y, nb_classes, eps, clip_min, clip_max, nb_iter, report_path, spsa_samples=SPSA.DEFAULT_SPSA_SAMPLES, spsa_iters=SPSA.DEFAULT_SPSA_ITERS, ...
[ "Runs", "the", "MaxConfidence", "attack", "using", "SPSA", "as", "the", "underlying", "optimizer", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attack_bundling.py#L1112-L1156
[ "def", "spsa_max_confidence_recipe", "(", "sess", ",", "model", ",", "x", ",", "y", ",", "nb_classes", ",", "eps", ",", "clip_min", ",", "clip_max", ",", "nb_iter", ",", "report_path", ",", "spsa_samples", "=", "SPSA", ".", "DEFAULT_SPSA_SAMPLES", ",", "spsa...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
AttackGoal.get_criteria
Returns a dictionary mapping the name of each criterion to a NumPy array containing the value of that criterion for each adversarial example. Subclasses can add extra criteria by implementing the `extra_criteria` method. :param sess: tf.session.Session :param model: cleverhans.model.Model :...
cleverhans/attack_bundling.py
def get_criteria(self, sess, model, advx, y, batch_size=BATCH_SIZE): """ Returns a dictionary mapping the name of each criterion to a NumPy array containing the value of that criterion for each adversarial example. Subclasses can add extra criteria by implementing the `extra_criteria` method. ...
def get_criteria(self, sess, model, advx, y, batch_size=BATCH_SIZE): """ Returns a dictionary mapping the name of each criterion to a NumPy array containing the value of that criterion for each adversarial example. Subclasses can add extra criteria by implementing the `extra_criteria` method. ...
[ "Returns", "a", "dictionary", "mapping", "the", "name", "of", "each", "criterion", "to", "a", "NumPy", "array", "containing", "the", "value", "of", "that", "criterion", "for", "each", "adversarial", "example", ".", "Subclasses", "can", "add", "extra", "criteri...
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attack_bundling.py#L532-L554
[ "def", "get_criteria", "(", "self", ",", "sess", ",", "model", ",", "advx", ",", "y", ",", "batch_size", "=", "BATCH_SIZE", ")", ":", "names", ",", "factory", "=", "self", ".", "extra_criteria", "(", ")", "factory", "=", "_CriteriaFactory", "(", "model",...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
AttackGoal.request_examples
Returns a numpy array of integer example indices to run in the next batch.
cleverhans/attack_bundling.py
def request_examples(self, attack_config, criteria, run_counts, batch_size): """ Returns a numpy array of integer example indices to run in the next batch. """ raise NotImplementedError(str(type(self)) + "needs to implement request_examples")
def request_examples(self, attack_config, criteria, run_counts, batch_size): """ Returns a numpy array of integer example indices to run in the next batch. """ raise NotImplementedError(str(type(self)) + "needs to implement request_examples")
[ "Returns", "a", "numpy", "array", "of", "integer", "example", "indices", "to", "run", "in", "the", "next", "batch", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attack_bundling.py#L563-L568
[ "def", "request_examples", "(", "self", ",", "attack_config", ",", "criteria", ",", "run_counts", ",", "batch_size", ")", ":", "raise", "NotImplementedError", "(", "str", "(", "type", "(", "self", ")", ")", "+", "\"needs to implement request_examples\"", ")" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
train
AttackGoal.new_wins
Returns a bool indicating whether a new adversarial example is better than the pre-existing one for the same clean example. :param orig_criteria: dict mapping names of criteria to their value for each example in the whole dataset :param orig_idx: The position of the pre-existing example within the ...
cleverhans/attack_bundling.py
def new_wins(self, orig_criteria, orig_idx, new_criteria, new_idx): """ Returns a bool indicating whether a new adversarial example is better than the pre-existing one for the same clean example. :param orig_criteria: dict mapping names of criteria to their value for each example in the whole data...
def new_wins(self, orig_criteria, orig_idx, new_criteria, new_idx): """ Returns a bool indicating whether a new adversarial example is better than the pre-existing one for the same clean example. :param orig_criteria: dict mapping names of criteria to their value for each example in the whole data...
[ "Returns", "a", "bool", "indicating", "whether", "a", "new", "adversarial", "example", "is", "better", "than", "the", "pre", "-", "existing", "one", "for", "the", "same", "clean", "example", ".", ":", "param", "orig_criteria", ":", "dict", "mapping", "names"...
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attack_bundling.py#L593-L607
[ "def", "new_wins", "(", "self", ",", "orig_criteria", ",", "orig_idx", ",", "new_criteria", ",", "new_idx", ")", ":", "raise", "NotImplementedError", "(", "str", "(", "type", "(", "self", ")", ")", "+", "\" needs to implement new_wins.\"", ")" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
train
Misclassify.filter
Return run counts only for examples that are still correctly classified
cleverhans/attack_bundling.py
def filter(self, run_counts, criteria): """ Return run counts only for examples that are still correctly classified """ correctness = criteria['correctness'] assert correctness.dtype == np.bool filtered_counts = deep_copy(run_counts) for key in filtered_counts: filtered_counts[key] = f...
def filter(self, run_counts, criteria): """ Return run counts only for examples that are still correctly classified """ correctness = criteria['correctness'] assert correctness.dtype == np.bool filtered_counts = deep_copy(run_counts) for key in filtered_counts: filtered_counts[key] = f...
[ "Return", "run", "counts", "only", "for", "examples", "that", "are", "still", "correctly", "classified" ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attack_bundling.py#L690-L699
[ "def", "filter", "(", "self", ",", "run_counts", ",", "criteria", ")", ":", "correctness", "=", "criteria", "[", "'correctness'", "]", "assert", "correctness", ".", "dtype", "==", "np", ".", "bool", "filtered_counts", "=", "deep_copy", "(", "run_counts", ")"...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
MaxConfidence.filter
Return the counts for only those examples that are below the threshold
cleverhans/attack_bundling.py
def filter(self, run_counts, criteria): """ Return the counts for only those examples that are below the threshold """ wrong_confidence = criteria['wrong_confidence'] below_t = wrong_confidence <= self.t filtered_counts = deep_copy(run_counts) for key in filtered_counts: filtered_count...
def filter(self, run_counts, criteria): """ Return the counts for only those examples that are below the threshold """ wrong_confidence = criteria['wrong_confidence'] below_t = wrong_confidence <= self.t filtered_counts = deep_copy(run_counts) for key in filtered_counts: filtered_count...
[ "Return", "the", "counts", "for", "only", "those", "examples", "that", "are", "below", "the", "threshold" ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attack_bundling.py#L799-L808
[ "def", "filter", "(", "self", ",", "run_counts", ",", "criteria", ")", ":", "wrong_confidence", "=", "criteria", "[", "'wrong_confidence'", "]", "below_t", "=", "wrong_confidence", "<=", "self", ".", "t", "filtered_counts", "=", "deep_copy", "(", "run_counts", ...
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/tf2/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/tf2/attacks/projected_gradient_descent.py#L10-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
clip_image
Clip an image, or an image batch, with upper and lower threshold.
cleverhans/attacks/bapp.py
def clip_image(image, clip_min, clip_max): """ Clip an image, or an image batch, with upper and lower threshold. """ return np.minimum(np.maximum(clip_min, image), clip_max)
def clip_image(image, clip_min, clip_max): """ Clip an image, or an image batch, with upper and lower threshold. """ return np.minimum(np.maximum(clip_min, image), clip_max)
[ "Clip", "an", "image", "or", "an", "image", "batch", "with", "upper", "and", "lower", "threshold", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/bapp.py#L353-L355
[ "def", "clip_image", "(", "image", ",", "clip_min", ",", "clip_max", ")", ":", "return", "np", ".", "minimum", "(", "np", ".", "maximum", "(", "clip_min", ",", "image", ")", ",", "clip_max", ")" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
train
compute_distance
Compute the distance between two images.
cleverhans/attacks/bapp.py
def compute_distance(x_ori, x_pert, constraint='l2'): """ Compute the distance between two images. """ if constraint == 'l2': dist = np.linalg.norm(x_ori - x_pert) elif constraint == 'linf': dist = np.max(abs(x_ori - x_pert)) return dist
def compute_distance(x_ori, x_pert, constraint='l2'): """ Compute the distance between two images. """ if constraint == 'l2': dist = np.linalg.norm(x_ori - x_pert) elif constraint == 'linf': dist = np.max(abs(x_ori - x_pert)) return dist
[ "Compute", "the", "distance", "between", "two", "images", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/bapp.py#L358-L364
[ "def", "compute_distance", "(", "x_ori", ",", "x_pert", ",", "constraint", "=", "'l2'", ")", ":", "if", "constraint", "==", "'l2'", ":", "dist", "=", "np", ".", "linalg", ".", "norm", "(", "x_ori", "-", "x_pert", ")", "elif", "constraint", "==", "'linf...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
approximate_gradient
Gradient direction estimation
cleverhans/attacks/bapp.py
def approximate_gradient(decision_function, sample, num_evals, delta, constraint, shape, clip_min, clip_max): """ Gradient direction estimation """ # Generate random vectors. noise_shape = [num_evals] + list(shape) if constraint == 'l2': rv = np.random.randn(*noise_shape) elif con...
def approximate_gradient(decision_function, sample, num_evals, delta, constraint, shape, clip_min, clip_max): """ Gradient direction estimation """ # Generate random vectors. noise_shape = [num_evals] + list(shape) if constraint == 'l2': rv = np.random.randn(*noise_shape) elif con...
[ "Gradient", "direction", "estimation" ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/bapp.py#L366-L399
[ "def", "approximate_gradient", "(", "decision_function", ",", "sample", ",", "num_evals", ",", "delta", ",", "constraint", ",", "shape", ",", "clip_min", ",", "clip_max", ")", ":", "# Generate random vectors.", "noise_shape", "=", "[", "num_evals", "]", "+", "li...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
project
Projection onto given l2 / linf balls in a batch.
cleverhans/attacks/bapp.py
def project(original_image, perturbed_images, alphas, shape, constraint): """ Projection onto given l2 / linf balls in a batch. """ alphas_shape = [len(alphas)] + [1] * len(shape) alphas = alphas.reshape(alphas_shape) if constraint == 'l2': projected = (1-alphas) * original_image + alphas * perturbed_images...
def project(original_image, perturbed_images, alphas, shape, constraint): """ Projection onto given l2 / linf balls in a batch. """ alphas_shape = [len(alphas)] + [1] * len(shape) alphas = alphas.reshape(alphas_shape) if constraint == 'l2': projected = (1-alphas) * original_image + alphas * perturbed_images...
[ "Projection", "onto", "given", "l2", "/", "linf", "balls", "in", "a", "batch", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/bapp.py#L402-L414
[ "def", "project", "(", "original_image", ",", "perturbed_images", ",", "alphas", ",", "shape", ",", "constraint", ")", ":", "alphas_shape", "=", "[", "len", "(", "alphas", ")", "]", "+", "[", "1", "]", "*", "len", "(", "shape", ")", "alphas", "=", "a...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
binary_search_batch
Binary search to approach the boundary.
cleverhans/attacks/bapp.py
def binary_search_batch(original_image, perturbed_images, decision_function, shape, constraint, theta): """ Binary search to approach the boundary. """ # Compute distance between each of perturbed image and original image. dists_post_update = np.array([ compute_distance( o...
def binary_search_batch(original_image, perturbed_images, decision_function, shape, constraint, theta): """ Binary search to approach the boundary. """ # Compute distance between each of perturbed image and original image. dists_post_update = np.array([ compute_distance( o...
[ "Binary", "search", "to", "approach", "the", "boundary", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/bapp.py#L417-L468
[ "def", "binary_search_batch", "(", "original_image", ",", "perturbed_images", ",", "decision_function", ",", "shape", ",", "constraint", ",", "theta", ")", ":", "# Compute distance between each of perturbed image and original image.", "dists_post_update", "=", "np", ".", "a...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
initialize
Efficient Implementation of BlendedUniformNoiseAttack in Foolbox.
cleverhans/attacks/bapp.py
def initialize(decision_function, sample, shape, clip_min, clip_max): """ Efficient Implementation of BlendedUniformNoiseAttack in Foolbox. """ success = 0 num_evals = 0 # Find a misclassified random noise. while True: random_noise = np.random.uniform(clip_min, clip_max, size=shape) success = dec...
def initialize(decision_function, sample, shape, clip_min, clip_max): """ Efficient Implementation of BlendedUniformNoiseAttack in Foolbox. """ success = 0 num_evals = 0 # Find a misclassified random noise. while True: random_noise = np.random.uniform(clip_min, clip_max, size=shape) success = dec...
[ "Efficient", "Implementation", "of", "BlendedUniformNoiseAttack", "in", "Foolbox", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/bapp.py#L471-L501
[ "def", "initialize", "(", "decision_function", ",", "sample", ",", "shape", ",", "clip_min", ",", "clip_max", ")", ":", "success", "=", "0", "num_evals", "=", "0", "# Find a misclassified random noise.", "while", "True", ":", "random_noise", "=", "np", ".", "r...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
geometric_progression_for_stepsize
Geometric progression to search for stepsize. Keep decreasing stepsize by half until reaching the desired side of the boundary.
cleverhans/attacks/bapp.py
def geometric_progression_for_stepsize(x, update, dist, decision_function, current_iteration): """ Geometric progression to search for stepsize. Keep decreasing stepsize by half until reaching the desired side of the boundary. """ epsilon = dist / np.sqrt(current...
def geometric_progression_for_stepsize(x, update, dist, decision_function, current_iteration): """ Geometric progression to search for stepsize. Keep decreasing stepsize by half until reaching the desired side of the boundary. """ epsilon = dist / np.sqrt(current...
[ "Geometric", "progression", "to", "search", "for", "stepsize", ".", "Keep", "decreasing", "stepsize", "by", "half", "until", "reaching", "the", "desired", "side", "of", "the", "boundary", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/bapp.py#L504-L519
[ "def", "geometric_progression_for_stepsize", "(", "x", ",", "update", ",", "dist", ",", "decision_function", ",", "current_iteration", ")", ":", "epsilon", "=", "dist", "/", "np", ".", "sqrt", "(", "current_iteration", ")", "while", "True", ":", "updated", "="...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
select_delta
Choose the delta at the scale of distance between x and perturbed sample.
cleverhans/attacks/bapp.py
def select_delta(dist_post_update, current_iteration, clip_max, clip_min, d, theta, constraint): """ Choose the delta at the scale of distance between x and perturbed sample. """ if current_iteration == 1: delta = 0.1 * (clip_max - clip_min) else: if constraint == 'l2': delta...
def select_delta(dist_post_update, current_iteration, clip_max, clip_min, d, theta, constraint): """ Choose the delta at the scale of distance between x and perturbed sample. """ if current_iteration == 1: delta = 0.1 * (clip_max - clip_min) else: if constraint == 'l2': delta...
[ "Choose", "the", "delta", "at", "the", "scale", "of", "distance", "between", "x", "and", "perturbed", "sample", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/bapp.py#L522-L536
[ "def", "select_delta", "(", "dist_post_update", ",", "current_iteration", ",", "clip_max", ",", "clip_min", ",", "d", ",", "theta", ",", "constraint", ")", ":", "if", "current_iteration", "==", "1", ":", "delta", "=", "0.1", "*", "(", "clip_max", "-", "cli...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
BoundaryAttackPlusPlus.generate
Return a tensor that constructs adversarial examples for the given input. Generate uses tf.py_func in order to operate over tensors. :param x: A tensor with the inputs. :param kwargs: See `parse_params`
cleverhans/attacks/bapp.py
def generate(self, x, **kwargs): """ Return a tensor that constructs adversarial examples for the given input. Generate uses tf.py_func in order to operate over tensors. :param x: A tensor with the inputs. :param kwargs: See `parse_params` """ self.parse_params(**kwargs) shape = [int(i) ...
def generate(self, x, **kwargs): """ Return a tensor that constructs adversarial examples for the given input. Generate uses tf.py_func in order to operate over tensors. :param x: A tensor with the inputs. :param kwargs: See `parse_params` """ self.parse_params(**kwargs) shape = [int(i) ...
[ "Return", "a", "tensor", "that", "constructs", "adversarial", "examples", "for", "the", "given", "input", ".", "Generate", "uses", "tf", ".", "py_func", "in", "order", "to", "operate", "over", "tensors", ".", ":", "param", "x", ":", "A", "tensor", "with", ...
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/bapp.py#L61-L120
[ "def", "generate", "(", "self", ",", "x", ",", "*", "*", "kwargs", ")", ":", "self", ".", "parse_params", "(", "*", "*", "kwargs", ")", "shape", "=", "[", "int", "(", "i", ")", "for", "i", "in", "x", ".", "get_shape", "(", ")", ".", "as_list", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
BoundaryAttackPlusPlus.generate_np
Generate adversarial images in a for loop. :param y: An array of shape (n, nb_classes) for true labels. :param y_target: An array of shape (n, nb_classes) for target labels. Required for targeted attack. :param image_target: An array of shape (n, **image shape) for initial target images. Required f...
cleverhans/attacks/bapp.py
def generate_np(self, x, **kwargs): """ Generate adversarial images in a for loop. :param y: An array of shape (n, nb_classes) for true labels. :param y_target: An array of shape (n, nb_classes) for target labels. Required for targeted attack. :param image_target: An array of shape (n, **image ...
def generate_np(self, x, **kwargs): """ Generate adversarial images in a for loop. :param y: An array of shape (n, nb_classes) for true labels. :param y_target: An array of shape (n, nb_classes) for target labels. Required for targeted attack. :param image_target: An array of shape (n, **image ...
[ "Generate", "adversarial", "images", "in", "a", "for", "loop", ".", ":", "param", "y", ":", "An", "array", "of", "shape", "(", "n", "nb_classes", ")", "for", "true", "labels", ".", ":", "param", "y_target", ":", "An", "array", "of", "shape", "(", "n"...
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/bapp.py#L122-L159
[ "def", "generate_np", "(", "self", ",", "x", ",", "*", "*", "kwargs", ")", ":", "x_adv", "=", "[", "]", "if", "'image_target'", "in", "kwargs", "and", "kwargs", "[", "'image_target'", "]", "is", "not", "None", ":", "image_target", "=", "np", ".", "co...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
BoundaryAttackPlusPlus.parse_params
:param y: A tensor of shape (1, nb_classes) for true labels. :param y_target: A tensor of shape (1, nb_classes) for target labels. Required for targeted attack. :param image_target: A tensor of shape (1, **image shape) for initial target images. Required for targeted attack. :param initial_num_eval...
cleverhans/attacks/bapp.py
def parse_params(self, y_target=None, image_target=None, initial_num_evals=100, max_num_evals=10000, stepsize_search='grid_search', num_iterations=64, gamma=0.01, const...
def parse_params(self, y_target=None, image_target=None, initial_num_evals=100, max_num_evals=10000, stepsize_search='grid_search', num_iterations=64, gamma=0.01, const...
[ ":", "param", "y", ":", "A", "tensor", "of", "shape", "(", "1", "nb_classes", ")", "for", "true", "labels", ".", ":", "param", "y_target", ":", "A", "tensor", "of", "shape", "(", "1", "nb_classes", ")", "for", "target", "labels", ".", "Required", "fo...
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/bapp.py#L161-L213
[ "def", "parse_params", "(", "self", ",", "y_target", "=", "None", ",", "image_target", "=", "None", ",", "initial_num_evals", "=", "100", ",", "max_num_evals", "=", "10000", ",", "stepsize_search", "=", "'grid_search'", ",", "num_iterations", "=", "64", ",", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
BoundaryAttackPlusPlus._bapp
Main algorithm for Boundary Attack ++. Return a tensor that constructs adversarial examples for the given input. Generate uses tf.py_func in order to operate over tensors. :param sample: input image. Without the batchsize dimension. :param target_label: integer for targeted attack, None for nont...
cleverhans/attacks/bapp.py
def _bapp(self, sample, target_label, target_image): """ Main algorithm for Boundary Attack ++. Return a tensor that constructs adversarial examples for the given input. Generate uses tf.py_func in order to operate over tensors. :param sample: input image. Without the batchsize dimension. :par...
def _bapp(self, sample, target_label, target_image): """ Main algorithm for Boundary Attack ++. Return a tensor that constructs adversarial examples for the given input. Generate uses tf.py_func in order to operate over tensors. :param sample: input image. Without the batchsize dimension. :par...
[ "Main", "algorithm", "for", "Boundary", "Attack", "++", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/bapp.py#L215-L339
[ "def", "_bapp", "(", "self", ",", "sample", ",", "target_label", ",", "target_image", ")", ":", "# Original label required for untargeted attack.", "if", "target_label", "is", "None", ":", "original_label", "=", "np", ".", "argmax", "(", "self", ".", "sess", "."...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
FastFeatureAdversaries.parse_params
Take in a dictionary of parameters and applies attack-specific checks before saving them as attributes. Attack-specific parameters: :param layer: (required str) name of the layer to target. :param eps: (optional float) maximum distortion of adversarial example compared to original inpu...
cleverhans/attacks/fast_feature_adversaries.py
def parse_params(self, layer=None, eps=0.3, eps_iter=0.05, nb_iter=10, ord=np.inf, clip_min=None, clip_max=None, **kwargs): """ Take in a dictionary of paramete...
def parse_params(self, layer=None, eps=0.3, eps_iter=0.05, nb_iter=10, ord=np.inf, clip_min=None, clip_max=None, **kwargs): """ Take in a dictionary of paramete...
[ "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/cleverhans/attacks/fast_feature_adversaries.py#L44-L86
[ "def", "parse_params", "(", "self", ",", "layer", "=", "None", ",", "eps", "=", "0.3", ",", "eps_iter", "=", "0.05", ",", "nb_iter", "=", "10", ",", "ord", "=", "np", ".", "inf", ",", "clip_min", "=", "None", ",", "clip_max", "=", "None", ",", "*...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
FastFeatureAdversaries.attack_single_step
TensorFlow implementation of the Fast Feature Gradient. This is a single step attack similar to Fast Gradient Method that attacks an internal representation. :param x: the input placeholder :param eta: A tensor the same shape as x that holds the perturbation. :param g_feat: model's internal tensor ...
cleverhans/attacks/fast_feature_adversaries.py
def attack_single_step(self, x, eta, g_feat): """ TensorFlow implementation of the Fast Feature Gradient. This is a single step attack similar to Fast Gradient Method that attacks an internal representation. :param x: the input placeholder :param eta: A tensor the same shape as x that holds the...
def attack_single_step(self, x, eta, g_feat): """ TensorFlow implementation of the Fast Feature Gradient. This is a single step attack similar to Fast Gradient Method that attacks an internal representation. :param x: the input placeholder :param eta: A tensor the same shape as x that holds the...
[ "TensorFlow", "implementation", "of", "the", "Fast", "Feature", "Gradient", ".", "This", "is", "a", "single", "step", "attack", "similar", "to", "Fast", "Gradient", "Method", "that", "attacks", "an", "internal", "representation", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/fast_feature_adversaries.py#L88-L129
[ "def", "attack_single_step", "(", "self", ",", "x", ",", "eta", ",", "g_feat", ")", ":", "adv_x", "=", "x", "+", "eta", "a_feat", "=", "self", ".", "model", ".", "fprop", "(", "adv_x", ")", "[", "self", ".", "layer", "]", "# feat.shape = (batch, c) or ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
FastFeatureAdversaries.generate
Generate symbolic graph for adversarial examples and return. :param x: The model's symbolic inputs. :param g: The target value of the symbolic representation :param kwargs: See `parse_params`
cleverhans/attacks/fast_feature_adversaries.py
def generate(self, x, g, **kwargs): """ Generate symbolic graph for adversarial examples and return. :param x: The model's symbolic inputs. :param g: The target value of the symbolic representation :param kwargs: See `parse_params` """ # Parse and save attack-specific parameters assert...
def generate(self, x, g, **kwargs): """ Generate symbolic graph for adversarial examples and return. :param x: The model's symbolic inputs. :param g: The target value of the symbolic representation :param kwargs: See `parse_params` """ # Parse and save attack-specific parameters assert...
[ "Generate", "symbolic", "graph", "for", "adversarial", "examples", "and", "return", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/fast_feature_adversaries.py#L131-L165
[ "def", "generate", "(", "self", ",", "x", ",", "g", ",", "*", "*", "kwargs", ")", ":", "# Parse and save attack-specific parameters", "assert", "self", ".", "parse_params", "(", "*", "*", "kwargs", ")", "g_feat", "=", "self", ".", "model", ".", "fprop", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
main
Make a confidence report and save it to disk.
scripts/make_confidence_report_bundled.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) print(filepath) make_confidence_report_bundled(filepath=filepath, test_start=FLAGS.test_start, ...
def main(argv=None): """ Make a confidence report and save it to disk. """ try: _name_of_script, filepath = argv except ValueError: raise ValueError(argv) print(filepath) make_confidence_report_bundled(filepath=filepath, test_start=FLAGS.test_start, ...
[ "Make", "a", "confidence", "report", "and", "save", "it", "to", "disk", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/scripts/make_confidence_report_bundled.py#L42-L56
[ "def", "main", "(", "argv", "=", "None", ")", ":", "try", ":", "_name_of_script", ",", "filepath", "=", "argv", "except", "ValueError", ":", "raise", "ValueError", "(", "argv", ")", "print", "(", "filepath", ")", "make_confidence_report_bundled", "(", "filep...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
block35
Builds the 35x35 resnet block.
examples/nips17_adversarial_competition/dev_toolkit/sample_defenses/ens_adv_inception_resnet_v2/inception_resnet_v2.py
def block35(net, scale=1.0, activation_fn=tf.nn.relu, scope=None, reuse=None): """Builds the 35x35 resnet block.""" with tf.variable_scope(scope, 'Block35', [net], reuse=reuse): with tf.variable_scope('Branch_0'): tower_conv = slim.conv2d(net, 32, 1, scope='Conv2d_1x1') with tf.variable_scope('Branch_...
def block35(net, scale=1.0, activation_fn=tf.nn.relu, scope=None, reuse=None): """Builds the 35x35 resnet block.""" with tf.variable_scope(scope, 'Block35', [net], reuse=reuse): with tf.variable_scope('Branch_0'): tower_conv = slim.conv2d(net, 32, 1, scope='Conv2d_1x1') with tf.variable_scope('Branch_...
[ "Builds", "the", "35x35", "resnet", "block", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/sample_defenses/ens_adv_inception_resnet_v2/inception_resnet_v2.py#L35-L54
[ "def", "block35", "(", "net", ",", "scale", "=", "1.0", ",", "activation_fn", "=", "tf", ".", "nn", ".", "relu", ",", "scope", "=", "None", ",", "reuse", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "scope", ",", "'Block35'", ",...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
block17
Builds the 17x17 resnet block.
examples/nips17_adversarial_competition/dev_toolkit/sample_defenses/ens_adv_inception_resnet_v2/inception_resnet_v2.py
def block17(net, scale=1.0, activation_fn=tf.nn.relu, scope=None, reuse=None): """Builds the 17x17 resnet block.""" with tf.variable_scope(scope, 'Block17', [net], reuse=reuse): with tf.variable_scope('Branch_0'): tower_conv = slim.conv2d(net, 192, 1, scope='Conv2d_1x1') with tf.variable_scope('Branch...
def block17(net, scale=1.0, activation_fn=tf.nn.relu, scope=None, reuse=None): """Builds the 17x17 resnet block.""" with tf.variable_scope(scope, 'Block17', [net], reuse=reuse): with tf.variable_scope('Branch_0'): tower_conv = slim.conv2d(net, 192, 1, scope='Conv2d_1x1') with tf.variable_scope('Branch...
[ "Builds", "the", "17x17", "resnet", "block", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/sample_defenses/ens_adv_inception_resnet_v2/inception_resnet_v2.py#L57-L74
[ "def", "block17", "(", "net", ",", "scale", "=", "1.0", ",", "activation_fn", "=", "tf", ".", "nn", ".", "relu", ",", "scope", "=", "None", ",", "reuse", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "scope", ",", "'Block17'", ",...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
inception_resnet_v2_base
Inception model from http://arxiv.org/abs/1602.07261. Constructs an Inception Resnet v2 network from inputs to the given final endpoint. This method can construct the network up to the final inception block Conv2d_7b_1x1. Args: inputs: a tensor of size [batch_size, height, width, channels]. final_end...
examples/nips17_adversarial_competition/dev_toolkit/sample_defenses/ens_adv_inception_resnet_v2/inception_resnet_v2.py
def inception_resnet_v2_base(inputs, final_endpoint='Conv2d_7b_1x1', output_stride=16, align_feature_maps=False, scope=None): """Inception model from http://arxiv.org/abs/1602.07261. Constructs an I...
def inception_resnet_v2_base(inputs, final_endpoint='Conv2d_7b_1x1', output_stride=16, align_feature_maps=False, scope=None): """Inception model from http://arxiv.org/abs/1602.07261. Constructs an I...
[ "Inception", "model", "from", "http", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1602", ".", "07261", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/sample_defenses/ens_adv_inception_resnet_v2/inception_resnet_v2.py#L97-L285
[ "def", "inception_resnet_v2_base", "(", "inputs", ",", "final_endpoint", "=", "'Conv2d_7b_1x1'", ",", "output_stride", "=", "16", ",", "align_feature_maps", "=", "False", ",", "scope", "=", "None", ")", ":", "if", "output_stride", "!=", "8", "and", "output_strid...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
inception_resnet_v2
Creates the Inception Resnet V2 model. Args: inputs: a 4-D tensor of size [batch_size, height, width, 3]. nb_classes: number of predicted classes. is_training: whether is training or not. dropout_keep_prob: float, the fraction to keep before final layer. reuse: whether or not the network and its ...
examples/nips17_adversarial_competition/dev_toolkit/sample_defenses/ens_adv_inception_resnet_v2/inception_resnet_v2.py
def inception_resnet_v2(inputs, nb_classes=1001, is_training=True, dropout_keep_prob=0.8, reuse=None, scope='InceptionResnetV2', create_aux_logits=True, num_classes=None): """Creates the Inception R...
def inception_resnet_v2(inputs, nb_classes=1001, is_training=True, dropout_keep_prob=0.8, reuse=None, scope='InceptionResnetV2', create_aux_logits=True, num_classes=None): """Creates the Inception R...
[ "Creates", "the", "Inception", "Resnet", "V2", "model", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/sample_defenses/ens_adv_inception_resnet_v2/inception_resnet_v2.py#L288-L352
[ "def", "inception_resnet_v2", "(", "inputs", ",", "nb_classes", "=", "1001", ",", "is_training", "=", "True", ",", "dropout_keep_prob", "=", "0.8", ",", "reuse", "=", "None", ",", "scope", "=", "'InceptionResnetV2'", ",", "create_aux_logits", "=", "True", ",",...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
inception_resnet_v2_arg_scope
Returns the scope with the default parameters for inception_resnet_v2. Args: weight_decay: the weight decay for weights variables. batch_norm_decay: decay for the moving average of batch_norm momentums. batch_norm_epsilon: small float added to variance to avoid dividing by zero. Returns: a arg_sco...
examples/nips17_adversarial_competition/dev_toolkit/sample_defenses/ens_adv_inception_resnet_v2/inception_resnet_v2.py
def inception_resnet_v2_arg_scope(weight_decay=0.00004, batch_norm_decay=0.9997, batch_norm_epsilon=0.001): """Returns the scope with the default parameters for inception_resnet_v2. Args: weight_decay: the weight decay for weights variables. ...
def inception_resnet_v2_arg_scope(weight_decay=0.00004, batch_norm_decay=0.9997, batch_norm_epsilon=0.001): """Returns the scope with the default parameters for inception_resnet_v2. Args: weight_decay: the weight decay for weights variables. ...
[ "Returns", "the", "scope", "with", "the", "default", "parameters", "for", "inception_resnet_v2", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/sample_defenses/ens_adv_inception_resnet_v2/inception_resnet_v2.py#L358-L384
[ "def", "inception_resnet_v2_arg_scope", "(", "weight_decay", "=", "0.00004", ",", "batch_norm_decay", "=", "0.9997", ",", "batch_norm_epsilon", "=", "0.001", ")", ":", "# Set weight_decay for weights in conv2d and fully_connected layers.", "with", "slim", ".", "arg_scope", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
ld_mnist
Load training and test data.
tutorials/future/tf2/mnist_tutorial.py
def ld_mnist(): """Load training and test data.""" def convert_types(image, label): image = tf.cast(image, tf.float32) image /= 255 return image, label dataset, info = tfds.load('mnist', data_dir='gs://tfds-data/datasets', with_info=True, as_supervised=True) mnist_train...
def ld_mnist(): """Load training and test data.""" def convert_types(image, label): image = tf.cast(image, tf.float32) image /= 255 return image, label dataset, info = tfds.load('mnist', data_dir='gs://tfds-data/datasets', with_info=True, as_supervised=True) mnist_train...
[ "Load", "training", "and", "test", "data", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/tutorials/future/tf2/mnist_tutorial.py#L29-L42
[ "def", "ld_mnist", "(", ")", ":", "def", "convert_types", "(", "image", ",", "label", ")", ":", "image", "=", "tf", ".", "cast", "(", "image", ",", "tf", ".", "float32", ")", "image", "/=", "255", "return", "image", ",", "label", "dataset", ",", "i...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
mnist_tutorial
MNIST CleverHans tutorial :param train_start: index of first training set example :param train_end: index of last training set example :param test_start: index of first test set example :param test_end: index of last test set example :param nb_epochs: number of epochs to train model :param batch_size: size ...
cleverhans_tutorials/mnist_tutorial_keras.py
def mnist_tutorial(train_start=0, train_end=60000, test_start=0, test_end=10000, nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE, learning_rate=LEARNING_RATE, testing=False, label_smoothing=0.1): """ MNIST CleverHans tutorial :param train_start: index of first t...
def mnist_tutorial(train_start=0, train_end=60000, test_start=0, test_end=10000, nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE, learning_rate=LEARNING_RATE, testing=False, label_smoothing=0.1): """ MNIST CleverHans tutorial :param train_start: index of first t...
[ "MNIST", "CleverHans", "tutorial", ":", "param", "train_start", ":", "index", "of", "first", "training", "set", "example", ":", "param", "train_end", ":", "index", "of", "last", "training", "set", "example", ":", "param", "test_start", ":", "index", "of", "f...
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans_tutorials/mnist_tutorial_keras.py#L30-L167
[ "def", "mnist_tutorial", "(", "train_start", "=", "0", ",", "train_end", "=", "60000", ",", "test_start", "=", "0", ",", "test_end", "=", "10000", ",", "nb_epochs", "=", "NB_EPOCHS", ",", "batch_size", "=", "BATCH_SIZE", ",", "learning_rate", "=", "LEARNING_...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
main
Validate all submissions and copy them into place
examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_and_copy_submissions.py
def main(args): """Validate all submissions and copy them into place""" random.seed() temp_dir = tempfile.mkdtemp() logging.info('Created temporary directory: %s', temp_dir) validator = SubmissionValidator( source_dir=args.source_dir, target_dir=args.target_dir, temp_dir=temp_dir, do_c...
def main(args): """Validate all submissions and copy them into place""" random.seed() temp_dir = tempfile.mkdtemp() logging.info('Created temporary directory: %s', temp_dir) validator = SubmissionValidator( source_dir=args.source_dir, target_dir=args.target_dir, temp_dir=temp_dir, do_c...
[ "Validate", "all", "submissions", "and", "copy", "them", "into", "place" ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_and_copy_submissions.py#L229-L243
[ "def", "main", "(", "args", ")", ":", "random", ".", "seed", "(", ")", "temp_dir", "=", "tempfile", ".", "mkdtemp", "(", ")", "logging", ".", "info", "(", "'Created temporary directory: %s'", ",", "temp_dir", ")", "validator", "=", "SubmissionValidator", "("...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
ValidationStats._update_stat
Common method to update submission statistics.
examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_and_copy_submissions.py
def _update_stat(self, submission_type, increase_success, increase_fail): """Common method to update submission statistics.""" stat = self.stats.get(submission_type, (0, 0)) stat = (stat[0] + increase_success, stat[1] + increase_fail) self.stats[submission_type] = stat
def _update_stat(self, submission_type, increase_success, increase_fail): """Common method to update submission statistics.""" stat = self.stats.get(submission_type, (0, 0)) stat = (stat[0] + increase_success, stat[1] + increase_fail) self.stats[submission_type] = stat
[ "Common", "method", "to", "update", "submission", "statistics", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_and_copy_submissions.py#L64-L68
[ "def", "_update_stat", "(", "self", ",", "submission_type", ",", "increase_success", ",", "increase_fail", ")", ":", "stat", "=", "self", ".", "stats", ".", "get", "(", "submission_type", ",", "(", "0", ",", "0", ")", ")", "stat", "=", "(", "stat", "["...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
ValidationStats.log_stats
Print statistics into log.
examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_and_copy_submissions.py
def log_stats(self): """Print statistics into log.""" logging.info('Validation statistics: ') for k, v in iteritems(self.stats): logging.info('%s - %d valid out of %d total submissions', k, v[0], v[0] + v[1])
def log_stats(self): """Print statistics into log.""" logging.info('Validation statistics: ') for k, v in iteritems(self.stats): logging.info('%s - %d valid out of %d total submissions', k, v[0], v[0] + v[1])
[ "Print", "statistics", "into", "log", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_and_copy_submissions.py#L78-L83
[ "def", "log_stats", "(", "self", ")", ":", "logging", ".", "info", "(", "'Validation statistics: '", ")", "for", "k", ",", "v", "in", "iteritems", "(", "self", ".", "stats", ")", ":", "logging", ".", "info", "(", "'%s - %d valid out of %d total submissions'", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
SubmissionValidator.copy_submission_locally
Copies submission from Google Cloud Storage to local directory. Args: cloud_path: path of the submission in Google Cloud Storage Returns: name of the local file where submission is copied to
examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_and_copy_submissions.py
def copy_submission_locally(self, cloud_path): """Copies submission from Google Cloud Storage to local directory. Args: cloud_path: path of the submission in Google Cloud Storage Returns: name of the local file where submission is copied to """ local_path = os.path.join(self.download_d...
def copy_submission_locally(self, cloud_path): """Copies submission from Google Cloud Storage to local directory. Args: cloud_path: path of the submission in Google Cloud Storage Returns: name of the local file where submission is copied to """ local_path = os.path.join(self.download_d...
[ "Copies", "submission", "from", "Google", "Cloud", "Storage", "to", "local", "directory", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_and_copy_submissions.py#L119-L133
[ "def", "copy_submission_locally", "(", "self", ",", "cloud_path", ")", ":", "local_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "download_dir", ",", "os", ".", "path", ".", "basename", "(", "cloud_path", ")", ")", "cmd", "=", "[", "'gs...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
SubmissionValidator.copy_submission_to_destination
Copies submission to target directory. Args: src_filename: source filename of the submission dst_subdir: subdirectory of the target directory where submission should be copied to submission_id: ID of the submission, will be used as a new submission filename (before extension)
examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_and_copy_submissions.py
def copy_submission_to_destination(self, src_filename, dst_subdir, submission_id): """Copies submission to target directory. Args: src_filename: source filename of the submission dst_subdir: subdirectory of the target directory where submission should be...
def copy_submission_to_destination(self, src_filename, dst_subdir, submission_id): """Copies submission to target directory. Args: src_filename: source filename of the submission dst_subdir: subdirectory of the target directory where submission should be...
[ "Copies", "submission", "to", "target", "directory", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_and_copy_submissions.py#L135-L157
[ "def", "copy_submission_to_destination", "(", "self", ",", "src_filename", ",", "dst_subdir", ",", "submission_id", ")", ":", "extension", "=", "[", "e", "for", "e", "in", "ALLOWED_EXTENSIONS", "if", "src_filename", ".", "endswith", "(", "e", ")", "]", "if", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
SubmissionValidator.validate_and_copy_one_submission
Validates one submission and copies it to target directory. Args: submission_path: path in Google Cloud Storage of the submission file
examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_and_copy_submissions.py
def validate_and_copy_one_submission(self, submission_path): """Validates one submission and copies it to target directory. Args: submission_path: path in Google Cloud Storage of the submission file """ if os.path.exists(self.download_dir): shutil.rmtree(self.download_dir) os.makedirs(s...
def validate_and_copy_one_submission(self, submission_path): """Validates one submission and copies it to target directory. Args: submission_path: path in Google Cloud Storage of the submission file """ if os.path.exists(self.download_dir): shutil.rmtree(self.download_dir) os.makedirs(s...
[ "Validates", "one", "submission", "and", "copies", "it", "to", "target", "directory", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_and_copy_submissions.py#L159-L190
[ "def", "validate_and_copy_one_submission", "(", "self", ",", "submission_path", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "self", ".", "download_dir", ")", ":", "shutil", ".", "rmtree", "(", "self", ".", "download_dir", ")", "os", ".", "makedi...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
SubmissionValidator.save_id_to_path_mapping
Saves mapping from submission IDs to original filenames. This mapping is saved as CSV file into target directory.
examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_and_copy_submissions.py
def save_id_to_path_mapping(self): """Saves mapping from submission IDs to original filenames. This mapping is saved as CSV file into target directory. """ if not self.id_to_path_mapping: return with open(self.local_id_to_path_mapping_file, 'w') as f: writer = csv.writer(f) writer...
def save_id_to_path_mapping(self): """Saves mapping from submission IDs to original filenames. This mapping is saved as CSV file into target directory. """ if not self.id_to_path_mapping: return with open(self.local_id_to_path_mapping_file, 'w') as f: writer = csv.writer(f) writer...
[ "Saves", "mapping", "from", "submission", "IDs", "to", "original", "filenames", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_and_copy_submissions.py#L192-L207
[ "def", "save_id_to_path_mapping", "(", "self", ")", ":", "if", "not", "self", ".", "id_to_path_mapping", ":", "return", "with", "open", "(", "self", ".", "local_id_to_path_mapping_file", ",", "'w'", ")", "as", "f", ":", "writer", "=", "csv", ".", "writer", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
SubmissionValidator.run
Runs validation of all submissions.
examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_and_copy_submissions.py
def run(self): """Runs validation of all submissions.""" cmd = ['gsutil', 'ls', os.path.join(self.source_dir, '**')] try: files_list = subprocess.check_output(cmd).split('\n') except subprocess.CalledProcessError: logging.error('Can''t read source directory') all_submissions = [ ...
def run(self): """Runs validation of all submissions.""" cmd = ['gsutil', 'ls', os.path.join(self.source_dir, '**')] try: files_list = subprocess.check_output(cmd).split('\n') except subprocess.CalledProcessError: logging.error('Can''t read source directory') all_submissions = [ ...
[ "Runs", "validation", "of", "all", "submissions", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_and_copy_submissions.py#L209-L226
[ "def", "run", "(", "self", ")", ":", "cmd", "=", "[", "'gsutil'", ",", "'ls'", ",", "os", ".", "path", ".", "join", "(", "self", ".", "source_dir", ",", "'**'", ")", "]", "try", ":", "files_list", "=", "subprocess", ".", "check_output", "(", "cmd",...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
main
Takes the path to a directory with reports and renders success fail plots.
scripts/plot_success_fail_curve.py
def main(argv=None): """Takes the path to a directory with reports and renders success fail plots.""" report_paths = argv[1:] fail_names = FLAGS.fail_names.split(',') for report_path in report_paths: plot_report_from_path(report_path, label=report_path, fail_names=fail_names) pyplot.legend() pyplot.x...
def main(argv=None): """Takes the path to a directory with reports and renders success fail plots.""" report_paths = argv[1:] fail_names = FLAGS.fail_names.split(',') for report_path in report_paths: plot_report_from_path(report_path, label=report_path, fail_names=fail_names) pyplot.legend() pyplot.x...
[ "Takes", "the", "path", "to", "a", "directory", "with", "reports", "and", "renders", "success", "fail", "plots", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/scripts/plot_success_fail_curve.py#L25-L38
[ "def", "main", "(", "argv", "=", "None", ")", ":", "report_paths", "=", "argv", "[", "1", ":", "]", "fail_names", "=", "FLAGS", ".", "fail_names", ".", "split", "(", "','", ")", "for", "report_path", "in", "report_paths", ":", "plot_report_from_path", "(...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
is_unclaimed
Returns True if work piece is unclaimed.
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py
def is_unclaimed(work): """Returns True if work piece is unclaimed.""" if work['is_completed']: return False cutoff_time = time.time() - MAX_PROCESSING_TIME if (work['claimed_worker_id'] and work['claimed_worker_start_time'] is not None and work['claimed_worker_start_time'] >= cutoff_time): ...
def is_unclaimed(work): """Returns True if work piece is unclaimed.""" if work['is_completed']: return False cutoff_time = time.time() - MAX_PROCESSING_TIME if (work['claimed_worker_id'] and work['claimed_worker_start_time'] is not None and work['claimed_worker_start_time'] >= cutoff_time): ...
[ "Returns", "True", "if", "work", "piece", "is", "unclaimed", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py#L46-L55
[ "def", "is_unclaimed", "(", "work", ")", ":", "if", "work", "[", "'is_completed'", "]", ":", "return", "False", "cutoff_time", "=", "time", ".", "time", "(", ")", "-", "MAX_PROCESSING_TIME", "if", "(", "work", "[", "'claimed_worker_id'", "]", "and", "work"...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
WorkPiecesBase.write_all_to_datastore
Writes all work pieces into datastore. Each work piece is identified by ID. This method writes/updates only those work pieces which IDs are stored in this class. For examples, if this class has only work pieces with IDs '1' ... '100' and datastore already contains work pieces with IDs '50' ... '200' t...
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py
def write_all_to_datastore(self): """Writes all work pieces into datastore. Each work piece is identified by ID. This method writes/updates only those work pieces which IDs are stored in this class. For examples, if this class has only work pieces with IDs '1' ... '100' and datastore already contains ...
def write_all_to_datastore(self): """Writes all work pieces into datastore. Each work piece is identified by ID. This method writes/updates only those work pieces which IDs are stored in this class. For examples, if this class has only work pieces with IDs '1' ... '100' and datastore already contains ...
[ "Writes", "all", "work", "pieces", "into", "datastore", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py#L150-L168
[ "def", "write_all_to_datastore", "(", "self", ")", ":", "client", "=", "self", ".", "_datastore_client", "with", "client", ".", "no_transact_batch", "(", ")", "as", "batch", ":", "parent_key", "=", "client", ".", "key", "(", "KIND_WORK_TYPE", ",", "self", "....
97488e215760547b81afc53f5e5de8ba7da5bd98
train
WorkPiecesBase.read_all_from_datastore
Reads all work pieces from the datastore.
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py
def read_all_from_datastore(self): """Reads all work pieces from the datastore.""" self._work = {} client = self._datastore_client parent_key = client.key(KIND_WORK_TYPE, self._work_type_entity_id) for entity in client.query_fetch(kind=KIND_WORK, ancestor=parent_key): work_id = entity.key.flat...
def read_all_from_datastore(self): """Reads all work pieces from the datastore.""" self._work = {} client = self._datastore_client parent_key = client.key(KIND_WORK_TYPE, self._work_type_entity_id) for entity in client.query_fetch(kind=KIND_WORK, ancestor=parent_key): work_id = entity.key.flat...
[ "Reads", "all", "work", "pieces", "from", "the", "datastore", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py#L170-L177
[ "def", "read_all_from_datastore", "(", "self", ")", ":", "self", ".", "_work", "=", "{", "}", "client", "=", "self", ".", "_datastore_client", "parent_key", "=", "client", ".", "key", "(", "KIND_WORK_TYPE", ",", "self", ".", "_work_type_entity_id", ")", "for...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
WorkPiecesBase._read_undone_shard_from_datastore
Reads undone worke pieces which are assigned to shard with given id.
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py
def _read_undone_shard_from_datastore(self, shard_id=None): """Reads undone worke pieces which are assigned to shard with given id.""" self._work = {} client = self._datastore_client parent_key = client.key(KIND_WORK_TYPE, self._work_type_entity_id) filters = [('is_completed', '=', False)] if sh...
def _read_undone_shard_from_datastore(self, shard_id=None): """Reads undone worke pieces which are assigned to shard with given id.""" self._work = {} client = self._datastore_client parent_key = client.key(KIND_WORK_TYPE, self._work_type_entity_id) filters = [('is_completed', '=', False)] if sh...
[ "Reads", "undone", "worke", "pieces", "which", "are", "assigned", "to", "shard", "with", "given", "id", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py#L179-L192
[ "def", "_read_undone_shard_from_datastore", "(", "self", ",", "shard_id", "=", "None", ")", ":", "self", ".", "_work", "=", "{", "}", "client", "=", "self", ".", "_datastore_client", "parent_key", "=", "client", ".", "key", "(", "KIND_WORK_TYPE", ",", "self"...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
WorkPiecesBase.read_undone_from_datastore
Reads undone work from the datastore. If shard_id and num_shards are specified then this method will attempt to read undone work for shard with id shard_id. If no undone work was found then it will try to read shard (shard_id+1) and so on until either found shard with undone work or all shards are read...
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py
def read_undone_from_datastore(self, shard_id=None, num_shards=None): """Reads undone work from the datastore. If shard_id and num_shards are specified then this method will attempt to read undone work for shard with id shard_id. If no undone work was found then it will try to read shard (shard_id+1) a...
def read_undone_from_datastore(self, shard_id=None, num_shards=None): """Reads undone work from the datastore. If shard_id and num_shards are specified then this method will attempt to read undone work for shard with id shard_id. If no undone work was found then it will try to read shard (shard_id+1) a...
[ "Reads", "undone", "work", "from", "the", "datastore", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py#L194-L219
[ "def", "read_undone_from_datastore", "(", "self", ",", "shard_id", "=", "None", ",", "num_shards", "=", "None", ")", ":", "if", "shard_id", "is", "not", "None", ":", "shards_list", "=", "[", "(", "i", "+", "shard_id", ")", "%", "num_shards", "for", "i", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
WorkPiecesBase.try_pick_piece_of_work
Tries pick next unclaimed piece of work to do. Attempt to claim work piece is done using Cloud Datastore transaction, so only one worker can claim any work piece at a time. Args: worker_id: ID of current worker submission_id: if not None then this method will try to pick piece of work ...
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py
def try_pick_piece_of_work(self, worker_id, submission_id=None): """Tries pick next unclaimed piece of work to do. Attempt to claim work piece is done using Cloud Datastore transaction, so only one worker can claim any work piece at a time. Args: worker_id: ID of current worker submission_...
def try_pick_piece_of_work(self, worker_id, submission_id=None): """Tries pick next unclaimed piece of work to do. Attempt to claim work piece is done using Cloud Datastore transaction, so only one worker can claim any work piece at a time. Args: worker_id: ID of current worker submission_...
[ "Tries", "pick", "next", "unclaimed", "piece", "of", "work", "to", "do", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py#L221-L261
[ "def", "try_pick_piece_of_work", "(", "self", ",", "worker_id", ",", "submission_id", "=", "None", ")", ":", "client", "=", "self", ".", "_datastore_client", "unclaimed_work_ids", "=", "None", "if", "submission_id", ":", "unclaimed_work_ids", "=", "[", "k", "for...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
WorkPiecesBase.update_work_as_completed
Updates work piece in datastore as completed. Args: worker_id: ID of the worker which did the work work_id: ID of the work which was done other_values: dictionary with additonal values which should be saved with the work piece error: if not None then error occurred during computatio...
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py
def update_work_as_completed(self, worker_id, work_id, other_values=None, error=None): """Updates work piece in datastore as completed. Args: worker_id: ID of the worker which did the work work_id: ID of the work which was done other_values: dictionary with addi...
def update_work_as_completed(self, worker_id, work_id, other_values=None, error=None): """Updates work piece in datastore as completed. Args: worker_id: ID of the worker which did the work work_id: ID of the work which was done other_values: dictionary with addi...
[ "Updates", "work", "piece", "in", "datastore", "as", "completed", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py#L263-L294
[ "def", "update_work_as_completed", "(", "self", ",", "worker_id", ",", "work_id", ",", "other_values", "=", "None", ",", "error", "=", "None", ")", ":", "client", "=", "self", ".", "_datastore_client", "try", ":", "with", "client", ".", "transaction", "(", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
WorkPiecesBase.compute_work_statistics
Computes statistics from all work pieces stored in this class.
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py
def compute_work_statistics(self): """Computes statistics from all work pieces stored in this class.""" result = {} for v in itervalues(self.work): submission_id = v['submission_id'] if submission_id not in result: result[submission_id] = { 'completed': 0, 'num_er...
def compute_work_statistics(self): """Computes statistics from all work pieces stored in this class.""" result = {} for v in itervalues(self.work): submission_id = v['submission_id'] if submission_id not in result: result[submission_id] = { 'completed': 0, 'num_er...
[ "Computes", "statistics", "from", "all", "work", "pieces", "stored", "in", "this", "class", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py#L296-L326
[ "def", "compute_work_statistics", "(", "self", ")", ":", "result", "=", "{", "}", "for", "v", "in", "itervalues", "(", "self", ".", "work", ")", ":", "submission_id", "=", "v", "[", "'submission_id'", "]", "if", "submission_id", "not", "in", "result", ":...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
AttackWorkPieces.init_from_adversarial_batches
Initializes work pieces from adversarial batches. Args: adv_batches: dict with adversarial batches, could be obtained as AversarialBatches.data
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py
def init_from_adversarial_batches(self, adv_batches): """Initializes work pieces from adversarial batches. Args: adv_batches: dict with adversarial batches, could be obtained as AversarialBatches.data """ for idx, (adv_batch_id, adv_batch_val) in enumerate(iteritems(adv_batches)): w...
def init_from_adversarial_batches(self, adv_batches): """Initializes work pieces from adversarial batches. Args: adv_batches: dict with adversarial batches, could be obtained as AversarialBatches.data """ for idx, (adv_batch_id, adv_batch_val) in enumerate(iteritems(adv_batches)): w...
[ "Initializes", "work", "pieces", "from", "adversarial", "batches", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py#L349-L367
[ "def", "init_from_adversarial_batches", "(", "self", ",", "adv_batches", ")", ":", "for", "idx", ",", "(", "adv_batch_id", ",", "adv_batch_val", ")", "in", "enumerate", "(", "iteritems", "(", "adv_batches", ")", ")", ":", "work_id", "=", "ATTACK_WORK_ID_PATTERN"...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
DefenseWorkPieces.init_from_class_batches
Initializes work pieces from classification batches. Args: class_batches: dict with classification batches, could be obtained as ClassificationBatches.data num_shards: number of shards to split data into, if None then no sharding is done.
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py
def init_from_class_batches(self, class_batches, num_shards=None): """Initializes work pieces from classification batches. Args: class_batches: dict with classification batches, could be obtained as ClassificationBatches.data num_shards: number of shards to split data into, if None ...
def init_from_class_batches(self, class_batches, num_shards=None): """Initializes work pieces from classification batches. Args: class_batches: dict with classification batches, could be obtained as ClassificationBatches.data num_shards: number of shards to split data into, if None ...
[ "Initializes", "work", "pieces", "from", "classification", "batches", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py#L379-L411
[ "def", "init_from_class_batches", "(", "self", ",", "class_batches", ",", "num_shards", "=", "None", ")", ":", "shards_for_submissions", "=", "{", "}", "shard_idx", "=", "0", "for", "idx", ",", "(", "batch_id", ",", "batch_val", ")", "in", "enumerate", "(", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
main
Make a confidence report and save it to disk.
scripts/make_confidence_report_bundle_examples.py
def main(argv=None): """ Make a confidence report and save it to disk. """ assert len(argv) >= 3 _name_of_script = argv[0] model_filepath = argv[1] adv_x_filepaths = argv[2:] sess = tf.Session() with sess.as_default(): model = serial.load(model_filepath) factory = model.dataset_factory facto...
def main(argv=None): """ Make a confidence report and save it to disk. """ assert len(argv) >= 3 _name_of_script = argv[0] model_filepath = argv[1] adv_x_filepaths = argv[2:] sess = tf.Session() with sess.as_default(): model = serial.load(model_filepath) factory = model.dataset_factory facto...
[ "Make", "a", "confidence", "report", "and", "save", "it", "to", "disk", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/scripts/make_confidence_report_bundle_examples.py#L48-L95
[ "def", "main", "(", "argv", "=", "None", ")", ":", "assert", "len", "(", "argv", ")", ">=", "3", "_name_of_script", "=", "argv", "[", "0", "]", "model_filepath", "=", "argv", "[", "1", "]", "adv_x_filepaths", "=", "argv", "[", "2", ":", "]", "sess"...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
fgm
TensorFlow implementation of the Fast Gradient Method. :param x: the input placeholder :param logits: output of model.get_logits :param y: (optional) A placeholder for the true labels. If targeted is true, then provide the target label. Otherwise, only provide this parameter if you'd like ...
cleverhans/attacks/fast_gradient_method.py
def fgm(x, logits, y=None, eps=0.3, ord=np.inf, clip_min=None, clip_max=None, targeted=False, sanity_checks=True): """ TensorFlow implementation of the Fast Gradient Method. :param x: the input placeholder :param logits: output of model.get_logits ...
def fgm(x, logits, y=None, eps=0.3, ord=np.inf, clip_min=None, clip_max=None, targeted=False, sanity_checks=True): """ TensorFlow implementation of the Fast Gradient Method. :param x: the input placeholder :param logits: output of model.get_logits ...
[ "TensorFlow", "implementation", "of", "the", "Fast", "Gradient", "Method", ".", ":", "param", "x", ":", "the", "input", "placeholder", ":", "param", "logits", ":", "output", "of", "model", ".", "get_logits", ":", "param", "y", ":", "(", "optional", ")", ...
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/fast_gradient_method.py#L119-L194
[ "def", "fgm", "(", "x", ",", "logits", ",", "y", "=", "None", ",", "eps", "=", "0.3", ",", "ord", "=", "np", ".", "inf", ",", "clip_min", "=", "None", ",", "clip_max", "=", "None", ",", "targeted", "=", "False", ",", "sanity_checks", "=", "True",...
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: tf tensor containing a batch of gradients :param eps: float scalar specifying size of constraint region :param ord: int specifying order of norm :re...
cleverhans/attacks/fast_gradient_method.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: tf tensor containing a batch of gradients :param eps: float scalar specifying size of constraint reg...
def optimize_linear(grad, eps, ord=np.inf): """ Solves for the optimal input to a linear function under a norm constraint. Optimal_perturbation = argmax_{eta, ||eta||_{ord} < eps} dot(eta, grad) :param grad: tf tensor containing a batch of gradients :param eps: float scalar specifying size of constraint reg...
[ "Solves", "for", "the", "optimal", "input", "to", "a", "linear", "function", "under", "a", "norm", "constraint", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/fast_gradient_method.py#L197-L243
[ "def", "optimize_linear", "(", "grad", ",", "eps", ",", "ord", "=", "np", ".", "inf", ")", ":", "# In Python 2, the `list` call in the following line is redundant / harmless.", "# In Python 3, the `list` call is needed to convert the iterator returned by `range` into a list.", "red_i...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
FastGradientMethod.generate
Returns the graph for Fast Gradient Method adversarial examples. :param x: The model's symbolic inputs. :param kwargs: See `parse_params`
cleverhans/attacks/fast_gradient_method.py
def generate(self, x, **kwargs): """ Returns the graph for Fast Gradient Method adversarial examples. :param x: The model's symbolic inputs. :param kwargs: See `parse_params` """ # Parse and save attack-specific parameters assert self.parse_params(**kwargs) labels, _nb_classes = self.g...
def generate(self, x, **kwargs): """ Returns the graph for Fast Gradient Method adversarial examples. :param x: The model's symbolic inputs. :param kwargs: See `parse_params` """ # Parse and save attack-specific parameters assert self.parse_params(**kwargs) labels, _nb_classes = self.g...
[ "Returns", "the", "graph", "for", "Fast", "Gradient", "Method", "adversarial", "examples", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/fast_gradient_method.py#L40-L61
[ "def", "generate", "(", "self", ",", "x", ",", "*", "*", "kwargs", ")", ":", "# Parse and save attack-specific parameters", "assert", "self", ".", "parse_params", "(", "*", "*", "kwargs", ")", "labels", ",", "_nb_classes", "=", "self", ".", "get_or_guess_label...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
load_network_from_checkpoint
Function to read the weights from checkpoint based on json description. Args: checkpoint: tensorflow checkpoint with trained model to verify model_json: path of json file with model description of the network list of dictionary items for each layer containing 'type', 'weight_var...
cleverhans/experimental/certification/nn.py
def load_network_from_checkpoint(checkpoint, model_json, input_shape=None): """Function to read the weights from checkpoint based on json description. Args: checkpoint: tensorflow checkpoint with trained model to verify model_json: path of json file with model description of the netwo...
def load_network_from_checkpoint(checkpoint, model_json, input_shape=None): """Function to read the weights from checkpoint based on json description. Args: checkpoint: tensorflow checkpoint with trained model to verify model_json: path of json file with model description of the netwo...
[ "Function", "to", "read", "the", "weights", "from", "checkpoint", "based", "on", "json", "description", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/nn.py#L161-L226
[ "def", "load_network_from_checkpoint", "(", "checkpoint", ",", "model_json", ",", "input_shape", "=", "None", ")", ":", "# Load checkpoint", "reader", "=", "tf", ".", "train", ".", "load_checkpoint", "(", "checkpoint", ")", "variable_map", "=", "reader", ".", "g...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
NeuralNetwork.forward_pass
Performs forward pass through the layer weights at layer_index. Args: vector: vector that has to be passed through in forward pass layer_index: index of the layer is_transpose: whether the weights of the layer have to be transposed is_abs: whether to take the absolute value of the weights ...
cleverhans/experimental/certification/nn.py
def forward_pass(self, vector, layer_index, is_transpose=False, is_abs=False): """Performs forward pass through the layer weights at layer_index. Args: vector: vector that has to be passed through in forward pass layer_index: index of the layer is_transpose: whether the weights of the layer h...
def forward_pass(self, vector, layer_index, is_transpose=False, is_abs=False): """Performs forward pass through the layer weights at layer_index. Args: vector: vector that has to be passed through in forward pass layer_index: index of the layer is_transpose: whether the weights of the layer h...
[ "Performs", "forward", "pass", "through", "the", "layer", "weights", "at", "layer_index", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/nn.py#L111-L159
[ "def", "forward_pass", "(", "self", ",", "vector", ",", "layer_index", ",", "is_transpose", "=", "False", ",", "is_abs", "=", "False", ")", ":", "if", "(", "layer_index", "<", "0", "or", "layer_index", ">", "self", ".", "num_hidden_layers", ")", ":", "ra...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
dev_version
Returns a hexdigest of all the python files in the module.
cleverhans/devtools/version.py
def dev_version(): """ Returns a hexdigest of all the python files in the module. """ md5_hash = hashlib.md5() py_files = sorted(list_files(suffix=".py")) if not py_files: return '' for filename in py_files: with open(filename, 'rb') as fobj: content = fobj.read() md5_hash.update(conten...
def dev_version(): """ Returns a hexdigest of all the python files in the module. """ md5_hash = hashlib.md5() py_files = sorted(list_files(suffix=".py")) if not py_files: return '' for filename in py_files: with open(filename, 'rb') as fobj: content = fobj.read() md5_hash.update(conten...
[ "Returns", "a", "hexdigest", "of", "all", "the", "python", "files", "in", "the", "module", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/devtools/version.py#L11-L24
[ "def", "dev_version", "(", ")", ":", "md5_hash", "=", "hashlib", ".", "md5", "(", ")", "py_files", "=", "sorted", "(", "list_files", "(", "suffix", "=", "\".py\"", ")", ")", "if", "not", "py_files", ":", "return", "''", "for", "filename", "in", "py_fil...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
current
The current implementation of report printing. :param report: ConfidenceReport
scripts/print_report.py
def current(report): """ The current implementation of report printing. :param report: ConfidenceReport """ if hasattr(report, "completed"): if report.completed: print("Report completed") else: print("REPORT NOT COMPLETED") else: warnings.warn("This report does not indicate whether i...
def current(report): """ The current implementation of report printing. :param report: ConfidenceReport """ if hasattr(report, "completed"): if report.completed: print("Report completed") else: print("REPORT NOT COMPLETED") else: warnings.warn("This report does not indicate whether i...
[ "The", "current", "implementation", "of", "report", "printing", ".", ":", "param", "report", ":", "ConfidenceReport" ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/scripts/print_report.py#L23-L41
[ "def", "current", "(", "report", ")", ":", "if", "hasattr", "(", "report", ",", "\"completed\"", ")", ":", "if", "report", ".", "completed", ":", "print", "(", "\"Report completed\"", ")", "else", ":", "print", "(", "\"REPORT NOT COMPLETED\"", ")", "else", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
deprecated
The deprecated implementation of report printing. :param report: dict
scripts/print_report.py
def deprecated(report): """ The deprecated implementation of report printing. :param report: dict """ warnings.warn("Printing dict-based reports is deprecated. This function " "is included only to support a private development branch " "and may be removed without warning.") ...
def deprecated(report): """ The deprecated implementation of report printing. :param report: dict """ warnings.warn("Printing dict-based reports is deprecated. This function " "is included only to support a private development branch " "and may be removed without warning.") ...
[ "The", "deprecated", "implementation", "of", "report", "printing", ".", ":", "param", "report", ":", "dict" ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/scripts/print_report.py#L43-L65
[ "def", "deprecated", "(", "report", ")", ":", "warnings", ".", "warn", "(", "\"Printing dict-based reports is deprecated. This function \"", "\"is included only to support a private development branch \"", "\"and may be removed without warning.\"", ")", "for", "key", "in", "report"...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
SNNL_example
A simple model trained to minimize Cross Entropy and Maximize Soft Nearest Neighbor Loss at each internal layer. This outputs a TSNE of the sign of the adversarial gradients of a trained model. A model with a negative SNNL_factor will show little or no class clusters, while a model with a 0 SNNL_factor will hav...
cleverhans/model_zoo/soft_nearest_neighbor_loss/SNNL_regularized_train.py
def SNNL_example(train_start=0, train_end=60000, test_start=0, test_end=10000, nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE, learning_rate=LEARNING_RATE, nb_filters=NB_FILTERS, SNNL_factor=SNNL_FACTOR, output_dir=OUTPUT_DIR): """ A s...
def SNNL_example(train_start=0, train_end=60000, test_start=0, test_end=10000, nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE, learning_rate=LEARNING_RATE, nb_filters=NB_FILTERS, SNNL_factor=SNNL_FACTOR, output_dir=OUTPUT_DIR): """ A s...
[ "A", "simple", "model", "trained", "to", "minimize", "Cross", "Entropy", "and", "Maximize", "Soft", "Nearest", "Neighbor", "Loss", "at", "each", "internal", "layer", ".", "This", "outputs", "a", "TSNE", "of", "the", "sign", "of", "the", "adversarial", "gradi...
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model_zoo/soft_nearest_neighbor_loss/SNNL_regularized_train.py#L37-L149
[ "def", "SNNL_example", "(", "train_start", "=", "0", ",", "train_end", "=", "60000", ",", "test_start", "=", "0", ",", "test_end", "=", "10000", ",", "nb_epochs", "=", "NB_EPOCHS", ",", "batch_size", "=", "BATCH_SIZE", ",", "learning_rate", "=", "LEARNING_RA...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
ProjectedGradientDescent.generate
Generate symbolic graph for adversarial examples and return. :param x: The model's symbolic inputs. :param kwargs: See `parse_params`
cleverhans/attacks/projected_gradient_descent.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) asserts = [] # If a data ra...
def generate(self, x, **kwargs): """ Generate symbolic graph for adversarial examples and return. :param x: The model's symbolic inputs. :param kwargs: See `parse_params` """ # Parse and save attack-specific parameters assert self.parse_params(**kwargs) asserts = [] # If a data ra...
[ "Generate", "symbolic", "graph", "for", "adversarial", "examples", "and", "return", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/projected_gradient_descent.py#L48-L166
[ "def", "generate", "(", "self", ",", "x", ",", "*", "*", "kwargs", ")", ":", "# Parse and save attack-specific parameters", "assert", "self", ".", "parse_params", "(", "*", "*", "kwargs", ")", "asserts", "=", "[", "]", "# If a data range was specified, check that ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
ProjectedGradientDescent.parse_params
Take in a dictionary of parameters and applies attack-specific checks before saving them as attributes. Attack-specific parameters: :param eps: (optional float) maximum distortion of adversarial example compared to original input :param eps_iter: (optional float) step size for each att...
cleverhans/attacks/projected_gradient_descent.py
def parse_params(self, eps=0.3, eps_iter=0.05, nb_iter=10, y=None, ord=np.inf, clip_min=None, clip_max=None, y_target=None, rand_init=None, ...
def parse_params(self, eps=0.3, eps_iter=0.05, nb_iter=10, y=None, ord=np.inf, clip_min=None, clip_max=None, y_target=None, rand_init=None, ...
[ "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/cleverhans/attacks/projected_gradient_descent.py#L168-L237
[ "def", "parse_params", "(", "self", ",", "eps", "=", "0.3", ",", "eps_iter", "=", "0.05", ",", "nb_iter", "=", "10", ",", "y", "=", "None", ",", "ord", "=", "np", ".", "inf", ",", "clip_min", "=", "None", ",", "clip_max", "=", "None", ",", "y_tar...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
train
Train a TF Eager model :param model: cleverhans.model.Model :param X_train: numpy array with training inputs :param Y_train: numpy array with training outputs :param save: boolean controlling the save operation :param predictions_adv: if set with the adversarial example tensor, will ...
cleverhans/utils_tfe.py
def train(model, X_train=None, Y_train=None, save=False, predictions_adv=None, evaluate=None, args=None, rng=None, var_list=None, attack=None, attack_args=None): """ Train a TF Eager model :param model: cleverhans.model.Model :param X_train: numpy array with training inputs :para...
def train(model, X_train=None, Y_train=None, save=False, predictions_adv=None, evaluate=None, args=None, rng=None, var_list=None, attack=None, attack_args=None): """ Train a TF Eager model :param model: cleverhans.model.Model :param X_train: numpy array with training inputs :para...
[ "Train", "a", "TF", "Eager", "model", ":", "param", "model", ":", "cleverhans", ".", "model", ".", "Model", ":", "param", "X_train", ":", "numpy", "array", "with", "training", "inputs", ":", "param", "Y_train", ":", "numpy", "array", "with", "training", ...
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_tfe.py#L24-L128
[ "def", "train", "(", "model", ",", "X_train", "=", "None", ",", "Y_train", "=", "None", ",", "save", "=", "False", ",", "predictions_adv", "=", "None", ",", "evaluate", "=", "None", ",", "args", "=", "None", ",", "rng", "=", "None", ",", "var_list", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
model_eval
Compute the accuracy of a TF Eager model on some data :param model: instance of cleverhans.model.Model_Eager with pretrained weights for evaluation. :param X_test: numpy array with training inputs :param Y_test: numpy array with training outputs :param args: dict or argparse `Namespace` object...
cleverhans/utils_tfe.py
def model_eval(model, X_test=None, Y_test=None, args=None, attack=None, attack_args=None): """ Compute the accuracy of a TF Eager model on some data :param model: instance of cleverhans.model.Model_Eager with pretrained weights for evaluation. :param X_test: numpy array with tra...
def model_eval(model, X_test=None, Y_test=None, args=None, attack=None, attack_args=None): """ Compute the accuracy of a TF Eager model on some data :param model: instance of cleverhans.model.Model_Eager with pretrained weights for evaluation. :param X_test: numpy array with tra...
[ "Compute", "the", "accuracy", "of", "a", "TF", "Eager", "model", "on", "some", "data", ":", "param", "model", ":", "instance", "of", "cleverhans", ".", "model", ".", "Model_Eager", "with", "pretrained", "weights", "for", "evaluation", ".", ":", "param", "X...
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_tfe.py#L131-L202
[ "def", "model_eval", "(", "model", ",", "X_test", "=", "None", ",", "Y_test", "=", "None", ",", "args", "=", "None", ",", "attack", "=", "None", ",", "attack_args", "=", "None", ")", ":", "args", "=", "_ArgsWrapper", "(", "args", "or", "{", "}", ")...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
model_argmax
Helper function that computes the current class prediction :param samples: numpy array with input samples (dims must match x) :return: the argmax output of predictions, i.e. the current predicted class
cleverhans/utils_tfe.py
def model_argmax(model, samples): """ Helper function that computes the current class prediction :param samples: numpy array with input samples (dims must match x) :return: the argmax output of predictions, i.e. the current predicted class """ tfe = tf.contrib.eager tf_samples = tfe.Variable(samples) pr...
def model_argmax(model, samples): """ Helper function that computes the current class prediction :param samples: numpy array with input samples (dims must match x) :return: the argmax output of predictions, i.e. the current predicted class """ tfe = tf.contrib.eager tf_samples = tfe.Variable(samples) pr...
[ "Helper", "function", "that", "computes", "the", "current", "class", "prediction", ":", "param", "samples", ":", "numpy", "array", "with", "input", "samples", "(", "dims", "must", "match", "x", ")", ":", "return", ":", "the", "argmax", "output", "of", "pre...
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_tfe.py#L205-L218
[ "def", "model_argmax", "(", "model", ",", "samples", ")", ":", "tfe", "=", "tf", ".", "contrib", ".", "eager", "tf_samples", "=", "tfe", ".", "Variable", "(", "samples", ")", "probabilities", "=", "model", ".", "get_probs", "(", "tf_samples", ")", "if", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
Noise.generate
Generate symbolic graph for adversarial examples and return. :param x: The model's symbolic inputs. :param kwargs: See `parse_params`
cleverhans/attacks/noise.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) if self.ord != np.inf: rai...
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) if self.ord != np.inf: rai...
[ "Generate", "symbolic", "graph", "for", "adversarial", "examples", "and", "return", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/noise.py#L38-L57
[ "def", "generate", "(", "self", ",", "x", ",", "*", "*", "kwargs", ")", ":", "# Parse and save attack-specific parameters", "assert", "self", ".", "parse_params", "(", "*", "*", "kwargs", ")", "if", "self", ".", "ord", "!=", "np", ".", "inf", ":", "raise...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
initialize_dual
Function to initialize the dual variables of the class. Args: neural_net_params_object: Object with the neural net weights, biases and types init_dual_file: Path to file containing dual variables, if the path is empty, perform random initialization Expects numpy dictionary with lambda...
cleverhans/experimental/certification/utils.py
def initialize_dual(neural_net_params_object, init_dual_file=None, random_init_variance=0.01, init_nu=200.0): """Function to initialize the dual variables of the class. Args: neural_net_params_object: Object with the neural net weights, biases and types init_dual_file: Path to fil...
def initialize_dual(neural_net_params_object, init_dual_file=None, random_init_variance=0.01, init_nu=200.0): """Function to initialize the dual variables of the class. Args: neural_net_params_object: Object with the neural net weights, biases and types init_dual_file: Path to fil...
[ "Function", "to", "initialize", "the", "dual", "variables", "of", "the", "class", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/utils.py#L22-L93
[ "def", "initialize_dual", "(", "neural_net_params_object", ",", "init_dual_file", "=", "None", ",", "random_init_variance", "=", "0.01", ",", "init_nu", "=", "200.0", ")", ":", "lambda_pos", "=", "[", "]", "lambda_neg", "=", "[", "]", "lambda_quad", "=", "[", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
eig_one_step
Function that performs one step of gd (variant) for min eigen value. Args: current_vector: current estimate of the eigen vector with minimum eigen value. learning_rate: learning rate. vector_prod_fn: function which returns product H*x, where H is a matrix for which we computing eigenvector. ...
cleverhans/experimental/certification/utils.py
def eig_one_step(current_vector, learning_rate, vector_prod_fn): """Function that performs one step of gd (variant) for min eigen value. Args: current_vector: current estimate of the eigen vector with minimum eigen value. learning_rate: learning rate. vector_prod_fn: function which returns produc...
def eig_one_step(current_vector, learning_rate, vector_prod_fn): """Function that performs one step of gd (variant) for min eigen value. Args: current_vector: current estimate of the eigen vector with minimum eigen value. learning_rate: learning rate. vector_prod_fn: function which returns produc...
[ "Function", "that", "performs", "one", "step", "of", "gd", "(", "variant", ")", "for", "min", "eigen", "value", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/utils.py#L95-L159
[ "def", "eig_one_step", "(", "current_vector", ",", "learning_rate", ",", "vector_prod_fn", ")", ":", "grad", "=", "2", "*", "vector_prod_fn", "(", "current_vector", ")", "# Current objective = (1/2)*v^T (2*M*v); v = current_vector", "# grad = 2*M*v", "current_objective", "=...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
minimum_eigen_vector
Computes eigenvector which corresponds to minimum eigenvalue. Args: x: initial value of eigenvector. num_steps: number of optimization steps. learning_rate: learning rate. vector_prod_fn: function which takes x and returns product H*x. Returns: approximate value of eigenvector. This functio...
cleverhans/experimental/certification/utils.py
def minimum_eigen_vector(x, num_steps, learning_rate, vector_prod_fn): """Computes eigenvector which corresponds to minimum eigenvalue. Args: x: initial value of eigenvector. num_steps: number of optimization steps. learning_rate: learning rate. vector_prod_fn: function which takes x and returns pr...
def minimum_eigen_vector(x, num_steps, learning_rate, vector_prod_fn): """Computes eigenvector which corresponds to minimum eigenvalue. Args: x: initial value of eigenvector. num_steps: number of optimization steps. learning_rate: learning rate. vector_prod_fn: function which takes x and returns pr...
[ "Computes", "eigenvector", "which", "corresponds", "to", "minimum", "eigenvalue", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/utils.py#L162-L181
[ "def", "minimum_eigen_vector", "(", "x", ",", "num_steps", ",", "learning_rate", ",", "vector_prod_fn", ")", ":", "x", "=", "tf", ".", "nn", ".", "l2_normalize", "(", "x", ")", "for", "_", "in", "range", "(", "num_steps", ")", ":", "x", "=", "eig_one_s...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
tf_lanczos_smallest_eigval
Computes smallest eigenvector and eigenvalue using Lanczos in pure TF. This function computes smallest eigenvector and eigenvalue of the matrix which is implicitly specified by `vector_prod_fn`. `vector_prod_fn` is a function which takes `x` and returns a product of matrix in consideration and `x`. Computati...
cleverhans/experimental/certification/utils.py
def tf_lanczos_smallest_eigval(vector_prod_fn, matrix_dim, initial_vector, num_iter=1000, max_iter=1000, collapse_tol=1e-9, dtype=tf.f...
def tf_lanczos_smallest_eigval(vector_prod_fn, matrix_dim, initial_vector, num_iter=1000, max_iter=1000, collapse_tol=1e-9, dtype=tf.f...
[ "Computes", "smallest", "eigenvector", "and", "eigenvalue", "using", "Lanczos", "in", "pure", "TF", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/utils.py#L184-L278
[ "def", "tf_lanczos_smallest_eigval", "(", "vector_prod_fn", ",", "matrix_dim", ",", "initial_vector", ",", "num_iter", "=", "1000", ",", "max_iter", "=", "1000", ",", "collapse_tol", "=", "1e-9", ",", "dtype", "=", "tf", ".", "float32", ")", ":", "# alpha will...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
NoRefModel.get_vars
Provides access to the model's Variables. This may include Variables that are not parameters, such as batch norm running moments. :return: A list of all Variables defining the model.
cleverhans/serial.py
def get_vars(self): """ Provides access to the model's Variables. This may include Variables that are not parameters, such as batch norm running moments. :return: A list of all Variables defining the model. """ # Catch eager execution and assert function overload. try: if tf.execu...
def get_vars(self): """ Provides access to the model's Variables. This may include Variables that are not parameters, such as batch norm running moments. :return: A list of all Variables defining the model. """ # Catch eager execution and assert function overload. try: if tf.execu...
[ "Provides", "access", "to", "the", "model", "s", "Variables", ".", "This", "may", "include", "Variables", "that", "are", "not", "parameters", "such", "as", "batch", "norm", "running", "moments", ".", ":", "return", ":", "A", "list", "of", "all", "Variables...
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/serial.py#L151-L194
[ "def", "get_vars", "(", "self", ")", ":", "# Catch eager execution and assert function overload.", "try", ":", "if", "tf", ".", "executing_eagerly", "(", ")", ":", "raise", "NotImplementedError", "(", "\"For Eager execution - get_vars \"", "\"must be overridden.\"", ")", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
Dropout.fprop
Forward propagation as either no-op or dropping random units. :param x: The input to the layer :param dropout: bool specifying whether to drop units :param dropout_dict: dict This dictionary is usually not needed. In rare cases, generally for research purposes, this dictionary makes ...
cleverhans/picklable_model.py
def fprop(self, x, dropout=False, dropout_dict=None, **kwargs): """ Forward propagation as either no-op or dropping random units. :param x: The input to the layer :param dropout: bool specifying whether to drop units :param dropout_dict: dict This dictionary is usually not needed. In...
def fprop(self, x, dropout=False, dropout_dict=None, **kwargs): """ Forward propagation as either no-op or dropping random units. :param x: The input to the layer :param dropout: bool specifying whether to drop units :param dropout_dict: dict This dictionary is usually not needed. In...
[ "Forward", "propagation", "as", "either", "no", "-", "op", "or", "dropping", "random", "units", ".", ":", "param", "x", ":", "The", "input", "to", "the", "layer", ":", "param", "dropout", ":", "bool", "specifying", "whether", "to", "drop", "units", ":", ...
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/picklable_model.py#L616-L639
[ "def", "fprop", "(", "self", ",", "x", ",", "dropout", "=", "False", ",", "dropout_dict", "=", "None", ",", "*", "*", "kwargs", ")", ":", "include_prob", "=", "self", ".", "include_prob", "if", "dropout_dict", "is", "not", "None", ":", "assert", "dropo...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
CarliniWagnerL2.generate
Return a tensor that constructs adversarial examples for the given input. Generate uses tf.py_func in order to operate over tensors. :param x: A tensor with the inputs. :param kwargs: See `parse_params`
cleverhans/attacks/carlini_wagner_l2.py
def generate(self, x, **kwargs): """ Return a tensor that constructs adversarial examples for the given input. Generate uses tf.py_func in order to operate over tensors. :param x: A tensor with the inputs. :param kwargs: See `parse_params` """ assert self.sess is not None, \ 'Cannot...
def generate(self, x, **kwargs): """ Return a tensor that constructs adversarial examples for the given input. Generate uses tf.py_func in order to operate over tensors. :param x: A tensor with the inputs. :param kwargs: See `parse_params` """ assert self.sess is not None, \ 'Cannot...
[ "Return", "a", "tensor", "that", "constructs", "adversarial", "examples", "for", "the", "given", "input", ".", "Generate", "uses", "tf", ".", "py_func", "in", "order", "to", "operate", "over", "tensors", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/carlini_wagner_l2.py#L58-L85
[ "def", "generate", "(", "self", ",", "x", ",", "*", "*", "kwargs", ")", ":", "assert", "self", ".", "sess", "is", "not", "None", ",", "'Cannot use `generate` when no `sess` was provided'", "self", ".", "parse_params", "(", "*", "*", "kwargs", ")", "labels", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
CarliniWagnerL2.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 confidence: Confide...
cleverhans/attacks/carlini_wagner_l2.py
def parse_params(self, y=None, y_target=None, batch_size=1, confidence=0, learning_rate=5e-3, binary_search_steps=5, max_iterations=1000, abort_early=True, ...
def parse_params(self, y=None, y_target=None, batch_size=1, confidence=0, learning_rate=5e-3, binary_search_steps=5, max_iterations=1000, abort_early=True, ...
[ ":", "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/carlini_wagner_l2.py#L87-L143
[ "def", "parse_params", "(", "self", ",", "y", "=", "None", ",", "y_target", "=", "None", ",", "batch_size", "=", "1", ",", "confidence", "=", "0", ",", "learning_rate", "=", "5e-3", ",", "binary_search_steps", "=", "5", ",", "max_iterations", "=", "1000"...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
CWL2.attack
Perform the L_2 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/carlini_wagner_l2.py
def attack(self, imgs, targets): """ Perform the L_2 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 """ r = [] for i in range(0, len(imgs), sel...
def attack(self, imgs, targets): """ Perform the L_2 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 """ r = [] for i in range(0, len(imgs), sel...
[ "Perform", "the", "L_2", "attack", "on", "the", "given", "instance", "for", "the", "given", "targets", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/carlini_wagner_l2.py#L276-L291
[ "def", "attack", "(", "self", ",", "imgs", ",", "targets", ")", ":", "r", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "imgs", ")", ",", "self", ".", "batch_size", ")", ":", "_logger", ".", "debug", "(", "(", "\"Running ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
CWL2.attack_batch
Run the attack on a batch of instance and labels.
cleverhans/attacks/carlini_wagner_l2.py
def attack_batch(self, imgs, labs): """ Run the attack on a batch of instance and labels. """ def compare(x, y): if not isinstance(x, (float, int, np.int64)): x = np.copy(x) if self.TARGETED: x[y] -= self.CONFIDENCE else: x[y] += self.CONFIDENCE ...
def attack_batch(self, imgs, labs): """ Run the attack on a batch of instance and labels. """ def compare(x, y): if not isinstance(x, (float, int, np.int64)): x = np.copy(x) if self.TARGETED: x[y] -= self.CONFIDENCE else: x[y] += self.CONFIDENCE ...
[ "Run", "the", "attack", "on", "a", "batch", "of", "instance", "and", "labels", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/carlini_wagner_l2.py#L293-L415
[ "def", "attack_batch", "(", "self", ",", "imgs", ",", "labs", ")", ":", "def", "compare", "(", "x", ",", "y", ")", ":", "if", "not", "isinstance", "(", "x", ",", "(", "float", ",", "int", ",", "np", ".", "int64", ")", ")", ":", "x", "=", "np"...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
maybe_load_model
Load model if present at the specified path.
examples/RL-attack/train.py
def maybe_load_model(savedir, container): """Load model if present at the specified path.""" if savedir is None: return state_path = os.path.join(os.path.join(savedir, 'training_state.pkl.zip')) if container is not None: logger.log("Attempting to download model from Azure") found_model = container....
def maybe_load_model(savedir, container): """Load model if present at the specified path.""" if savedir is None: return state_path = os.path.join(os.path.join(savedir, 'training_state.pkl.zip')) if container is not None: logger.log("Attempting to download model from Azure") found_model = container....
[ "Load", "model", "if", "present", "at", "the", "specified", "path", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/RL-attack/train.py#L130-L149
[ "def", "maybe_load_model", "(", "savedir", ",", "container", ")", ":", "if", "savedir", "is", "None", ":", "return", "state_path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "join", "(", "savedir", ",", "'training_state.pkl.zip'", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
check_installation
Warn user if running cleverhans from a different directory than tutorial.
cleverhans_tutorials/__init__.py
def check_installation(cur_file): """Warn user if running cleverhans from a different directory than tutorial.""" cur_dir = os.path.split(os.path.dirname(os.path.abspath(cur_file)))[0] ch_dir = os.path.split(cleverhans.__path__[0])[0] if cur_dir != ch_dir: warnings.warn("It appears that you have at least tw...
def check_installation(cur_file): """Warn user if running cleverhans from a different directory than tutorial.""" cur_dir = os.path.split(os.path.dirname(os.path.abspath(cur_file)))[0] ch_dir = os.path.split(cleverhans.__path__[0])[0] if cur_dir != ch_dir: warnings.warn("It appears that you have at least tw...
[ "Warn", "user", "if", "running", "cleverhans", "from", "a", "different", "directory", "than", "tutorial", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans_tutorials/__init__.py#L13-L24
[ "def", "check_installation", "(", "cur_file", ")", ":", "cur_dir", "=", "os", ".", "path", ".", "split", "(", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "cur_file", ")", ")", ")", "[", "0", "]", "ch_dir", "=", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
parse_args
Parses command line arguments.
examples/nips17_adversarial_competition/dataset/download_images.py
def parse_args(): """Parses command line arguments.""" parser = argparse.ArgumentParser( description='Tool to download dataset images.') parser.add_argument('--input_file', required=True, help='Location of dataset.csv') parser.add_argument('--output_dir', required=True, ...
def parse_args(): """Parses command line arguments.""" parser = argparse.ArgumentParser( description='Tool to download dataset images.') parser.add_argument('--input_file', required=True, help='Location of dataset.csv') parser.add_argument('--output_dir', required=True, ...
[ "Parses", "command", "line", "arguments", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dataset/download_images.py#L43-L54
[ "def", "parse_args", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Tool to download dataset images.'", ")", "parser", ".", "add_argument", "(", "'--input_file'", ",", "required", "=", "True", ",", "help", "=", "'Loca...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
get_image
Downloads the image that corresponds to the given row. Prints a notification if the download fails.
examples/nips17_adversarial_competition/dataset/download_images.py
def get_image(row, output_dir): """Downloads the image that corresponds to the given row. Prints a notification if the download fails.""" if not download_image(image_id=row[0], url=row[1], x1=float(row[2]), y1=float(row[3]), ...
def get_image(row, output_dir): """Downloads the image that corresponds to the given row. Prints a notification if the download fails.""" if not download_image(image_id=row[0], url=row[1], x1=float(row[2]), y1=float(row[3]), ...
[ "Downloads", "the", "image", "that", "corresponds", "to", "the", "given", "row", ".", "Prints", "a", "notification", "if", "the", "download", "fails", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dataset/download_images.py#L57-L67
[ "def", "get_image", "(", "row", ",", "output_dir", ")", ":", "if", "not", "download_image", "(", "image_id", "=", "row", "[", "0", "]", ",", "url", "=", "row", "[", "1", "]", ",", "x1", "=", "float", "(", "row", "[", "2", "]", ")", ",", "y1", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
download_image
Downloads one image, crops it, resizes it and saves it locally.
examples/nips17_adversarial_competition/dataset/download_images.py
def download_image(image_id, url, x1, y1, x2, y2, output_dir): """Downloads one image, crops it, resizes it and saves it locally.""" output_filename = os.path.join(output_dir, image_id + '.png') if os.path.exists(output_filename): # Don't download image if it's already there return True try: # Downl...
def download_image(image_id, url, x1, y1, x2, y2, output_dir): """Downloads one image, crops it, resizes it and saves it locally.""" output_filename = os.path.join(output_dir, image_id + '.png') if os.path.exists(output_filename): # Don't download image if it's already there return True try: # Downl...
[ "Downloads", "one", "image", "crops", "it", "resizes", "it", "and", "saves", "it", "locally", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dataset/download_images.py#L70-L92
[ "def", "download_image", "(", "image_id", ",", "url", ",", "x1", ",", "y1", ",", "x2", ",", "y2", ",", "output_dir", ")", ":", "output_filename", "=", "os", ".", "path", ".", "join", "(", "output_dir", ",", "image_id", "+", "'.png'", ")", "if", "os",...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
py_func_grad
Custom py_func with gradient support
examples/robust_vision_benchmark/cleverhans_attack_example/utils.py
def py_func_grad(func, inp, Tout, stateful=True, name=None, grad=None): """Custom py_func with gradient support """ # Need to generate a unique name to avoid duplicates: rnd_name = 'PyFuncGrad' + str(np.random.randint(0, 1E+8)) tf.RegisterGradient(rnd_name)(grad) g = tf.get_default_graph() with g.gradie...
def py_func_grad(func, inp, Tout, stateful=True, name=None, grad=None): """Custom py_func with gradient support """ # Need to generate a unique name to avoid duplicates: rnd_name = 'PyFuncGrad' + str(np.random.randint(0, 1E+8)) tf.RegisterGradient(rnd_name)(grad) g = tf.get_default_graph() with g.gradie...
[ "Custom", "py_func", "with", "gradient", "support" ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/robust_vision_benchmark/cleverhans_attack_example/utils.py#L25-L36
[ "def", "py_func_grad", "(", "func", ",", "inp", ",", "Tout", ",", "stateful", "=", "True", ",", "name", "=", "None", ",", "grad", "=", "None", ")", ":", "# Need to generate a unique name to avoid duplicates:", "rnd_name", "=", "'PyFuncGrad'", "+", "str", "(", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
ModelBasicCNNTFE.fprop
Forward propagation throught the network :return: dictionary with layer names mapping to activation values.
cleverhans_tutorials/tutorial_models_tfe.py
def fprop(self, x): """ Forward propagation throught the network :return: dictionary with layer names mapping to activation values. """ # Feed forward through the network layers for layer_name in self.layer_names: if layer_name == 'input': prev_layer_act = x continue ...
def fprop(self, x): """ Forward propagation throught the network :return: dictionary with layer names mapping to activation values. """ # Feed forward through the network layers for layer_name in self.layer_names: if layer_name == 'input': prev_layer_act = x continue ...
[ "Forward", "propagation", "throught", "the", "network", ":", "return", ":", "dictionary", "with", "layer", "names", "mapping", "to", "activation", "values", "." ]
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans_tutorials/tutorial_models_tfe.py#L54-L73
[ "def", "fprop", "(", "self", ",", "x", ")", ":", "# Feed forward through the network layers", "for", "layer_name", "in", "self", ".", "layer_names", ":", "if", "layer_name", "==", "'input'", ":", "prev_layer_act", "=", "x", "continue", "else", ":", "self", "."...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
ModelBasicCNNTFE.get_layer_params
Provides access to the parameters of the given layer. Works arounds the non-availability of graph collections in eager mode. :layer_name: name of the layer for which parameters are required, must be one of the string in the list layer_names :return: list of pa...
cleverhans_tutorials/tutorial_models_tfe.py
def get_layer_params(self, layer_name): """ Provides access to the parameters of the given layer. Works arounds the non-availability of graph collections in eager mode. :layer_name: name of the layer for which parameters are required, must be one of the string in the ...
def get_layer_params(self, layer_name): """ Provides access to the parameters of the given layer. Works arounds the non-availability of graph collections in eager mode. :layer_name: name of the layer for which parameters are required, must be one of the string in the ...
[ "Provides", "access", "to", "the", "parameters", "of", "the", "given", "layer", ".", "Works", "arounds", "the", "non", "-", "availability", "of", "graph", "collections", "in", "eager", "mode", ".", ":", "layer_name", ":", "name", "of", "the", "layer", "for...
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans_tutorials/tutorial_models_tfe.py#L75-L96
[ "def", "get_layer_params", "(", "self", ",", "layer_name", ")", ":", "assert", "layer_name", "in", "self", ".", "layer_names", "out", "=", "[", "]", "layer", "=", "self", ".", "layers", "[", "layer_name", "]", "layer_variables", "=", "layer", ".", "variabl...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
ModelBasicCNNTFE.get_params
Provides access to the model's parameters. Works arounds the non-availability of graph collections in eager mode. :return: A list of all Variables defining the model parameters.
cleverhans_tutorials/tutorial_models_tfe.py
def get_params(self): """ Provides access to the model's parameters. Works arounds the non-availability of graph collections in eager mode. :return: A list of all Variables defining the model parameters. """ assert tf.executing_eagerly() out = [] # Collecting params ...
def get_params(self): """ Provides access to the model's parameters. Works arounds the non-availability of graph collections in eager mode. :return: A list of all Variables defining the model parameters. """ assert tf.executing_eagerly() out = [] # Collecting params ...
[ "Provides", "access", "to", "the", "model", "s", "parameters", ".", "Works", "arounds", "the", "non", "-", "availability", "of", "graph", "collections", "in", "eager", "mode", ".", ":", "return", ":", "A", "list", "of", "all", "Variables", "defining", "the...
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans_tutorials/tutorial_models_tfe.py#L98-L111
[ "def", "get_params", "(", "self", ")", ":", "assert", "tf", ".", "executing_eagerly", "(", ")", "out", "=", "[", "]", "# Collecting params from each layer.", "for", "layer_name", "in", "self", ".", "layers", ":", "out", "+=", "self", ".", "get_layer_params", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
train
pair_visual
This function displays two images: the original and the adversarial sample :param original: the original input :param adversarial: the input after perturbations have been applied :param figure: if we've already displayed images, use the same plot :return: the matplot figure to reuse for future samples
cleverhans/plot/pyplot_image.py
def pair_visual(original, adversarial, figure=None): """ This function displays two images: the original and the adversarial sample :param original: the original input :param adversarial: the input after perturbations have been applied :param figure: if we've already displayed images, use the same plot :ret...
def pair_visual(original, adversarial, figure=None): """ This function displays two images: the original and the adversarial sample :param original: the original input :param adversarial: the input after perturbations have been applied :param figure: if we've already displayed images, use the same plot :ret...
[ "This", "function", "displays", "two", "images", ":", "the", "original", "and", "the", "adversarial", "sample", ":", "param", "original", ":", "the", "original", "input", ":", "param", "adversarial", ":", "the", "input", "after", "perturbations", "have", "been...
tensorflow/cleverhans
python
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/plot/pyplot_image.py#L9-L49
[ "def", "pair_visual", "(", "original", ",", "adversarial", ",", "figure", "=", "None", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "# Squeeze the image to remove single-dimensional entries from array shape", "original", "=", "np", ".", "squeeze", "("...
97488e215760547b81afc53f5e5de8ba7da5bd98