partition stringclasses 3
values | func_name stringlengths 1 134 | docstring stringlengths 1 46.9k | path stringlengths 4 223 | original_string stringlengths 75 104k | code stringlengths 75 104k | docstring_tokens listlengths 1 1.97k | repo stringlengths 7 55 | language stringclasses 1
value | url stringlengths 87 315 | code_tokens listlengths 19 28.4k | sha stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|
train | div | A wrapper around tf division that does more automatic casting of
the input. | cleverhans/utils_tf.py | def div(a, b):
"""
A wrapper around tf division that does more automatic casting of
the input.
"""
def divide(a, b):
"""Division"""
return a / b
return op_with_scalar_cast(a, b, divide) | def div(a, b):
"""
A wrapper around tf division that does more automatic casting of
the input.
"""
def divide(a, b):
"""Division"""
return a / b
return op_with_scalar_cast(a, b, divide) | [
"A",
"wrapper",
"around",
"tf",
"division",
"that",
"does",
"more",
"automatic",
"casting",
"of",
"the",
"input",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_tf.py#L571-L579 | [
"def",
"div",
"(",
"a",
",",
"b",
")",
":",
"def",
"divide",
"(",
"a",
",",
"b",
")",
":",
"\"\"\"Division\"\"\"",
"return",
"a",
"/",
"b",
"return",
"op_with_scalar_cast",
"(",
"a",
",",
"b",
",",
"divide",
")"
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | op_with_scalar_cast | Builds the graph to compute f(a, b).
If only one of the two arguments is a scalar and the operation would
cause a type error without casting, casts the scalar to match the
tensor.
:param a: a tf-compatible array or scalar
:param b: a tf-compatible array or scalar | cleverhans/utils_tf.py | def op_with_scalar_cast(a, b, f):
"""
Builds the graph to compute f(a, b).
If only one of the two arguments is a scalar and the operation would
cause a type error without casting, casts the scalar to match the
tensor.
:param a: a tf-compatible array or scalar
:param b: a tf-compatible array or scalar
""... | def op_with_scalar_cast(a, b, f):
"""
Builds the graph to compute f(a, b).
If only one of the two arguments is a scalar and the operation would
cause a type error without casting, casts the scalar to match the
tensor.
:param a: a tf-compatible array or scalar
:param b: a tf-compatible array or scalar
""... | [
"Builds",
"the",
"graph",
"to",
"compute",
"f",
"(",
"a",
"b",
")",
".",
"If",
"only",
"one",
"of",
"the",
"two",
"arguments",
"is",
"a",
"scalar",
"and",
"the",
"operation",
"would",
"cause",
"a",
"type",
"error",
"without",
"casting",
"casts",
"the",... | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_tf.py#L581-L618 | [
"def",
"op_with_scalar_cast",
"(",
"a",
",",
"b",
",",
"f",
")",
":",
"try",
":",
"return",
"f",
"(",
"a",
",",
"b",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"pass",
"def",
"is_scalar",
"(",
"x",
")",
":",
"\"\"\"Return True if `... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | jacobian_graph | Create the Jacobian graph to be ran later in a TF session
:param predictions: the model's symbolic output (linear output,
pre-softmax)
:param x: the input placeholder
:param nb_classes: the number of classes the model has
:return: | cleverhans/utils_tf.py | def jacobian_graph(predictions, x, nb_classes):
"""
Create the Jacobian graph to be ran later in a TF session
:param predictions: the model's symbolic output (linear output,
pre-softmax)
:param x: the input placeholder
:param nb_classes: the number of classes the model has
:return:
"""
# This fun... | def jacobian_graph(predictions, x, nb_classes):
"""
Create the Jacobian graph to be ran later in a TF session
:param predictions: the model's symbolic output (linear output,
pre-softmax)
:param x: the input placeholder
:param nb_classes: the number of classes the model has
:return:
"""
# This fun... | [
"Create",
"the",
"Jacobian",
"graph",
"to",
"be",
"ran",
"later",
"in",
"a",
"TF",
"session",
":",
"param",
"predictions",
":",
"the",
"model",
"s",
"symbolic",
"output",
"(",
"linear",
"output",
"pre",
"-",
"softmax",
")",
":",
"param",
"x",
":",
"the... | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_tf.py#L647-L665 | [
"def",
"jacobian_graph",
"(",
"predictions",
",",
"x",
",",
"nb_classes",
")",
":",
"# This function will return a list of TF gradients",
"list_derivatives",
"=",
"[",
"]",
"# Define the TF graph elements to compute our derivatives for each class",
"for",
"class_ind",
"in",
"xr... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | jacobian_augmentation | Augment an adversary's substitute training set using the Jacobian
of a substitute model to generate new synthetic inputs.
See https://arxiv.org/abs/1602.02697 for more details.
See cleverhans_tutorials/mnist_blackbox.py for example use case
:param sess: TF session in which the substitute model is defined
:par... | cleverhans/utils_tf.py | def jacobian_augmentation(sess,
x,
X_sub_prev,
Y_sub,
grads,
lmbda,
aug_batch_size=512,
feed=None):
"""
Augment an adversary's substit... | def jacobian_augmentation(sess,
x,
X_sub_prev,
Y_sub,
grads,
lmbda,
aug_batch_size=512,
feed=None):
"""
Augment an adversary's substit... | [
"Augment",
"an",
"adversary",
"s",
"substitute",
"training",
"set",
"using",
"the",
"Jacobian",
"of",
"a",
"substitute",
"model",
"to",
"generate",
"new",
"synthetic",
"inputs",
".",
"See",
"https",
":",
"//",
"arxiv",
".",
"org",
"/",
"abs",
"/",
"1602",
... | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_tf.py#L667-L722 | [
"def",
"jacobian_augmentation",
"(",
"sess",
",",
"x",
",",
"X_sub_prev",
",",
"Y_sub",
",",
"grads",
",",
"lmbda",
",",
"aug_batch_size",
"=",
"512",
",",
"feed",
"=",
"None",
")",
":",
"assert",
"len",
"(",
"x",
".",
"get_shape",
"(",
")",
")",
"==... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | evaluate_model | Run evaluation on a saved model
:param filepath: path to model to evaluate
: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 batch_size: size o... | cleverhans_tutorials/evaluate_pickled_model.py | def evaluate_model(filepath,
train_start=0, train_end=60000, test_start=0,
test_end=10000, batch_size=128,
testing=False, num_threads=None):
"""
Run evaluation on a saved model
:param filepath: path to model to evaluate
:param train_start: index of first ... | def evaluate_model(filepath,
train_start=0, train_end=60000, test_start=0,
test_end=10000, batch_size=128,
testing=False, num_threads=None):
"""
Run evaluation on a saved model
:param filepath: path to model to evaluate
:param train_start: index of first ... | [
"Run",
"evaluation",
"on",
"a",
"saved",
"model",
":",
"param",
"filepath",
":",
"path",
"to",
"model",
"to",
"evaluate",
":",
"param",
"train_start",
":",
"index",
"of",
"first",
"training",
"set",
"example",
":",
"param",
"train_end",
":",
"index",
"of",... | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans_tutorials/evaluate_pickled_model.py#L26-L99 | [
"def",
"evaluate_model",
"(",
"filepath",
",",
"train_start",
"=",
"0",
",",
"train_end",
"=",
"60000",
",",
"test_start",
"=",
"0",
",",
"test_end",
"=",
"10000",
",",
"batch_size",
"=",
"128",
",",
"testing",
"=",
"False",
",",
"num_threads",
"=",
"Non... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | RunnerMultiGPU.set_input | Preprocessing the inputs before calling session.run()
:param X_batch: A dictionary of inputs to the first sub-graph
:return: A tuple, `(fetches, fd)`, with `fetches` being a list of
Tensors to be fetches and `fd` the feed dictionary. | examples/multigpu_advtrain/runner.py | def set_input(self, X_batch=None):
"""
Preprocessing the inputs before calling session.run()
:param X_batch: A dictionary of inputs to the first sub-graph
:return: A tuple, `(fetches, fd)`, with `fetches` being a list of
Tensors to be fetches and `fd` the feed dictionary.
"""
input... | def set_input(self, X_batch=None):
"""
Preprocessing the inputs before calling session.run()
:param X_batch: A dictionary of inputs to the first sub-graph
:return: A tuple, `(fetches, fd)`, with `fetches` being a list of
Tensors to be fetches and `fd` the feed dictionary.
"""
input... | [
"Preprocessing",
"the",
"inputs",
"before",
"calling",
"session",
".",
"run",
"()"
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/runner.py#L66-L106 | [
"def",
"set_input",
"(",
"self",
",",
"X_batch",
"=",
"None",
")",
":",
"inputs",
"=",
"self",
".",
"inputs",
"outputs",
"=",
"self",
".",
"outputs",
"# data for first gpu",
"fd",
"=",
"{",
"}",
"if",
"X_batch",
"is",
"not",
"None",
":",
"self",
".",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | RunnerMultiGPU.proc_fvals | Postprocess the outputs of the Session.run(). Move the outputs of
sub-graphs to next ones and return the output of the last sub-graph.
:param fvals: A list of fetched values returned by Session.run()
:return: A dictionary of fetched values returned by the last sub-graph. | examples/multigpu_advtrain/runner.py | def proc_fvals(self, fvals):
"""
Postprocess the outputs of the Session.run(). Move the outputs of
sub-graphs to next ones and return the output of the last sub-graph.
:param fvals: A list of fetched values returned by Session.run()
:return: A dictionary of fetched values returned by the last sub-g... | def proc_fvals(self, fvals):
"""
Postprocess the outputs of the Session.run(). Move the outputs of
sub-graphs to next ones and return the output of the last sub-graph.
:param fvals: A list of fetched values returned by Session.run()
:return: A dictionary of fetched values returned by the last sub-g... | [
"Postprocess",
"the",
"outputs",
"of",
"the",
"Session",
".",
"run",
"()",
".",
"Move",
"the",
"outputs",
"of",
"sub",
"-",
"graphs",
"to",
"next",
"ones",
"and",
"return",
"the",
"output",
"of",
"the",
"last",
"sub",
"-",
"graph",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/runner.py#L108-L139 | [
"def",
"proc_fvals",
"(",
"self",
",",
"fvals",
")",
":",
"inputs",
"=",
"self",
".",
"inputs",
"outputs",
"=",
"self",
".",
"outputs",
"# Move data to the next sub-graph for the next step",
"cur",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"input... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | ImageBatchesBase._write_single_batch_images_internal | Helper method to write images from single batch into datastore. | examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py | def _write_single_batch_images_internal(self, batch_id, client_batch):
"""Helper method to write images from single batch into datastore."""
client = self._datastore_client
batch_key = client.key(self._entity_kind_batches, batch_id)
for img_id, img in iteritems(self._data[batch_id]['images']):
img... | def _write_single_batch_images_internal(self, batch_id, client_batch):
"""Helper method to write images from single batch into datastore."""
client = self._datastore_client
batch_key = client.key(self._entity_kind_batches, batch_id)
for img_id, img in iteritems(self._data[batch_id]['images']):
img... | [
"Helper",
"method",
"to",
"write",
"images",
"from",
"single",
"batch",
"into",
"datastore",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py#L72-L81 | [
"def",
"_write_single_batch_images_internal",
"(",
"self",
",",
"batch_id",
",",
"client_batch",
")",
":",
"client",
"=",
"self",
".",
"_datastore_client",
"batch_key",
"=",
"client",
".",
"key",
"(",
"self",
".",
"_entity_kind_batches",
",",
"batch_id",
")",
"f... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | ImageBatchesBase.write_to_datastore | Writes all image batches to the datastore. | examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py | def write_to_datastore(self):
"""Writes all image batches to the datastore."""
client = self._datastore_client
with client.no_transact_batch() as client_batch:
for batch_id, batch_data in iteritems(self._data):
batch_key = client.key(self._entity_kind_batches, batch_id)
batch_entity = ... | def write_to_datastore(self):
"""Writes all image batches to the datastore."""
client = self._datastore_client
with client.no_transact_batch() as client_batch:
for batch_id, batch_data in iteritems(self._data):
batch_key = client.key(self._entity_kind_batches, batch_id)
batch_entity = ... | [
"Writes",
"all",
"image",
"batches",
"to",
"the",
"datastore",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py#L83-L94 | [
"def",
"write_to_datastore",
"(",
"self",
")",
":",
"client",
"=",
"self",
".",
"_datastore_client",
"with",
"client",
".",
"no_transact_batch",
"(",
")",
"as",
"client_batch",
":",
"for",
"batch_id",
",",
"batch_data",
"in",
"iteritems",
"(",
"self",
".",
"... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | ImageBatchesBase.write_single_batch_images_to_datastore | Writes only images from one batch to the datastore. | examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py | def write_single_batch_images_to_datastore(self, batch_id):
"""Writes only images from one batch to the datastore."""
client = self._datastore_client
with client.no_transact_batch() as client_batch:
self._write_single_batch_images_internal(batch_id, client_batch) | def write_single_batch_images_to_datastore(self, batch_id):
"""Writes only images from one batch to the datastore."""
client = self._datastore_client
with client.no_transact_batch() as client_batch:
self._write_single_batch_images_internal(batch_id, client_batch) | [
"Writes",
"only",
"images",
"from",
"one",
"batch",
"to",
"the",
"datastore",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py#L96-L100 | [
"def",
"write_single_batch_images_to_datastore",
"(",
"self",
",",
"batch_id",
")",
":",
"client",
"=",
"self",
".",
"_datastore_client",
"with",
"client",
".",
"no_transact_batch",
"(",
")",
"as",
"client_batch",
":",
"self",
".",
"_write_single_batch_images_internal... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | ImageBatchesBase.init_from_datastore | Initializes batches by reading from the datastore. | examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py | def init_from_datastore(self):
"""Initializes batches by reading from the datastore."""
self._data = {}
for entity in self._datastore_client.query_fetch(
kind=self._entity_kind_batches):
batch_id = entity.key.flat_path[-1]
self._data[batch_id] = dict(entity)
self._data[batch_id]['i... | def init_from_datastore(self):
"""Initializes batches by reading from the datastore."""
self._data = {}
for entity in self._datastore_client.query_fetch(
kind=self._entity_kind_batches):
batch_id = entity.key.flat_path[-1]
self._data[batch_id] = dict(entity)
self._data[batch_id]['i... | [
"Initializes",
"batches",
"by",
"reading",
"from",
"the",
"datastore",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py#L102-L114 | [
"def",
"init_from_datastore",
"(",
"self",
")",
":",
"self",
".",
"_data",
"=",
"{",
"}",
"for",
"entity",
"in",
"self",
".",
"_datastore_client",
".",
"query_fetch",
"(",
"kind",
"=",
"self",
".",
"_entity_kind_batches",
")",
":",
"batch_id",
"=",
"entity... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | ImageBatchesBase.add_batch | Adds batch with give ID and list of properties. | examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py | def add_batch(self, batch_id, batch_properties=None):
"""Adds batch with give ID and list of properties."""
if batch_properties is None:
batch_properties = {}
if not isinstance(batch_properties, dict):
raise ValueError('batch_properties has to be dict, however it was: '
+ ... | def add_batch(self, batch_id, batch_properties=None):
"""Adds batch with give ID and list of properties."""
if batch_properties is None:
batch_properties = {}
if not isinstance(batch_properties, dict):
raise ValueError('batch_properties has to be dict, however it was: '
+ ... | [
"Adds",
"batch",
"with",
"give",
"ID",
"and",
"list",
"of",
"properties",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py#L125-L133 | [
"def",
"add_batch",
"(",
"self",
",",
"batch_id",
",",
"batch_properties",
"=",
"None",
")",
":",
"if",
"batch_properties",
"is",
"None",
":",
"batch_properties",
"=",
"{",
"}",
"if",
"not",
"isinstance",
"(",
"batch_properties",
",",
"dict",
")",
":",
"ra... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | ImageBatchesBase.add_image | Adds image to given batch. | examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py | def add_image(self, batch_id, image_id, image_properties=None):
"""Adds image to given batch."""
if batch_id not in self._data:
raise KeyError('Batch with ID "{0}" does not exist'.format(batch_id))
if image_properties is None:
image_properties = {}
if not isinstance(image_properties, dict):
... | def add_image(self, batch_id, image_id, image_properties=None):
"""Adds image to given batch."""
if batch_id not in self._data:
raise KeyError('Batch with ID "{0}" does not exist'.format(batch_id))
if image_properties is None:
image_properties = {}
if not isinstance(image_properties, dict):
... | [
"Adds",
"image",
"to",
"given",
"batch",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py#L135-L144 | [
"def",
"add_image",
"(",
"self",
",",
"batch_id",
",",
"image_id",
",",
"image_properties",
"=",
"None",
")",
":",
"if",
"batch_id",
"not",
"in",
"self",
".",
"_data",
":",
"raise",
"KeyError",
"(",
"'Batch with ID \"{0}\" does not exist'",
".",
"format",
"(",... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | DatasetBatches._read_image_list | Reads list of dataset images from the datastore. | examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py | def _read_image_list(self, skip_image_ids=None):
"""Reads list of dataset images from the datastore."""
if skip_image_ids is None:
skip_image_ids = []
images = self._storage_client.list_blobs(
prefix=os.path.join('dataset', self._dataset_name) + '/')
zip_files = [i for i in images if i.end... | def _read_image_list(self, skip_image_ids=None):
"""Reads list of dataset images from the datastore."""
if skip_image_ids is None:
skip_image_ids = []
images = self._storage_client.list_blobs(
prefix=os.path.join('dataset', self._dataset_name) + '/')
zip_files = [i for i in images if i.end... | [
"Reads",
"list",
"of",
"dataset",
"images",
"from",
"the",
"datastore",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py#L189-L222 | [
"def",
"_read_image_list",
"(",
"self",
",",
"skip_image_ids",
"=",
"None",
")",
":",
"if",
"skip_image_ids",
"is",
"None",
":",
"skip_image_ids",
"=",
"[",
"]",
"images",
"=",
"self",
".",
"_storage_client",
".",
"list_blobs",
"(",
"prefix",
"=",
"os",
".... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | DatasetBatches.init_from_storage_write_to_datastore | Initializes dataset batches from the list of images in the datastore.
Args:
batch_size: batch size
allowed_epsilon: list of allowed epsilon or None to use default
skip_image_ids: list of image ids to skip
max_num_images: maximum number of images to read | examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py | def init_from_storage_write_to_datastore(self,
batch_size=100,
allowed_epsilon=None,
skip_image_ids=None,
max_num_images=None):
"""Initializes d... | def init_from_storage_write_to_datastore(self,
batch_size=100,
allowed_epsilon=None,
skip_image_ids=None,
max_num_images=None):
"""Initializes d... | [
"Initializes",
"dataset",
"batches",
"from",
"the",
"list",
"of",
"images",
"in",
"the",
"datastore",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py#L224-L255 | [
"def",
"init_from_storage_write_to_datastore",
"(",
"self",
",",
"batch_size",
"=",
"100",
",",
"allowed_epsilon",
"=",
"None",
",",
"skip_image_ids",
"=",
"None",
",",
"max_num_images",
"=",
"None",
")",
":",
"if",
"allowed_epsilon",
"is",
"None",
":",
"allowed... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | AversarialBatches.init_from_dataset_and_submissions_write_to_datastore | Init list of adversarial batches from dataset batches and submissions.
Args:
dataset_batches: instances of DatasetBatches
attack_submission_ids: iterable with IDs of all (targeted and nontargeted)
attack submissions, could be obtains as
CompetitionSubmissions.get_all_attack_ids() | examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py | def init_from_dataset_and_submissions_write_to_datastore(
self, dataset_batches, attack_submission_ids):
"""Init list of adversarial batches from dataset batches and submissions.
Args:
dataset_batches: instances of DatasetBatches
attack_submission_ids: iterable with IDs of all (targeted and n... | def init_from_dataset_and_submissions_write_to_datastore(
self, dataset_batches, attack_submission_ids):
"""Init list of adversarial batches from dataset batches and submissions.
Args:
dataset_batches: instances of DatasetBatches
attack_submission_ids: iterable with IDs of all (targeted and n... | [
"Init",
"list",
"of",
"adversarial",
"batches",
"from",
"dataset",
"batches",
"and",
"submissions",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py#L272-L289 | [
"def",
"init_from_dataset_and_submissions_write_to_datastore",
"(",
"self",
",",
"dataset_batches",
",",
"attack_submission_ids",
")",
":",
"batches_x_attacks",
"=",
"itertools",
".",
"product",
"(",
"dataset_batches",
".",
"data",
".",
"keys",
"(",
")",
",",
"attack_... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | AversarialBatches.count_generated_adv_examples | Returns total number of all generated adversarial examples. | examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py | def count_generated_adv_examples(self):
"""Returns total number of all generated adversarial examples."""
result = {}
for v in itervalues(self.data):
s_id = v['submission_id']
result[s_id] = result.get(s_id, 0) + len(v['images'])
return result | def count_generated_adv_examples(self):
"""Returns total number of all generated adversarial examples."""
result = {}
for v in itervalues(self.data):
s_id = v['submission_id']
result[s_id] = result.get(s_id, 0) + len(v['images'])
return result | [
"Returns",
"total",
"number",
"of",
"all",
"generated",
"adversarial",
"examples",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py#L291-L297 | [
"def",
"count_generated_adv_examples",
"(",
"self",
")",
":",
"result",
"=",
"{",
"}",
"for",
"v",
"in",
"itervalues",
"(",
"self",
".",
"data",
")",
":",
"s_id",
"=",
"v",
"[",
"'submission_id'",
"]",
"result",
"[",
"s_id",
"]",
"=",
"result",
".",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | make_confidence_report_bundled | Load a saved model, gather its predictions, and save a confidence report.
:param filepath: path to model to evaluate
:param train_start: index of first training set example to use
:param train_end: index of last training set example to use
:param test_start: index of first test set example to use
:param test_... | cleverhans/confidence_report.py | def make_confidence_report_bundled(filepath, train_start=TRAIN_START,
train_end=TRAIN_END, test_start=TEST_START,
test_end=TEST_END, which_set=WHICH_SET,
recipe=RECIPE, report_path=REPORT_PATH,
... | def make_confidence_report_bundled(filepath, train_start=TRAIN_START,
train_end=TRAIN_END, test_start=TEST_START,
test_end=TEST_END, which_set=WHICH_SET,
recipe=RECIPE, report_path=REPORT_PATH,
... | [
"Load",
"a",
"saved",
"model",
"gather",
"its",
"predictions",
"and",
"save",
"a",
"confidence",
"report",
".",
":",
"param",
"filepath",
":",
"path",
"to",
"model",
"to",
"evaluate",
":",
"param",
"train_start",
":",
"index",
"of",
"first",
"training",
"s... | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/confidence_report.py#L124-L235 | [
"def",
"make_confidence_report_bundled",
"(",
"filepath",
",",
"train_start",
"=",
"TRAIN_START",
",",
"train_end",
"=",
"TRAIN_END",
",",
"test_start",
"=",
"TEST_START",
",",
"test_end",
"=",
"TEST_END",
",",
"which_set",
"=",
"WHICH_SET",
",",
"recipe",
"=",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | print_stats | Prints out accuracy, coverage, etc. statistics
:param correctness: ndarray
One bool per example specifying whether it was correctly classified
:param confidence: ndarray
The probability associated with each prediction
:param name: str
The name of this type of data (e.g. "clean", "MaxConfidence") | cleverhans/confidence_report.py | def print_stats(correctness, confidence, name):
"""
Prints out accuracy, coverage, etc. statistics
:param correctness: ndarray
One bool per example specifying whether it was correctly classified
:param confidence: ndarray
The probability associated with each prediction
:param name: str
The name of... | def print_stats(correctness, confidence, name):
"""
Prints out accuracy, coverage, etc. statistics
:param correctness: ndarray
One bool per example specifying whether it was correctly classified
:param confidence: ndarray
The probability associated with each prediction
:param name: str
The name of... | [
"Prints",
"out",
"accuracy",
"coverage",
"etc",
".",
"statistics",
":",
"param",
"correctness",
":",
"ndarray",
"One",
"bool",
"per",
"example",
"specifying",
"whether",
"it",
"was",
"correctly",
"classified",
":",
"param",
"confidence",
":",
"ndarray",
"The",
... | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/confidence_report.py#L238-L270 | [
"def",
"print_stats",
"(",
"correctness",
",",
"confidence",
",",
"name",
")",
":",
"accuracy",
"=",
"correctness",
".",
"mean",
"(",
")",
"wrongness",
"=",
"1",
"-",
"correctness",
"denom1",
"=",
"np",
".",
"maximum",
"(",
"1",
",",
"wrongness",
".",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | make_confidence_report | Load a saved model, gather its predictions, and save a confidence report.
This function works by running a single MaxConfidence attack on each example.
This provides a reasonable estimate of the true failure rate quickly, so
long as the model does not suffer from gradient masking.
However, this estimate is mo... | cleverhans/confidence_report.py | def make_confidence_report(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,
mc_batch_size=MC_BATCH_SIZE,
... | def make_confidence_report(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,
mc_batch_size=MC_BATCH_SIZE,
... | [
"Load",
"a",
"saved",
"model",
"gather",
"its",
"predictions",
"and",
"save",
"a",
"confidence",
"report",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/confidence_report.py#L273-L404 | [
"def",
"make_confidence_report",
"(",
"filepath",
",",
"train_start",
"=",
"TRAIN_START",
",",
"train_end",
"=",
"TRAIN_END",
",",
"test_start",
"=",
"TEST_START",
",",
"test_end",
"=",
"TEST_END",
",",
"batch_size",
"=",
"BATCH_SIZE",
",",
"which_set",
"=",
"WH... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | mnist_tutorial | MNIST CleverHans tutorial
:param train_start: index of first training set example
:param train_end: index of last training set example
:param test_start: index of first test set example
:param test_end: index of last test set example
:param nb_epochs: number of epochs to train model
:param batch_size: size ... | cleverhans_tutorials/mnist_tutorial_keras_tf.py | def mnist_tutorial(train_start=0, train_end=60000, test_start=0,
test_end=10000, nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE,
learning_rate=LEARNING_RATE, train_dir=TRAIN_DIR,
filename=FILENAME, load_model=LOAD_MODEL,
testing=False, label_smooth... | def mnist_tutorial(train_start=0, train_end=60000, test_start=0,
test_end=10000, nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE,
learning_rate=LEARNING_RATE, train_dir=TRAIN_DIR,
filename=FILENAME, load_model=LOAD_MODEL,
testing=False, label_smooth... | [
"MNIST",
"CleverHans",
"tutorial",
":",
"param",
"train_start",
":",
"index",
"of",
"first",
"training",
"set",
"example",
":",
"param",
"train_end",
":",
"index",
"of",
"last",
"training",
"set",
"example",
":",
"param",
"test_start",
":",
"index",
"of",
"f... | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans_tutorials/mnist_tutorial_keras_tf.py#L41-L209 | [
"def",
"mnist_tutorial",
"(",
"train_start",
"=",
"0",
",",
"train_end",
"=",
"60000",
",",
"test_start",
"=",
"0",
",",
"test_end",
"=",
"10000",
",",
"nb_epochs",
"=",
"NB_EPOCHS",
",",
"batch_size",
"=",
"BATCH_SIZE",
",",
"learning_rate",
"=",
"LEARNING_... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | MaxConfidence.generate | Generate symbolic graph for adversarial examples and return.
:param x: The model's symbolic inputs.
:param kwargs: Keyword arguments for the base attacker | cleverhans/attacks/max_confidence.py | def generate(self, x, **kwargs):
"""
Generate symbolic graph for adversarial examples and return.
:param x: The model's symbolic inputs.
:param kwargs: Keyword arguments for the base attacker
"""
assert self.parse_params(**kwargs)
labels, _nb_classes = self.get_or_guess_labels(x, kwargs)
... | def generate(self, x, **kwargs):
"""
Generate symbolic graph for adversarial examples and return.
:param x: The model's symbolic inputs.
:param kwargs: Keyword arguments for the base attacker
"""
assert self.parse_params(**kwargs)
labels, _nb_classes = self.get_or_guess_labels(x, kwargs)
... | [
"Generate",
"symbolic",
"graph",
"for",
"adversarial",
"examples",
"and",
"return",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/max_confidence.py#L41-L53 | [
"def",
"generate",
"(",
"self",
",",
"x",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"self",
".",
"parse_params",
"(",
"*",
"*",
"kwargs",
")",
"labels",
",",
"_nb_classes",
"=",
"self",
".",
"get_or_guess_labels",
"(",
"x",
",",
"kwargs",
")",
"ad... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | MaxConfidence.attack | Runs the untargeted attack.
:param x: The input
:param true_y: The correct label for `x`. This attack aims to produce misclassification. | cleverhans/attacks/max_confidence.py | def attack(self, x, true_y):
"""
Runs the untargeted attack.
:param x: The input
:param true_y: The correct label for `x`. This attack aims to produce misclassification.
"""
adv_x_cls = []
prob_cls = []
m = tf.shape(x)[0]
true_y_idx = tf.argmax(true_y, axis=1)
expanded_x = tf.co... | def attack(self, x, true_y):
"""
Runs the untargeted attack.
:param x: The input
:param true_y: The correct label for `x`. This attack aims to produce misclassification.
"""
adv_x_cls = []
prob_cls = []
m = tf.shape(x)[0]
true_y_idx = tf.argmax(true_y, axis=1)
expanded_x = tf.co... | [
"Runs",
"the",
"untargeted",
"attack",
".",
":",
"param",
"x",
":",
"The",
"input",
":",
"param",
"true_y",
":",
"The",
"correct",
"label",
"for",
"x",
".",
"This",
"attack",
"aims",
"to",
"produce",
"misclassification",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/max_confidence.py#L64-L110 | [
"def",
"attack",
"(",
"self",
",",
"x",
",",
"true_y",
")",
":",
"adv_x_cls",
"=",
"[",
"]",
"prob_cls",
"=",
"[",
"]",
"m",
"=",
"tf",
".",
"shape",
"(",
"x",
")",
"[",
"0",
"]",
"true_y_idx",
"=",
"tf",
".",
"argmax",
"(",
"true_y",
",",
"a... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | MaxConfidence.attack_class | Run the attack on a specific target class.
:param x: tf Tensor. The input example.
:param target_y: tf Tensor. The attacker's desired target class.
Returns:
A targeted adversarial example, intended to be classified as the target class. | cleverhans/attacks/max_confidence.py | def attack_class(self, x, target_y):
"""
Run the attack on a specific target class.
:param x: tf Tensor. The input example.
:param target_y: tf Tensor. The attacker's desired target class.
Returns:
A targeted adversarial example, intended to be classified as the target class.
"""
adv =... | def attack_class(self, x, target_y):
"""
Run the attack on a specific target class.
:param x: tf Tensor. The input example.
:param target_y: tf Tensor. The attacker's desired target class.
Returns:
A targeted adversarial example, intended to be classified as the target class.
"""
adv =... | [
"Run",
"the",
"attack",
"on",
"a",
"specific",
"target",
"class",
".",
":",
"param",
"x",
":",
"tf",
"Tensor",
".",
"The",
"input",
"example",
".",
":",
"param",
"target_y",
":",
"tf",
"Tensor",
".",
"The",
"attacker",
"s",
"desired",
"target",
"class"... | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/max_confidence.py#L112-L121 | [
"def",
"attack_class",
"(",
"self",
",",
"x",
",",
"target_y",
")",
":",
"adv",
"=",
"self",
".",
"base_attacker",
".",
"generate",
"(",
"x",
",",
"y_target",
"=",
"target_y",
",",
"*",
"*",
"self",
".",
"params",
")",
"return",
"adv"
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | batch_indices | This helper function computes a batch start and end index
:param batch_nb: the batch number
:param data_length: the total length of the data being parsed by batches
:param batch_size: the number of inputs in each batch
:return: pair of (start, end) indices | cleverhans/utils.py | def batch_indices(batch_nb, data_length, batch_size):
"""
This helper function computes a batch start and end index
:param batch_nb: the batch number
:param data_length: the total length of the data being parsed by batches
:param batch_size: the number of inputs in each batch
:return: pair of (start, end) i... | def batch_indices(batch_nb, data_length, batch_size):
"""
This helper function computes a batch start and end index
:param batch_nb: the batch number
:param data_length: the total length of the data being parsed by batches
:param batch_size: the number of inputs in each batch
:return: pair of (start, end) i... | [
"This",
"helper",
"function",
"computes",
"a",
"batch",
"start",
"and",
"end",
"index",
":",
"param",
"batch_nb",
":",
"the",
"batch",
"number",
":",
"param",
"data_length",
":",
"the",
"total",
"length",
"of",
"the",
"data",
"being",
"parsed",
"by",
"batc... | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils.py#L63-L82 | [
"def",
"batch_indices",
"(",
"batch_nb",
",",
"data_length",
",",
"batch_size",
")",
":",
"# Batch start and end index",
"start",
"=",
"int",
"(",
"batch_nb",
"*",
"batch_size",
")",
"end",
"=",
"int",
"(",
"(",
"batch_nb",
"+",
"1",
")",
"*",
"batch_size",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | other_classes | Returns a list of class indices excluding the class indexed by class_ind
:param nb_classes: number of classes in the task
:param class_ind: the class index to be omitted
:return: list of class indices excluding the class indexed by class_ind | cleverhans/utils.py | def other_classes(nb_classes, class_ind):
"""
Returns a list of class indices excluding the class indexed by class_ind
:param nb_classes: number of classes in the task
:param class_ind: the class index to be omitted
:return: list of class indices excluding the class indexed by class_ind
"""
if class_ind <... | def other_classes(nb_classes, class_ind):
"""
Returns a list of class indices excluding the class indexed by class_ind
:param nb_classes: number of classes in the task
:param class_ind: the class index to be omitted
:return: list of class indices excluding the class indexed by class_ind
"""
if class_ind <... | [
"Returns",
"a",
"list",
"of",
"class",
"indices",
"excluding",
"the",
"class",
"indexed",
"by",
"class_ind",
":",
"param",
"nb_classes",
":",
"number",
"of",
"classes",
"in",
"the",
"task",
":",
"param",
"class_ind",
":",
"the",
"class",
"index",
"to",
"be... | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils.py#L85-L99 | [
"def",
"other_classes",
"(",
"nb_classes",
",",
"class_ind",
")",
":",
"if",
"class_ind",
"<",
"0",
"or",
"class_ind",
">=",
"nb_classes",
":",
"error_str",
"=",
"\"class_ind must be within the range (0, nb_classes - 1)\"",
"raise",
"ValueError",
"(",
"error_str",
")"... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | to_categorical | Converts a class vector (integers) to binary class matrix.
This is adapted from the Keras function with the same name.
:param y: class vector to be converted into a matrix
(integers from 0 to nb_classes).
:param nb_classes: nb_classes: total number of classes.
:param num_classses: depricated version... | cleverhans/utils.py | def to_categorical(y, nb_classes, num_classes=None):
"""
Converts a class vector (integers) to binary class matrix.
This is adapted from the Keras function with the same name.
:param y: class vector to be converted into a matrix
(integers from 0 to nb_classes).
:param nb_classes: nb_classes: total... | def to_categorical(y, nb_classes, num_classes=None):
"""
Converts a class vector (integers) to binary class matrix.
This is adapted from the Keras function with the same name.
:param y: class vector to be converted into a matrix
(integers from 0 to nb_classes).
:param nb_classes: nb_classes: total... | [
"Converts",
"a",
"class",
"vector",
"(",
"integers",
")",
"to",
"binary",
"class",
"matrix",
".",
"This",
"is",
"adapted",
"from",
"the",
"Keras",
"function",
"with",
"the",
"same",
"name",
".",
":",
"param",
"y",
":",
"class",
"vector",
"to",
"be",
"c... | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils.py#L102-L124 | [
"def",
"to_categorical",
"(",
"y",
",",
"nb_classes",
",",
"num_classes",
"=",
"None",
")",
":",
"if",
"num_classes",
"is",
"not",
"None",
":",
"if",
"nb_classes",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"\"Should not specify both nb_classes and it... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | random_targets | Take in an array of correct labels and randomly select a different label
for each label in the array. This is typically used to randomly select a
target class in targeted adversarial examples attacks (i.e., when the
search algorithm takes in both a source class and target class to compute
the adversarial exampl... | cleverhans/utils.py | def random_targets(gt, nb_classes):
"""
Take in an array of correct labels and randomly select a different label
for each label in the array. This is typically used to randomly select a
target class in targeted adversarial examples attacks (i.e., when the
search algorithm takes in both a source class and targ... | def random_targets(gt, nb_classes):
"""
Take in an array of correct labels and randomly select a different label
for each label in the array. This is typically used to randomly select a
target class in targeted adversarial examples attacks (i.e., when the
search algorithm takes in both a source class and targ... | [
"Take",
"in",
"an",
"array",
"of",
"correct",
"labels",
"and",
"randomly",
"select",
"a",
"different",
"label",
"for",
"each",
"label",
"in",
"the",
"array",
".",
"This",
"is",
"typically",
"used",
"to",
"randomly",
"select",
"a",
"target",
"class",
"in",
... | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils.py#L127-L164 | [
"def",
"random_targets",
"(",
"gt",
",",
"nb_classes",
")",
":",
"# If the ground truth labels are encoded as one-hot, convert to labels.",
"if",
"len",
"(",
"gt",
".",
"shape",
")",
"==",
"2",
":",
"gt",
"=",
"np",
".",
"argmax",
"(",
"gt",
",",
"axis",
"=",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | pair_visual | Deprecation wrapper | cleverhans/utils.py | def pair_visual(*args, **kwargs):
"""Deprecation wrapper"""
warnings.warn("`pair_visual` has moved to `cleverhans.plot.pyplot_image`. "
"cleverhans.utils.pair_visual may be removed on or after "
"2019-04-24.")
from cleverhans.plot.pyplot_image import pair_visual as new_pair_visual
... | def pair_visual(*args, **kwargs):
"""Deprecation wrapper"""
warnings.warn("`pair_visual` has moved to `cleverhans.plot.pyplot_image`. "
"cleverhans.utils.pair_visual may be removed on or after "
"2019-04-24.")
from cleverhans.plot.pyplot_image import pair_visual as new_pair_visual
... | [
"Deprecation",
"wrapper"
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils.py#L167-L173 | [
"def",
"pair_visual",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"warnings",
".",
"warn",
"(",
"\"`pair_visual` has moved to `cleverhans.plot.pyplot_image`. \"",
"\"cleverhans.utils.pair_visual may be removed on or after \"",
"\"2019-04-24.\"",
")",
"from",
"cleverh... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | grid_visual | Deprecation wrapper | cleverhans/utils.py | def grid_visual(*args, **kwargs):
"""Deprecation wrapper"""
warnings.warn("`grid_visual` has moved to `cleverhans.plot.pyplot_image`. "
"cleverhans.utils.grid_visual may be removed on or after "
"2019-04-24.")
from cleverhans.plot.pyplot_image import grid_visual as new_grid_visual
... | def grid_visual(*args, **kwargs):
"""Deprecation wrapper"""
warnings.warn("`grid_visual` has moved to `cleverhans.plot.pyplot_image`. "
"cleverhans.utils.grid_visual may be removed on or after "
"2019-04-24.")
from cleverhans.plot.pyplot_image import grid_visual as new_grid_visual
... | [
"Deprecation",
"wrapper"
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils.py#L176-L182 | [
"def",
"grid_visual",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"warnings",
".",
"warn",
"(",
"\"`grid_visual` has moved to `cleverhans.plot.pyplot_image`. \"",
"\"cleverhans.utils.grid_visual may be removed on or after \"",
"\"2019-04-24.\"",
")",
"from",
"cleverh... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | get_logits_over_interval | Deprecation wrapper | cleverhans/utils.py | def get_logits_over_interval(*args, **kwargs):
"""Deprecation wrapper"""
warnings.warn("`get_logits_over_interval` has moved to "
"`cleverhans.plot.pyplot_image`. "
"cleverhans.utils.get_logits_over_interval may be removed on "
"or after 2019-04-24.")
# pylint:disab... | def get_logits_over_interval(*args, **kwargs):
"""Deprecation wrapper"""
warnings.warn("`get_logits_over_interval` has moved to "
"`cleverhans.plot.pyplot_image`. "
"cleverhans.utils.get_logits_over_interval may be removed on "
"or after 2019-04-24.")
# pylint:disab... | [
"Deprecation",
"wrapper"
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils.py#L185-L193 | [
"def",
"get_logits_over_interval",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"warnings",
".",
"warn",
"(",
"\"`get_logits_over_interval` has moved to \"",
"\"`cleverhans.plot.pyplot_image`. \"",
"\"cleverhans.utils.get_logits_over_interval may be removed on \"",
"\"or ... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | linear_extrapolation_plot | Deprecation wrapper | cleverhans/utils.py | def linear_extrapolation_plot(*args, **kwargs):
"""Deprecation wrapper"""
warnings.warn("`linear_extrapolation_plot` has moved to "
"`cleverhans.plot.pyplot_image`. "
"cleverhans.utils.linear_extrapolation_plot may be removed on "
"or after 2019-04-24.")
# pylint:di... | def linear_extrapolation_plot(*args, **kwargs):
"""Deprecation wrapper"""
warnings.warn("`linear_extrapolation_plot` has moved to "
"`cleverhans.plot.pyplot_image`. "
"cleverhans.utils.linear_extrapolation_plot may be removed on "
"or after 2019-04-24.")
# pylint:di... | [
"Deprecation",
"wrapper"
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils.py#L196-L204 | [
"def",
"linear_extrapolation_plot",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"warnings",
".",
"warn",
"(",
"\"`linear_extrapolation_plot` has moved to \"",
"\"`cleverhans.plot.pyplot_image`. \"",
"\"cleverhans.utils.linear_extrapolation_plot may be removed on \"",
"\"... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | create_logger | Create a logger object with the given name.
If this is the first time that we call this method, then initialize the
formatter. | cleverhans/utils.py | def create_logger(name):
"""
Create a logger object with the given name.
If this is the first time that we call this method, then initialize the
formatter.
"""
base = logging.getLogger("cleverhans")
if len(base.handlers) == 0:
ch = logging.StreamHandler()
formatter = logging.Formatter('[%(levelna... | def create_logger(name):
"""
Create a logger object with the given name.
If this is the first time that we call this method, then initialize the
formatter.
"""
base = logging.getLogger("cleverhans")
if len(base.handlers) == 0:
ch = logging.StreamHandler()
formatter = logging.Formatter('[%(levelna... | [
"Create",
"a",
"logger",
"object",
"with",
"the",
"given",
"name",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils.py#L247-L262 | [
"def",
"create_logger",
"(",
"name",
")",
":",
"base",
"=",
"logging",
".",
"getLogger",
"(",
"\"cleverhans\"",
")",
"if",
"len",
"(",
"base",
".",
"handlers",
")",
"==",
"0",
":",
"ch",
"=",
"logging",
".",
"StreamHandler",
"(",
")",
"formatter",
"=",... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | deterministic_dict | Returns a version of `normal_dict` whose iteration order is always the same | cleverhans/utils.py | def deterministic_dict(normal_dict):
"""
Returns a version of `normal_dict` whose iteration order is always the same
"""
out = OrderedDict()
for key in sorted(normal_dict.keys()):
out[key] = normal_dict[key]
return out | def deterministic_dict(normal_dict):
"""
Returns a version of `normal_dict` whose iteration order is always the same
"""
out = OrderedDict()
for key in sorted(normal_dict.keys()):
out[key] = normal_dict[key]
return out | [
"Returns",
"a",
"version",
"of",
"normal_dict",
"whose",
"iteration",
"order",
"is",
"always",
"the",
"same"
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils.py#L265-L272 | [
"def",
"deterministic_dict",
"(",
"normal_dict",
")",
":",
"out",
"=",
"OrderedDict",
"(",
")",
"for",
"key",
"in",
"sorted",
"(",
"normal_dict",
".",
"keys",
"(",
")",
")",
":",
"out",
"[",
"key",
"]",
"=",
"normal_dict",
"[",
"key",
"]",
"return",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | ordered_union | Return the union of l1 and l2, with a deterministic ordering.
(Union of python sets does not necessarily have a consisten iteration
order)
:param l1: list of items
:param l2: list of items
:returns: list containing one copy of each item that is in l1 or in l2 | cleverhans/utils.py | def ordered_union(l1, l2):
"""
Return the union of l1 and l2, with a deterministic ordering.
(Union of python sets does not necessarily have a consisten iteration
order)
:param l1: list of items
:param l2: list of items
:returns: list containing one copy of each item that is in l1 or in l2
"""
out = [... | def ordered_union(l1, l2):
"""
Return the union of l1 and l2, with a deterministic ordering.
(Union of python sets does not necessarily have a consisten iteration
order)
:param l1: list of items
:param l2: list of items
:returns: list containing one copy of each item that is in l1 or in l2
"""
out = [... | [
"Return",
"the",
"union",
"of",
"l1",
"and",
"l2",
"with",
"a",
"deterministic",
"ordering",
".",
"(",
"Union",
"of",
"python",
"sets",
"does",
"not",
"necessarily",
"have",
"a",
"consisten",
"iteration",
"order",
")",
":",
"param",
"l1",
":",
"list",
"o... | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils.py#L275-L288 | [
"def",
"ordered_union",
"(",
"l1",
",",
"l2",
")",
":",
"out",
"=",
"[",
"]",
"for",
"e",
"in",
"l1",
"+",
"l2",
":",
"if",
"e",
"not",
"in",
"out",
":",
"out",
".",
"append",
"(",
"e",
")",
"return",
"out"
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | safe_zip | like zip but with these properties:
- returns a list, rather than an iterator. This is the old Python2 zip behavior.
- a guarantee that all arguments are the same length.
(normal zip silently drops entries to make them the same length) | cleverhans/utils.py | def safe_zip(*args):
"""like zip but with these properties:
- returns a list, rather than an iterator. This is the old Python2 zip behavior.
- a guarantee that all arguments are the same length.
(normal zip silently drops entries to make them the same length)
"""
length = len(args[0])
if not all(len(arg) ... | def safe_zip(*args):
"""like zip but with these properties:
- returns a list, rather than an iterator. This is the old Python2 zip behavior.
- a guarantee that all arguments are the same length.
(normal zip silently drops entries to make them the same length)
"""
length = len(args[0])
if not all(len(arg) ... | [
"like",
"zip",
"but",
"with",
"these",
"properties",
":",
"-",
"returns",
"a",
"list",
"rather",
"than",
"an",
"iterator",
".",
"This",
"is",
"the",
"old",
"Python2",
"zip",
"behavior",
".",
"-",
"a",
"guarantee",
"that",
"all",
"arguments",
"are",
"the"... | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils.py#L291-L301 | [
"def",
"safe_zip",
"(",
"*",
"args",
")",
":",
"length",
"=",
"len",
"(",
"args",
"[",
"0",
"]",
")",
"if",
"not",
"all",
"(",
"len",
"(",
"arg",
")",
"==",
"length",
"for",
"arg",
"in",
"args",
")",
":",
"raise",
"ValueError",
"(",
"\"Lengths of... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | shell_call | Calls shell command with argument substitution.
Args:
command: command represented as a list. Each element of the list is one
token of the command. For example "cp a b" becomes ['cp', 'a', 'b']
If any element of the list looks like '${NAME}' then it will be replaced
by value from **kwargs with ... | cleverhans/utils.py | def shell_call(command, **kwargs):
"""Calls shell command with argument substitution.
Args:
command: command represented as a list. Each element of the list is one
token of the command. For example "cp a b" becomes ['cp', 'a', 'b']
If any element of the list looks like '${NAME}' then it will be rep... | def shell_call(command, **kwargs):
"""Calls shell command with argument substitution.
Args:
command: command represented as a list. Each element of the list is one
token of the command. For example "cp a b" becomes ['cp', 'a', 'b']
If any element of the list looks like '${NAME}' then it will be rep... | [
"Calls",
"shell",
"command",
"with",
"argument",
"substitution",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils.py#L304-L339 | [
"def",
"shell_call",
"(",
"command",
",",
"*",
"*",
"kwargs",
")",
":",
"# Regular expression to find instances of '${NAME}' in a string",
"CMD_VARIABLE_RE",
"=",
"re",
".",
"compile",
"(",
"'^\\\\$\\\\{(\\\\w+)\\\\}$'",
")",
"command",
"=",
"list",
"(",
"command",
")... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | deep_copy | Returns a copy of a dictionary whose values are numpy arrays.
Copies their values rather than copying references to them. | cleverhans/utils.py | def deep_copy(numpy_dict):
"""
Returns a copy of a dictionary whose values are numpy arrays.
Copies their values rather than copying references to them.
"""
out = {}
for key in numpy_dict:
out[key] = numpy_dict[key].copy()
return out | def deep_copy(numpy_dict):
"""
Returns a copy of a dictionary whose values are numpy arrays.
Copies their values rather than copying references to them.
"""
out = {}
for key in numpy_dict:
out[key] = numpy_dict[key].copy()
return out | [
"Returns",
"a",
"copy",
"of",
"a",
"dictionary",
"whose",
"values",
"are",
"numpy",
"arrays",
".",
"Copies",
"their",
"values",
"rather",
"than",
"copying",
"references",
"to",
"them",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils.py#L341-L349 | [
"def",
"deep_copy",
"(",
"numpy_dict",
")",
":",
"out",
"=",
"{",
"}",
"for",
"key",
"in",
"numpy_dict",
":",
"out",
"[",
"key",
"]",
"=",
"numpy_dict",
"[",
"key",
"]",
".",
"copy",
"(",
")",
"return",
"out"
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | data_mnist | Load and preprocess MNIST dataset
:param datadir: path to folder where data should be stored
:param train_start: index of first training set example
:param train_end: index of last training set example
:param test_start: index of first test set example
:param test_end: index of last test set example
:return... | cleverhans/dataset.py | def data_mnist(datadir=tempfile.gettempdir(), train_start=0,
train_end=60000, test_start=0, test_end=10000):
"""
Load and preprocess MNIST dataset
:param datadir: path to folder where data should be stored
:param train_start: index of first training set example
:param train_end: index of last t... | def data_mnist(datadir=tempfile.gettempdir(), train_start=0,
train_end=60000, test_start=0, test_end=10000):
"""
Load and preprocess MNIST dataset
:param datadir: path to folder where data should be stored
:param train_start: index of first training set example
:param train_end: index of last t... | [
"Load",
"and",
"preprocess",
"MNIST",
"dataset",
":",
"param",
"datadir",
":",
"path",
"to",
"folder",
"where",
"data",
"should",
"be",
"stored",
":",
"param",
"train_start",
":",
"index",
"of",
"first",
"training",
"set",
"example",
":",
"param",
"train_end... | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/dataset.py#L230-L266 | [
"def",
"data_mnist",
"(",
"datadir",
"=",
"tempfile",
".",
"gettempdir",
"(",
")",
",",
"train_start",
"=",
"0",
",",
"train_end",
"=",
"60000",
",",
"test_start",
"=",
"0",
",",
"test_end",
"=",
"10000",
")",
":",
"assert",
"isinstance",
"(",
"train_sta... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | data_cifar10 | Preprocess CIFAR10 dataset
:return: | cleverhans/dataset.py | def data_cifar10(train_start=0, train_end=50000, test_start=0, test_end=10000):
"""
Preprocess CIFAR10 dataset
:return:
"""
# These values are specific to CIFAR10
img_rows = 32
img_cols = 32
nb_classes = 10
# the data, shuffled and split between train and test sets
(x_train, y_train), (x_test, y_... | def data_cifar10(train_start=0, train_end=50000, test_start=0, test_end=10000):
"""
Preprocess CIFAR10 dataset
:return:
"""
# These values are specific to CIFAR10
img_rows = 32
img_cols = 32
nb_classes = 10
# the data, shuffled and split between train and test sets
(x_train, y_train), (x_test, y_... | [
"Preprocess",
"CIFAR10",
"dataset",
":",
"return",
":"
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/dataset.py#L269-L307 | [
"def",
"data_cifar10",
"(",
"train_start",
"=",
"0",
",",
"train_end",
"=",
"50000",
",",
"test_start",
"=",
"0",
",",
"test_end",
"=",
"10000",
")",
":",
"# These values are specific to CIFAR10",
"img_rows",
"=",
"32",
"img_cols",
"=",
"32",
"nb_classes",
"="... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | print_accuracies | Load a saved model and print out its accuracy on different data distributions
This function works by running a single attack on each example.
This provides a reasonable estimate of the true failure rate quickly, so
long as the model does not suffer from gradient masking.
However, this estimate is mostly intend... | scripts/compute_accuracy.py | def print_accuracies(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,
base_eps_iter=BASE_EPS_ITER,
nb_iter=NB_ITER):
"""
Load a saved model... | def print_accuracies(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,
base_eps_iter=BASE_EPS_ITER,
nb_iter=NB_ITER):
"""
Load a saved model... | [
"Load",
"a",
"saved",
"model",
"and",
"print",
"out",
"its",
"accuracy",
"on",
"different",
"data",
"distributions"
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/scripts/compute_accuracy.py#L53-L98 | [
"def",
"print_accuracies",
"(",
"filepath",
",",
"train_start",
"=",
"TRAIN_START",
",",
"train_end",
"=",
"TRAIN_END",
",",
"test_start",
"=",
"TEST_START",
",",
"test_end",
"=",
"TEST_END",
",",
"batch_size",
"=",
"BATCH_SIZE",
",",
"which_set",
"=",
"WHICH_SE... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | impl | The actual implementation of the evaluation.
:param sess: tf.Session
:param model: cleverhans.model.Model
:param dataset: cleverhans.dataset.Dataset
:param factory: the dataset factory corresponding to `dataset`
:param x_data: numpy array of input examples
:param y_data: numpy array of class labels
:param... | scripts/compute_accuracy.py | def impl(sess, model, dataset, factory, x_data, y_data,
base_eps_iter=BASE_EPS_ITER, nb_iter=NB_ITER,
batch_size=BATCH_SIZE):
"""
The actual implementation of the evaluation.
:param sess: tf.Session
:param model: cleverhans.model.Model
:param dataset: cleverhans.dataset.Dataset
:param fact... | def impl(sess, model, dataset, factory, x_data, y_data,
base_eps_iter=BASE_EPS_ITER, nb_iter=NB_ITER,
batch_size=BATCH_SIZE):
"""
The actual implementation of the evaluation.
:param sess: tf.Session
:param model: cleverhans.model.Model
:param dataset: cleverhans.dataset.Dataset
:param fact... | [
"The",
"actual",
"implementation",
"of",
"the",
"evaluation",
".",
":",
"param",
"sess",
":",
"tf",
".",
"Session",
":",
"param",
"model",
":",
"cleverhans",
".",
"model",
".",
"Model",
":",
"param",
"dataset",
":",
"cleverhans",
".",
"dataset",
".",
"Da... | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/scripts/compute_accuracy.py#L100-L159 | [
"def",
"impl",
"(",
"sess",
",",
"model",
",",
"dataset",
",",
"factory",
",",
"x_data",
",",
"y_data",
",",
"base_eps_iter",
"=",
"BASE_EPS_ITER",
",",
"nb_iter",
"=",
"NB_ITER",
",",
"batch_size",
"=",
"BATCH_SIZE",
")",
":",
"center",
"=",
"dataset",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | main | Print accuracies | scripts/compute_accuracy.py | def main(argv=None):
"""
Print accuracies
"""
try:
_name_of_script, filepath = argv
except ValueError:
raise ValueError(argv)
print_accuracies(filepath=filepath, test_start=FLAGS.test_start,
test_end=FLAGS.test_end, which_set=FLAGS.which_set,
nb_iter=FLAGS.nb_it... | def main(argv=None):
"""
Print accuracies
"""
try:
_name_of_script, filepath = argv
except ValueError:
raise ValueError(argv)
print_accuracies(filepath=filepath, test_start=FLAGS.test_start,
test_end=FLAGS.test_end, which_set=FLAGS.which_set,
nb_iter=FLAGS.nb_it... | [
"Print",
"accuracies"
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/scripts/compute_accuracy.py#L162-L173 | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"try",
":",
"_name_of_script",
",",
"filepath",
"=",
"argv",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"argv",
")",
"print_accuracies",
"(",
"filepath",
"=",
"filepath",
",",
"test_start",
"... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | fast_gradient_method | PyTorch implementation of the Fast Gradient Method.
:param model_fn: a callable that takes an input tensor and returns the model logits.
:param x: input tensor.
:param eps: epsilon (input variation parameter); see https://arxiv.org/abs/1412.6572.
:param ord: Order of the norm (mimics NumPy). Possible values: np... | cleverhans/future/torch/attacks/fast_gradient_method.py | def fast_gradient_method(model_fn, x, eps, ord,
clip_min=None, clip_max=None, y=None, targeted=False, sanity_checks=False):
"""
PyTorch implementation of the Fast Gradient Method.
:param model_fn: a callable that takes an input tensor and returns the model logits.
:param x: input tensor... | def fast_gradient_method(model_fn, x, eps, ord,
clip_min=None, clip_max=None, y=None, targeted=False, sanity_checks=False):
"""
PyTorch implementation of the Fast Gradient Method.
:param model_fn: a callable that takes an input tensor and returns the model logits.
:param x: input tensor... | [
"PyTorch",
"implementation",
"of",
"the",
"Fast",
"Gradient",
"Method",
".",
":",
"param",
"model_fn",
":",
"a",
"callable",
"that",
"takes",
"an",
"input",
"tensor",
"and",
"returns",
"the",
"model",
"logits",
".",
":",
"param",
"x",
":",
"input",
"tensor... | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/future/torch/attacks/fast_gradient_method.py#L8-L73 | [
"def",
"fast_gradient_method",
"(",
"model_fn",
",",
"x",
",",
"eps",
",",
"ord",
",",
"clip_min",
"=",
"None",
",",
"clip_max",
"=",
"None",
",",
"y",
"=",
"None",
",",
"targeted",
"=",
"False",
",",
"sanity_checks",
"=",
"False",
")",
":",
"if",
"o... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | load_images | Read png images from input directory in batches.
Args:
input_dir: input directory
batch_shape: shape of minibatch array, i.e. [batch_size, height, width, 3]
Yields:
filenames: list file names without path of each image
Lenght of this list could be less than batch_size, in this case only
fi... | examples/nips17_adversarial_competition/dev_toolkit/sample_attacks/fgsm/attack_fgsm.py | def load_images(input_dir, batch_shape):
"""Read png images from input directory in batches.
Args:
input_dir: input directory
batch_shape: shape of minibatch array, i.e. [batch_size, height, width, 3]
Yields:
filenames: list file names without path of each image
Lenght of this list could be le... | def load_images(input_dir, batch_shape):
"""Read png images from input directory in batches.
Args:
input_dir: input directory
batch_shape: shape of minibatch array, i.e. [batch_size, height, width, 3]
Yields:
filenames: list file names without path of each image
Lenght of this list could be le... | [
"Read",
"png",
"images",
"from",
"input",
"directory",
"in",
"batches",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/sample_attacks/fgsm/attack_fgsm.py#L47-L77 | [
"def",
"load_images",
"(",
"input_dir",
",",
"batch_shape",
")",
":",
"images",
"=",
"np",
".",
"zeros",
"(",
"batch_shape",
")",
"filenames",
"=",
"[",
"]",
"idx",
"=",
"0",
"batch_size",
"=",
"batch_shape",
"[",
"0",
"]",
"for",
"filepath",
"in",
"tf... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | save_images | Saves images to the output directory.
Args:
images: array with minibatch of images
filenames: list of filenames without path
If number of file names in this list less than number of images in
the minibatch then only first len(filenames) images will be saved.
output_dir: directory where to sav... | examples/nips17_adversarial_competition/dev_toolkit/sample_attacks/fgsm/attack_fgsm.py | def save_images(images, filenames, output_dir):
"""Saves images to the output directory.
Args:
images: array with minibatch of images
filenames: list of filenames without path
If number of file names in this list less than number of images in
the minibatch then only first len(filenames) images ... | def save_images(images, filenames, output_dir):
"""Saves images to the output directory.
Args:
images: array with minibatch of images
filenames: list of filenames without path
If number of file names in this list less than number of images in
the minibatch then only first len(filenames) images ... | [
"Saves",
"images",
"to",
"the",
"output",
"directory",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/sample_attacks/fgsm/attack_fgsm.py#L80-L95 | [
"def",
"save_images",
"(",
"images",
",",
"filenames",
",",
"output_dir",
")",
":",
"for",
"i",
",",
"filename",
"in",
"enumerate",
"(",
"filenames",
")",
":",
"# Images for inception classifier are normalized to be in [-1, 1] interval,",
"# so rescale them back to [0, 1]."... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | main | Run the sample attack | examples/nips17_adversarial_competition/dev_toolkit/sample_attacks/fgsm/attack_fgsm.py | def main(_):
"""Run the sample attack"""
# Images for inception classifier are normalized to be in [-1, 1] interval,
# eps is a difference between pixels so it should be in [0, 2] interval.
# Renormalizing epsilon from [0, 255] to [0, 2].
eps = 2.0 * FLAGS.max_epsilon / 255.0
batch_shape = [FLAGS.batch_size... | 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
batch_shape = [FLAGS.batch_size... | [
"Run",
"the",
"sample",
"attack"
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/sample_attacks/fgsm/attack_fgsm.py#L127-L157 | [
"def",
"main",
"(",
"_",
")",
":",
"# Images for inception classifier are normalized to be in [-1, 1] interval,",
"# eps is a difference between pixels so it should be in [0, 2] interval.",
"# Renormalizing epsilon from [0, 255] to [0, 2].",
"eps",
"=",
"2.0",
"*",
"FLAGS",
".",
"max_e... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | ld_cifar10 | Load training and test data. | tutorials/future/torch/cifar10_tutorial.py | def ld_cifar10():
"""Load training and test data."""
train_transforms = torchvision.transforms.Compose([torchvision.transforms.ToTensor()])
test_transforms = torchvision.transforms.Compose([torchvision.transforms.ToTensor()])
train_dataset = torchvision.datasets.CIFAR10(root='/tmp/data', train=True, transform=t... | def ld_cifar10():
"""Load training and test data."""
train_transforms = torchvision.transforms.Compose([torchvision.transforms.ToTensor()])
test_transforms = torchvision.transforms.Compose([torchvision.transforms.ToTensor()])
train_dataset = torchvision.datasets.CIFAR10(root='/tmp/data', train=True, transform=t... | [
"Load",
"training",
"and",
"test",
"data",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/tutorials/future/torch/cifar10_tutorial.py#L33-L41 | [
"def",
"ld_cifar10",
"(",
")",
":",
"train_transforms",
"=",
"torchvision",
".",
"transforms",
".",
"Compose",
"(",
"[",
"torchvision",
".",
"transforms",
".",
"ToTensor",
"(",
")",
"]",
")",
"test_transforms",
"=",
"torchvision",
".",
"transforms",
".",
"Co... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | plot_report_from_path | Plots a success-fail curve from a confidence report stored on disk,
:param path: string filepath for the stored report.
(Should be the output of make_confidence_report*.py)
:param success_name: The name (confidence report key) of the data that
should be used to measure success rate
:param fail_names: A li... | cleverhans/plot/success_fail.py | def plot_report_from_path(path, success_name=DEFAULT_SUCCESS_NAME,
fail_names=DEFAULT_FAIL_NAMES, label=None,
is_max_confidence=True,
linewidth=LINEWIDTH,
plot_upper_bound=True):
"""
Plots a success-fail curve fr... | def plot_report_from_path(path, success_name=DEFAULT_SUCCESS_NAME,
fail_names=DEFAULT_FAIL_NAMES, label=None,
is_max_confidence=True,
linewidth=LINEWIDTH,
plot_upper_bound=True):
"""
Plots a success-fail curve fr... | [
"Plots",
"a",
"success",
"-",
"fail",
"curve",
"from",
"a",
"confidence",
"report",
"stored",
"on",
"disk",
":",
"param",
"path",
":",
"string",
"filepath",
"for",
"the",
"stored",
"report",
".",
"(",
"Should",
"be",
"the",
"output",
"of",
"make_confidence... | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/plot/success_fail.py#L18-L54 | [
"def",
"plot_report_from_path",
"(",
"path",
",",
"success_name",
"=",
"DEFAULT_SUCCESS_NAME",
",",
"fail_names",
"=",
"DEFAULT_FAIL_NAMES",
",",
"label",
"=",
"None",
",",
"is_max_confidence",
"=",
"True",
",",
"linewidth",
"=",
"LINEWIDTH",
",",
"plot_upper_bound"... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | plot_report | Plot a success fail curve from a confidence report
:param report: A confidence report
(the type of object saved by make_confidence_report.py)
:param success_name: see plot_report_from_path
:param fail_names: see plot_report_from_path
:param label: see plot_report_from_path
:param is_max_confidence: see pl... | cleverhans/plot/success_fail.py | def plot_report(report, success_name, fail_names, label=None,
is_max_confidence=True,
linewidth=LINEWIDTH,
plot_upper_bound=True):
"""
Plot a success fail curve from a confidence report
:param report: A confidence report
(the type of object saved by make_confide... | def plot_report(report, success_name, fail_names, label=None,
is_max_confidence=True,
linewidth=LINEWIDTH,
plot_upper_bound=True):
"""
Plot a success fail curve from a confidence report
:param report: A confidence report
(the type of object saved by make_confide... | [
"Plot",
"a",
"success",
"fail",
"curve",
"from",
"a",
"confidence",
"report",
":",
"param",
"report",
":",
"A",
"confidence",
"report",
"(",
"the",
"type",
"of",
"object",
"saved",
"by",
"make_confidence_report",
".",
"py",
")",
":",
"param",
"success_name",... | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/plot/success_fail.py#L57-L97 | [
"def",
"plot_report",
"(",
"report",
",",
"success_name",
",",
"fail_names",
",",
"label",
"=",
"None",
",",
"is_max_confidence",
"=",
"True",
",",
"linewidth",
"=",
"LINEWIDTH",
",",
"plot_upper_bound",
"=",
"True",
")",
":",
"(",
"fail_optimal",
",",
"succ... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | make_curve | Make a success-failure curve.
:param report: A confidence report
(the type of object saved by make_confidence_report.py)
:param success_name: see plot_report_from_path
:param fail_names: see plot_report_from_path
:returns:
fail_optimal: list of failure rates on adversarial data for the optimal
(t ... | cleverhans/plot/success_fail.py | def make_curve(report, success_name, fail_names):
"""
Make a success-failure curve.
:param report: A confidence report
(the type of object saved by make_confidence_report.py)
:param success_name: see plot_report_from_path
:param fail_names: see plot_report_from_path
:returns:
fail_optimal: list of f... | def make_curve(report, success_name, fail_names):
"""
Make a success-failure curve.
:param report: A confidence report
(the type of object saved by make_confidence_report.py)
:param success_name: see plot_report_from_path
:param fail_names: see plot_report_from_path
:returns:
fail_optimal: list of f... | [
"Make",
"a",
"success",
"-",
"failure",
"curve",
".",
":",
"param",
"report",
":",
"A",
"confidence",
"report",
"(",
"the",
"type",
"of",
"object",
"saved",
"by",
"make_confidence_report",
".",
"py",
")",
":",
"param",
"success_name",
":",
"see",
"plot_rep... | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/plot/success_fail.py#L100-L274 | [
"def",
"make_curve",
"(",
"report",
",",
"success_name",
",",
"fail_names",
")",
":",
"success_results",
"=",
"report",
"[",
"success_name",
"]",
"fail_name",
"=",
"None",
"# pacify pylint",
"found",
"=",
"False",
"for",
"fail_name",
"in",
"fail_names",
":",
"... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | TrainManager.model_train | Train a TF graph
:param sess: TF session to use when training the graph
:param x: input placeholder
:param y: output placeholder (for labels)
:param predictions: model output predictions
:param X_train: numpy array with training inputs
:param Y_train: numpy array with training outputs
:param... | examples/multigpu_advtrain/trainer.py | def model_train(self):
"""
Train a TF graph
:param sess: TF session to use when training the graph
:param x: input placeholder
:param y: output placeholder (for labels)
:param predictions: model output predictions
:param X_train: numpy array with training inputs
:param Y_train: numpy arr... | def model_train(self):
"""
Train a TF graph
:param sess: TF session to use when training the graph
:param x: input placeholder
:param y: output placeholder (for labels)
:param predictions: model output predictions
:param X_train: numpy array with training inputs
:param Y_train: numpy arr... | [
"Train",
"a",
"TF",
"graph",
":",
"param",
"sess",
":",
"TF",
"session",
"to",
"use",
"when",
"training",
"the",
"graph",
":",
"param",
"x",
":",
"input",
"placeholder",
":",
"param",
"y",
":",
"output",
"placeholder",
"(",
"for",
"labels",
")",
":",
... | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/trainer.py#L191-L274 | [
"def",
"model_train",
"(",
"self",
")",
":",
"assert",
"self",
".",
"runner",
"is",
"not",
"None",
",",
"(",
"\"\"\"Runner is not initialized. TrainerSingleGPU or TrainerMultiGPU\n instantiate a Runner object at initialization time.\"\"\"",
")",
"hparams",
"=",
"self... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | TrainerMultiGPU.clone_g0_inputs_on_ngpus | Clone variables unused by the attack on all GPUs. Specifically, the
ground-truth label, y, has to be preserved until the training step.
:param inputs: A list of dictionaries as the inputs to each step.
:param outputs: A list of dictionaries as the outputs of each step.
:param g0_inputs: Initial variabl... | examples/multigpu_advtrain/trainer.py | def clone_g0_inputs_on_ngpus(self, inputs, outputs, g0_inputs):
"""
Clone variables unused by the attack on all GPUs. Specifically, the
ground-truth label, y, has to be preserved until the training step.
:param inputs: A list of dictionaries as the inputs to each step.
:param outputs: A list of dic... | def clone_g0_inputs_on_ngpus(self, inputs, outputs, g0_inputs):
"""
Clone variables unused by the attack on all GPUs. Specifically, the
ground-truth label, y, has to be preserved until the training step.
:param inputs: A list of dictionaries as the inputs to each step.
:param outputs: A list of dic... | [
"Clone",
"variables",
"unused",
"by",
"the",
"attack",
"on",
"all",
"GPUs",
".",
"Specifically",
"the",
"ground",
"-",
"truth",
"label",
"y",
"has",
"to",
"be",
"preserved",
"until",
"the",
"training",
"step",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/trainer.py#L313-L341 | [
"def",
"clone_g0_inputs_on_ngpus",
"(",
"self",
",",
"inputs",
",",
"outputs",
",",
"g0_inputs",
")",
":",
"assert",
"len",
"(",
"inputs",
")",
"==",
"len",
"(",
"outputs",
")",
",",
"(",
"'Inputs and outputs should have the same number of elements.'",
")",
"input... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | LBFGS.generate | Return a tensor that constructs adversarial examples for the given
input. Generate uses tf.py_func in order to operate over tensors.
:param x: (required) A tensor with the inputs.
:param kwargs: See `parse_params` | cleverhans/attacks/lbfgs.py | def generate(self, x, **kwargs):
"""
Return a tensor that constructs adversarial examples for the given
input. Generate uses tf.py_func in order to operate over tensors.
:param x: (required) A tensor with the inputs.
:param kwargs: See `parse_params`
"""
assert self.sess is not None, \
... | def generate(self, x, **kwargs):
"""
Return a tensor that constructs adversarial examples for the given
input. Generate uses tf.py_func in order to operate over tensors.
:param x: (required) A tensor with the inputs.
:param kwargs: See `parse_params`
"""
assert self.sess is not None, \
... | [
"Return",
"a",
"tensor",
"that",
"constructs",
"adversarial",
"examples",
"for",
"the",
"given",
"input",
".",
"Generate",
"uses",
"tf",
".",
"py_func",
"in",
"order",
"to",
"operate",
"over",
"tensors",
".",
":",
"param",
"x",
":",
"(",
"required",
")",
... | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/lbfgs.py#L41-L74 | [
"def",
"generate",
"(",
"self",
",",
"x",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"self",
".",
"sess",
"is",
"not",
"None",
",",
"'Cannot use `generate` when no `sess` was provided'",
"self",
".",
"parse_params",
"(",
"*",
"*",
"kwargs",
")",
"if",
"s... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | LBFGS.parse_params | :param y_target: (optional) A tensor with the one-hot target labels.
:param batch_size: The number of inputs to include in a batch and
process simultaneously.
:param binary_search_steps: The number of times we perform binary
search to find the optimal trade... | cleverhans/attacks/lbfgs.py | def parse_params(self,
y_target=None,
batch_size=1,
binary_search_steps=5,
max_iterations=1000,
initial_const=1e-2,
clip_min=0,
clip_max=1):
"""
:param y_target: (optional) A tens... | def parse_params(self,
y_target=None,
batch_size=1,
binary_search_steps=5,
max_iterations=1000,
initial_const=1e-2,
clip_min=0,
clip_max=1):
"""
:param y_target: (optional) A tens... | [
":",
"param",
"y_target",
":",
"(",
"optional",
")",
"A",
"tensor",
"with",
"the",
"one",
"-",
"hot",
"target",
"labels",
".",
":",
"param",
"batch_size",
":",
"The",
"number",
"of",
"inputs",
"to",
"include",
"in",
"a",
"batch",
"and",
"process",
"sim... | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/lbfgs.py#L76-L105 | [
"def",
"parse_params",
"(",
"self",
",",
"y_target",
"=",
"None",
",",
"batch_size",
"=",
"1",
",",
"binary_search_steps",
"=",
"5",
",",
"max_iterations",
"=",
"1000",
",",
"initial_const",
"=",
"1e-2",
",",
"clip_min",
"=",
"0",
",",
"clip_max",
"=",
"... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | LBFGS_impl.attack | Perform the attack on the given instance for the given targets. | cleverhans/attacks/lbfgs.py | def attack(self, x_val, targets):
"""
Perform the attack on the given instance for the given targets.
"""
def lbfgs_objective(adv_x, self, targets, oimgs, CONST):
""" returns the function value and the gradient for fmin_l_bfgs_b """
loss = self.sess.run(
self.loss,
feed_... | def attack(self, x_val, targets):
"""
Perform the attack on the given instance for the given targets.
"""
def lbfgs_objective(adv_x, self, targets, oimgs, CONST):
""" returns the function value and the gradient for fmin_l_bfgs_b """
loss = self.sess.run(
self.loss,
feed_... | [
"Perform",
"the",
"attack",
"on",
"the",
"given",
"instance",
"for",
"the",
"given",
"targets",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/lbfgs.py#L166-L281 | [
"def",
"attack",
"(",
"self",
",",
"x_val",
",",
"targets",
")",
":",
"def",
"lbfgs_objective",
"(",
"adv_x",
",",
"self",
",",
"targets",
",",
"oimgs",
",",
"CONST",
")",
":",
"\"\"\" returns the function value and the gradient for fmin_l_bfgs_b \"\"\"",
"loss",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | MLPnGPU.set_device | Set the device before the next fprop to create a new graph on the
specified device. | examples/multigpu_advtrain/model.py | def set_device(self, device_name):
"""
Set the device before the next fprop to create a new graph on the
specified device.
"""
device_name = unify_device_name(device_name)
self.device_name = device_name
for layer in self.layers:
layer.device_name = device_name | def set_device(self, device_name):
"""
Set the device before the next fprop to create a new graph on the
specified device.
"""
device_name = unify_device_name(device_name)
self.device_name = device_name
for layer in self.layers:
layer.device_name = device_name | [
"Set",
"the",
"device",
"before",
"the",
"next",
"fprop",
"to",
"create",
"a",
"new",
"graph",
"on",
"the",
"specified",
"device",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/model.py#L206-L214 | [
"def",
"set_device",
"(",
"self",
",",
"device_name",
")",
":",
"device_name",
"=",
"unify_device_name",
"(",
"device_name",
")",
"self",
".",
"device_name",
"=",
"device_name",
"for",
"layer",
"in",
"self",
".",
"layers",
":",
"layer",
".",
"device_name",
"... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | MLPnGPU.create_sync_ops | Return a list of assignment operations that syncs the parameters
of all model copies with the one on host_device.
:param host_device: (required str) the name of the device with latest
parameters | examples/multigpu_advtrain/model.py | def create_sync_ops(self, host_device):
"""
Return a list of assignment operations that syncs the parameters
of all model copies with the one on host_device.
:param host_device: (required str) the name of the device with latest
parameters
"""
host_device = unify_device_na... | def create_sync_ops(self, host_device):
"""
Return a list of assignment operations that syncs the parameters
of all model copies with the one on host_device.
:param host_device: (required str) the name of the device with latest
parameters
"""
host_device = unify_device_na... | [
"Return",
"a",
"list",
"of",
"assignment",
"operations",
"that",
"syncs",
"the",
"parameters",
"of",
"all",
"model",
"copies",
"with",
"the",
"one",
"on",
"host_device",
".",
":",
"param",
"host_device",
":",
"(",
"required",
"str",
")",
"the",
"name",
"of... | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/model.py#L216-L228 | [
"def",
"create_sync_ops",
"(",
"self",
",",
"host_device",
")",
":",
"host_device",
"=",
"unify_device_name",
"(",
"host_device",
")",
"sync_ops",
"=",
"[",
"]",
"for",
"layer",
"in",
"self",
".",
"layers",
":",
"if",
"isinstance",
"(",
"layer",
",",
"Laye... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | LayernGPU.get_variable | Create and initialize a variable using a numpy array and set trainable.
:param name: (required str) name of the variable
:param initializer: a numpy array or a tensor | examples/multigpu_advtrain/model.py | def get_variable(self, name, initializer):
"""
Create and initialize a variable using a numpy array and set trainable.
:param name: (required str) name of the variable
:param initializer: a numpy array or a tensor
"""
v = tf.get_variable(name, shape=initializer.shape,
ini... | def get_variable(self, name, initializer):
"""
Create and initialize a variable using a numpy array and set trainable.
:param name: (required str) name of the variable
:param initializer: a numpy array or a tensor
"""
v = tf.get_variable(name, shape=initializer.shape,
ini... | [
"Create",
"and",
"initialize",
"a",
"variable",
"using",
"a",
"numpy",
"array",
"and",
"set",
"trainable",
".",
":",
"param",
"name",
":",
"(",
"required",
"str",
")",
"name",
"of",
"the",
"variable",
":",
"param",
"initializer",
":",
"a",
"numpy",
"arra... | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/model.py#L254-L264 | [
"def",
"get_variable",
"(",
"self",
",",
"name",
",",
"initializer",
")",
":",
"v",
"=",
"tf",
".",
"get_variable",
"(",
"name",
",",
"shape",
"=",
"initializer",
".",
"shape",
",",
"initializer",
"=",
"(",
"lambda",
"shape",
",",
"dtype",
",",
"partit... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | LayernGPU.set_input_shape_ngpu | Create and initialize layer parameters on the device previously set
in self.device_name.
:param new_input_shape: a list or tuple for the shape of the input. | examples/multigpu_advtrain/model.py | def set_input_shape_ngpu(self, new_input_shape):
"""
Create and initialize layer parameters on the device previously set
in self.device_name.
:param new_input_shape: a list or tuple for the shape of the input.
"""
assert self.device_name, "Device name has not been set."
device_name = self.... | def set_input_shape_ngpu(self, new_input_shape):
"""
Create and initialize layer parameters on the device previously set
in self.device_name.
:param new_input_shape: a list or tuple for the shape of the input.
"""
assert self.device_name, "Device name has not been set."
device_name = self.... | [
"Create",
"and",
"initialize",
"layer",
"parameters",
"on",
"the",
"device",
"previously",
"set",
"in",
"self",
".",
"device_name",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/model.py#L266-L297 | [
"def",
"set_input_shape_ngpu",
"(",
"self",
",",
"new_input_shape",
")",
":",
"assert",
"self",
".",
"device_name",
",",
"\"Device name has not been set.\"",
"device_name",
"=",
"self",
".",
"device_name",
"if",
"self",
".",
"input_shape",
"is",
"None",
":",
"# Fi... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | LayernGPU.create_sync_ops | Create an assignment operation for each weight on all devices. The
weight is assigned the value of the copy on the `host_device'. | examples/multigpu_advtrain/model.py | def create_sync_ops(self, host_device):
"""Create an assignment operation for each weight on all devices. The
weight is assigned the value of the copy on the `host_device'.
"""
sync_ops = []
host_params = self.params_device[host_device]
for device, params in (self.params_device).iteritems():
... | def create_sync_ops(self, host_device):
"""Create an assignment operation for each weight on all devices. The
weight is assigned the value of the copy on the `host_device'.
"""
sync_ops = []
host_params = self.params_device[host_device]
for device, params in (self.params_device).iteritems():
... | [
"Create",
"an",
"assignment",
"operation",
"for",
"each",
"weight",
"on",
"all",
"devices",
".",
"The",
"weight",
"is",
"assigned",
"the",
"value",
"of",
"the",
"copy",
"on",
"the",
"host_device",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/model.py#L299-L311 | [
"def",
"create_sync_ops",
"(",
"self",
",",
"host_device",
")",
":",
"sync_ops",
"=",
"[",
"]",
"host_params",
"=",
"self",
".",
"params_device",
"[",
"host_device",
"]",
"for",
"device",
",",
"params",
"in",
"(",
"self",
".",
"params_device",
")",
".",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | vatm | Tensorflow implementation of the perturbation method used for virtual
adversarial training: https://arxiv.org/abs/1507.00677
:param model: the model which returns the network unnormalized logits
:param x: the input placeholder
:param logits: the model's unnormalized output tensor (the input to
... | cleverhans/attacks/virtual_adversarial_method.py | def vatm(model,
x,
logits,
eps,
num_iterations=1,
xi=1e-6,
clip_min=None,
clip_max=None,
scope=None):
"""
Tensorflow implementation of the perturbation method used for virtual
adversarial training: https://arxiv.org/abs/1507.00677
:param mo... | def vatm(model,
x,
logits,
eps,
num_iterations=1,
xi=1e-6,
clip_min=None,
clip_max=None,
scope=None):
"""
Tensorflow implementation of the perturbation method used for virtual
adversarial training: https://arxiv.org/abs/1507.00677
:param mo... | [
"Tensorflow",
"implementation",
"of",
"the",
"perturbation",
"method",
"used",
"for",
"virtual",
"adversarial",
"training",
":",
"https",
":",
"//",
"arxiv",
".",
"org",
"/",
"abs",
"/",
"1507",
".",
"00677",
":",
"param",
"model",
":",
"the",
"model",
"wh... | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/virtual_adversarial_method.py#L107-L145 | [
"def",
"vatm",
"(",
"model",
",",
"x",
",",
"logits",
",",
"eps",
",",
"num_iterations",
"=",
"1",
",",
"xi",
"=",
"1e-6",
",",
"clip_min",
"=",
"None",
",",
"clip_max",
"=",
"None",
",",
"scope",
"=",
"None",
")",
":",
"with",
"tf",
".",
"name_s... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | VirtualAdversarialMethod.generate | Generate symbolic graph for adversarial examples and return.
:param x: The model's symbolic inputs.
:param kwargs: See `parse_params` | cleverhans/attacks/virtual_adversarial_method.py | def generate(self, x, **kwargs):
"""
Generate symbolic graph for adversarial examples and return.
:param x: The model's symbolic inputs.
:param kwargs: See `parse_params`
"""
# Parse and save attack-specific parameters
assert self.parse_params(**kwargs)
return vatm(
self.model,... | def generate(self, x, **kwargs):
"""
Generate symbolic graph for adversarial examples and return.
:param x: The model's symbolic inputs.
:param kwargs: See `parse_params`
"""
# Parse and save attack-specific parameters
assert self.parse_params(**kwargs)
return vatm(
self.model,... | [
"Generate",
"symbolic",
"graph",
"for",
"adversarial",
"examples",
"and",
"return",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/virtual_adversarial_method.py#L43-L61 | [
"def",
"generate",
"(",
"self",
",",
"x",
",",
"*",
"*",
"kwargs",
")",
":",
"# Parse and save attack-specific parameters",
"assert",
"self",
".",
"parse_params",
"(",
"*",
"*",
"kwargs",
")",
"return",
"vatm",
"(",
"self",
".",
"model",
",",
"x",
",",
"... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | VirtualAdversarialMethod.parse_params | Take in a dictionary of parameters and applies attack-specific checks
before saving them as attributes.
Attack-specific parameters:
:param eps: (optional float )the epsilon (input variation parameter)
:param nb_iter: (optional) the number of iterations
Defaults to 1 if not specified
:param x... | cleverhans/attacks/virtual_adversarial_method.py | def parse_params(self,
eps=2.0,
nb_iter=None,
xi=1e-6,
clip_min=None,
clip_max=None,
num_iterations=None,
**kwargs):
"""
Take in a dictionary of parameters and applies attack-spec... | def parse_params(self,
eps=2.0,
nb_iter=None,
xi=1e-6,
clip_min=None,
clip_max=None,
num_iterations=None,
**kwargs):
"""
Take in a dictionary of parameters and applies attack-spec... | [
"Take",
"in",
"a",
"dictionary",
"of",
"parameters",
"and",
"applies",
"attack",
"-",
"specific",
"checks",
"before",
"saving",
"them",
"as",
"attributes",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/virtual_adversarial_method.py#L63-L104 | [
"def",
"parse_params",
"(",
"self",
",",
"eps",
"=",
"2.0",
",",
"nb_iter",
"=",
"None",
",",
"xi",
"=",
"1e-6",
",",
"clip_min",
"=",
"None",
",",
"clip_max",
"=",
"None",
",",
"num_iterations",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# S... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | iterate_with_exp_backoff | Iterate with exponential backoff on failures.
Useful to wrap results of datastore Query.fetch to avoid 429 error.
Args:
base_iter: basic iterator of generator object
max_num_tries: maximum number of tries for each request
max_backoff: maximum backoff, in seconds
start_backoff: initial value of bac... | examples/nips17_adversarial_competition/eval_infra/code/eval_lib/cloud_client.py | def iterate_with_exp_backoff(base_iter,
max_num_tries=6,
max_backoff=300.0,
start_backoff=4.0,
backoff_multiplier=2.0,
frac_random_backoff=0.25):
"""Iterate with exponential... | def iterate_with_exp_backoff(base_iter,
max_num_tries=6,
max_backoff=300.0,
start_backoff=4.0,
backoff_multiplier=2.0,
frac_random_backoff=0.25):
"""Iterate with exponential... | [
"Iterate",
"with",
"exponential",
"backoff",
"on",
"failures",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/cloud_client.py#L167-L209 | [
"def",
"iterate_with_exp_backoff",
"(",
"base_iter",
",",
"max_num_tries",
"=",
"6",
",",
"max_backoff",
"=",
"300.0",
",",
"start_backoff",
"=",
"4.0",
",",
"backoff_multiplier",
"=",
"2.0",
",",
"frac_random_backoff",
"=",
"0.25",
")",
":",
"try_number",
"=",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | CompetitionStorageClient.list_blobs | Lists names of all blobs by their prefix. | examples/nips17_adversarial_competition/eval_infra/code/eval_lib/cloud_client.py | def list_blobs(self, prefix=''):
"""Lists names of all blobs by their prefix."""
return [b.name for b in self.bucket.list_blobs(prefix=prefix)] | def list_blobs(self, prefix=''):
"""Lists names of all blobs by their prefix."""
return [b.name for b in self.bucket.list_blobs(prefix=prefix)] | [
"Lists",
"names",
"of",
"all",
"blobs",
"by",
"their",
"prefix",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/cloud_client.py#L43-L45 | [
"def",
"list_blobs",
"(",
"self",
",",
"prefix",
"=",
"''",
")",
":",
"return",
"[",
"b",
".",
"name",
"for",
"b",
"in",
"self",
".",
"bucket",
".",
"list_blobs",
"(",
"prefix",
"=",
"prefix",
")",
"]"
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | NoTransactionBatch.begin | Begins a batch. | examples/nips17_adversarial_competition/eval_infra/code/eval_lib/cloud_client.py | def begin(self):
"""Begins a batch."""
if self._cur_batch:
raise ValueError('Previous batch is not committed.')
self._cur_batch = self._client.batch()
self._cur_batch.begin()
self._num_mutations = 0 | def begin(self):
"""Begins a batch."""
if self._cur_batch:
raise ValueError('Previous batch is not committed.')
self._cur_batch = self._client.batch()
self._cur_batch.begin()
self._num_mutations = 0 | [
"Begins",
"a",
"batch",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/cloud_client.py#L93-L99 | [
"def",
"begin",
"(",
"self",
")",
":",
"if",
"self",
".",
"_cur_batch",
":",
"raise",
"ValueError",
"(",
"'Previous batch is not committed.'",
")",
"self",
".",
"_cur_batch",
"=",
"self",
".",
"_client",
".",
"batch",
"(",
")",
"self",
".",
"_cur_batch",
"... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | NoTransactionBatch.rollback | Rolls back pending mutations.
Keep in mind that NoTransactionBatch splits all mutations into smaller
batches and commit them as soon as mutation buffer reaches maximum length.
That's why rollback method will only roll back pending mutations from the
buffer, but won't be able to rollback already committ... | examples/nips17_adversarial_competition/eval_infra/code/eval_lib/cloud_client.py | def rollback(self):
"""Rolls back pending mutations.
Keep in mind that NoTransactionBatch splits all mutations into smaller
batches and commit them as soon as mutation buffer reaches maximum length.
That's why rollback method will only roll back pending mutations from the
buffer, but won't be able ... | def rollback(self):
"""Rolls back pending mutations.
Keep in mind that NoTransactionBatch splits all mutations into smaller
batches and commit them as soon as mutation buffer reaches maximum length.
That's why rollback method will only roll back pending mutations from the
buffer, but won't be able ... | [
"Rolls",
"back",
"pending",
"mutations",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/cloud_client.py#L107-L122 | [
"def",
"rollback",
"(",
"self",
")",
":",
"try",
":",
"if",
"self",
".",
"_cur_batch",
":",
"self",
".",
"_cur_batch",
".",
"rollback",
"(",
")",
"except",
"ValueError",
":",
"# ignore \"Batch must be in progress to rollback\" error",
"pass",
"self",
".",
"_cur_... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | NoTransactionBatch.put | Adds mutation of the entity to the mutation buffer.
If mutation buffer reaches its capacity then this method commit all pending
mutations from the buffer and emties it.
Args:
entity: entity which should be put into the datastore | examples/nips17_adversarial_competition/eval_infra/code/eval_lib/cloud_client.py | def put(self, entity):
"""Adds mutation of the entity to the mutation buffer.
If mutation buffer reaches its capacity then this method commit all pending
mutations from the buffer and emties it.
Args:
entity: entity which should be put into the datastore
"""
self._cur_batch.put(entity)
... | def put(self, entity):
"""Adds mutation of the entity to the mutation buffer.
If mutation buffer reaches its capacity then this method commit all pending
mutations from the buffer and emties it.
Args:
entity: entity which should be put into the datastore
"""
self._cur_batch.put(entity)
... | [
"Adds",
"mutation",
"of",
"the",
"entity",
"to",
"the",
"mutation",
"buffer",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/cloud_client.py#L124-L137 | [
"def",
"put",
"(",
"self",
",",
"entity",
")",
":",
"self",
".",
"_cur_batch",
".",
"put",
"(",
"entity",
")",
"self",
".",
"_num_mutations",
"+=",
"1",
"if",
"self",
".",
"_num_mutations",
">=",
"MAX_MUTATIONS_IN_BATCH",
":",
"self",
".",
"commit",
"(",... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | NoTransactionBatch.delete | Adds deletion of the entity with given key to the mutation buffer.
If mutation buffer reaches its capacity then this method commit all pending
mutations from the buffer and emties it.
Args:
key: key of the entity which should be deleted | examples/nips17_adversarial_competition/eval_infra/code/eval_lib/cloud_client.py | def delete(self, key):
"""Adds deletion of the entity with given key to the mutation buffer.
If mutation buffer reaches its capacity then this method commit all pending
mutations from the buffer and emties it.
Args:
key: key of the entity which should be deleted
"""
self._cur_batch.delet... | def delete(self, key):
"""Adds deletion of the entity with given key to the mutation buffer.
If mutation buffer reaches its capacity then this method commit all pending
mutations from the buffer and emties it.
Args:
key: key of the entity which should be deleted
"""
self._cur_batch.delet... | [
"Adds",
"deletion",
"of",
"the",
"entity",
"with",
"given",
"key",
"to",
"the",
"mutation",
"buffer",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/cloud_client.py#L139-L152 | [
"def",
"delete",
"(",
"self",
",",
"key",
")",
":",
"self",
".",
"_cur_batch",
".",
"delete",
"(",
"key",
")",
"self",
".",
"_num_mutations",
"+=",
"1",
"if",
"self",
".",
"_num_mutations",
">=",
"MAX_MUTATIONS_IN_BATCH",
":",
"self",
".",
"commit",
"(",... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | CompetitionDatastoreClient.get | Retrieves an entity given its key. | examples/nips17_adversarial_competition/eval_infra/code/eval_lib/cloud_client.py | def get(self, key, transaction=None):
"""Retrieves an entity given its key."""
return self._client.get(key, transaction=transaction) | def get(self, key, transaction=None):
"""Retrieves an entity given its key."""
return self._client.get(key, transaction=transaction) | [
"Retrieves",
"an",
"entity",
"given",
"its",
"key",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/cloud_client.py#L239-L241 | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"transaction",
"=",
"None",
")",
":",
"return",
"self",
".",
"_client",
".",
"get",
"(",
"key",
",",
"transaction",
"=",
"transaction",
")"
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | mnist_tutorial_cw | MNIST tutorial for Carlini and Wagner's attack
: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) activate plots of adversa... | cleverhans_tutorials/mnist_tutorial_cw.py | def mnist_tutorial_cw(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_cw(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,
... | [
"MNIST",
"tutorial",
"for",
"Carlini",
"and",
"Wagner",
"s",
"attack",
":",
"param",
"train_start",
":",
"index",
"of",
"first",
"training",
"set",
"example",
":",
"param",
"train_end",
":",
"index",
"of",
"last",
"training",
"set",
"example",
":",
"param",
... | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans_tutorials/mnist_tutorial_cw.py#L41-L235 | [
"def",
"mnist_tutorial_cw",
"(",
"train_start",
"=",
"0",
",",
"train_end",
"=",
"60000",
",",
"test_start",
"=",
"0",
",",
"test_end",
"=",
"10000",
",",
"viz_enabled",
"=",
"VIZ_ENABLED",
",",
"nb_epochs",
"=",
"NB_EPOCHS",
",",
"batch_size",
"=",
"BATCH_S... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | attack_selection | Selects the Attack Class using string input.
:param attack_string: adversarial attack name in string format
:return: attack class defined in cleverhans.attacks_eager | cleverhans_tutorials/mnist_tutorial_tfe.py | def attack_selection(attack_string):
"""
Selects the Attack Class using string input.
:param attack_string: adversarial attack name in string format
:return: attack class defined in cleverhans.attacks_eager
"""
# List of Implemented attacks
attacks_list = AVAILABLE_ATTACKS.keys()
# Checking for reque... | def attack_selection(attack_string):
"""
Selects the Attack Class using string input.
:param attack_string: adversarial attack name in string format
:return: attack class defined in cleverhans.attacks_eager
"""
# List of Implemented attacks
attacks_list = AVAILABLE_ATTACKS.keys()
# Checking for reque... | [
"Selects",
"the",
"Attack",
"Class",
"using",
"string",
"input",
".",
":",
"param",
"attack_string",
":",
"adversarial",
"attack",
"name",
"in",
"string",
"format",
":",
"return",
":",
"attack",
"class",
"defined",
"in",
"cleverhans",
".",
"attacks_eager"
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans_tutorials/mnist_tutorial_tfe.py#L54-L73 | [
"def",
"attack_selection",
"(",
"attack_string",
")",
":",
"# List of Implemented attacks",
"attacks_list",
"=",
"AVAILABLE_ATTACKS",
".",
"keys",
"(",
")",
"# Checking for requested attack in list of available attacks.",
"if",
"attack_string",
"is",
"None",
":",
"raise",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | mnist_tutorial | MNIST cleverhans tutorial
:param train_start: index of first training set example.
:param train_end: index of last training set example.
:param test_start: index of first test set example.
:param test_end: index of last test set example.
:param nb_epochs: number of epochs to train model.
:param batch_size: ... | cleverhans_tutorials/mnist_tutorial_tfe.py | def mnist_tutorial(train_start=0, train_end=60000, test_start=0,
test_end=10000, nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE,
learning_rate=LEARNING_RATE,
clean_train=True,
testing=False,
backprop_through_attack=False,
... | def mnist_tutorial(train_start=0, train_end=60000, test_start=0,
test_end=10000, nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE,
learning_rate=LEARNING_RATE,
clean_train=True,
testing=False,
backprop_through_attack=False,
... | [
"MNIST",
"cleverhans",
"tutorial",
":",
"param",
"train_start",
":",
"index",
"of",
"first",
"training",
"set",
"example",
".",
":",
"param",
"train_end",
":",
"index",
"of",
"last",
"training",
"set",
"example",
".",
":",
"param",
"test_start",
":",
"index"... | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans_tutorials/mnist_tutorial_tfe.py#L76-L219 | [
"def",
"mnist_tutorial",
"(",
"train_start",
"=",
"0",
",",
"train_end",
"=",
"60000",
",",
"test_start",
"=",
"0",
",",
"test_end",
"=",
"10000",
",",
"nb_epochs",
"=",
"NB_EPOCHS",
",",
"batch_size",
"=",
"BATCH_SIZE",
",",
"learning_rate",
"=",
"LEARNING_... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | sudo_remove_dirtree | Removes directory tree as a superuser.
Args:
dir_name: name of the directory to remove.
This function is necessary to cleanup directories created from inside a
Docker, since they usually written as a root, thus have to be removed as a
root. | examples/nips17_adversarial_competition/eval_infra/code/worker.py | def sudo_remove_dirtree(dir_name):
"""Removes directory tree as a superuser.
Args:
dir_name: name of the directory to remove.
This function is necessary to cleanup directories created from inside a
Docker, since they usually written as a root, thus have to be removed as a
root.
"""
try:
subproce... | def sudo_remove_dirtree(dir_name):
"""Removes directory tree as a superuser.
Args:
dir_name: name of the directory to remove.
This function is necessary to cleanup directories created from inside a
Docker, since they usually written as a root, thus have to be removed as a
root.
"""
try:
subproce... | [
"Removes",
"directory",
"tree",
"as",
"a",
"superuser",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L116-L129 | [
"def",
"sudo_remove_dirtree",
"(",
"dir_name",
")",
":",
"try",
":",
"subprocess",
".",
"check_output",
"(",
"[",
"'sudo'",
",",
"'rm'",
",",
"'-rf'",
",",
"dir_name",
"]",
")",
"except",
"subprocess",
".",
"CalledProcessError",
"as",
"e",
":",
"raise",
"W... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | main | Main function which runs worker. | examples/nips17_adversarial_competition/eval_infra/code/worker.py | def main(args):
"""Main function which runs worker."""
title = '## Starting evaluation of round {0} ##'.format(args.round_name)
logging.info('\n'
+ '#' * len(title) + '\n'
+ '#' * len(title) + '\n'
+ '##' + ' ' * (len(title)-2) + '##' + '\n'
+ title + '\... | def main(args):
"""Main function which runs worker."""
title = '## Starting evaluation of round {0} ##'.format(args.round_name)
logging.info('\n'
+ '#' * len(title) + '\n'
+ '#' * len(title) + '\n'
+ '##' + ' ' * (len(title)-2) + '##' + '\n'
+ title + '\... | [
"Main",
"function",
"which",
"runs",
"worker",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L900-L929 | [
"def",
"main",
"(",
"args",
")",
":",
"title",
"=",
"'## Starting evaluation of round {0} ##'",
".",
"format",
"(",
"args",
".",
"round_name",
")",
"logging",
".",
"info",
"(",
"'\\n'",
"+",
"'#'",
"*",
"len",
"(",
"title",
")",
"+",
"'\\n'",
"+",
"'#'",... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | ExecutableSubmission.download | Method which downloads submission to local directory. | examples/nips17_adversarial_competition/eval_infra/code/worker.py | 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):
"""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... | [
"Method",
"which",
"downloads",
"submission",
"to",
"local",
"directory",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L211-L309 | [
"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... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | ExecutableSubmission.temp_copy_extracted_submission | 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:
... | examples/nips17_adversarial_competition/eval_infra/code/worker.py | 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):
"""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... | [
"Creates",
"a",
"temporary",
"copy",
"of",
"extracted",
"submission",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L311-L325 | [
"def",
"temp_copy_extracted_submission",
"(",
"self",
")",
":",
"tmp_copy_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"submission_dir",
",",
"'tmp_copy'",
")",
"shell_call",
"(",
"[",
"'cp'",
",",
"'-R'",
",",
"os",
".",
"path",
".",
"jo... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | ExecutableSubmission.run_without_time_limit | 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 | examples/nips17_adversarial_competition/eval_infra/code/worker.py | 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):
"""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 ... | [
"Runs",
"docker",
"command",
"without",
"time",
"limit",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L327-L350 | [
"def",
"run_without_time_limit",
"(",
"self",
",",
"cmd",
")",
":",
"cmd",
"=",
"[",
"DOCKER_BINARY",
",",
"'run'",
",",
"DOCKER_NVIDIA_RUNTIME",
"]",
"+",
"cmd",
"logging",
".",
"info",
"(",
"'Docker command: %s'",
",",
"' '",
".",
"join",
"(",
"cmd",
")"... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | ExecutableSubmission.run_with_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:
how long it took to run submission in seconds
Raises:
Worker... | examples/nips17_adversarial_competition/eval_infra/code/worker.py | 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):
"""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:
... | [
"Runs",
"docker",
"command",
"and",
"enforces",
"time",
"limit",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L352-L388 | [
"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",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | AttackSubmission.run | Runs attack inside Docker.
Args:
input_dir: directory with input (dataset).
output_dir: directory where output (adversarial images) should be written.
epsilon: maximum allowed size of adversarial perturbation,
should be in range [0, 255].
Returns:
how long it took to run submis... | examples/nips17_adversarial_competition/eval_infra/code/worker.py | def run(self, input_dir, output_dir, epsilon):
"""Runs attack inside Docker.
Args:
input_dir: directory with input (dataset).
output_dir: directory where output (adversarial images) should be written.
epsilon: maximum allowed size of adversarial perturbation,
should be in range [0, 25... | def run(self, input_dir, output_dir, epsilon):
"""Runs attack inside Docker.
Args:
input_dir: directory with input (dataset).
output_dir: directory where output (adversarial images) should be written.
epsilon: maximum allowed size of adversarial perturbation,
should be in range [0, 25... | [
"Runs",
"attack",
"inside",
"Docker",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L411-L439 | [
"def",
"run",
"(",
"self",
",",
"input_dir",
",",
"output_dir",
",",
"epsilon",
")",
":",
"logging",
".",
"info",
"(",
"'Running attack %s'",
",",
"self",
".",
"submission_id",
")",
"tmp_run_dir",
"=",
"self",
".",
"temp_copy_extracted_submission",
"(",
")",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | DefenseSubmission.run | 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 | examples/nips17_adversarial_competition/eval_infra/code/worker.py | 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):
"""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... | [
"Runs",
"defense",
"inside",
"Docker",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L462-L489 | [
"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"... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | EvaluationWorker.read_dataset_metadata | Read `dataset_meta` field from bucket | examples/nips17_adversarial_competition/eval_infra/code/worker.py | 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):
"""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... | [
"Read",
"dataset_meta",
"field",
"from",
"bucket"
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L556-L565 | [
"def",
"read_dataset_metadata",
"(",
"self",
")",
":",
"if",
"self",
".",
"dataset_meta",
":",
"return",
"shell_call",
"(",
"[",
"'gsutil'",
",",
"'cp'",
",",
"'gs://'",
"+",
"self",
".",
"storage_client",
".",
"bucket_name",
"+",
"'/'",
"+",
"'dataset/'",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | EvaluationWorker.fetch_attacks_data | Initializes data necessary to execute attacks.
This method could be called multiple times, only first call does
initialization, subsequent calls are noop. | examples/nips17_adversarial_competition/eval_infra/code/worker.py | 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):
"""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... | [
"Initializes",
"data",
"necessary",
"to",
"execute",
"attacks",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L567-L589 | [
"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"... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | EvaluationWorker.run_attack_work | 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. | examples/nips17_adversarial_competition/eval_infra/code/worker.py | 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):
"""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... | [
"Runs",
"one",
"attack",
"work",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L591-L687 | [
"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... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | EvaluationWorker.run_attacks | Method which evaluates all attack work.
In a loop this method queries not completed attack work, picks one
attack work and runs it. | examples/nips17_adversarial_competition/eval_infra/code/worker.py | 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):
"""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... | [
"Method",
"which",
"evaluates",
"all",
"attack",
"work",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L689-L732 | [
"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... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | EvaluationWorker.fetch_defense_data | Lazy initialization of data necessary to execute defenses. | examples/nips17_adversarial_competition/eval_infra/code/worker.py | 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):
"""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... | [
"Lazy",
"initialization",
"of",
"data",
"necessary",
"to",
"execute",
"defenses",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L734-L746 | [
"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... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | EvaluationWorker.run_defense_work | 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. | examples/nips17_adversarial_competition/eval_infra/code/worker.py | 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):
"""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 = (
... | [
"Runs",
"one",
"defense",
"work",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L748-L824 | [
"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",
".... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | EvaluationWorker.run_defenses | Method which evaluates all defense work.
In a loop this method queries not completed defense work,
picks one defense work and runs it. | examples/nips17_adversarial_competition/eval_infra/code/worker.py | 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):
"""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... | [
"Method",
"which",
"evaluates",
"all",
"defense",
"work",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L826-L890 | [
"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... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | EvaluationWorker.run_work | Run attacks and defenses | examples/nips17_adversarial_competition/eval_infra/code/worker.py | 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):
"""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() | [
"Run",
"attacks",
"and",
"defenses"
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L892-L897 | [
"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",
"(",
")"
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | arg_type | 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... | cleverhans/attacks/attack.py | 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):
"""
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... | [
"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",
... | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/attack.py#L304-L347 | [
"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",
"=",
"[",
"]",
"... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | Attack.construct_graph | 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... | cleverhans/attacks/attack.py | 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):
"""
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... | [
"Construct",
"the",
"graph",
"required",
"to",
"run",
"the",
"attack",
"through",
"generate_np",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/attack.py#L113-L165 | [
"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",
"=... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | Attack.generate_np | 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... | cleverhans/attacks/attack.py | 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):
"""
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... | [
"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",
... | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/attack.py#L167-L200 | [
"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",
".",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | Attack.construct_variables | 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 | cleverhans/attacks/attack.py | 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):
"""
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",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/attack.py#L202-L258 | [
"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.\"",
"\... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | Attack.get_or_guess_labels | Get the label to use in generating an adversarial example for x.
The kwargs are fed directly from the kwargs of the attack.
If 'y' is in kwargs, then assume it's an untargeted attack and
use that as the label.
If 'y_target' is in kwargs and is not none, then assume it's a
targeted attack and use tha... | cleverhans/attacks/attack.py | 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):
"""
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... | [
"Get",
"the",
"label",
"to",
"use",
"in",
"generating",
"an",
"adversarial",
"example",
"for",
"x",
".",
"The",
"kwargs",
"are",
"fed",
"directly",
"from",
"the",
"kwargs",
"of",
"the",
"attack",
".",
"If",
"y",
"is",
"in",
"kwargs",
"then",
"assume",
... | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/attack.py#L260-L287 | [
"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",
":"... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | dueling_model | As described in https://arxiv.org/abs/1511.06581 | examples/RL-attack/model.py | 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):
"""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... | [
"As",
"described",
"in",
"https",
":",
"//",
"arxiv",
".",
"org",
"/",
"abs",
"/",
"1511",
".",
"06581"
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/RL-attack/model.py#L38-L95 | [
"def",
"dueling_model",
"(",
"img_in",
",",
"num_actions",
",",
"scope",
",",
"noisy",
"=",
"False",
",",
"reuse",
"=",
"False",
",",
"concat_softmax",
"=",
"False",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"scope",
",",
"reuse",
"=",
"reuse",... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | mnist_tutorial_jsma | 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... | cleverhans_tutorials/mnist_tutorial_jsma.py | 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_SIZE,
source_samples=SOURCE_SAMPLES,
learning_rate=LEARNING_RATE):
"""
... | [
"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... | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans_tutorials/mnist_tutorial_jsma.py#L37-L208 | [
"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... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | MomentumIterativeMethod.generate | Generate symbolic graph for adversarial examples and return.
:param x: The model's symbolic inputs.
:param kwargs: Keyword arguments. See `parse_params` for documentation. | cleverhans/attacks/momentum_iterative_method.py | 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):
"""
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)... | [
"Generate",
"symbolic",
"graph",
"for",
"adversarial",
"examples",
"and",
"return",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/momentum_iterative_method.py#L43-L123 | [
"def",
"generate",
"(",
"self",
",",
"x",
",",
"*",
"*",
"kwargs",
")",
":",
"# Parse and save attack-specific parameters",
"assert",
"self",
".",
"parse_params",
"(",
"*",
"*",
"kwargs",
")",
"asserts",
"=",
"[",
"]",
"# If a data range was specified, check that ... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | MomentumIterativeMethod.parse_params | Take in a dictionary of parameters and applies attack-specific checks
before saving them as attributes.
Attack-specific parameters:
:param eps: (optional float) maximum distortion of adversarial example
compared to original input
:param eps_iter: (optional float) step size for each att... | cleverhans/attacks/momentum_iterative_method.py | 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,
clip_max=None,
y_target=None,
... | [
"Take",
"in",
"a",
"dictionary",
"of",
"parameters",
"and",
"applies",
"attack",
"-",
"specific",
"checks",
"before",
"saving",
"them",
"as",
"attributes",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/momentum_iterative_method.py#L125-L180 | [
"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... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | train | 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... | cleverhans/train.py | 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, 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... | [
"Run",
"(",
"optionally",
"multi",
"-",
"replica",
"synchronous",
")",
"training",
"to",
"minimize",
"loss",
":",
"param",
"sess",
":",
"TF",
"session",
"to",
"use",
"when",
"training",
"the",
"graph",
":",
"param",
"loss",
":",
"tensor",
"the",
"loss",
... | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/train.py#L38-L274 | [
"def",
"train",
"(",
"sess",
",",
"loss",
",",
"x_train",
",",
"y_train",
",",
"init_all",
"=",
"False",
",",
"evaluate",
"=",
"None",
",",
"feed",
"=",
"None",
",",
"args",
"=",
"None",
",",
"rng",
"=",
"None",
",",
"var_list",
"=",
"None",
",",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.