repo stringclasses 85
values | path stringlengths 8 121 | func_name stringlengths 1 82 | original_string stringlengths 112 65.5k | language stringclasses 1
value | code stringlengths 112 65.5k | code_tokens listlengths 20 4.09k | docstring stringlengths 3 46.3k | docstring_tokens listlengths 1 564 | sha stringclasses 85
values | url stringlengths 93 218 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
tensorflow/cleverhans | examples/nips17_adversarial_competition/eval_infra/code/worker.py | ExecutableSubmission.download | def download(self):
"""Method which downloads submission to local directory."""
# Structure of the download directory:
# submission_dir=LOCAL_SUBMISSIONS_DIR/submission_id
# submission_dir/s.ext <-- archived submission
# submission_dir/extracted <-- extracted submission
# Check whether s... | python | def download(self):
"""Method which downloads submission to local directory."""
# Structure of the download directory:
# submission_dir=LOCAL_SUBMISSIONS_DIR/submission_id
# submission_dir/s.ext <-- archived submission
# submission_dir/extracted <-- extracted submission
# Check whether s... | [
"def",
"download",
"(",
"self",
")",
":",
"# Structure of the download directory:",
"# submission_dir=LOCAL_SUBMISSIONS_DIR/submission_id",
"# submission_dir/s.ext <-- archived submission",
"# submission_dir/extracted <-- extracted submission",
"# Check whether submission is already there... | Method which downloads submission to local directory. | [
"Method",
"which",
"downloads",
"submission",
"to",
"local",
"directory",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L211-L309 | train |
tensorflow/cleverhans | examples/nips17_adversarial_competition/eval_infra/code/worker.py | ExecutableSubmission.temp_copy_extracted_submission | def temp_copy_extracted_submission(self):
"""Creates a temporary copy of extracted submission.
When executed, submission is allowed to modify it's own directory. So
to ensure that submission does not pass any data between runs, new
copy of the submission is made before each run. After a run temporary c... | python | def temp_copy_extracted_submission(self):
"""Creates a temporary copy of extracted submission.
When executed, submission is allowed to modify it's own directory. So
to ensure that submission does not pass any data between runs, new
copy of the submission is made before each run. After a run temporary c... | [
"def",
"temp_copy_extracted_submission",
"(",
"self",
")",
":",
"tmp_copy_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"submission_dir",
",",
"'tmp_copy'",
")",
"shell_call",
"(",
"[",
"'cp'",
",",
"'-R'",
",",
"os",
".",
"path",
".",
"jo... | Creates a temporary copy of extracted submission.
When executed, submission is allowed to modify it's own directory. So
to ensure that submission does not pass any data between runs, new
copy of the submission is made before each run. After a run temporary copy
of submission is deleted.
Returns:
... | [
"Creates",
"a",
"temporary",
"copy",
"of",
"extracted",
"submission",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L311-L325 | train |
tensorflow/cleverhans | examples/nips17_adversarial_competition/eval_infra/code/worker.py | ExecutableSubmission.run_without_time_limit | def run_without_time_limit(self, cmd):
"""Runs docker command without time limit.
Args:
cmd: list with the command line arguments which are passed to docker
binary
Returns:
how long it took to run submission in seconds
Raises:
WorkerError: if error occurred during execution ... | python | def run_without_time_limit(self, cmd):
"""Runs docker command without time limit.
Args:
cmd: list with the command line arguments which are passed to docker
binary
Returns:
how long it took to run submission in seconds
Raises:
WorkerError: if error occurred during execution ... | [
"def",
"run_without_time_limit",
"(",
"self",
",",
"cmd",
")",
":",
"cmd",
"=",
"[",
"DOCKER_BINARY",
",",
"'run'",
",",
"DOCKER_NVIDIA_RUNTIME",
"]",
"+",
"cmd",
"logging",
".",
"info",
"(",
"'Docker command: %s'",
",",
"' '",
".",
"join",
"(",
"cmd",
")"... | Runs docker command without time limit.
Args:
cmd: list with the command line arguments which are passed to docker
binary
Returns:
how long it took to run submission in seconds
Raises:
WorkerError: if error occurred during execution of the submission | [
"Runs",
"docker",
"command",
"without",
"time",
"limit",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L327-L350 | train |
tensorflow/cleverhans | examples/nips17_adversarial_competition/eval_infra/code/worker.py | ExecutableSubmission.run_with_time_limit | def run_with_time_limit(self, cmd, time_limit=SUBMISSION_TIME_LIMIT):
"""Runs docker command and enforces time limit.
Args:
cmd: list with the command line arguments which are passed to docker
binary after run
time_limit: time limit, in seconds. Negative value means no limit.
Returns:
... | python | def run_with_time_limit(self, cmd, time_limit=SUBMISSION_TIME_LIMIT):
"""Runs docker command and enforces time limit.
Args:
cmd: list with the command line arguments which are passed to docker
binary after run
time_limit: time limit, in seconds. Negative value means no limit.
Returns:
... | [
"def",
"run_with_time_limit",
"(",
"self",
",",
"cmd",
",",
"time_limit",
"=",
"SUBMISSION_TIME_LIMIT",
")",
":",
"if",
"time_limit",
"<",
"0",
":",
"return",
"self",
".",
"run_without_time_limit",
"(",
"cmd",
")",
"container_name",
"=",
"str",
"(",
"uuid",
... | Runs docker command and enforces time limit.
Args:
cmd: list with the command line arguments which are passed to docker
binary after run
time_limit: time limit, in seconds. Negative value means no limit.
Returns:
how long it took to run submission in seconds
Raises:
Worker... | [
"Runs",
"docker",
"command",
"and",
"enforces",
"time",
"limit",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L352-L388 | train |
tensorflow/cleverhans | examples/nips17_adversarial_competition/eval_infra/code/worker.py | AttackSubmission.run | def run(self, input_dir, output_dir, epsilon):
"""Runs attack inside Docker.
Args:
input_dir: directory with input (dataset).
output_dir: directory where output (adversarial images) should be written.
epsilon: maximum allowed size of adversarial perturbation,
should be in range [0, 25... | python | def run(self, input_dir, output_dir, epsilon):
"""Runs attack inside Docker.
Args:
input_dir: directory with input (dataset).
output_dir: directory where output (adversarial images) should be written.
epsilon: maximum allowed size of adversarial perturbation,
should be in range [0, 25... | [
"def",
"run",
"(",
"self",
",",
"input_dir",
",",
"output_dir",
",",
"epsilon",
")",
":",
"logging",
".",
"info",
"(",
"'Running attack %s'",
",",
"self",
".",
"submission_id",
")",
"tmp_run_dir",
"=",
"self",
".",
"temp_copy_extracted_submission",
"(",
")",
... | 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].
Returns:
how long it took to run submis... | [
"Runs",
"attack",
"inside",
"Docker",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L411-L439 | train |
tensorflow/cleverhans | examples/nips17_adversarial_competition/eval_infra/code/worker.py | DefenseSubmission.run | def run(self, input_dir, output_file_path):
"""Runs defense inside Docker.
Args:
input_dir: directory with input (adversarial images).
output_file_path: path of the output file.
Returns:
how long it took to run submission in seconds
"""
logging.info('Running defense %s', self.sub... | python | def run(self, input_dir, output_file_path):
"""Runs defense inside Docker.
Args:
input_dir: directory with input (adversarial images).
output_file_path: path of the output file.
Returns:
how long it took to run submission in seconds
"""
logging.info('Running defense %s', self.sub... | [
"def",
"run",
"(",
"self",
",",
"input_dir",
",",
"output_file_path",
")",
":",
"logging",
".",
"info",
"(",
"'Running defense %s'",
",",
"self",
".",
"submission_id",
")",
"tmp_run_dir",
"=",
"self",
".",
"temp_copy_extracted_submission",
"(",
")",
"output_dir"... | Runs defense inside Docker.
Args:
input_dir: directory with input (adversarial images).
output_file_path: path of the output file.
Returns:
how long it took to run submission in seconds | [
"Runs",
"defense",
"inside",
"Docker",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L462-L489 | train |
tensorflow/cleverhans | examples/nips17_adversarial_competition/eval_infra/code/worker.py | EvaluationWorker.read_dataset_metadata | def read_dataset_metadata(self):
"""Read `dataset_meta` field from bucket"""
if self.dataset_meta:
return
shell_call(['gsutil', 'cp',
'gs://' + self.storage_client.bucket_name + '/'
+ 'dataset/' + self.dataset_name + '_dataset.csv',
LOCAL_DATASET_METADAT... | python | def read_dataset_metadata(self):
"""Read `dataset_meta` field from bucket"""
if self.dataset_meta:
return
shell_call(['gsutil', 'cp',
'gs://' + self.storage_client.bucket_name + '/'
+ 'dataset/' + self.dataset_name + '_dataset.csv',
LOCAL_DATASET_METADAT... | [
"def",
"read_dataset_metadata",
"(",
"self",
")",
":",
"if",
"self",
".",
"dataset_meta",
":",
"return",
"shell_call",
"(",
"[",
"'gsutil'",
",",
"'cp'",
",",
"'gs://'",
"+",
"self",
".",
"storage_client",
".",
"bucket_name",
"+",
"'/'",
"+",
"'dataset/'",
... | Read `dataset_meta` field from bucket | [
"Read",
"dataset_meta",
"field",
"from",
"bucket"
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L556-L565 | train |
tensorflow/cleverhans | examples/nips17_adversarial_competition/eval_infra/code/worker.py | EvaluationWorker.fetch_attacks_data | def fetch_attacks_data(self):
"""Initializes data necessary to execute attacks.
This method could be called multiple times, only first call does
initialization, subsequent calls are noop.
"""
if self.attacks_data_initialized:
return
# init data from datastore
self.submissions.init_fro... | python | def fetch_attacks_data(self):
"""Initializes data necessary to execute attacks.
This method could be called multiple times, only first call does
initialization, subsequent calls are noop.
"""
if self.attacks_data_initialized:
return
# init data from datastore
self.submissions.init_fro... | [
"def",
"fetch_attacks_data",
"(",
"self",
")",
":",
"if",
"self",
".",
"attacks_data_initialized",
":",
"return",
"# init data from datastore",
"self",
".",
"submissions",
".",
"init_from_datastore",
"(",
")",
"self",
".",
"dataset_batches",
".",
"init_from_datastore"... | Initializes data necessary to execute attacks.
This method could be called multiple times, only first call does
initialization, subsequent calls are noop. | [
"Initializes",
"data",
"necessary",
"to",
"execute",
"attacks",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L567-L589 | train |
tensorflow/cleverhans | examples/nips17_adversarial_competition/eval_infra/code/worker.py | EvaluationWorker.run_attack_work | def run_attack_work(self, work_id):
"""Runs one attack work.
Args:
work_id: ID of the piece of work to run
Returns:
elapsed_time_sec, submission_id - elapsed time and id of the submission
Raises:
WorkerError: if error occurred during execution.
"""
adv_batch_id = (
s... | python | def run_attack_work(self, work_id):
"""Runs one attack work.
Args:
work_id: ID of the piece of work to run
Returns:
elapsed_time_sec, submission_id - elapsed time and id of the submission
Raises:
WorkerError: if error occurred during execution.
"""
adv_batch_id = (
s... | [
"def",
"run_attack_work",
"(",
"self",
",",
"work_id",
")",
":",
"adv_batch_id",
"=",
"(",
"self",
".",
"attack_work",
".",
"work",
"[",
"work_id",
"]",
"[",
"'output_adversarial_batch_id'",
"]",
")",
"adv_batch",
"=",
"self",
".",
"adv_batches",
"[",
"adv_b... | Runs one attack work.
Args:
work_id: ID of the piece of work to run
Returns:
elapsed_time_sec, submission_id - elapsed time and id of the submission
Raises:
WorkerError: if error occurred during execution. | [
"Runs",
"one",
"attack",
"work",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L591-L687 | train |
tensorflow/cleverhans | examples/nips17_adversarial_competition/eval_infra/code/worker.py | EvaluationWorker.run_attacks | def run_attacks(self):
"""Method which evaluates all attack work.
In a loop this method queries not completed attack work, picks one
attack work and runs it.
"""
logging.info('******** Start evaluation of attacks ********')
prev_submission_id = None
while True:
# wait until work is av... | python | def run_attacks(self):
"""Method which evaluates all attack work.
In a loop this method queries not completed attack work, picks one
attack work and runs it.
"""
logging.info('******** Start evaluation of attacks ********')
prev_submission_id = None
while True:
# wait until work is av... | [
"def",
"run_attacks",
"(",
"self",
")",
":",
"logging",
".",
"info",
"(",
"'******** Start evaluation of attacks ********'",
")",
"prev_submission_id",
"=",
"None",
"while",
"True",
":",
"# wait until work is available",
"self",
".",
"attack_work",
".",
"read_all_from_d... | Method which evaluates all attack work.
In a loop this method queries not completed attack work, picks one
attack work and runs it. | [
"Method",
"which",
"evaluates",
"all",
"attack",
"work",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L689-L732 | train |
tensorflow/cleverhans | examples/nips17_adversarial_competition/eval_infra/code/worker.py | EvaluationWorker.fetch_defense_data | def fetch_defense_data(self):
"""Lazy initialization of data necessary to execute defenses."""
if self.defenses_data_initialized:
return
logging.info('Fetching defense data from datastore')
# init data from datastore
self.submissions.init_from_datastore()
self.dataset_batches.init_from_dat... | python | def fetch_defense_data(self):
"""Lazy initialization of data necessary to execute defenses."""
if self.defenses_data_initialized:
return
logging.info('Fetching defense data from datastore')
# init data from datastore
self.submissions.init_from_datastore()
self.dataset_batches.init_from_dat... | [
"def",
"fetch_defense_data",
"(",
"self",
")",
":",
"if",
"self",
".",
"defenses_data_initialized",
":",
"return",
"logging",
".",
"info",
"(",
"'Fetching defense data from datastore'",
")",
"# init data from datastore",
"self",
".",
"submissions",
".",
"init_from_datas... | Lazy initialization of data necessary to execute defenses. | [
"Lazy",
"initialization",
"of",
"data",
"necessary",
"to",
"execute",
"defenses",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L734-L746 | train |
tensorflow/cleverhans | examples/nips17_adversarial_competition/eval_infra/code/worker.py | EvaluationWorker.run_defense_work | def run_defense_work(self, work_id):
"""Runs one defense work.
Args:
work_id: ID of the piece of work to run
Returns:
elapsed_time_sec, submission_id - elapsed time and id of the submission
Raises:
WorkerError: if error occurred during execution.
"""
class_batch_id = (
... | python | def run_defense_work(self, work_id):
"""Runs one defense work.
Args:
work_id: ID of the piece of work to run
Returns:
elapsed_time_sec, submission_id - elapsed time and id of the submission
Raises:
WorkerError: if error occurred during execution.
"""
class_batch_id = (
... | [
"def",
"run_defense_work",
"(",
"self",
",",
"work_id",
")",
":",
"class_batch_id",
"=",
"(",
"self",
".",
"defense_work",
".",
"work",
"[",
"work_id",
"]",
"[",
"'output_classification_batch_id'",
"]",
")",
"class_batch",
"=",
"self",
".",
"class_batches",
".... | Runs one defense work.
Args:
work_id: ID of the piece of work to run
Returns:
elapsed_time_sec, submission_id - elapsed time and id of the submission
Raises:
WorkerError: if error occurred during execution. | [
"Runs",
"one",
"defense",
"work",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L748-L824 | train |
tensorflow/cleverhans | examples/nips17_adversarial_competition/eval_infra/code/worker.py | EvaluationWorker.run_defenses | def run_defenses(self):
"""Method which evaluates all defense work.
In a loop this method queries not completed defense work,
picks one defense work and runs it.
"""
logging.info('******** Start evaluation of defenses ********')
prev_submission_id = None
need_reload_work = True
while Tr... | python | def run_defenses(self):
"""Method which evaluates all defense work.
In a loop this method queries not completed defense work,
picks one defense work and runs it.
"""
logging.info('******** Start evaluation of defenses ********')
prev_submission_id = None
need_reload_work = True
while Tr... | [
"def",
"run_defenses",
"(",
"self",
")",
":",
"logging",
".",
"info",
"(",
"'******** Start evaluation of defenses ********'",
")",
"prev_submission_id",
"=",
"None",
"need_reload_work",
"=",
"True",
"while",
"True",
":",
"# wait until work is available",
"if",
"need_re... | Method which evaluates all defense work.
In a loop this method queries not completed defense work,
picks one defense work and runs it. | [
"Method",
"which",
"evaluates",
"all",
"defense",
"work",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L826-L890 | train |
tensorflow/cleverhans | examples/nips17_adversarial_competition/eval_infra/code/worker.py | EvaluationWorker.run_work | def run_work(self):
"""Run attacks and defenses"""
if os.path.exists(LOCAL_EVAL_ROOT_DIR):
sudo_remove_dirtree(LOCAL_EVAL_ROOT_DIR)
self.run_attacks()
self.run_defenses() | python | def run_work(self):
"""Run attacks and defenses"""
if os.path.exists(LOCAL_EVAL_ROOT_DIR):
sudo_remove_dirtree(LOCAL_EVAL_ROOT_DIR)
self.run_attacks()
self.run_defenses() | [
"def",
"run_work",
"(",
"self",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"LOCAL_EVAL_ROOT_DIR",
")",
":",
"sudo_remove_dirtree",
"(",
"LOCAL_EVAL_ROOT_DIR",
")",
"self",
".",
"run_attacks",
"(",
")",
"self",
".",
"run_defenses",
"(",
")"
] | Run attacks and defenses | [
"Run",
"attacks",
"and",
"defenses"
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L892-L897 | train |
tensorflow/cleverhans | cleverhans/attacks/attack.py | arg_type | def arg_type(arg_names, kwargs):
"""
Returns a hashable summary of the types of arg_names within kwargs.
:param arg_names: tuple containing names of relevant arguments
:param kwargs: dict mapping string argument names to values.
These must be values for which we can create a tf placeholder.
Currently su... | python | def arg_type(arg_names, kwargs):
"""
Returns a hashable summary of the types of arg_names within kwargs.
:param arg_names: tuple containing names of relevant arguments
:param kwargs: dict mapping string argument names to values.
These must be values for which we can create a tf placeholder.
Currently su... | [
"def",
"arg_type",
"(",
"arg_names",
",",
"kwargs",
")",
":",
"assert",
"isinstance",
"(",
"arg_names",
",",
"tuple",
")",
"passed",
"=",
"tuple",
"(",
"name",
"in",
"kwargs",
"for",
"name",
"in",
"arg_names",
")",
"passed_and_not_none",
"=",
"[",
"]",
"... | Returns a hashable summary of the types of arg_names within kwargs.
:param arg_names: tuple containing names of relevant arguments
:param kwargs: dict mapping string argument names to values.
These must be values for which we can create a tf placeholder.
Currently supported: numpy darray or something that c... | [
"Returns",
"a",
"hashable",
"summary",
"of",
"the",
"types",
"of",
"arg_names",
"within",
"kwargs",
".",
":",
"param",
"arg_names",
":",
"tuple",
"containing",
"names",
"of",
"relevant",
"arguments",
":",
"param",
"kwargs",
":",
"dict",
"mapping",
"string",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/attack.py#L304-L347 | train |
tensorflow/cleverhans | cleverhans/attacks/attack.py | Attack.construct_graph | def construct_graph(self, fixed, feedable, x_val, hash_key):
"""
Construct the graph required to run the attack through generate_np.
:param fixed: Structural elements that require defining a new graph.
:param feedable: Arguments that can be fed to the same graph when
they take diff... | python | def construct_graph(self, fixed, feedable, x_val, hash_key):
"""
Construct the graph required to run the attack through generate_np.
:param fixed: Structural elements that require defining a new graph.
:param feedable: Arguments that can be fed to the same graph when
they take diff... | [
"def",
"construct_graph",
"(",
"self",
",",
"fixed",
",",
"feedable",
",",
"x_val",
",",
"hash_key",
")",
":",
"# try our very best to create a TF placeholder for each of the",
"# feedable keyword arguments, and check the types are one of",
"# the allowed types",
"class_name",
"=... | Construct the graph required to run the attack through generate_np.
:param fixed: Structural elements that require defining a new graph.
:param feedable: Arguments that can be fed to the same graph when
they take different values.
:param x_val: symbolic adversarial example
:param h... | [
"Construct",
"the",
"graph",
"required",
"to",
"run",
"the",
"attack",
"through",
"generate_np",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/attack.py#L113-L165 | train |
tensorflow/cleverhans | cleverhans/attacks/attack.py | Attack.generate_np | def generate_np(self, x_val, **kwargs):
"""
Generate adversarial examples and return them as a NumPy array.
Sub-classes *should not* implement this method unless they must
perform special handling of arguments.
:param x_val: A NumPy array with the original inputs.
:param **kwargs: optional para... | python | def generate_np(self, x_val, **kwargs):
"""
Generate adversarial examples and return them as a NumPy array.
Sub-classes *should not* implement this method unless they must
perform special handling of arguments.
:param x_val: A NumPy array with the original inputs.
:param **kwargs: optional para... | [
"def",
"generate_np",
"(",
"self",
",",
"x_val",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"sess",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Cannot use `generate_np` when no `sess` was\"",
"\" provided\"",
")",
"packed",
"=",
"self",
".",
... | Generate adversarial examples and return them as a NumPy array.
Sub-classes *should not* implement this method unless they must
perform special handling of arguments.
:param x_val: A NumPy array with the original inputs.
:param **kwargs: optional parameters used by child classes.
:return: A NumPy a... | [
"Generate",
"adversarial",
"examples",
"and",
"return",
"them",
"as",
"a",
"NumPy",
"array",
".",
"Sub",
"-",
"classes",
"*",
"should",
"not",
"*",
"implement",
"this",
"method",
"unless",
"they",
"must",
"perform",
"special",
"handling",
"of",
"arguments",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/attack.py#L167-L200 | train |
tensorflow/cleverhans | cleverhans/attacks/attack.py | Attack.construct_variables | def construct_variables(self, kwargs):
"""
Construct the inputs to the attack graph to be used by generate_np.
:param kwargs: Keyword arguments to generate_np.
:return:
Structural arguments
Feedable arguments
Output of `arg_type` describing feedable arguments
A unique key
""... | python | def construct_variables(self, kwargs):
"""
Construct the inputs to the attack graph to be used by generate_np.
:param kwargs: Keyword arguments to generate_np.
:return:
Structural arguments
Feedable arguments
Output of `arg_type` describing feedable arguments
A unique key
""... | [
"def",
"construct_variables",
"(",
"self",
",",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"feedable_kwargs",
",",
"dict",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Using a dict for `feedable_kwargs is deprecated.\"",
"\"Switch to using a tuple.\"",
"\... | Construct the inputs to the attack graph to be used by generate_np.
:param kwargs: Keyword arguments to generate_np.
:return:
Structural arguments
Feedable arguments
Output of `arg_type` describing feedable arguments
A unique key | [
"Construct",
"the",
"inputs",
"to",
"the",
"attack",
"graph",
"to",
"be",
"used",
"by",
"generate_np",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/attack.py#L202-L258 | train |
tensorflow/cleverhans | cleverhans/attacks/attack.py | Attack.get_or_guess_labels | def get_or_guess_labels(self, x, kwargs):
"""
Get the label to use in generating an adversarial example for x.
The kwargs are fed directly from the kwargs of the attack.
If 'y' is in kwargs, then assume it's an untargeted attack and
use that as the label.
If 'y_target' is in kwargs and is not no... | python | def get_or_guess_labels(self, x, kwargs):
"""
Get the label to use in generating an adversarial example for x.
The kwargs are fed directly from the kwargs of the attack.
If 'y' is in kwargs, then assume it's an untargeted attack and
use that as the label.
If 'y_target' is in kwargs and is not no... | [
"def",
"get_or_guess_labels",
"(",
"self",
",",
"x",
",",
"kwargs",
")",
":",
"if",
"'y'",
"in",
"kwargs",
"and",
"'y_target'",
"in",
"kwargs",
":",
"raise",
"ValueError",
"(",
"\"Can not set both 'y' and 'y_target'.\"",
")",
"elif",
"'y'",
"in",
"kwargs",
":"... | Get the label to use in generating an adversarial example for x.
The kwargs are fed directly from the kwargs of the attack.
If 'y' is in kwargs, then assume it's an untargeted attack and
use that as the label.
If 'y_target' is in kwargs and is not none, then assume it's a
targeted attack and use tha... | [
"Get",
"the",
"label",
"to",
"use",
"in",
"generating",
"an",
"adversarial",
"example",
"for",
"x",
".",
"The",
"kwargs",
"are",
"fed",
"directly",
"from",
"the",
"kwargs",
"of",
"the",
"attack",
".",
"If",
"y",
"is",
"in",
"kwargs",
"then",
"assume",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/attack.py#L260-L287 | train |
tensorflow/cleverhans | examples/RL-attack/model.py | dueling_model | def dueling_model(img_in, num_actions, scope, noisy=False, reuse=False,
concat_softmax=False):
"""As described in https://arxiv.org/abs/1511.06581"""
with tf.variable_scope(scope, reuse=reuse):
out = img_in
with tf.variable_scope("convnet"):
# original architecture
out = layers... | python | def dueling_model(img_in, num_actions, scope, noisy=False, reuse=False,
concat_softmax=False):
"""As described in https://arxiv.org/abs/1511.06581"""
with tf.variable_scope(scope, reuse=reuse):
out = img_in
with tf.variable_scope("convnet"):
# original architecture
out = layers... | [
"def",
"dueling_model",
"(",
"img_in",
",",
"num_actions",
",",
"scope",
",",
"noisy",
"=",
"False",
",",
"reuse",
"=",
"False",
",",
"concat_softmax",
"=",
"False",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"scope",
",",
"reuse",
"=",
"reuse",... | As described in https://arxiv.org/abs/1511.06581 | [
"As",
"described",
"in",
"https",
":",
"//",
"arxiv",
".",
"org",
"/",
"abs",
"/",
"1511",
".",
"06581"
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/RL-attack/model.py#L38-L95 | train |
tensorflow/cleverhans | cleverhans_tutorials/mnist_tutorial_jsma.py | mnist_tutorial_jsma | def mnist_tutorial_jsma(train_start=0, train_end=60000, test_start=0,
test_end=10000, viz_enabled=VIZ_ENABLED,
nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE,
source_samples=SOURCE_SAMPLES,
learning_rate=LEARNING_RATE):
"""
... | python | def mnist_tutorial_jsma(train_start=0, train_end=60000, test_start=0,
test_end=10000, viz_enabled=VIZ_ENABLED,
nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE,
source_samples=SOURCE_SAMPLES,
learning_rate=LEARNING_RATE):
"""
... | [
"def",
"mnist_tutorial_jsma",
"(",
"train_start",
"=",
"0",
",",
"train_end",
"=",
"60000",
",",
"test_start",
"=",
"0",
",",
"test_end",
"=",
"10000",
",",
"viz_enabled",
"=",
"VIZ_ENABLED",
",",
"nb_epochs",
"=",
"NB_EPOCHS",
",",
"batch_size",
"=",
"BATCH... | MNIST tutorial for the Jacobian-based saliency map approach (JSMA)
: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 viz_enabled: (boolean) activ... | [
"MNIST",
"tutorial",
"for",
"the",
"Jacobian",
"-",
"based",
"saliency",
"map",
"approach",
"(",
"JSMA",
")",
":",
"param",
"train_start",
":",
"index",
"of",
"first",
"training",
"set",
"example",
":",
"param",
"train_end",
":",
"index",
"of",
"last",
"tr... | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans_tutorials/mnist_tutorial_jsma.py#L37-L208 | train |
tensorflow/cleverhans | cleverhans/attacks/momentum_iterative_method.py | MomentumIterativeMethod.generate | def generate(self, x, **kwargs):
"""
Generate symbolic graph for adversarial examples and return.
:param x: The model's symbolic inputs.
:param kwargs: Keyword arguments. See `parse_params` for documentation.
"""
# Parse and save attack-specific parameters
assert self.parse_params(**kwargs)... | python | def generate(self, x, **kwargs):
"""
Generate symbolic graph for adversarial examples and return.
:param x: The model's symbolic inputs.
:param kwargs: Keyword arguments. See `parse_params` for documentation.
"""
# Parse and save attack-specific parameters
assert self.parse_params(**kwargs)... | [
"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 ... | Generate symbolic graph for adversarial examples and return.
:param x: The model's symbolic inputs.
:param kwargs: Keyword arguments. See `parse_params` for documentation. | [
"Generate",
"symbolic",
"graph",
"for",
"adversarial",
"examples",
"and",
"return",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/momentum_iterative_method.py#L43-L123 | train |
tensorflow/cleverhans | cleverhans/attacks/momentum_iterative_method.py | MomentumIterativeMethod.parse_params | def parse_params(self,
eps=0.3,
eps_iter=0.06,
nb_iter=10,
y=None,
ord=np.inf,
decay_factor=1.0,
clip_min=None,
clip_max=None,
y_target=None,
... | python | def parse_params(self,
eps=0.3,
eps_iter=0.06,
nb_iter=10,
y=None,
ord=np.inf,
decay_factor=1.0,
clip_min=None,
clip_max=None,
y_target=None,
... | [
"def",
"parse_params",
"(",
"self",
",",
"eps",
"=",
"0.3",
",",
"eps_iter",
"=",
"0.06",
",",
"nb_iter",
"=",
"10",
",",
"y",
"=",
"None",
",",
"ord",
"=",
"np",
".",
"inf",
",",
"decay_factor",
"=",
"1.0",
",",
"clip_min",
"=",
"None",
",",
"cl... | 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... | [
"Take",
"in",
"a",
"dictionary",
"of",
"parameters",
"and",
"applies",
"attack",
"-",
"specific",
"checks",
"before",
"saving",
"them",
"as",
"attributes",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/momentum_iterative_method.py#L125-L180 | train |
tensorflow/cleverhans | cleverhans/train.py | train | def train(sess, loss, x_train, y_train,
init_all=False, evaluate=None, feed=None, args=None,
rng=None, var_list=None, fprop_args=None, optimizer=None,
devices=None, x_batch_preprocessor=None, use_ema=False,
ema_decay=.998, run_canary=None,
loss_threshold=1e5, dataset_tr... | python | def train(sess, loss, x_train, y_train,
init_all=False, evaluate=None, feed=None, args=None,
rng=None, var_list=None, fprop_args=None, optimizer=None,
devices=None, x_batch_preprocessor=None, use_ema=False,
ema_decay=.998, run_canary=None,
loss_threshold=1e5, dataset_tr... | [
"def",
"train",
"(",
"sess",
",",
"loss",
",",
"x_train",
",",
"y_train",
",",
"init_all",
"=",
"False",
",",
"evaluate",
"=",
"None",
",",
"feed",
"=",
"None",
",",
"args",
"=",
"None",
",",
"rng",
"=",
"None",
",",
"var_list",
"=",
"None",
",",
... | Run (optionally multi-replica, synchronous) training to minimize `loss`
:param sess: TF session to use when training the graph
:param loss: tensor, the loss to minimize
:param x_train: numpy array with training inputs or tf Dataset
:param y_train: numpy array with training outputs or tf Dataset
:param init_al... | [
"Run",
"(",
"optionally",
"multi",
"-",
"replica",
"synchronous",
")",
"training",
"to",
"minimize",
"loss",
":",
"param",
"sess",
":",
"TF",
"session",
"to",
"use",
"when",
"training",
"the",
"graph",
":",
"param",
"loss",
":",
"tensor",
"the",
"loss",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/train.py#L38-L274 | train |
tensorflow/cleverhans | cleverhans/train.py | avg_grads | def avg_grads(tower_grads):
"""Calculate the average gradient for each shared variable across all
towers.
Note that this function provides a synchronization point across all towers.
Args:
tower_grads: List of lists of (gradient, variable) tuples. The outer list
is over individual gradients. The inner ... | python | def avg_grads(tower_grads):
"""Calculate the average gradient for each shared variable across all
towers.
Note that this function provides a synchronization point across all towers.
Args:
tower_grads: List of lists of (gradient, variable) tuples. The outer list
is over individual gradients. The inner ... | [
"def",
"avg_grads",
"(",
"tower_grads",
")",
":",
"if",
"len",
"(",
"tower_grads",
")",
"==",
"1",
":",
"return",
"tower_grads",
"[",
"0",
"]",
"average_grads",
"=",
"[",
"]",
"for",
"grad_and_vars",
"in",
"zip",
"(",
"*",
"tower_grads",
")",
":",
"# N... | Calculate the average gradient for each shared variable across all
towers.
Note that this function provides a synchronization point across all towers.
Args:
tower_grads: List of lists of (gradient, variable) tuples. The outer list
is over individual gradients. The inner list is over the gradient
c... | [
"Calculate",
"the",
"average",
"gradient",
"for",
"each",
"shared",
"variable",
"across",
"all",
"towers",
".",
"Note",
"that",
"this",
"function",
"provides",
"a",
"synchronization",
"point",
"across",
"all",
"towers",
".",
"Args",
":",
"tower_grads",
":",
"L... | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/train.py#L277-L309 | train |
tensorflow/cleverhans | examples/multigpu_advtrain/evaluator.py | create_adv_by_name | def create_adv_by_name(model, x, attack_type, sess, dataset, y=None, **kwargs):
"""
Creates the symbolic graph of an adversarial example given the name of
an attack. Simplifies creating the symbolic graph of an attack by defining
dataset-specific parameters.
Dataset-specific default parameters are used unless... | python | def create_adv_by_name(model, x, attack_type, sess, dataset, y=None, **kwargs):
"""
Creates the symbolic graph of an adversarial example given the name of
an attack. Simplifies creating the symbolic graph of an attack by defining
dataset-specific parameters.
Dataset-specific default parameters are used unless... | [
"def",
"create_adv_by_name",
"(",
"model",
",",
"x",
",",
"attack_type",
",",
"sess",
",",
"dataset",
",",
"y",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# TODO: black box attacks",
"attack_names",
"=",
"{",
"'FGSM'",
":",
"FastGradientMethod",
",",
... | Creates the symbolic graph of an adversarial example given the name of
an attack. Simplifies creating the symbolic graph of an attack by defining
dataset-specific parameters.
Dataset-specific default parameters are used unless a different value is
given in kwargs.
:param model: an object of Model class
:pa... | [
"Creates",
"the",
"symbolic",
"graph",
"of",
"an",
"adversarial",
"example",
"given",
"the",
"name",
"of",
"an",
"attack",
".",
"Simplifies",
"creating",
"the",
"symbolic",
"graph",
"of",
"an",
"attack",
"by",
"defining",
"dataset",
"-",
"specific",
"parameter... | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/evaluator.py#L16-L66 | train |
tensorflow/cleverhans | examples/multigpu_advtrain/evaluator.py | Evaluator.log_value | def log_value(self, tag, val, desc=''):
"""
Log values to standard output and Tensorflow summary.
:param tag: summary tag.
:param val: (required float or numpy array) value to be logged.
:param desc: (optional) additional description to be printed.
"""
logging.info('%s (%s): %.4f' % (desc, ... | python | def log_value(self, tag, val, desc=''):
"""
Log values to standard output and Tensorflow summary.
:param tag: summary tag.
:param val: (required float or numpy array) value to be logged.
:param desc: (optional) additional description to be printed.
"""
logging.info('%s (%s): %.4f' % (desc, ... | [
"def",
"log_value",
"(",
"self",
",",
"tag",
",",
"val",
",",
"desc",
"=",
"''",
")",
":",
"logging",
".",
"info",
"(",
"'%s (%s): %.4f'",
"%",
"(",
"desc",
",",
"tag",
",",
"val",
")",
")",
"self",
".",
"summary",
".",
"value",
".",
"add",
"(",
... | Log values to standard output and Tensorflow summary.
:param tag: summary tag.
:param val: (required float or numpy array) value to be logged.
:param desc: (optional) additional description to be printed. | [
"Log",
"values",
"to",
"standard",
"output",
"and",
"Tensorflow",
"summary",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/evaluator.py#L127-L136 | train |
tensorflow/cleverhans | examples/multigpu_advtrain/evaluator.py | Evaluator.eval_advs | def eval_advs(self, x, y, preds_adv, X_test, Y_test, att_type):
"""
Evaluate the accuracy of the model on adversarial examples
:param x: symbolic input to model.
:param y: symbolic variable for the label.
:param preds_adv: symbolic variable for the prediction on an
adversarial... | python | def eval_advs(self, x, y, preds_adv, X_test, Y_test, att_type):
"""
Evaluate the accuracy of the model on adversarial examples
:param x: symbolic input to model.
:param y: symbolic variable for the label.
:param preds_adv: symbolic variable for the prediction on an
adversarial... | [
"def",
"eval_advs",
"(",
"self",
",",
"x",
",",
"y",
",",
"preds_adv",
",",
"X_test",
",",
"Y_test",
",",
"att_type",
")",
":",
"end",
"=",
"(",
"len",
"(",
"X_test",
")",
"//",
"self",
".",
"batch_size",
")",
"*",
"self",
".",
"batch_size",
"if",
... | Evaluate the accuracy of the model on adversarial examples
:param x: symbolic input to model.
:param y: symbolic variable for the label.
:param preds_adv: symbolic variable for the prediction on an
adversarial example.
:param X_test: NumPy array of test set inputs.
:param Y_te... | [
"Evaluate",
"the",
"accuracy",
"of",
"the",
"model",
"on",
"adversarial",
"examples"
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/evaluator.py#L138-L159 | train |
tensorflow/cleverhans | examples/multigpu_advtrain/evaluator.py | Evaluator.eval_multi | def eval_multi(self, inc_epoch=True):
"""
Run the evaluation on multiple attacks.
"""
sess = self.sess
preds = self.preds
x = self.x_pre
y = self.y
X_train = self.X_train
Y_train = self.Y_train
X_test = self.X_test
Y_test = self.Y_test
writer = self.writer
self.summa... | python | def eval_multi(self, inc_epoch=True):
"""
Run the evaluation on multiple attacks.
"""
sess = self.sess
preds = self.preds
x = self.x_pre
y = self.y
X_train = self.X_train
Y_train = self.Y_train
X_test = self.X_test
Y_test = self.Y_test
writer = self.writer
self.summa... | [
"def",
"eval_multi",
"(",
"self",
",",
"inc_epoch",
"=",
"True",
")",
":",
"sess",
"=",
"self",
".",
"sess",
"preds",
"=",
"self",
".",
"preds",
"x",
"=",
"self",
".",
"x_pre",
"y",
"=",
"self",
".",
"y",
"X_train",
"=",
"self",
".",
"X_train",
"... | Run the evaluation on multiple attacks. | [
"Run",
"the",
"evaluation",
"on",
"multiple",
"attacks",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/evaluator.py#L161-L215 | train |
tensorflow/cleverhans | cleverhans/canary.py | run_canary | def run_canary():
"""
Runs some code that will crash if the GPUs / GPU driver are suffering from
a common bug. This helps to prevent contaminating results in the rest of
the library with incorrect calculations.
"""
# Note: please do not edit this function unless you have access to a machine
# with GPUs s... | python | def run_canary():
"""
Runs some code that will crash if the GPUs / GPU driver are suffering from
a common bug. This helps to prevent contaminating results in the rest of
the library with incorrect calculations.
"""
# Note: please do not edit this function unless you have access to a machine
# with GPUs s... | [
"def",
"run_canary",
"(",
")",
":",
"# Note: please do not edit this function unless you have access to a machine",
"# with GPUs suffering from the bug and can verify that the canary still",
"# crashes after your edits. Due to the transient nature of the GPU bug it is",
"# not possible to unit test ... | Runs some code that will crash if the GPUs / GPU driver are suffering from
a common bug. This helps to prevent contaminating results in the rest of
the library with incorrect calculations. | [
"Runs",
"some",
"code",
"that",
"will",
"crash",
"if",
"the",
"GPUs",
"/",
"GPU",
"driver",
"are",
"suffering",
"from",
"a",
"common",
"bug",
".",
"This",
"helps",
"to",
"prevent",
"contaminating",
"results",
"in",
"the",
"rest",
"of",
"the",
"library",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/canary.py#L13-L72 | train |
tensorflow/cleverhans | cleverhans/compat.py | _wrap | def _wrap(f):
"""
Wraps a callable `f` in a function that warns that the function is deprecated.
"""
def wrapper(*args, **kwargs):
"""
Issues a deprecation warning and passes through the arguments.
"""
warnings.warn(str(f) + " is deprecated. Switch to calling the equivalent function in tensorflo... | python | def _wrap(f):
"""
Wraps a callable `f` in a function that warns that the function is deprecated.
"""
def wrapper(*args, **kwargs):
"""
Issues a deprecation warning and passes through the arguments.
"""
warnings.warn(str(f) + " is deprecated. Switch to calling the equivalent function in tensorflo... | [
"def",
"_wrap",
"(",
"f",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"\n Issues a deprecation warning and passes through the arguments.\n \"\"\"",
"warnings",
".",
"warn",
"(",
"str",
"(",
"f",
")",
"+",
"\" is d... | Wraps a callable `f` in a function that warns that the function is deprecated. | [
"Wraps",
"a",
"callable",
"f",
"in",
"a",
"function",
"that",
"warns",
"that",
"the",
"function",
"is",
"deprecated",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/compat.py#L14-L26 | train |
tensorflow/cleverhans | cleverhans/compat.py | reduce_function | def reduce_function(op_func, input_tensor, axis=None, keepdims=None,
name=None, reduction_indices=None):
"""
This function used to be needed to support tf 1.4 and early, but support for tf 1.4 and earlier is now dropped.
:param op_func: expects the function to handle eg: tf.reduce_sum.
:para... | python | def reduce_function(op_func, input_tensor, axis=None, keepdims=None,
name=None, reduction_indices=None):
"""
This function used to be needed to support tf 1.4 and early, but support for tf 1.4 and earlier is now dropped.
:param op_func: expects the function to handle eg: tf.reduce_sum.
:para... | [
"def",
"reduce_function",
"(",
"op_func",
",",
"input_tensor",
",",
"axis",
"=",
"None",
",",
"keepdims",
"=",
"None",
",",
"name",
"=",
"None",
",",
"reduction_indices",
"=",
"None",
")",
":",
"warnings",
".",
"warn",
"(",
"\"`reduce_function` is deprecated a... | This function used to be needed to support tf 1.4 and early, but support for tf 1.4 and earlier is now dropped.
:param op_func: expects the function to handle eg: tf.reduce_sum.
:param input_tensor: The tensor to reduce. Should have numeric type.
:param axis: The dimensions to reduce. If None (the default),
... | [
"This",
"function",
"used",
"to",
"be",
"needed",
"to",
"support",
"tf",
"1",
".",
"4",
"and",
"early",
"but",
"support",
"for",
"tf",
"1",
".",
"4",
"and",
"earlier",
"is",
"now",
"dropped",
".",
":",
"param",
"op_func",
":",
"expects",
"the",
"func... | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/compat.py#L35-L54 | train |
tensorflow/cleverhans | cleverhans/compat.py | softmax_cross_entropy_with_logits | def softmax_cross_entropy_with_logits(sentinel=None,
labels=None,
logits=None,
dim=-1):
"""
Wrapper around tf.nn.softmax_cross_entropy_with_logits_v2 to handle
deprecated warning
"""
# Make sure t... | python | def softmax_cross_entropy_with_logits(sentinel=None,
labels=None,
logits=None,
dim=-1):
"""
Wrapper around tf.nn.softmax_cross_entropy_with_logits_v2 to handle
deprecated warning
"""
# Make sure t... | [
"def",
"softmax_cross_entropy_with_logits",
"(",
"sentinel",
"=",
"None",
",",
"labels",
"=",
"None",
",",
"logits",
"=",
"None",
",",
"dim",
"=",
"-",
"1",
")",
":",
"# Make sure that all arguments were passed as named arguments.",
"if",
"sentinel",
"is",
"not",
... | Wrapper around tf.nn.softmax_cross_entropy_with_logits_v2 to handle
deprecated warning | [
"Wrapper",
"around",
"tf",
".",
"nn",
".",
"softmax_cross_entropy_with_logits_v2",
"to",
"handle",
"deprecated",
"warning"
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/compat.py#L56-L81 | train |
tensorflow/cleverhans | examples/nips17_adversarial_competition/eval_infra/code/eval_lib/dataset_helper.py | enforce_epsilon_and_compute_hash | def enforce_epsilon_and_compute_hash(dataset_batch_dir, adv_dir, output_dir,
epsilon):
"""Enforces size of perturbation on images, and compute hashes for all images.
Args:
dataset_batch_dir: directory with the images of specific dataset batch
adv_dir: directory with gen... | python | def enforce_epsilon_and_compute_hash(dataset_batch_dir, adv_dir, output_dir,
epsilon):
"""Enforces size of perturbation on images, and compute hashes for all images.
Args:
dataset_batch_dir: directory with the images of specific dataset batch
adv_dir: directory with gen... | [
"def",
"enforce_epsilon_and_compute_hash",
"(",
"dataset_batch_dir",
",",
"adv_dir",
",",
"output_dir",
",",
"epsilon",
")",
":",
"dataset_images",
"=",
"[",
"f",
"for",
"f",
"in",
"os",
".",
"listdir",
"(",
"dataset_batch_dir",
")",
"if",
"f",
".",
"endswith"... | Enforces size of perturbation on images, and compute hashes for all images.
Args:
dataset_batch_dir: directory with the images of specific dataset batch
adv_dir: directory with generated adversarial images
output_dir: directory where to copy result
epsilon: size of perturbation
Returns:
dictio... | [
"Enforces",
"size",
"of",
"perturbation",
"on",
"images",
"and",
"compute",
"hashes",
"for",
"all",
"images",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/dataset_helper.py#L81-L124 | train |
tensorflow/cleverhans | examples/nips17_adversarial_competition/eval_infra/code/eval_lib/dataset_helper.py | download_dataset | def download_dataset(storage_client, image_batches, target_dir,
local_dataset_copy=None):
"""Downloads dataset, organize it by batches and rename images.
Args:
storage_client: instance of the CompetitionStorageClient
image_batches: subclass of ImageBatchesBase with data about images
... | python | def download_dataset(storage_client, image_batches, target_dir,
local_dataset_copy=None):
"""Downloads dataset, organize it by batches and rename images.
Args:
storage_client: instance of the CompetitionStorageClient
image_batches: subclass of ImageBatchesBase with data about images
... | [
"def",
"download_dataset",
"(",
"storage_client",
",",
"image_batches",
",",
"target_dir",
",",
"local_dataset_copy",
"=",
"None",
")",
":",
"for",
"batch_id",
",",
"batch_value",
"in",
"iteritems",
"(",
"image_batches",
".",
"data",
")",
":",
"batch_dir",
"=",
... | Downloads dataset, organize it by batches and rename images.
Args:
storage_client: instance of the CompetitionStorageClient
image_batches: subclass of ImageBatchesBase with data about images
target_dir: target directory, should exist and be empty
local_dataset_copy: directory with local dataset copy,... | [
"Downloads",
"dataset",
"organize",
"it",
"by",
"batches",
"and",
"rename",
"images",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/dataset_helper.py#L127-L159 | train |
tensorflow/cleverhans | examples/nips17_adversarial_competition/eval_infra/code/eval_lib/dataset_helper.py | DatasetMetadata.save_target_classes_for_batch | def save_target_classes_for_batch(self,
filename,
image_batches,
batch_id):
"""Saves file with target class for given dataset batch.
Args:
filename: output filename
image_batches: instance of... | python | def save_target_classes_for_batch(self,
filename,
image_batches,
batch_id):
"""Saves file with target class for given dataset batch.
Args:
filename: output filename
image_batches: instance of... | [
"def",
"save_target_classes_for_batch",
"(",
"self",
",",
"filename",
",",
"image_batches",
",",
"batch_id",
")",
":",
"images",
"=",
"image_batches",
".",
"data",
"[",
"batch_id",
"]",
"[",
"'images'",
"]",
"with",
"open",
"(",
"filename",
",",
"'w'",
")",
... | Saves file with target class for given dataset batch.
Args:
filename: output filename
image_batches: instance of ImageBatchesBase with dataset batches
batch_id: dataset batch ID | [
"Saves",
"file",
"with",
"target",
"class",
"for",
"given",
"dataset",
"batch",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/dataset_helper.py#L63-L78 | train |
tensorflow/cleverhans | cleverhans/experimental/certification/optimization.py | Optimization.tf_min_eig_vec | def tf_min_eig_vec(self):
"""Function for min eigen vector using tf's full eigen decomposition."""
# Full eigen decomposition requires the explicit psd matrix M
_, matrix_m = self.dual_object.get_full_psd_matrix()
[eig_vals, eig_vectors] = tf.self_adjoint_eig(matrix_m)
index = tf.argmin(eig_vals)
... | python | def tf_min_eig_vec(self):
"""Function for min eigen vector using tf's full eigen decomposition."""
# Full eigen decomposition requires the explicit psd matrix M
_, matrix_m = self.dual_object.get_full_psd_matrix()
[eig_vals, eig_vectors] = tf.self_adjoint_eig(matrix_m)
index = tf.argmin(eig_vals)
... | [
"def",
"tf_min_eig_vec",
"(",
"self",
")",
":",
"# Full eigen decomposition requires the explicit psd matrix M",
"_",
",",
"matrix_m",
"=",
"self",
".",
"dual_object",
".",
"get_full_psd_matrix",
"(",
")",
"[",
"eig_vals",
",",
"eig_vectors",
"]",
"=",
"tf",
".",
... | Function for min eigen vector using tf's full eigen decomposition. | [
"Function",
"for",
"min",
"eigen",
"vector",
"using",
"tf",
"s",
"full",
"eigen",
"decomposition",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/optimization.py#L56-L63 | train |
tensorflow/cleverhans | cleverhans/experimental/certification/optimization.py | Optimization.tf_smooth_eig_vec | def tf_smooth_eig_vec(self):
"""Function that returns smoothed version of min eigen vector."""
_, matrix_m = self.dual_object.get_full_psd_matrix()
# Easier to think in terms of max so negating the matrix
[eig_vals, eig_vectors] = tf.self_adjoint_eig(-matrix_m)
exp_eig_vals = tf.exp(tf.divide(eig_va... | python | def tf_smooth_eig_vec(self):
"""Function that returns smoothed version of min eigen vector."""
_, matrix_m = self.dual_object.get_full_psd_matrix()
# Easier to think in terms of max so negating the matrix
[eig_vals, eig_vectors] = tf.self_adjoint_eig(-matrix_m)
exp_eig_vals = tf.exp(tf.divide(eig_va... | [
"def",
"tf_smooth_eig_vec",
"(",
"self",
")",
":",
"_",
",",
"matrix_m",
"=",
"self",
".",
"dual_object",
".",
"get_full_psd_matrix",
"(",
")",
"# Easier to think in terms of max so negating the matrix",
"[",
"eig_vals",
",",
"eig_vectors",
"]",
"=",
"tf",
".",
"s... | Function that returns smoothed version of min eigen vector. | [
"Function",
"that",
"returns",
"smoothed",
"version",
"of",
"min",
"eigen",
"vector",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/optimization.py#L65-L79 | train |
tensorflow/cleverhans | cleverhans/experimental/certification/optimization.py | Optimization.get_min_eig_vec_proxy | def get_min_eig_vec_proxy(self, use_tf_eig=False):
"""Computes the min eigen value and corresponding vector of matrix M.
Args:
use_tf_eig: Whether to use tf's default full eigen decomposition
Returns:
eig_vec: Minimum absolute eigen value
eig_val: Corresponding eigen vector
"""
if... | python | def get_min_eig_vec_proxy(self, use_tf_eig=False):
"""Computes the min eigen value and corresponding vector of matrix M.
Args:
use_tf_eig: Whether to use tf's default full eigen decomposition
Returns:
eig_vec: Minimum absolute eigen value
eig_val: Corresponding eigen vector
"""
if... | [
"def",
"get_min_eig_vec_proxy",
"(",
"self",
",",
"use_tf_eig",
"=",
"False",
")",
":",
"if",
"use_tf_eig",
":",
"# If smoothness parameter is too small, essentially no smoothing",
"# Just output the eigen vector corresponding to min",
"return",
"tf",
".",
"cond",
"(",
"self"... | Computes the min eigen value and corresponding vector of matrix M.
Args:
use_tf_eig: Whether to use tf's default full eigen decomposition
Returns:
eig_vec: Minimum absolute eigen value
eig_val: Corresponding eigen vector | [
"Computes",
"the",
"min",
"eigen",
"value",
"and",
"corresponding",
"vector",
"of",
"matrix",
"M",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/optimization.py#L81-L109 | train |
tensorflow/cleverhans | cleverhans/experimental/certification/optimization.py | Optimization.get_scipy_eig_vec | def get_scipy_eig_vec(self):
"""Computes scipy estimate of min eigenvalue for matrix M.
Returns:
eig_vec: Minimum absolute eigen value
eig_val: Corresponding eigen vector
"""
if not self.params['has_conv']:
matrix_m = self.sess.run(self.dual_object.matrix_m)
min_eig_vec_val, est... | python | def get_scipy_eig_vec(self):
"""Computes scipy estimate of min eigenvalue for matrix M.
Returns:
eig_vec: Minimum absolute eigen value
eig_val: Corresponding eigen vector
"""
if not self.params['has_conv']:
matrix_m = self.sess.run(self.dual_object.matrix_m)
min_eig_vec_val, est... | [
"def",
"get_scipy_eig_vec",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"params",
"[",
"'has_conv'",
"]",
":",
"matrix_m",
"=",
"self",
".",
"sess",
".",
"run",
"(",
"self",
".",
"dual_object",
".",
"matrix_m",
")",
"min_eig_vec_val",
",",
"estimate... | Computes scipy estimate of min eigenvalue for matrix M.
Returns:
eig_vec: Minimum absolute eigen value
eig_val: Corresponding eigen vector | [
"Computes",
"scipy",
"estimate",
"of",
"min",
"eigenvalue",
"for",
"matrix",
"M",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/optimization.py#L111-L138 | train |
tensorflow/cleverhans | cleverhans/experimental/certification/optimization.py | Optimization.prepare_for_optimization | def prepare_for_optimization(self):
"""Create tensorflow op for running one step of descent."""
if self.params['eig_type'] == 'TF':
self.eig_vec_estimate = self.get_min_eig_vec_proxy()
elif self.params['eig_type'] == 'LZS':
self.eig_vec_estimate = self.dual_object.m_min_vec
else:
self.... | python | def prepare_for_optimization(self):
"""Create tensorflow op for running one step of descent."""
if self.params['eig_type'] == 'TF':
self.eig_vec_estimate = self.get_min_eig_vec_proxy()
elif self.params['eig_type'] == 'LZS':
self.eig_vec_estimate = self.dual_object.m_min_vec
else:
self.... | [
"def",
"prepare_for_optimization",
"(",
"self",
")",
":",
"if",
"self",
".",
"params",
"[",
"'eig_type'",
"]",
"==",
"'TF'",
":",
"self",
".",
"eig_vec_estimate",
"=",
"self",
".",
"get_min_eig_vec_proxy",
"(",
")",
"elif",
"self",
".",
"params",
"[",
"'ei... | Create tensorflow op for running one step of descent. | [
"Create",
"tensorflow",
"op",
"for",
"running",
"one",
"step",
"of",
"descent",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/optimization.py#L140-L212 | train |
tensorflow/cleverhans | cleverhans/experimental/certification/optimization.py | Optimization.run_one_step | def run_one_step(self, eig_init_vec_val, eig_num_iter_val, smooth_val,
penalty_val, learning_rate_val):
"""Run one step of gradient descent for optimization.
Args:
eig_init_vec_val: Start value for eigen value computations
eig_num_iter_val: Number of iterations to run for eigen c... | python | def run_one_step(self, eig_init_vec_val, eig_num_iter_val, smooth_val,
penalty_val, learning_rate_val):
"""Run one step of gradient descent for optimization.
Args:
eig_init_vec_val: Start value for eigen value computations
eig_num_iter_val: Number of iterations to run for eigen c... | [
"def",
"run_one_step",
"(",
"self",
",",
"eig_init_vec_val",
",",
"eig_num_iter_val",
",",
"smooth_val",
",",
"penalty_val",
",",
"learning_rate_val",
")",
":",
"# Running step",
"step_feed_dict",
"=",
"{",
"self",
".",
"eig_init_vec_placeholder",
":",
"eig_init_vec_v... | Run one step of gradient descent for optimization.
Args:
eig_init_vec_val: Start value for eigen value computations
eig_num_iter_val: Number of iterations to run for eigen computations
smooth_val: Value of smoothness parameter
penalty_val: Value of penalty for the current step
learnin... | [
"Run",
"one",
"step",
"of",
"gradient",
"descent",
"for",
"optimization",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/optimization.py#L214-L296 | train |
tensorflow/cleverhans | cleverhans/experimental/certification/optimization.py | Optimization.run_optimization | def run_optimization(self):
"""Run the optimization, call run_one_step with suitable placeholders.
Returns:
True if certificate is found
False otherwise
"""
penalty_val = self.params['init_penalty']
# Don't use smoothing initially - very inaccurate for large dimension
self.smooth_on... | python | def run_optimization(self):
"""Run the optimization, call run_one_step with suitable placeholders.
Returns:
True if certificate is found
False otherwise
"""
penalty_val = self.params['init_penalty']
# Don't use smoothing initially - very inaccurate for large dimension
self.smooth_on... | [
"def",
"run_optimization",
"(",
"self",
")",
":",
"penalty_val",
"=",
"self",
".",
"params",
"[",
"'init_penalty'",
"]",
"# Don't use smoothing initially - very inaccurate for large dimension",
"self",
".",
"smooth_on",
"=",
"False",
"smooth_val",
"=",
"0",
"learning_ra... | Run the optimization, call run_one_step with suitable placeholders.
Returns:
True if certificate is found
False otherwise | [
"Run",
"the",
"optimization",
"call",
"run_one_step",
"with",
"suitable",
"placeholders",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/optimization.py#L298-L347 | train |
tensorflow/cleverhans | examples/nips17_adversarial_competition/dev_toolkit/sample_targeted_attacks/iter_target_class/attack_iter_target_class.py | load_target_class | def load_target_class(input_dir):
"""Loads target classes."""
with tf.gfile.Open(os.path.join(input_dir, 'target_class.csv')) as f:
return {row[0]: int(row[1]) for row in csv.reader(f) if len(row) >= 2} | python | def load_target_class(input_dir):
"""Loads target classes."""
with tf.gfile.Open(os.path.join(input_dir, 'target_class.csv')) as f:
return {row[0]: int(row[1]) for row in csv.reader(f) if len(row) >= 2} | [
"def",
"load_target_class",
"(",
"input_dir",
")",
":",
"with",
"tf",
".",
"gfile",
".",
"Open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"input_dir",
",",
"'target_class.csv'",
")",
")",
"as",
"f",
":",
"return",
"{",
"row",
"[",
"0",
"]",
":",
"... | Loads target classes. | [
"Loads",
"target",
"classes",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/sample_targeted_attacks/iter_target_class/attack_iter_target_class.py#L53-L56 | train |
tensorflow/cleverhans | examples/nips17_adversarial_competition/dev_toolkit/sample_targeted_attacks/iter_target_class/attack_iter_target_class.py | save_images | def save_images(images, filenames, output_dir):
"""Saves images to the output directory.
Args:
images: array with minibatch of images
filenames: list of filenames without path
If number of file names in this list less than number of images in
the minibatch then only first len(filenames) images ... | python | def save_images(images, filenames, output_dir):
"""Saves images to the output directory.
Args:
images: array with minibatch of images
filenames: list of filenames without path
If number of file names in this list less than number of images in
the minibatch then only first len(filenames) images ... | [
"def",
"save_images",
"(",
"images",
",",
"filenames",
",",
"output_dir",
")",
":",
"for",
"i",
",",
"filename",
"in",
"enumerate",
"(",
"filenames",
")",
":",
"# Images for inception classifier are normalized to be in [-1, 1] interval,",
"# so rescale them back to [0, 1]."... | Saves images to the output directory.
Args:
images: array with minibatch of images
filenames: list of filenames without path
If number of file names in this list less than number of images in
the minibatch then only first len(filenames) images will be saved.
output_dir: directory where to sav... | [
"Saves",
"images",
"to",
"the",
"output",
"directory",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/sample_targeted_attacks/iter_target_class/attack_iter_target_class.py#L92-L106 | train |
tensorflow/cleverhans | examples/nips17_adversarial_competition/dev_toolkit/sample_targeted_attacks/iter_target_class/attack_iter_target_class.py | main | def main(_):
"""Run the sample attack"""
# Images for inception classifier are normalized to be in [-1, 1] interval,
# eps is a difference between pixels so it should be in [0, 2] interval.
# Renormalizing epsilon from [0, 255] to [0, 2].
eps = 2.0 * FLAGS.max_epsilon / 255.0
alpha = 2.0 * FLAGS.iter_alpha ... | python | def main(_):
"""Run the sample attack"""
# Images for inception classifier are normalized to be in [-1, 1] interval,
# eps is a difference between pixels so it should be in [0, 2] interval.
# Renormalizing epsilon from [0, 255] to [0, 2].
eps = 2.0 * FLAGS.max_epsilon / 255.0
alpha = 2.0 * FLAGS.iter_alpha ... | [
"def",
"main",
"(",
"_",
")",
":",
"# Images for inception classifier are normalized to be in [-1, 1] interval,",
"# eps is a difference between pixels so it should be in [0, 2] interval.",
"# Renormalizing epsilon from [0, 255] to [0, 2].",
"eps",
"=",
"2.0",
"*",
"FLAGS",
".",
"max_e... | Run the sample attack | [
"Run",
"the",
"sample",
"attack"
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/sample_targeted_attacks/iter_target_class/attack_iter_target_class.py#L109-L171 | train |
tensorflow/cleverhans | cleverhans/attacks/deep_fool.py | deepfool_batch | def deepfool_batch(sess,
x,
pred,
logits,
grads,
X,
nb_candidate,
overshoot,
max_iter,
clip_min,
clip_max,
nb_c... | python | def deepfool_batch(sess,
x,
pred,
logits,
grads,
X,
nb_candidate,
overshoot,
max_iter,
clip_min,
clip_max,
nb_c... | [
"def",
"deepfool_batch",
"(",
"sess",
",",
"x",
",",
"pred",
",",
"logits",
",",
"grads",
",",
"X",
",",
"nb_candidate",
",",
"overshoot",
",",
"max_iter",
",",
"clip_min",
",",
"clip_max",
",",
"nb_classes",
",",
"feed",
"=",
"None",
")",
":",
"X_adv"... | Applies DeepFool to a batch of inputs
:param sess: TF session
:param x: The input placeholder
:param pred: The model's sorted symbolic output of logits, only the top
nb_candidate classes are contained
:param logits: The model's unnormalized output tensor (the input to
the softmax... | [
"Applies",
"DeepFool",
"to",
"a",
"batch",
"of",
"inputs",
":",
"param",
"sess",
":",
"TF",
"session",
":",
"param",
"x",
":",
"The",
"input",
"placeholder",
":",
"param",
"pred",
":",
"The",
"model",
"s",
"sorted",
"symbolic",
"output",
"of",
"logits",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/deep_fool.py#L115-L165 | train |
tensorflow/cleverhans | cleverhans/attacks/deep_fool.py | deepfool_attack | def deepfool_attack(sess,
x,
predictions,
logits,
grads,
sample,
nb_candidate,
overshoot,
max_iter,
clip_min,
clip_max,
... | python | def deepfool_attack(sess,
x,
predictions,
logits,
grads,
sample,
nb_candidate,
overshoot,
max_iter,
clip_min,
clip_max,
... | [
"def",
"deepfool_attack",
"(",
"sess",
",",
"x",
",",
"predictions",
",",
"logits",
",",
"grads",
",",
"sample",
",",
"nb_candidate",
",",
"overshoot",
",",
"max_iter",
",",
"clip_min",
",",
"clip_max",
",",
"feed",
"=",
"None",
")",
":",
"adv_x",
"=",
... | TensorFlow implementation of DeepFool.
Paper link: see https://arxiv.org/pdf/1511.04599.pdf
:param sess: TF session
:param x: The input placeholder
:param predictions: The model's sorted symbolic output of logits, only the
top nb_candidate classes are contained
:param logits: The model's ... | [
"TensorFlow",
"implementation",
"of",
"DeepFool",
".",
"Paper",
"link",
":",
"see",
"https",
":",
"//",
"arxiv",
".",
"org",
"/",
"pdf",
"/",
"1511",
".",
"04599",
".",
"pdf",
":",
"param",
"sess",
":",
"TF",
"session",
":",
"param",
"x",
":",
"The",... | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/deep_fool.py#L168-L252 | train |
tensorflow/cleverhans | cleverhans/attacks/deep_fool.py | DeepFool.generate | def generate(self, x, **kwargs):
"""
Generate symbolic graph for adversarial examples and return.
:param x: The model's symbolic inputs.
:param kwargs: See `parse_params`
"""
assert self.sess is not None, \
'Cannot use `generate` when no `sess` was provided'
from cleverhans.utils_tf... | python | def generate(self, x, **kwargs):
"""
Generate symbolic graph for adversarial examples and return.
:param x: The model's symbolic inputs.
:param kwargs: See `parse_params`
"""
assert self.sess is not None, \
'Cannot use `generate` when no `sess` was provided'
from cleverhans.utils_tf... | [
"def",
"generate",
"(",
"self",
",",
"x",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"self",
".",
"sess",
"is",
"not",
"None",
",",
"'Cannot use `generate` when no `sess` was provided'",
"from",
"cleverhans",
".",
"utils_tf",
"import",
"jacobian_graph",
"# Par... | Generate symbolic graph for adversarial examples and return.
:param x: The model's symbolic inputs.
:param kwargs: See `parse_params` | [
"Generate",
"symbolic",
"graph",
"for",
"adversarial",
"examples",
"and",
"return",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/deep_fool.py#L48-L83 | train |
tensorflow/cleverhans | cleverhans/attacks/deep_fool.py | DeepFool.parse_params | def parse_params(self,
nb_candidate=10,
overshoot=0.02,
max_iter=50,
clip_min=0.,
clip_max=1.,
**kwargs):
"""
:param nb_candidate: The number of classes to test against, i.e.,
... | python | def parse_params(self,
nb_candidate=10,
overshoot=0.02,
max_iter=50,
clip_min=0.,
clip_max=1.,
**kwargs):
"""
:param nb_candidate: The number of classes to test against, i.e.,
... | [
"def",
"parse_params",
"(",
"self",
",",
"nb_candidate",
"=",
"10",
",",
"overshoot",
"=",
"0.02",
",",
"max_iter",
"=",
"50",
",",
"clip_min",
"=",
"0.",
",",
"clip_max",
"=",
"1.",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"nb_candidate",
"="... | :param nb_candidate: The number of classes to test against, i.e.,
deepfool only consider nb_candidate classes when
attacking(thus accelerate speed). The nb_candidate
classes are chosen according to the prediction
confide... | [
":",
"param",
"nb_candidate",
":",
"The",
"number",
"of",
"classes",
"to",
"test",
"against",
"i",
".",
"e",
".",
"deepfool",
"only",
"consider",
"nb_candidate",
"classes",
"when",
"attacking",
"(",
"thus",
"accelerate",
"speed",
")",
".",
"The",
"nb_candida... | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/deep_fool.py#L85-L112 | train |
tensorflow/cleverhans | cleverhans/utils_pytorch.py | _py_func_with_gradient | def _py_func_with_gradient(func, inp, Tout, stateful=True, name=None,
grad_func=None):
"""
PyFunc defined as given by Tensorflow
:param func: Custom Function
:param inp: Function Inputs
:param Tout: Ouput Type of out Custom Function
:param stateful: Calculate Gradients when statef... | python | def _py_func_with_gradient(func, inp, Tout, stateful=True, name=None,
grad_func=None):
"""
PyFunc defined as given by Tensorflow
:param func: Custom Function
:param inp: Function Inputs
:param Tout: Ouput Type of out Custom Function
:param stateful: Calculate Gradients when statef... | [
"def",
"_py_func_with_gradient",
"(",
"func",
",",
"inp",
",",
"Tout",
",",
"stateful",
"=",
"True",
",",
"name",
"=",
"None",
",",
"grad_func",
"=",
"None",
")",
":",
"# Generate random name in order to avoid conflicts with inbuilt names",
"rnd_name",
"=",
"'PyFunc... | PyFunc defined as given by Tensorflow
:param func: Custom Function
:param inp: Function Inputs
:param Tout: Ouput Type of out Custom Function
:param stateful: Calculate Gradients when stateful is True
:param name: Name of the PyFunction
:param grad: Custom Gradient Function
:return: | [
"PyFunc",
"defined",
"as",
"given",
"by",
"Tensorflow",
":",
"param",
"func",
":",
"Custom",
"Function",
":",
"param",
"inp",
":",
"Function",
"Inputs",
":",
"param",
"Tout",
":",
"Ouput",
"Type",
"of",
"out",
"Custom",
"Function",
":",
"param",
"stateful"... | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_pytorch.py#L14-L38 | train |
tensorflow/cleverhans | cleverhans/utils_pytorch.py | convert_pytorch_model_to_tf | def convert_pytorch_model_to_tf(model, out_dims=None):
"""
Convert a pytorch model into a tensorflow op that allows backprop
:param model: A pytorch nn.Module object
:param out_dims: The number of output dimensions (classes) for the model
:return: A model function that maps an input (tf.Tensor) to the
outpu... | python | def convert_pytorch_model_to_tf(model, out_dims=None):
"""
Convert a pytorch model into a tensorflow op that allows backprop
:param model: A pytorch nn.Module object
:param out_dims: The number of output dimensions (classes) for the model
:return: A model function that maps an input (tf.Tensor) to the
outpu... | [
"def",
"convert_pytorch_model_to_tf",
"(",
"model",
",",
"out_dims",
"=",
"None",
")",
":",
"warnings",
".",
"warn",
"(",
"\"convert_pytorch_model_to_tf is deprecated, switch to\"",
"+",
"\" dedicated PyTorch support provided by CleverHans v4.\"",
")",
"torch_state",
"=",
"{"... | Convert a pytorch model into a tensorflow op that allows backprop
:param model: A pytorch nn.Module object
:param out_dims: The number of output dimensions (classes) for the model
:return: A model function that maps an input (tf.Tensor) to the
output of the model (tf.Tensor) | [
"Convert",
"a",
"pytorch",
"model",
"into",
"a",
"tensorflow",
"op",
"that",
"allows",
"backprop",
":",
"param",
"model",
":",
"A",
"pytorch",
"nn",
".",
"Module",
"object",
":",
"param",
"out_dims",
":",
"The",
"number",
"of",
"output",
"dimensions",
"(",... | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_pytorch.py#L41-L94 | train |
tensorflow/cleverhans | cleverhans/utils_pytorch.py | clip_eta | def clip_eta(eta, ord, eps):
"""
PyTorch implementation of the clip_eta in utils_tf.
:param eta: Tensor
:param ord: np.inf, 1, or 2
:param eps: float
"""
if ord not in [np.inf, 1, 2]:
raise ValueError('ord must be np.inf, 1, or 2.')
avoid_zero_div = torch.tensor(1e-12, dtype=eta.dtype, device=eta.... | python | def clip_eta(eta, ord, eps):
"""
PyTorch implementation of the clip_eta in utils_tf.
:param eta: Tensor
:param ord: np.inf, 1, or 2
:param eps: float
"""
if ord not in [np.inf, 1, 2]:
raise ValueError('ord must be np.inf, 1, or 2.')
avoid_zero_div = torch.tensor(1e-12, dtype=eta.dtype, device=eta.... | [
"def",
"clip_eta",
"(",
"eta",
",",
"ord",
",",
"eps",
")",
":",
"if",
"ord",
"not",
"in",
"[",
"np",
".",
"inf",
",",
"1",
",",
"2",
"]",
":",
"raise",
"ValueError",
"(",
"'ord must be np.inf, 1, or 2.'",
")",
"avoid_zero_div",
"=",
"torch",
".",
"t... | PyTorch implementation of the clip_eta in utils_tf.
:param eta: Tensor
:param ord: np.inf, 1, or 2
:param eps: float | [
"PyTorch",
"implementation",
"of",
"the",
"clip_eta",
"in",
"utils_tf",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_pytorch.py#L97-L130 | train |
tensorflow/cleverhans | cleverhans/utils_pytorch.py | get_or_guess_labels | def get_or_guess_labels(model, x, **kwargs):
"""
Get the label to use in generating an adversarial example for x.
The kwargs are fed directly from the kwargs of the attack.
If 'y' is in kwargs, then assume it's an untargeted attack and
use that as the label.
If 'y_target' is in kwargs and is not none, then ... | python | def get_or_guess_labels(model, x, **kwargs):
"""
Get the label to use in generating an adversarial example for x.
The kwargs are fed directly from the kwargs of the attack.
If 'y' is in kwargs, then assume it's an untargeted attack and
use that as the label.
If 'y_target' is in kwargs and is not none, then ... | [
"def",
"get_or_guess_labels",
"(",
"model",
",",
"x",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'y'",
"in",
"kwargs",
"and",
"'y_target'",
"in",
"kwargs",
":",
"raise",
"ValueError",
"(",
"\"Can not set both 'y' and 'y_target'.\"",
")",
"if",
"'y'",
"in",
"k... | Get the label to use in generating an adversarial example for x.
The kwargs are fed directly from the kwargs of the attack.
If 'y' is in kwargs, then assume it's an untargeted attack and
use that as the label.
If 'y_target' is in kwargs and is not none, then assume it's a
targeted attack and use that as the l... | [
"Get",
"the",
"label",
"to",
"use",
"in",
"generating",
"an",
"adversarial",
"example",
"for",
"x",
".",
"The",
"kwargs",
"are",
"fed",
"directly",
"from",
"the",
"kwargs",
"of",
"the",
"attack",
".",
"If",
"y",
"is",
"in",
"kwargs",
"then",
"assume",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_pytorch.py#L132-L156 | train |
tensorflow/cleverhans | cleverhans/utils_pytorch.py | optimize_linear | def optimize_linear(grad, eps, ord=np.inf):
"""
Solves for the optimal input to a linear function under a norm constraint.
Optimal_perturbation = argmax_{eta, ||eta||_{ord} < eps} dot(eta, grad)
:param grad: Tensor, shape (N, d_1, ...). Batch of gradients
:param eps: float. Scalar specifying size of constra... | python | def optimize_linear(grad, eps, ord=np.inf):
"""
Solves for the optimal input to a linear function under a norm constraint.
Optimal_perturbation = argmax_{eta, ||eta||_{ord} < eps} dot(eta, grad)
:param grad: Tensor, shape (N, d_1, ...). Batch of gradients
:param eps: float. Scalar specifying size of constra... | [
"def",
"optimize_linear",
"(",
"grad",
",",
"eps",
",",
"ord",
"=",
"np",
".",
"inf",
")",
":",
"red_ind",
"=",
"list",
"(",
"range",
"(",
"1",
",",
"len",
"(",
"grad",
".",
"size",
"(",
")",
")",
")",
")",
"avoid_zero_div",
"=",
"torch",
".",
... | Solves for the optimal input to a linear function under a norm constraint.
Optimal_perturbation = argmax_{eta, ||eta||_{ord} < eps} dot(eta, grad)
:param grad: Tensor, shape (N, d_1, ...). Batch of gradients
:param eps: float. Scalar specifying size of constraint region
:param ord: np.inf, 1, or 2. Order of n... | [
"Solves",
"for",
"the",
"optimal",
"input",
"to",
"a",
"linear",
"function",
"under",
"a",
"norm",
"constraint",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_pytorch.py#L159-L213 | train |
tensorflow/cleverhans | cleverhans/attacks/elastic_net_method.py | ElasticNetMethod.parse_params | def parse_params(self,
y=None,
y_target=None,
beta=1e-2,
decision_rule='EN',
batch_size=1,
confidence=0,
learning_rate=1e-2,
binary_search_steps=9,
m... | python | def parse_params(self,
y=None,
y_target=None,
beta=1e-2,
decision_rule='EN',
batch_size=1,
confidence=0,
learning_rate=1e-2,
binary_search_steps=9,
m... | [
"def",
"parse_params",
"(",
"self",
",",
"y",
"=",
"None",
",",
"y_target",
"=",
"None",
",",
"beta",
"=",
"1e-2",
",",
"decision_rule",
"=",
"'EN'",
",",
"batch_size",
"=",
"1",
",",
"confidence",
"=",
"0",
",",
"learning_rate",
"=",
"1e-2",
",",
"b... | :param y: (optional) A tensor with the true labels for an untargeted
attack. If None (and y_target is None) then use the
original labels the classifier assigns.
:param y_target: (optional) A tensor with the target labels for a
targeted attack.
:param beta: Trades off L2... | [
":",
"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... | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/elastic_net_method.py#L91-L162 | train |
tensorflow/cleverhans | cleverhans/attacks/elastic_net_method.py | EAD.attack | def attack(self, imgs, targets):
"""
Perform the EAD attack on the given instance for the given targets.
If self.targeted is true, then the targets represents the target labels
If self.targeted is false, then targets are the original class labels
"""
batch_size = self.batch_size
r = []
... | python | def attack(self, imgs, targets):
"""
Perform the EAD attack on the given instance for the given targets.
If self.targeted is true, then the targets represents the target labels
If self.targeted is false, then targets are the original class labels
"""
batch_size = self.batch_size
r = []
... | [
"def",
"attack",
"(",
"self",
",",
"imgs",
",",
"targets",
")",
":",
"batch_size",
"=",
"self",
".",
"batch_size",
"r",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"imgs",
")",
"//",
"batch_size",
")",
":",
"_logger",
"."... | Perform the EAD attack on the given instance for the given targets.
If self.targeted is true, then the targets represents the target labels
If self.targeted is false, then targets are the original class labels | [
"Perform",
"the",
"EAD",
"attack",
"on",
"the",
"given",
"instance",
"for",
"the",
"given",
"targets",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/elastic_net_method.py#L374-L404 | train |
tensorflow/cleverhans | examples/nips17_adversarial_competition/dev_toolkit/validation_tool/validate_submission.py | print_in_box | def print_in_box(text):
"""
Prints `text` surrounded by a box made of *s
"""
print('')
print('*' * (len(text) + 6))
print('** ' + text + ' **')
print('*' * (len(text) + 6))
print('') | python | def print_in_box(text):
"""
Prints `text` surrounded by a box made of *s
"""
print('')
print('*' * (len(text) + 6))
print('** ' + text + ' **')
print('*' * (len(text) + 6))
print('') | [
"def",
"print_in_box",
"(",
"text",
")",
":",
"print",
"(",
"''",
")",
"print",
"(",
"'*'",
"*",
"(",
"len",
"(",
"text",
")",
"+",
"6",
")",
")",
"print",
"(",
"'** '",
"+",
"text",
"+",
"' **'",
")",
"print",
"(",
"'*'",
"*",
"(",
"len",
"(... | Prints `text` surrounded by a box made of *s | [
"Prints",
"text",
"surrounded",
"by",
"a",
"box",
"made",
"of",
"*",
"s"
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/validation_tool/validate_submission.py#L30-L38 | train |
tensorflow/cleverhans | examples/nips17_adversarial_competition/dev_toolkit/validation_tool/validate_submission.py | main | def main(args):
"""
Validates the submission.
"""
print_in_box('Validating submission ' + args.submission_filename)
random.seed()
temp_dir = args.temp_dir
delete_temp_dir = False
if not temp_dir:
temp_dir = tempfile.mkdtemp()
logging.info('Created temporary directory: %s', temp_dir)
delete_t... | python | def main(args):
"""
Validates the submission.
"""
print_in_box('Validating submission ' + args.submission_filename)
random.seed()
temp_dir = args.temp_dir
delete_temp_dir = False
if not temp_dir:
temp_dir = tempfile.mkdtemp()
logging.info('Created temporary directory: %s', temp_dir)
delete_t... | [
"def",
"main",
"(",
"args",
")",
":",
"print_in_box",
"(",
"'Validating submission '",
"+",
"args",
".",
"submission_filename",
")",
"random",
".",
"seed",
"(",
")",
"temp_dir",
"=",
"args",
".",
"temp_dir",
"delete_temp_dir",
"=",
"False",
"if",
"not",
"tem... | Validates the submission. | [
"Validates",
"the",
"submission",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/validation_tool/validate_submission.py#L41-L62 | train |
tensorflow/cleverhans | scripts/make_confidence_report.py | main | def main(argv=None):
"""
Make a confidence report and save it to disk.
"""
try:
_name_of_script, filepath = argv
except ValueError:
raise ValueError(argv)
make_confidence_report(filepath=filepath, test_start=FLAGS.test_start,
test_end=FLAGS.test_end, which_set=FLAGS.which_se... | python | def main(argv=None):
"""
Make a confidence report and save it to disk.
"""
try:
_name_of_script, filepath = argv
except ValueError:
raise ValueError(argv)
make_confidence_report(filepath=filepath, test_start=FLAGS.test_start,
test_end=FLAGS.test_end, which_set=FLAGS.which_se... | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"try",
":",
"_name_of_script",
",",
"filepath",
"=",
"argv",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"argv",
")",
"make_confidence_report",
"(",
"filepath",
"=",
"filepath",
",",
"test_start... | Make a confidence report and save it to disk. | [
"Make",
"a",
"confidence",
"report",
"and",
"save",
"it",
"to",
"disk",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/scripts/make_confidence_report.py#L56-L71 | train |
tensorflow/cleverhans | scripts/make_confidence_report_spsa.py | make_confidence_report_spsa | def make_confidence_report_spsa(filepath, train_start=TRAIN_START,
train_end=TRAIN_END,
test_start=TEST_START, test_end=TEST_END,
batch_size=BATCH_SIZE, which_set=WHICH_SET,
report_path=REPORT... | python | def make_confidence_report_spsa(filepath, train_start=TRAIN_START,
train_end=TRAIN_END,
test_start=TEST_START, test_end=TEST_END,
batch_size=BATCH_SIZE, which_set=WHICH_SET,
report_path=REPORT... | [
"def",
"make_confidence_report_spsa",
"(",
"filepath",
",",
"train_start",
"=",
"TRAIN_START",
",",
"train_end",
"=",
"TRAIN_END",
",",
"test_start",
"=",
"TEST_START",
",",
"test_end",
"=",
"TEST_END",
",",
"batch_size",
"=",
"BATCH_SIZE",
",",
"which_set",
"=",
... | Load a saved model, gather its predictions, and save a confidence report.
This function works by running a single MaxConfidence attack on each example,
using SPSA as the underyling optimizer.
This is not intended to be a strong generic attack.
It is intended to be a test to uncover gradient masking.
:param... | [
"Load",
"a",
"saved",
"model",
"gather",
"its",
"predictions",
"and",
"save",
"a",
"confidence",
"report",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/scripts/make_confidence_report_spsa.py#L56-L133 | train |
tensorflow/cleverhans | scripts/make_confidence_report_spsa.py | main | def main(argv=None):
"""
Make a confidence report and save it to disk.
"""
try:
_name_of_script, filepath = argv
except ValueError:
raise ValueError(argv)
make_confidence_report_spsa(filepath=filepath, test_start=FLAGS.test_start,
test_end=FLAGS.test_end,
... | python | def main(argv=None):
"""
Make a confidence report and save it to disk.
"""
try:
_name_of_script, filepath = argv
except ValueError:
raise ValueError(argv)
make_confidence_report_spsa(filepath=filepath, test_start=FLAGS.test_start,
test_end=FLAGS.test_end,
... | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"try",
":",
"_name_of_script",
",",
"filepath",
"=",
"argv",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"argv",
")",
"make_confidence_report_spsa",
"(",
"filepath",
"=",
"filepath",
",",
"test_... | Make a confidence report and save it to disk. | [
"Make",
"a",
"confidence",
"report",
"and",
"save",
"it",
"to",
"disk",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/scripts/make_confidence_report_spsa.py#L135-L150 | train |
tensorflow/cleverhans | examples/multigpu_advtrain/attacks_multigpu.py | MadryEtAlMultiGPU.attack | def attack(self, x, y_p, **kwargs):
"""
This method creates a symoblic graph of the MadryEtAl attack on
multiple GPUs. The graph is created on the first n GPUs.
Stop gradient is needed to get the speed-up. This prevents us from
being able to back-prop through the attack.
:param x: A tensor wit... | python | def attack(self, x, y_p, **kwargs):
"""
This method creates a symoblic graph of the MadryEtAl attack on
multiple GPUs. The graph is created on the first n GPUs.
Stop gradient is needed to get the speed-up. This prevents us from
being able to back-prop through the attack.
:param x: A tensor wit... | [
"def",
"attack",
"(",
"self",
",",
"x",
",",
"y_p",
",",
"*",
"*",
"kwargs",
")",
":",
"inputs",
"=",
"[",
"]",
"outputs",
"=",
"[",
"]",
"# Create the initial random perturbation",
"device_name",
"=",
"'/gpu:0'",
"self",
".",
"model",
".",
"set_device",
... | This method creates a symoblic graph of the MadryEtAl attack on
multiple GPUs. The graph is created on the first n GPUs.
Stop gradient is needed to get the speed-up. This prevents us from
being able to back-prop through the attack.
:param x: A tensor with the input image.
:param y_p: Ground truth ... | [
"This",
"method",
"creates",
"a",
"symoblic",
"graph",
"of",
"the",
"MadryEtAl",
"attack",
"on",
"multiple",
"GPUs",
".",
"The",
"graph",
"is",
"created",
"on",
"the",
"first",
"n",
"GPUs",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/attacks_multigpu.py#L42-L106 | train |
tensorflow/cleverhans | examples/multigpu_advtrain/attacks_multigpu.py | MadryEtAlMultiGPU.generate_np | def generate_np(self, x_val, **kwargs):
"""
Facilitates testing this attack.
"""
_, feedable, _feedable_types, hash_key = self.construct_variables(kwargs)
if hash_key not in self.graphs:
with tf.variable_scope(None, 'attack_%d' % len(self.graphs)):
# x is a special placeholder we alwa... | python | def generate_np(self, x_val, **kwargs):
"""
Facilitates testing this attack.
"""
_, feedable, _feedable_types, hash_key = self.construct_variables(kwargs)
if hash_key not in self.graphs:
with tf.variable_scope(None, 'attack_%d' % len(self.graphs)):
# x is a special placeholder we alwa... | [
"def",
"generate_np",
"(",
"self",
",",
"x_val",
",",
"*",
"*",
"kwargs",
")",
":",
"_",
",",
"feedable",
",",
"_feedable_types",
",",
"hash_key",
"=",
"self",
".",
"construct_variables",
"(",
"kwargs",
")",
"if",
"hash_key",
"not",
"in",
"self",
".",
... | Facilitates testing this attack. | [
"Facilitates",
"testing",
"this",
"attack",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/attacks_multigpu.py#L108-L134 | train |
tensorflow/cleverhans | examples/multigpu_advtrain/attacks_multigpu.py | MadryEtAlMultiGPU.parse_params | def parse_params(self, ngpu=1, **kwargs):
"""
Take in a dictionary of parameters and applies attack-specific checks
before saving them as attributes.
Attack-specific parameters:
:param ngpu: (required int) the number of GPUs available.
:param kwargs: A dictionary of parameters for MadryEtAl att... | python | def parse_params(self, ngpu=1, **kwargs):
"""
Take in a dictionary of parameters and applies attack-specific checks
before saving them as attributes.
Attack-specific parameters:
:param ngpu: (required int) the number of GPUs available.
:param kwargs: A dictionary of parameters for MadryEtAl att... | [
"def",
"parse_params",
"(",
"self",
",",
"ngpu",
"=",
"1",
",",
"*",
"*",
"kwargs",
")",
":",
"return_status",
"=",
"super",
"(",
"MadryEtAlMultiGPU",
",",
"self",
")",
".",
"parse_params",
"(",
"*",
"*",
"kwargs",
")",
"self",
".",
"ngpu",
"=",
"ngp... | Take in a dictionary of parameters and applies attack-specific checks
before saving them as attributes.
Attack-specific parameters:
:param ngpu: (required int) the number of GPUs available.
:param kwargs: A dictionary of parameters for MadryEtAl attack. | [
"Take",
"in",
"a",
"dictionary",
"of",
"parameters",
"and",
"applies",
"attack",
"-",
"specific",
"checks",
"before",
"saving",
"them",
"as",
"attributes",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/attacks_multigpu.py#L136-L149 | train |
tensorflow/cleverhans | cleverhans/evaluation.py | accuracy | def accuracy(sess, model, x, y, batch_size=None, devices=None, feed=None,
attack=None, attack_params=None):
"""
Compute the accuracy of a TF model on some data
:param sess: TF session to use when training the graph
:param model: cleverhans.model.Model instance
:param x: numpy array containing inp... | python | def accuracy(sess, model, x, y, batch_size=None, devices=None, feed=None,
attack=None, attack_params=None):
"""
Compute the accuracy of a TF model on some data
:param sess: TF session to use when training the graph
:param model: cleverhans.model.Model instance
:param x: numpy array containing inp... | [
"def",
"accuracy",
"(",
"sess",
",",
"model",
",",
"x",
",",
"y",
",",
"batch_size",
"=",
"None",
",",
"devices",
"=",
"None",
",",
"feed",
"=",
"None",
",",
"attack",
"=",
"None",
",",
"attack_params",
"=",
"None",
")",
":",
"_check_x",
"(",
"x",
... | Compute the accuracy of a TF model on some data
:param sess: TF session to use when training the graph
:param model: cleverhans.model.Model instance
:param x: numpy array containing input examples (e.g. MNIST().x_test )
:param y: numpy array containing example labels (e.g. MNIST().y_test )
:param batch_size: ... | [
"Compute",
"the",
"accuracy",
"of",
"a",
"TF",
"model",
"on",
"some",
"data",
":",
"param",
"sess",
":",
"TF",
"session",
"to",
"use",
"when",
"training",
"the",
"graph",
":",
"param",
"model",
":",
"cleverhans",
".",
"model",
".",
"Model",
"instance",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/evaluation.py#L18-L60 | train |
tensorflow/cleverhans | cleverhans/evaluation.py | class_and_confidence | def class_and_confidence(sess, model, x, y=None, batch_size=None,
devices=None, feed=None, attack=None,
attack_params=None):
"""
Return the model's classification of the input data, and the confidence
(probability) assigned to each example.
:param sess: tf.Sessi... | python | def class_and_confidence(sess, model, x, y=None, batch_size=None,
devices=None, feed=None, attack=None,
attack_params=None):
"""
Return the model's classification of the input data, and the confidence
(probability) assigned to each example.
:param sess: tf.Sessi... | [
"def",
"class_and_confidence",
"(",
"sess",
",",
"model",
",",
"x",
",",
"y",
"=",
"None",
",",
"batch_size",
"=",
"None",
",",
"devices",
"=",
"None",
",",
"feed",
"=",
"None",
",",
"attack",
"=",
"None",
",",
"attack_params",
"=",
"None",
")",
":",... | Return the model's classification of the input data, and the confidence
(probability) assigned to each example.
:param sess: tf.Session
:param model: cleverhans.model.Model
:param x: numpy array containing input examples (e.g. MNIST().x_test )
:param y: numpy array containing true labels
(Needed only if u... | [
"Return",
"the",
"model",
"s",
"classification",
"of",
"the",
"input",
"data",
"and",
"the",
"confidence",
"(",
"probability",
")",
"assigned",
"to",
"each",
"example",
".",
":",
"param",
"sess",
":",
"tf",
".",
"Session",
":",
"param",
"model",
":",
"cl... | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/evaluation.py#L63-L126 | train |
tensorflow/cleverhans | cleverhans/evaluation.py | correctness_and_confidence | def correctness_and_confidence(sess, model, x, y, batch_size=None,
devices=None, feed=None, attack=None,
attack_params=None):
"""
Report whether the model is correct and its confidence on each example in
a dataset.
:param sess: tf.Session
:param mo... | python | def correctness_and_confidence(sess, model, x, y, batch_size=None,
devices=None, feed=None, attack=None,
attack_params=None):
"""
Report whether the model is correct and its confidence on each example in
a dataset.
:param sess: tf.Session
:param mo... | [
"def",
"correctness_and_confidence",
"(",
"sess",
",",
"model",
",",
"x",
",",
"y",
",",
"batch_size",
"=",
"None",
",",
"devices",
"=",
"None",
",",
"feed",
"=",
"None",
",",
"attack",
"=",
"None",
",",
"attack_params",
"=",
"None",
")",
":",
"_check_... | Report whether the model is correct and its confidence on each example in
a dataset.
:param sess: tf.Session
:param model: cleverhans.model.Model
:param x: numpy array containing input examples (e.g. MNIST().x_test )
:param y: numpy array containing example labels (e.g. MNIST().y_test )
:param batch_size: N... | [
"Report",
"whether",
"the",
"model",
"is",
"correct",
"and",
"its",
"confidence",
"on",
"each",
"example",
"in",
"a",
"dataset",
".",
":",
"param",
"sess",
":",
"tf",
".",
"Session",
":",
"param",
"model",
":",
"cleverhans",
".",
"model",
".",
"Model",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/evaluation.py#L129-L188 | train |
tensorflow/cleverhans | cleverhans/evaluation.py | run_attack | def run_attack(sess, model, x, y, attack, attack_params, batch_size=None,
devices=None, feed=None, pass_y=False):
"""
Run attack on every example in a dataset.
:param sess: tf.Session
:param model: cleverhans.model.Model
:param x: numpy array containing input examples (e.g. MNIST().x_test )
:... | python | def run_attack(sess, model, x, y, attack, attack_params, batch_size=None,
devices=None, feed=None, pass_y=False):
"""
Run attack on every example in a dataset.
:param sess: tf.Session
:param model: cleverhans.model.Model
:param x: numpy array containing input examples (e.g. MNIST().x_test )
:... | [
"def",
"run_attack",
"(",
"sess",
",",
"model",
",",
"x",
",",
"y",
",",
"attack",
",",
"attack_params",
",",
"batch_size",
"=",
"None",
",",
"devices",
"=",
"None",
",",
"feed",
"=",
"None",
",",
"pass_y",
"=",
"False",
")",
":",
"_check_x",
"(",
... | Run attack on every example in a dataset.
:param sess: tf.Session
:param model: cleverhans.model.Model
:param x: numpy array containing input examples (e.g. MNIST().x_test )
:param y: numpy array containing example labels (e.g. MNIST().y_test )
:param attack: cleverhans.attack.Attack
:param attack_params: d... | [
"Run",
"attack",
"on",
"every",
"example",
"in",
"a",
"dataset",
".",
":",
"param",
"sess",
":",
"tf",
".",
"Session",
":",
"param",
"model",
":",
"cleverhans",
".",
"model",
".",
"Model",
":",
"param",
"x",
":",
"numpy",
"array",
"containing",
"input"... | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/evaluation.py#L191-L228 | train |
tensorflow/cleverhans | cleverhans/evaluation.py | batch_eval_multi_worker | def batch_eval_multi_worker(sess, graph_factory, numpy_inputs, batch_size=None,
devices=None, feed=None):
"""
Generic computation engine for evaluating an expression across a whole
dataset, divided into batches.
This function assumes that the work can be parallelized with one worker... | python | def batch_eval_multi_worker(sess, graph_factory, numpy_inputs, batch_size=None,
devices=None, feed=None):
"""
Generic computation engine for evaluating an expression across a whole
dataset, divided into batches.
This function assumes that the work can be parallelized with one worker... | [
"def",
"batch_eval_multi_worker",
"(",
"sess",
",",
"graph_factory",
",",
"numpy_inputs",
",",
"batch_size",
"=",
"None",
",",
"devices",
"=",
"None",
",",
"feed",
"=",
"None",
")",
":",
"canary",
".",
"run_canary",
"(",
")",
"global",
"_batch_eval_multi_worke... | Generic computation engine for evaluating an expression across a whole
dataset, divided into batches.
This function assumes that the work can be parallelized with one worker
device handling one batch of data. If you need multiple devices per
batch, use `batch_eval`.
The tensorflow graph for multiple workers... | [
"Generic",
"computation",
"engine",
"for",
"evaluating",
"an",
"expression",
"across",
"a",
"whole",
"dataset",
"divided",
"into",
"batches",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/evaluation.py#L231-L411 | train |
tensorflow/cleverhans | cleverhans/evaluation.py | batch_eval | def batch_eval(sess, tf_inputs, tf_outputs, numpy_inputs, batch_size=None,
feed=None,
args=None):
"""
A helper function that computes a tensor on numpy inputs by batches.
This version uses exactly the tensorflow graph constructed by the
caller, so the caller can place specific ops ... | python | def batch_eval(sess, tf_inputs, tf_outputs, numpy_inputs, batch_size=None,
feed=None,
args=None):
"""
A helper function that computes a tensor on numpy inputs by batches.
This version uses exactly the tensorflow graph constructed by the
caller, so the caller can place specific ops ... | [
"def",
"batch_eval",
"(",
"sess",
",",
"tf_inputs",
",",
"tf_outputs",
",",
"numpy_inputs",
",",
"batch_size",
"=",
"None",
",",
"feed",
"=",
"None",
",",
"args",
"=",
"None",
")",
":",
"if",
"args",
"is",
"not",
"None",
":",
"warnings",
".",
"warn",
... | A helper function that computes a tensor on numpy inputs by batches.
This version uses exactly the tensorflow graph constructed by the
caller, so the caller can place specific ops on specific devices
to implement model parallelism.
Most users probably prefer `batch_eval_multi_worker` which maps
a single-devic... | [
"A",
"helper",
"function",
"that",
"computes",
"a",
"tensor",
"on",
"numpy",
"inputs",
"by",
"batches",
".",
"This",
"version",
"uses",
"exactly",
"the",
"tensorflow",
"graph",
"constructed",
"by",
"the",
"caller",
"so",
"the",
"caller",
"can",
"place",
"spe... | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/evaluation.py#L414-L488 | train |
tensorflow/cleverhans | cleverhans/evaluation.py | _check_y | def _check_y(y):
"""
Makes sure a `y` argument is a vliad numpy dataset.
"""
if not isinstance(y, np.ndarray):
raise TypeError("y must be numpy array. Typically y contains "
"the entire test set labels. Got " + str(y) + " of type " + str(type(y))) | python | def _check_y(y):
"""
Makes sure a `y` argument is a vliad numpy dataset.
"""
if not isinstance(y, np.ndarray):
raise TypeError("y must be numpy array. Typically y contains "
"the entire test set labels. Got " + str(y) + " of type " + str(type(y))) | [
"def",
"_check_y",
"(",
"y",
")",
":",
"if",
"not",
"isinstance",
"(",
"y",
",",
"np",
".",
"ndarray",
")",
":",
"raise",
"TypeError",
"(",
"\"y must be numpy array. Typically y contains \"",
"\"the entire test set labels. Got \"",
"+",
"str",
"(",
"y",
")",
"+"... | Makes sure a `y` argument is a vliad numpy dataset. | [
"Makes",
"sure",
"a",
"y",
"argument",
"is",
"a",
"vliad",
"numpy",
"dataset",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/evaluation.py#L726-L732 | train |
tensorflow/cleverhans | examples/nips17_adversarial_competition/dev_toolkit/sample_attacks/noop/attack_noop.py | load_images | def load_images(input_dir, batch_shape):
"""Read png images from input directory in batches.
Args:
input_dir: input directory
batch_shape: shape of minibatch array, i.e. [batch_size, height, width, 3]
Yields:
filenames: list file names without path of each image
Length of this list could be le... | python | def load_images(input_dir, batch_shape):
"""Read png images from input directory in batches.
Args:
input_dir: input directory
batch_shape: shape of minibatch array, i.e. [batch_size, height, width, 3]
Yields:
filenames: list file names without path of each image
Length of this list could be le... | [
"def",
"load_images",
"(",
"input_dir",
",",
"batch_shape",
")",
":",
"images",
"=",
"np",
".",
"zeros",
"(",
"batch_shape",
")",
"filenames",
"=",
"[",
"]",
"idx",
"=",
"0",
"batch_size",
"=",
"batch_shape",
"[",
"0",
"]",
"for",
"filepath",
"in",
"tf... | Read png images from input directory in batches.
Args:
input_dir: input directory
batch_shape: shape of minibatch array, i.e. [batch_size, height, width, 3]
Yields:
filenames: list file names without path of each image
Length of this list could be less than batch_size, in this case only
fi... | [
"Read",
"png",
"images",
"from",
"input",
"directory",
"in",
"batches",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/sample_attacks/noop/attack_noop.py#L40-L68 | train |
tensorflow/cleverhans | examples/nips17_adversarial_competition/dev_toolkit/sample_attacks/noop/attack_noop.py | main | def main(_):
"""Run the sample attack"""
batch_shape = [FLAGS.batch_size, FLAGS.image_height, FLAGS.image_width, 3]
for filenames, images in load_images(FLAGS.input_dir, batch_shape):
save_images(images, filenames, FLAGS.output_dir) | python | def main(_):
"""Run the sample attack"""
batch_shape = [FLAGS.batch_size, FLAGS.image_height, FLAGS.image_width, 3]
for filenames, images in load_images(FLAGS.input_dir, batch_shape):
save_images(images, filenames, FLAGS.output_dir) | [
"def",
"main",
"(",
"_",
")",
":",
"batch_shape",
"=",
"[",
"FLAGS",
".",
"batch_size",
",",
"FLAGS",
".",
"image_height",
",",
"FLAGS",
".",
"image_width",
",",
"3",
"]",
"for",
"filenames",
",",
"images",
"in",
"load_images",
"(",
"FLAGS",
".",
"inpu... | Run the sample attack | [
"Run",
"the",
"sample",
"attack"
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/sample_attacks/noop/attack_noop.py#L86-L90 | train |
tensorflow/cleverhans | examples/multigpu_advtrain/utils.py | preprocess_batch | def preprocess_batch(images_batch, preproc_func=None):
"""
Creates a preprocessing graph for a batch given a function that processes
a single image.
:param images_batch: A tensor for an image batch.
:param preproc_func: (optional function) A function that takes in a
tensor and returns a preprocessed in... | python | def preprocess_batch(images_batch, preproc_func=None):
"""
Creates a preprocessing graph for a batch given a function that processes
a single image.
:param images_batch: A tensor for an image batch.
:param preproc_func: (optional function) A function that takes in a
tensor and returns a preprocessed in... | [
"def",
"preprocess_batch",
"(",
"images_batch",
",",
"preproc_func",
"=",
"None",
")",
":",
"if",
"preproc_func",
"is",
"None",
":",
"return",
"images_batch",
"with",
"tf",
".",
"variable_scope",
"(",
"'preprocess'",
")",
":",
"images_list",
"=",
"tf",
".",
... | Creates a preprocessing graph for a batch given a function that processes
a single image.
:param images_batch: A tensor for an image batch.
:param preproc_func: (optional function) A function that takes in a
tensor and returns a preprocessed input. | [
"Creates",
"a",
"preprocessing",
"graph",
"for",
"a",
"batch",
"given",
"a",
"function",
"that",
"processes",
"a",
"single",
"image",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/utils.py#L5-L25 | train |
tensorflow/cleverhans | cleverhans/model.py | Model.get_logits | def get_logits(self, x, **kwargs):
"""
:param x: A symbolic representation (Tensor) of the network input
:return: A symbolic representation (Tensor) of the output logits
(i.e., the values fed as inputs to the softmax layer).
"""
outputs = self.fprop(x, **kwargs)
if self.O_LOGITS in outputs:
... | python | def get_logits(self, x, **kwargs):
"""
:param x: A symbolic representation (Tensor) of the network input
:return: A symbolic representation (Tensor) of the output logits
(i.e., the values fed as inputs to the softmax layer).
"""
outputs = self.fprop(x, **kwargs)
if self.O_LOGITS in outputs:
... | [
"def",
"get_logits",
"(",
"self",
",",
"x",
",",
"*",
"*",
"kwargs",
")",
":",
"outputs",
"=",
"self",
".",
"fprop",
"(",
"x",
",",
"*",
"*",
"kwargs",
")",
"if",
"self",
".",
"O_LOGITS",
"in",
"outputs",
":",
"return",
"outputs",
"[",
"self",
".... | :param x: A symbolic representation (Tensor) of the network input
:return: A symbolic representation (Tensor) of the output logits
(i.e., the values fed as inputs to the softmax layer). | [
":",
"param",
"x",
":",
"A",
"symbolic",
"representation",
"(",
"Tensor",
")",
"of",
"the",
"network",
"input",
":",
"return",
":",
"A",
"symbolic",
"representation",
"(",
"Tensor",
")",
"of",
"the",
"output",
"logits",
"(",
"i",
".",
"e",
".",
"the",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model.py#L59-L70 | train |
tensorflow/cleverhans | cleverhans/model.py | Model.get_predicted_class | def get_predicted_class(self, x, **kwargs):
"""
:param x: A symbolic representation (Tensor) of the network input
:return: A symbolic representation (Tensor) of the predicted label
"""
return tf.argmax(self.get_logits(x, **kwargs), axis=1) | python | def get_predicted_class(self, x, **kwargs):
"""
:param x: A symbolic representation (Tensor) of the network input
:return: A symbolic representation (Tensor) of the predicted label
"""
return tf.argmax(self.get_logits(x, **kwargs), axis=1) | [
"def",
"get_predicted_class",
"(",
"self",
",",
"x",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"tf",
".",
"argmax",
"(",
"self",
".",
"get_logits",
"(",
"x",
",",
"*",
"*",
"kwargs",
")",
",",
"axis",
"=",
"1",
")"
] | :param x: A symbolic representation (Tensor) of the network input
:return: A symbolic representation (Tensor) of the predicted label | [
":",
"param",
"x",
":",
"A",
"symbolic",
"representation",
"(",
"Tensor",
")",
"of",
"the",
"network",
"input",
":",
"return",
":",
"A",
"symbolic",
"representation",
"(",
"Tensor",
")",
"of",
"the",
"predicted",
"label"
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model.py#L72-L77 | train |
tensorflow/cleverhans | cleverhans/model.py | Model.get_probs | def get_probs(self, x, **kwargs):
"""
:param x: A symbolic representation (Tensor) of the network input
:return: A symbolic representation (Tensor) of the output
probabilities (i.e., the output values produced by the softmax layer).
"""
d = self.fprop(x, **kwargs)
if self.O_PROBS in d:
... | python | def get_probs(self, x, **kwargs):
"""
:param x: A symbolic representation (Tensor) of the network input
:return: A symbolic representation (Tensor) of the output
probabilities (i.e., the output values produced by the softmax layer).
"""
d = self.fprop(x, **kwargs)
if self.O_PROBS in d:
... | [
"def",
"get_probs",
"(",
"self",
",",
"x",
",",
"*",
"*",
"kwargs",
")",
":",
"d",
"=",
"self",
".",
"fprop",
"(",
"x",
",",
"*",
"*",
"kwargs",
")",
"if",
"self",
".",
"O_PROBS",
"in",
"d",
":",
"output",
"=",
"d",
"[",
"self",
".",
"O_PROBS... | :param x: A symbolic representation (Tensor) of the network input
:return: A symbolic representation (Tensor) of the output
probabilities (i.e., the output values produced by the softmax layer). | [
":",
"param",
"x",
":",
"A",
"symbolic",
"representation",
"(",
"Tensor",
")",
"of",
"the",
"network",
"input",
":",
"return",
":",
"A",
"symbolic",
"representation",
"(",
"Tensor",
")",
"of",
"the",
"output",
"probabilities",
"(",
"i",
".",
"e",
".",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model.py#L79-L100 | train |
tensorflow/cleverhans | cleverhans/model.py | Model.get_params | def get_params(self):
"""
Provides access to the model's parameters.
:return: A list of all Variables defining the model parameters.
"""
if hasattr(self, 'params'):
return list(self.params)
# Catch eager execution and assert function overload.
try:
if tf.executing_eagerly():
... | python | def get_params(self):
"""
Provides access to the model's parameters.
:return: A list of all Variables defining the model parameters.
"""
if hasattr(self, 'params'):
return list(self.params)
# Catch eager execution and assert function overload.
try:
if tf.executing_eagerly():
... | [
"def",
"get_params",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'params'",
")",
":",
"return",
"list",
"(",
"self",
".",
"params",
")",
"# Catch eager execution and assert function overload.",
"try",
":",
"if",
"tf",
".",
"executing_eagerly",
"... | Provides access to the model's parameters.
:return: A list of all Variables defining the model parameters. | [
"Provides",
"access",
"to",
"the",
"model",
"s",
"parameters",
".",
":",
"return",
":",
"A",
"list",
"of",
"all",
"Variables",
"defining",
"the",
"model",
"parameters",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model.py#L111-L150 | train |
tensorflow/cleverhans | cleverhans/model.py | Model.make_params | def make_params(self):
"""
Create all Variables to be returned later by get_params.
By default this is a no-op.
Models that need their fprop to be called for their params to be
created can set `needs_dummy_fprop=True` in the constructor.
"""
if self.needs_dummy_fprop:
if hasattr(self,... | python | def make_params(self):
"""
Create all Variables to be returned later by get_params.
By default this is a no-op.
Models that need their fprop to be called for their params to be
created can set `needs_dummy_fprop=True` in the constructor.
"""
if self.needs_dummy_fprop:
if hasattr(self,... | [
"def",
"make_params",
"(",
"self",
")",
":",
"if",
"self",
".",
"needs_dummy_fprop",
":",
"if",
"hasattr",
"(",
"self",
",",
"\"_dummy_input\"",
")",
":",
"return",
"self",
".",
"_dummy_input",
"=",
"self",
".",
"make_input_placeholder",
"(",
")",
"self",
... | Create all Variables to be returned later by get_params.
By default this is a no-op.
Models that need their fprop to be called for their params to be
created can set `needs_dummy_fprop=True` in the constructor. | [
"Create",
"all",
"Variables",
"to",
"be",
"returned",
"later",
"by",
"get_params",
".",
"By",
"default",
"this",
"is",
"a",
"no",
"-",
"op",
".",
"Models",
"that",
"need",
"their",
"fprop",
"to",
"be",
"called",
"for",
"their",
"params",
"to",
"be",
"c... | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model.py#L152-L164 | train |
tensorflow/cleverhans | cleverhans/model.py | Model.get_layer | def get_layer(self, x, layer, **kwargs):
"""Return a layer output.
:param x: tensor, the input to the network.
:param layer: str, the name of the layer to compute.
:param **kwargs: dict, extra optional params to pass to self.fprop.
:return: the content of layer `layer`
"""
return self.fprop(... | python | def get_layer(self, x, layer, **kwargs):
"""Return a layer output.
:param x: tensor, the input to the network.
:param layer: str, the name of the layer to compute.
:param **kwargs: dict, extra optional params to pass to self.fprop.
:return: the content of layer `layer`
"""
return self.fprop(... | [
"def",
"get_layer",
"(",
"self",
",",
"x",
",",
"layer",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"fprop",
"(",
"x",
",",
"*",
"*",
"kwargs",
")",
"[",
"layer",
"]"
] | Return a layer output.
:param x: tensor, the input to the network.
:param layer: str, the name of the layer to compute.
:param **kwargs: dict, extra optional params to pass to self.fprop.
:return: the content of layer `layer` | [
"Return",
"a",
"layer",
"output",
".",
":",
"param",
"x",
":",
"tensor",
"the",
"input",
"to",
"the",
"network",
".",
":",
"param",
"layer",
":",
"str",
"the",
"name",
"of",
"the",
"layer",
"to",
"compute",
".",
":",
"param",
"**",
"kwargs",
":",
"... | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model.py#L170-L177 | train |
tensorflow/cleverhans | cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py | plot_reliability_diagram | def plot_reliability_diagram(confidence, labels, filepath):
"""
Takes in confidence values for predictions and correct
labels for the data, plots a reliability diagram.
:param confidence: nb_samples x nb_classes (e.g., output of softmax)
:param labels: vector of nb_samples
:param filepath: where to save the... | python | def plot_reliability_diagram(confidence, labels, filepath):
"""
Takes in confidence values for predictions and correct
labels for the data, plots a reliability diagram.
:param confidence: nb_samples x nb_classes (e.g., output of softmax)
:param labels: vector of nb_samples
:param filepath: where to save the... | [
"def",
"plot_reliability_diagram",
"(",
"confidence",
",",
"labels",
",",
"filepath",
")",
":",
"assert",
"len",
"(",
"confidence",
".",
"shape",
")",
"==",
"2",
"assert",
"len",
"(",
"labels",
".",
"shape",
")",
"==",
"1",
"assert",
"confidence",
".",
"... | Takes in confidence values for predictions and correct
labels for the data, plots a reliability diagram.
:param confidence: nb_samples x nb_classes (e.g., output of softmax)
:param labels: vector of nb_samples
:param filepath: where to save the diagram
:return: | [
"Takes",
"in",
"confidence",
"values",
"for",
"predictions",
"and",
"correct",
"labels",
"for",
"the",
"data",
"plots",
"a",
"reliability",
"diagram",
".",
":",
"param",
"confidence",
":",
"nb_samples",
"x",
"nb_classes",
"(",
"e",
".",
"g",
".",
"output",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py#L266-L333 | train |
tensorflow/cleverhans | cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py | DkNNModel.init_lsh | def init_lsh(self):
"""
Initializes locality-sensitive hashing with FALCONN to find nearest neighbors in training data.
"""
self.query_objects = {
} # contains the object that can be queried to find nearest neighbors at each layer.
# mean of training data representation per layer (that needs to... | python | def init_lsh(self):
"""
Initializes locality-sensitive hashing with FALCONN to find nearest neighbors in training data.
"""
self.query_objects = {
} # contains the object that can be queried to find nearest neighbors at each layer.
# mean of training data representation per layer (that needs to... | [
"def",
"init_lsh",
"(",
"self",
")",
":",
"self",
".",
"query_objects",
"=",
"{",
"}",
"# contains the object that can be queried to find nearest neighbors at each layer.",
"# mean of training data representation per layer (that needs to be substracted before LSH).",
"self",
".",
"ce... | Initializes locality-sensitive hashing with FALCONN to find nearest neighbors in training data. | [
"Initializes",
"locality",
"-",
"sensitive",
"hashing",
"with",
"FALCONN",
"to",
"find",
"nearest",
"neighbors",
"in",
"training",
"data",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py#L88-L132 | train |
tensorflow/cleverhans | cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py | DkNNModel.find_train_knns | def find_train_knns(self, data_activations):
"""
Given a data_activation dictionary that contains a np array with activations for each layer,
find the knns in the training data.
"""
knns_ind = {}
knns_labels = {}
for layer in self.layers:
# Pre-process representations of data to norma... | python | def find_train_knns(self, data_activations):
"""
Given a data_activation dictionary that contains a np array with activations for each layer,
find the knns in the training data.
"""
knns_ind = {}
knns_labels = {}
for layer in self.layers:
# Pre-process representations of data to norma... | [
"def",
"find_train_knns",
"(",
"self",
",",
"data_activations",
")",
":",
"knns_ind",
"=",
"{",
"}",
"knns_labels",
"=",
"{",
"}",
"for",
"layer",
"in",
"self",
".",
"layers",
":",
"# Pre-process representations of data to normalize and remove training data mean.",
"d... | Given a data_activation dictionary that contains a np array with activations for each layer,
find the knns in the training data. | [
"Given",
"a",
"data_activation",
"dictionary",
"that",
"contains",
"a",
"np",
"array",
"with",
"activations",
"for",
"each",
"layer",
"find",
"the",
"knns",
"in",
"the",
"training",
"data",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py#L134-L168 | train |
tensorflow/cleverhans | cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py | DkNNModel.nonconformity | def nonconformity(self, knns_labels):
"""
Given an dictionary of nb_data x nb_classes dimension, compute the nonconformity of
each candidate label for each data point: i.e. the number of knns whose label is
different from the candidate label.
"""
nb_data = knns_labels[self.layers[0]].shape[0]
... | python | def nonconformity(self, knns_labels):
"""
Given an dictionary of nb_data x nb_classes dimension, compute the nonconformity of
each candidate label for each data point: i.e. the number of knns whose label is
different from the candidate label.
"""
nb_data = knns_labels[self.layers[0]].shape[0]
... | [
"def",
"nonconformity",
"(",
"self",
",",
"knns_labels",
")",
":",
"nb_data",
"=",
"knns_labels",
"[",
"self",
".",
"layers",
"[",
"0",
"]",
"]",
".",
"shape",
"[",
"0",
"]",
"knns_not_in_class",
"=",
"np",
".",
"zeros",
"(",
"(",
"nb_data",
",",
"se... | Given an dictionary of nb_data x nb_classes dimension, compute the nonconformity of
each candidate label for each data point: i.e. the number of knns whose label is
different from the candidate label. | [
"Given",
"an",
"dictionary",
"of",
"nb_data",
"x",
"nb_classes",
"dimension",
"compute",
"the",
"nonconformity",
"of",
"each",
"candidate",
"label",
"for",
"each",
"data",
"point",
":",
"i",
".",
"e",
".",
"the",
"number",
"of",
"knns",
"whose",
"label",
"... | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py#L170-L190 | train |
tensorflow/cleverhans | cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py | DkNNModel.preds_conf_cred | def preds_conf_cred(self, knns_not_in_class):
"""
Given an array of nb_data x nb_classes dimensions, use conformal prediction to compute
the DkNN's prediction, confidence and credibility.
"""
nb_data = knns_not_in_class.shape[0]
preds_knn = np.zeros(nb_data, dtype=np.int32)
confs = np.zeros(... | python | def preds_conf_cred(self, knns_not_in_class):
"""
Given an array of nb_data x nb_classes dimensions, use conformal prediction to compute
the DkNN's prediction, confidence and credibility.
"""
nb_data = knns_not_in_class.shape[0]
preds_knn = np.zeros(nb_data, dtype=np.int32)
confs = np.zeros(... | [
"def",
"preds_conf_cred",
"(",
"self",
",",
"knns_not_in_class",
")",
":",
"nb_data",
"=",
"knns_not_in_class",
".",
"shape",
"[",
"0",
"]",
"preds_knn",
"=",
"np",
".",
"zeros",
"(",
"nb_data",
",",
"dtype",
"=",
"np",
".",
"int32",
")",
"confs",
"=",
... | Given an array of nb_data x nb_classes dimensions, use conformal prediction to compute
the DkNN's prediction, confidence and credibility. | [
"Given",
"an",
"array",
"of",
"nb_data",
"x",
"nb_classes",
"dimensions",
"use",
"conformal",
"prediction",
"to",
"compute",
"the",
"DkNN",
"s",
"prediction",
"confidence",
"and",
"credibility",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py#L192-L214 | train |
tensorflow/cleverhans | cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py | DkNNModel.fprop_np | def fprop_np(self, data_np):
"""
Performs a forward pass through the DkNN on an numpy array of data.
"""
if not self.calibrated:
raise ValueError(
"DkNN needs to be calibrated by calling DkNNModel.calibrate method once before inferring.")
data_activations = self.get_activations(data_... | python | def fprop_np(self, data_np):
"""
Performs a forward pass through the DkNN on an numpy array of data.
"""
if not self.calibrated:
raise ValueError(
"DkNN needs to be calibrated by calling DkNNModel.calibrate method once before inferring.")
data_activations = self.get_activations(data_... | [
"def",
"fprop_np",
"(",
"self",
",",
"data_np",
")",
":",
"if",
"not",
"self",
".",
"calibrated",
":",
"raise",
"ValueError",
"(",
"\"DkNN needs to be calibrated by calling DkNNModel.calibrate method once before inferring.\"",
")",
"data_activations",
"=",
"self",
".",
... | Performs a forward pass through the DkNN on an numpy array of data. | [
"Performs",
"a",
"forward",
"pass",
"through",
"the",
"DkNN",
"on",
"an",
"numpy",
"array",
"of",
"data",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py#L216-L227 | train |
tensorflow/cleverhans | cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py | DkNNModel.fprop | def fprop(self, x):
"""
Performs a forward pass through the DkNN on a TF tensor by wrapping
the fprop_np method.
"""
logits = tf.py_func(self.fprop_np, [x], tf.float32)
return {self.O_LOGITS: logits} | python | def fprop(self, x):
"""
Performs a forward pass through the DkNN on a TF tensor by wrapping
the fprop_np method.
"""
logits = tf.py_func(self.fprop_np, [x], tf.float32)
return {self.O_LOGITS: logits} | [
"def",
"fprop",
"(",
"self",
",",
"x",
")",
":",
"logits",
"=",
"tf",
".",
"py_func",
"(",
"self",
".",
"fprop_np",
",",
"[",
"x",
"]",
",",
"tf",
".",
"float32",
")",
"return",
"{",
"self",
".",
"O_LOGITS",
":",
"logits",
"}"
] | Performs a forward pass through the DkNN on a TF tensor by wrapping
the fprop_np method. | [
"Performs",
"a",
"forward",
"pass",
"through",
"the",
"DkNN",
"on",
"a",
"TF",
"tensor",
"by",
"wrapping",
"the",
"fprop_np",
"method",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py#L229-L235 | train |
tensorflow/cleverhans | cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py | DkNNModel.calibrate | def calibrate(self, cali_data, cali_labels):
"""
Runs the DkNN on holdout data to calibrate the credibility metric.
:param cali_data: np array of calibration data.
:param cali_labels: np vector of calibration labels.
"""
self.nb_cali = cali_labels.shape[0]
self.cali_activations = self.get_ac... | python | def calibrate(self, cali_data, cali_labels):
"""
Runs the DkNN on holdout data to calibrate the credibility metric.
:param cali_data: np array of calibration data.
:param cali_labels: np vector of calibration labels.
"""
self.nb_cali = cali_labels.shape[0]
self.cali_activations = self.get_ac... | [
"def",
"calibrate",
"(",
"self",
",",
"cali_data",
",",
"cali_labels",
")",
":",
"self",
".",
"nb_cali",
"=",
"cali_labels",
".",
"shape",
"[",
"0",
"]",
"self",
".",
"cali_activations",
"=",
"self",
".",
"get_activations",
"(",
"cali_data",
")",
"self",
... | Runs the DkNN on holdout data to calibrate the credibility metric.
:param cali_data: np array of calibration data.
:param cali_labels: np vector of calibration labels. | [
"Runs",
"the",
"DkNN",
"on",
"holdout",
"data",
"to",
"calibrate",
"the",
"credibility",
"metric",
".",
":",
"param",
"cali_data",
":",
"np",
"array",
"of",
"calibration",
"data",
".",
":",
"param",
"cali_labels",
":",
"np",
"vector",
"of",
"calibration",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py#L237-L263 | train |
tensorflow/cleverhans | cleverhans_tutorials/mnist_tutorial_pytorch.py | mnist_tutorial | def mnist_tutorial(nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE,
train_end=-1, test_end=-1, learning_rate=LEARNING_RATE):
"""
MNIST cleverhans tutorial
:param nb_epochs: number of epochs to train model
:param batch_size: size of training batches
:param learning_rate: learning rate for trainin... | python | def mnist_tutorial(nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE,
train_end=-1, test_end=-1, learning_rate=LEARNING_RATE):
"""
MNIST cleverhans tutorial
:param nb_epochs: number of epochs to train model
:param batch_size: size of training batches
:param learning_rate: learning rate for trainin... | [
"def",
"mnist_tutorial",
"(",
"nb_epochs",
"=",
"NB_EPOCHS",
",",
"batch_size",
"=",
"BATCH_SIZE",
",",
"train_end",
"=",
"-",
"1",
",",
"test_end",
"=",
"-",
"1",
",",
"learning_rate",
"=",
"LEARNING_RATE",
")",
":",
"# Train a pytorch MNIST model",
"torch_mode... | MNIST cleverhans tutorial
:param nb_epochs: number of epochs to train model
:param batch_size: size of training batches
:param learning_rate: learning rate for training
:return: an AccuracyReport object | [
"MNIST",
"cleverhans",
"tutorial",
":",
"param",
"nb_epochs",
":",
"number",
"of",
"epochs",
"to",
"train",
"model",
":",
"param",
"batch_size",
":",
"size",
"of",
"training",
"batches",
":",
"param",
"learning_rate",
":",
"learning",
"rate",
"for",
"training"... | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans_tutorials/mnist_tutorial_pytorch.py#L68-L170 | train |
tensorflow/cleverhans | cleverhans/attacks_tf.py | apply_perturbations | def apply_perturbations(i, j, X, increase, theta, clip_min, clip_max):
"""
TensorFlow implementation for apply perturbations to input features based
on salency maps
:param i: index of first selected feature
:param j: index of second selected feature
:param X: a matrix containing our input features for our s... | python | def apply_perturbations(i, j, X, increase, theta, clip_min, clip_max):
"""
TensorFlow implementation for apply perturbations to input features based
on salency maps
:param i: index of first selected feature
:param j: index of second selected feature
:param X: a matrix containing our input features for our s... | [
"def",
"apply_perturbations",
"(",
"i",
",",
"j",
",",
"X",
",",
"increase",
",",
"theta",
",",
"clip_min",
",",
"clip_max",
")",
":",
"warnings",
".",
"warn",
"(",
"\"This function is dead code and will be removed on or after 2019-07-18\"",
")",
"# perturb our input ... | TensorFlow implementation for apply perturbations to input features based
on salency maps
:param i: index of first selected feature
:param j: index of second selected feature
:param X: a matrix containing our input features for our sample
:param increase: boolean; true if we are increasing pixels, false other... | [
"TensorFlow",
"implementation",
"for",
"apply",
"perturbations",
"to",
"input",
"features",
"based",
"on",
"salency",
"maps",
":",
"param",
"i",
":",
"index",
"of",
"first",
"selected",
"feature",
":",
"param",
"j",
":",
"index",
"of",
"second",
"selected",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks_tf.py#L55-L79 | train |
tensorflow/cleverhans | cleverhans/attacks_tf.py | saliency_map | def saliency_map(grads_target, grads_other, search_domain, increase):
"""
TensorFlow implementation for computing saliency maps
:param grads_target: a matrix containing forward derivatives for the
target class
:param grads_other: a matrix where every element is the sum of forward
... | python | def saliency_map(grads_target, grads_other, search_domain, increase):
"""
TensorFlow implementation for computing saliency maps
:param grads_target: a matrix containing forward derivatives for the
target class
:param grads_other: a matrix where every element is the sum of forward
... | [
"def",
"saliency_map",
"(",
"grads_target",
",",
"grads_other",
",",
"search_domain",
",",
"increase",
")",
":",
"warnings",
".",
"warn",
"(",
"\"This function is dead code and will be removed on or after 2019-07-18\"",
")",
"# Compute the size of the input (the number of feature... | TensorFlow implementation for computing saliency maps
:param grads_target: a matrix containing forward derivatives for the
target class
:param grads_other: a matrix where every element is the sum of forward
derivatives over all non-target classes at that index
:param s... | [
"TensorFlow",
"implementation",
"for",
"computing",
"saliency",
"maps",
":",
"param",
"grads_target",
":",
"a",
"matrix",
"containing",
"forward",
"derivatives",
"for",
"the",
"target",
"class",
":",
"param",
"grads_other",
":",
"a",
"matrix",
"where",
"every",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks_tf.py#L82-L130 | train |
tensorflow/cleverhans | cleverhans/attacks_tf.py | jacobian | def jacobian(sess, x, grads, target, X, nb_features, nb_classes, feed=None):
"""
TensorFlow implementation of the foward derivative / Jacobian
:param x: the input placeholder
:param grads: the list of TF gradients returned by jacobian_graph()
:param target: the target misclassification class
:param X: numpy... | python | def jacobian(sess, x, grads, target, X, nb_features, nb_classes, feed=None):
"""
TensorFlow implementation of the foward derivative / Jacobian
:param x: the input placeholder
:param grads: the list of TF gradients returned by jacobian_graph()
:param target: the target misclassification class
:param X: numpy... | [
"def",
"jacobian",
"(",
"sess",
",",
"x",
",",
"grads",
",",
"target",
",",
"X",
",",
"nb_features",
",",
"nb_classes",
",",
"feed",
"=",
"None",
")",
":",
"warnings",
".",
"warn",
"(",
"\"This function is dead code and will be removed on or after 2019-07-18\"",
... | TensorFlow implementation of the foward derivative / Jacobian
:param x: the input placeholder
:param grads: the list of TF gradients returned by jacobian_graph()
:param target: the target misclassification class
:param X: numpy array with sample input
:param nb_features: the number of features in the input
... | [
"TensorFlow",
"implementation",
"of",
"the",
"foward",
"derivative",
"/",
"Jacobian",
":",
"param",
"x",
":",
"the",
"input",
"placeholder",
":",
"param",
"grads",
":",
"the",
"list",
"of",
"TF",
"gradients",
"returned",
"by",
"jacobian_graph",
"()",
":",
"p... | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks_tf.py#L133-L164 | train |
tensorflow/cleverhans | cleverhans/future/torch/attacks/projected_gradient_descent.py | projected_gradient_descent | def projected_gradient_descent(model_fn, x, eps, eps_iter, nb_iter, ord,
clip_min=None, clip_max=None, y=None, targeted=False,
rand_init=None, rand_minmax=0.3, sanity_checks=True):
"""
This class implements either the Basic Iterative Method
(Kurakin et... | python | def projected_gradient_descent(model_fn, x, eps, eps_iter, nb_iter, ord,
clip_min=None, clip_max=None, y=None, targeted=False,
rand_init=None, rand_minmax=0.3, sanity_checks=True):
"""
This class implements either the Basic Iterative Method
(Kurakin et... | [
"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",
... | 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... | [
"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",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/future/torch/attacks/projected_gradient_descent.py#L9-L100 | train |
tensorflow/cleverhans | cleverhans/model_zoo/madry_lab_challenges/cifar10_model.py | _batch_norm | def _batch_norm(name, x):
"""Batch normalization."""
with tf.name_scope(name):
return tf.contrib.layers.batch_norm(
inputs=x,
decay=.9,
center=True,
scale=True,
activation_fn=None,
updates_collections=None,
is_training=False) | python | def _batch_norm(name, x):
"""Batch normalization."""
with tf.name_scope(name):
return tf.contrib.layers.batch_norm(
inputs=x,
decay=.9,
center=True,
scale=True,
activation_fn=None,
updates_collections=None,
is_training=False) | [
"def",
"_batch_norm",
"(",
"name",
",",
"x",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"name",
")",
":",
"return",
"tf",
".",
"contrib",
".",
"layers",
".",
"batch_norm",
"(",
"inputs",
"=",
"x",
",",
"decay",
"=",
".9",
",",
"center",
"=",
... | Batch normalization. | [
"Batch",
"normalization",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model_zoo/madry_lab_challenges/cifar10_model.py#L224-L234 | train |
tensorflow/cleverhans | cleverhans/model_zoo/madry_lab_challenges/cifar10_model.py | _residual | def _residual(x, in_filter, out_filter, stride,
activate_before_residual=False):
"""Residual unit with 2 sub layers."""
if activate_before_residual:
with tf.variable_scope('shared_activation'):
x = _batch_norm('init_bn', x)
x = _relu(x, 0.1)
orig_x = x
else:
with tf.variabl... | python | def _residual(x, in_filter, out_filter, stride,
activate_before_residual=False):
"""Residual unit with 2 sub layers."""
if activate_before_residual:
with tf.variable_scope('shared_activation'):
x = _batch_norm('init_bn', x)
x = _relu(x, 0.1)
orig_x = x
else:
with tf.variabl... | [
"def",
"_residual",
"(",
"x",
",",
"in_filter",
",",
"out_filter",
",",
"stride",
",",
"activate_before_residual",
"=",
"False",
")",
":",
"if",
"activate_before_residual",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"'shared_activation'",
")",
":",
"x",
"=... | Residual unit with 2 sub layers. | [
"Residual",
"unit",
"with",
"2",
"sub",
"layers",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model_zoo/madry_lab_challenges/cifar10_model.py#L237-L269 | train |
tensorflow/cleverhans | cleverhans/model_zoo/madry_lab_challenges/cifar10_model.py | _decay | def _decay():
"""L2 weight decay loss."""
costs = []
for var in tf.trainable_variables():
if var.op.name.find('DW') > 0:
costs.append(tf.nn.l2_loss(var))
return tf.add_n(costs) | python | def _decay():
"""L2 weight decay loss."""
costs = []
for var in tf.trainable_variables():
if var.op.name.find('DW') > 0:
costs.append(tf.nn.l2_loss(var))
return tf.add_n(costs) | [
"def",
"_decay",
"(",
")",
":",
"costs",
"=",
"[",
"]",
"for",
"var",
"in",
"tf",
".",
"trainable_variables",
"(",
")",
":",
"if",
"var",
".",
"op",
".",
"name",
".",
"find",
"(",
"'DW'",
")",
">",
"0",
":",
"costs",
".",
"append",
"(",
"tf",
... | L2 weight decay loss. | [
"L2",
"weight",
"decay",
"loss",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model_zoo/madry_lab_challenges/cifar10_model.py#L272-L278 | train |
tensorflow/cleverhans | cleverhans/model_zoo/madry_lab_challenges/cifar10_model.py | _relu | def _relu(x, leakiness=0.0):
"""Relu, with optional leaky support."""
return tf.where(tf.less(x, 0.0), leakiness * x, x, name='leaky_relu') | python | def _relu(x, leakiness=0.0):
"""Relu, with optional leaky support."""
return tf.where(tf.less(x, 0.0), leakiness * x, x, name='leaky_relu') | [
"def",
"_relu",
"(",
"x",
",",
"leakiness",
"=",
"0.0",
")",
":",
"return",
"tf",
".",
"where",
"(",
"tf",
".",
"less",
"(",
"x",
",",
"0.0",
")",
",",
"leakiness",
"*",
"x",
",",
"x",
",",
"name",
"=",
"'leaky_relu'",
")"
] | Relu, with optional leaky support. | [
"Relu",
"with",
"optional",
"leaky",
"support",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model_zoo/madry_lab_challenges/cifar10_model.py#L292-L294 | train |
tensorflow/cleverhans | cleverhans/model_zoo/madry_lab_challenges/cifar10_model.py | Input.set_input_shape | def set_input_shape(self, input_shape):
batch_size, rows, cols, input_channels = input_shape
# assert self.mode == 'train' or self.mode == 'eval'
"""Build the core model within the graph."""
input_shape = list(input_shape)
input_shape[0] = 1
dummy_batch = tf.zeros(input_shape)
dummy_output =... | python | def set_input_shape(self, input_shape):
batch_size, rows, cols, input_channels = input_shape
# assert self.mode == 'train' or self.mode == 'eval'
"""Build the core model within the graph."""
input_shape = list(input_shape)
input_shape[0] = 1
dummy_batch = tf.zeros(input_shape)
dummy_output =... | [
"def",
"set_input_shape",
"(",
"self",
",",
"input_shape",
")",
":",
"batch_size",
",",
"rows",
",",
"cols",
",",
"input_channels",
"=",
"input_shape",
"# assert self.mode == 'train' or self.mode == 'eval'",
"input_shape",
"=",
"list",
"(",
"input_shape",
")",
"input_... | Build the core model within the graph. | [
"Build",
"the",
"core",
"model",
"within",
"the",
"graph",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model_zoo/madry_lab_challenges/cifar10_model.py#L118-L128 | train |
tensorflow/cleverhans | cleverhans/experimental/certification/dual_formulation.py | DualFormulation.create_projected_dual | def create_projected_dual(self):
"""Function to create variables for the projected dual object.
Function that projects the input dual variables onto the feasible set.
Returns:
projected_dual: Feasible dual solution corresponding to current dual
"""
# TODO: consider whether we can use shallow c... | python | def create_projected_dual(self):
"""Function to create variables for the projected dual object.
Function that projects the input dual variables onto the feasible set.
Returns:
projected_dual: Feasible dual solution corresponding to current dual
"""
# TODO: consider whether we can use shallow c... | [
"def",
"create_projected_dual",
"(",
"self",
")",
":",
"# TODO: consider whether we can use shallow copy of the lists without",
"# using tf.identity",
"projected_nu",
"=",
"tf",
".",
"placeholder",
"(",
"tf",
".",
"float32",
",",
"shape",
"=",
"[",
"]",
")",
"min_eig_h"... | Function to create variables for the projected dual object.
Function that projects the input dual variables onto the feasible set.
Returns:
projected_dual: Feasible dual solution corresponding to current dual | [
"Function",
"to",
"create",
"variables",
"for",
"the",
"projected",
"dual",
"object",
".",
"Function",
"that",
"projects",
"the",
"input",
"dual",
"variables",
"onto",
"the",
"feasible",
"set",
".",
"Returns",
":",
"projected_dual",
":",
"Feasible",
"dual",
"s... | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/dual_formulation.py#L159-L203 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.