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 | SubmissionValidator._extract_submission | Extracts submission and moves it into self._extracted_submission_dir. | examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_submission_lib.py | def _extract_submission(self, filename):
"""Extracts submission and moves it into self._extracted_submission_dir."""
# verify filesize
file_size = os.path.getsize(filename)
if file_size > MAX_SUBMISSION_SIZE_ZIPPED:
logging.error('Submission archive size %d is exceeding limit %d',
... | def _extract_submission(self, filename):
"""Extracts submission and moves it into self._extracted_submission_dir."""
# verify filesize
file_size = os.path.getsize(filename)
if file_size > MAX_SUBMISSION_SIZE_ZIPPED:
logging.error('Submission archive size %d is exceeding limit %d',
... | [
"Extracts",
"submission",
"and",
"moves",
"it",
"into",
"self",
".",
"_extracted_submission_dir",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_submission_lib.py#L148-L194 | [
"def",
"_extract_submission",
"(",
"self",
",",
"filename",
")",
":",
"# verify filesize",
"file_size",
"=",
"os",
".",
"path",
".",
"getsize",
"(",
"filename",
")",
"if",
"file_size",
">",
"MAX_SUBMISSION_SIZE_ZIPPED",
":",
"logging",
".",
"error",
"(",
"'Sub... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | SubmissionValidator._verify_docker_image_size | Verifies size of Docker image.
Args:
image_name: name of the Docker image.
Returns:
True if image size is within the limits, False otherwise. | examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_submission_lib.py | def _verify_docker_image_size(self, image_name):
"""Verifies size of Docker image.
Args:
image_name: name of the Docker image.
Returns:
True if image size is within the limits, False otherwise.
"""
shell_call(['docker', 'pull', image_name])
try:
image_size = subprocess.check_... | def _verify_docker_image_size(self, image_name):
"""Verifies size of Docker image.
Args:
image_name: name of the Docker image.
Returns:
True if image size is within the limits, False otherwise.
"""
shell_call(['docker', 'pull', image_name])
try:
image_size = subprocess.check_... | [
"Verifies",
"size",
"of",
"Docker",
"image",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_submission_lib.py#L247-L267 | [
"def",
"_verify_docker_image_size",
"(",
"self",
",",
"image_name",
")",
":",
"shell_call",
"(",
"[",
"'docker'",
",",
"'pull'",
",",
"image_name",
"]",
")",
"try",
":",
"image_size",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"'docker'",
",",
"'inspe... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | SubmissionValidator._prepare_sample_data | Prepares sample data for the submission.
Args:
submission_type: type of the submission. | examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_submission_lib.py | def _prepare_sample_data(self, submission_type):
"""Prepares sample data for the submission.
Args:
submission_type: type of the submission.
"""
# write images
images = np.random.randint(0, 256,
size=[BATCH_SIZE, 299, 299, 3], dtype=np.uint8)
for i in range(B... | def _prepare_sample_data(self, submission_type):
"""Prepares sample data for the submission.
Args:
submission_type: type of the submission.
"""
# write images
images = np.random.randint(0, 256,
size=[BATCH_SIZE, 299, 299, 3], dtype=np.uint8)
for i in range(B... | [
"Prepares",
"sample",
"data",
"for",
"the",
"submission",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_submission_lib.py#L269-L288 | [
"def",
"_prepare_sample_data",
"(",
"self",
",",
"submission_type",
")",
":",
"# write images",
"images",
"=",
"np",
".",
"random",
".",
"randint",
"(",
"0",
",",
"256",
",",
"size",
"=",
"[",
"BATCH_SIZE",
",",
"299",
",",
"299",
",",
"3",
"]",
",",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | SubmissionValidator._verify_output | Verifies correctness of the submission output.
Args:
submission_type: type of the submission
Returns:
True if output looks valid | examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_submission_lib.py | def _verify_output(self, submission_type):
"""Verifies correctness of the submission output.
Args:
submission_type: type of the submission
Returns:
True if output looks valid
"""
result = True
if submission_type == 'defense':
try:
image_classification = load_defense_o... | def _verify_output(self, submission_type):
"""Verifies correctness of the submission output.
Args:
submission_type: type of the submission
Returns:
True if output looks valid
"""
result = True
if submission_type == 'defense':
try:
image_classification = load_defense_o... | [
"Verifies",
"correctness",
"of",
"the",
"submission",
"output",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_submission_lib.py#L336-L370 | [
"def",
"_verify_output",
"(",
"self",
",",
"submission_type",
")",
":",
"result",
"=",
"True",
"if",
"submission_type",
"==",
"'defense'",
":",
"try",
":",
"image_classification",
"=",
"load_defense_output",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | SubmissionValidator.validate_submission | Validates submission.
Args:
filename: submission filename
Returns:
submission metadata or None if submission is invalid | examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_submission_lib.py | def validate_submission(self, filename):
"""Validates submission.
Args:
filename: submission filename
Returns:
submission metadata or None if submission is invalid
"""
self._prepare_temp_dir()
# Convert filename to be absolute path, relative path might cause problems
# with mou... | def validate_submission(self, filename):
"""Validates submission.
Args:
filename: submission filename
Returns:
submission metadata or None if submission is invalid
"""
self._prepare_temp_dir()
# Convert filename to be absolute path, relative path might cause problems
# with mou... | [
"Validates",
"submission",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_submission_lib.py#L372-L408 | [
"def",
"validate_submission",
"(",
"self",
",",
"filename",
")",
":",
"self",
".",
"_prepare_temp_dir",
"(",
")",
"# Convert filename to be absolute path, relative path might cause problems",
"# with mounting directory in Docker",
"filename",
"=",
"os",
".",
"path",
".",
"a... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | Loss.save | Save loss in json format | cleverhans/loss.py | def save(self, path):
"""Save loss in json format
"""
json.dump(dict(loss=self.__class__.__name__,
params=self.hparams),
open(os.path.join(path, 'loss.json'), 'wb')) | def save(self, path):
"""Save loss in json format
"""
json.dump(dict(loss=self.__class__.__name__,
params=self.hparams),
open(os.path.join(path, 'loss.json'), 'wb')) | [
"Save",
"loss",
"in",
"json",
"format"
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/loss.py#L66-L71 | [
"def",
"save",
"(",
"self",
",",
"path",
")",
":",
"json",
".",
"dump",
"(",
"dict",
"(",
"loss",
"=",
"self",
".",
"__class__",
".",
"__name__",
",",
"params",
"=",
"self",
".",
"hparams",
")",
",",
"open",
"(",
"os",
".",
"path",
".",
"join",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | SNNLCrossEntropy.pairwise_euclid_distance | Pairwise Euclidean distance between two matrices.
:param A: a matrix.
:param B: a matrix.
:returns: A tensor for the pairwise Euclidean between A and B. | cleverhans/loss.py | def pairwise_euclid_distance(A, B):
"""Pairwise Euclidean distance between two matrices.
:param A: a matrix.
:param B: a matrix.
:returns: A tensor for the pairwise Euclidean between A and B.
"""
batchA = tf.shape(A)[0]
batchB = tf.shape(B)[0]
sqr_norm_A = tf.reshape(tf.reduce_sum(tf.p... | def pairwise_euclid_distance(A, B):
"""Pairwise Euclidean distance between two matrices.
:param A: a matrix.
:param B: a matrix.
:returns: A tensor for the pairwise Euclidean between A and B.
"""
batchA = tf.shape(A)[0]
batchB = tf.shape(B)[0]
sqr_norm_A = tf.reshape(tf.reduce_sum(tf.p... | [
"Pairwise",
"Euclidean",
"distance",
"between",
"two",
"matrices",
".",
":",
"param",
"A",
":",
"a",
"matrix",
".",
":",
"param",
"B",
":",
"a",
"matrix",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/loss.py#L376-L392 | [
"def",
"pairwise_euclid_distance",
"(",
"A",
",",
"B",
")",
":",
"batchA",
"=",
"tf",
".",
"shape",
"(",
"A",
")",
"[",
"0",
"]",
"batchB",
"=",
"tf",
".",
"shape",
"(",
"B",
")",
"[",
"0",
"]",
"sqr_norm_A",
"=",
"tf",
".",
"reshape",
"(",
"tf... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | SNNLCrossEntropy.pairwise_cos_distance | Pairwise cosine distance between two matrices.
:param A: a matrix.
:param B: a matrix.
:returns: A tensor for the pairwise cosine between A and B. | cleverhans/loss.py | def pairwise_cos_distance(A, B):
"""Pairwise cosine distance between two matrices.
:param A: a matrix.
:param B: a matrix.
:returns: A tensor for the pairwise cosine between A and B.
"""
normalized_A = tf.nn.l2_normalize(A, dim=1)
normalized_B = tf.nn.l2_normalize(B, dim=1)
prod = tf.ma... | def pairwise_cos_distance(A, B):
"""Pairwise cosine distance between two matrices.
:param A: a matrix.
:param B: a matrix.
:returns: A tensor for the pairwise cosine between A and B.
"""
normalized_A = tf.nn.l2_normalize(A, dim=1)
normalized_B = tf.nn.l2_normalize(B, dim=1)
prod = tf.ma... | [
"Pairwise",
"cosine",
"distance",
"between",
"two",
"matrices",
".",
":",
"param",
"A",
":",
"a",
"matrix",
".",
":",
"param",
"B",
":",
"a",
"matrix",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/loss.py#L395-L405 | [
"def",
"pairwise_cos_distance",
"(",
"A",
",",
"B",
")",
":",
"normalized_A",
"=",
"tf",
".",
"nn",
".",
"l2_normalize",
"(",
"A",
",",
"dim",
"=",
"1",
")",
"normalized_B",
"=",
"tf",
".",
"nn",
".",
"l2_normalize",
"(",
"B",
",",
"dim",
"=",
"1",... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | SNNLCrossEntropy.fits | Exponentiated pairwise distance between each element of A and
all those of B.
:param A: a matrix.
:param B: a matrix.
:param temp: Temperature
:cos_distance: Boolean for using cosine or Euclidean distance.
:returns: A tensor for the exponentiated pairwise distance between
each element and A... | cleverhans/loss.py | def fits(A, B, temp, cos_distance):
"""Exponentiated pairwise distance between each element of A and
all those of B.
:param A: a matrix.
:param B: a matrix.
:param temp: Temperature
:cos_distance: Boolean for using cosine or Euclidean distance.
:returns: A tensor for the exponentiated pairw... | def fits(A, B, temp, cos_distance):
"""Exponentiated pairwise distance between each element of A and
all those of B.
:param A: a matrix.
:param B: a matrix.
:param temp: Temperature
:cos_distance: Boolean for using cosine or Euclidean distance.
:returns: A tensor for the exponentiated pairw... | [
"Exponentiated",
"pairwise",
"distance",
"between",
"each",
"element",
"of",
"A",
"and",
"all",
"those",
"of",
"B",
".",
":",
"param",
"A",
":",
"a",
"matrix",
".",
":",
"param",
"B",
":",
"a",
"matrix",
".",
":",
"param",
"temp",
":",
"Temperature",
... | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/loss.py#L408-L423 | [
"def",
"fits",
"(",
"A",
",",
"B",
",",
"temp",
",",
"cos_distance",
")",
":",
"if",
"cos_distance",
":",
"distance_matrix",
"=",
"SNNLCrossEntropy",
".",
"pairwise_cos_distance",
"(",
"A",
",",
"B",
")",
"else",
":",
"distance_matrix",
"=",
"SNNLCrossEntrop... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | SNNLCrossEntropy.pick_probability | Row normalized exponentiated pairwise distance between all the elements
of x. Conceptualized as the probability of sampling a neighbor point for
every element of x, proportional to the distance between the points.
:param x: a matrix
:param temp: Temperature
:cos_distance: Boolean for using cosine or... | cleverhans/loss.py | def pick_probability(x, temp, cos_distance):
"""Row normalized exponentiated pairwise distance between all the elements
of x. Conceptualized as the probability of sampling a neighbor point for
every element of x, proportional to the distance between the points.
:param x: a matrix
:param temp: Temper... | def pick_probability(x, temp, cos_distance):
"""Row normalized exponentiated pairwise distance between all the elements
of x. Conceptualized as the probability of sampling a neighbor point for
every element of x, proportional to the distance between the points.
:param x: a matrix
:param temp: Temper... | [
"Row",
"normalized",
"exponentiated",
"pairwise",
"distance",
"between",
"all",
"the",
"elements",
"of",
"x",
".",
"Conceptualized",
"as",
"the",
"probability",
"of",
"sampling",
"a",
"neighbor",
"point",
"for",
"every",
"element",
"of",
"x",
"proportional",
"to... | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/loss.py#L426-L440 | [
"def",
"pick_probability",
"(",
"x",
",",
"temp",
",",
"cos_distance",
")",
":",
"f",
"=",
"SNNLCrossEntropy",
".",
"fits",
"(",
"x",
",",
"x",
",",
"temp",
",",
"cos_distance",
")",
"-",
"tf",
".",
"eye",
"(",
"tf",
".",
"shape",
"(",
"x",
")",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | SNNLCrossEntropy.same_label_mask | Masking matrix such that element i,j is 1 iff y[i] == y2[i].
:param y: a list of labels
:param y2: a list of labels
:returns: A tensor for the masking matrix. | cleverhans/loss.py | def same_label_mask(y, y2):
"""Masking matrix such that element i,j is 1 iff y[i] == y2[i].
:param y: a list of labels
:param y2: a list of labels
:returns: A tensor for the masking matrix.
"""
return tf.cast(tf.squeeze(tf.equal(y, tf.expand_dims(y2, 1))), tf.float32) | def same_label_mask(y, y2):
"""Masking matrix such that element i,j is 1 iff y[i] == y2[i].
:param y: a list of labels
:param y2: a list of labels
:returns: A tensor for the masking matrix.
"""
return tf.cast(tf.squeeze(tf.equal(y, tf.expand_dims(y2, 1))), tf.float32) | [
"Masking",
"matrix",
"such",
"that",
"element",
"i",
"j",
"is",
"1",
"iff",
"y",
"[",
"i",
"]",
"==",
"y2",
"[",
"i",
"]",
".",
":",
"param",
"y",
":",
"a",
"list",
"of",
"labels",
":",
"param",
"y2",
":",
"a",
"list",
"of",
"labels"
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/loss.py#L443-L450 | [
"def",
"same_label_mask",
"(",
"y",
",",
"y2",
")",
":",
"return",
"tf",
".",
"cast",
"(",
"tf",
".",
"squeeze",
"(",
"tf",
".",
"equal",
"(",
"y",
",",
"tf",
".",
"expand_dims",
"(",
"y2",
",",
"1",
")",
")",
")",
",",
"tf",
".",
"float32",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | SNNLCrossEntropy.masked_pick_probability | The pairwise sampling probabilities for the elements of x for neighbor
points which share labels.
:param x: a matrix
:param y: a list of labels for each element of x
:param temp: Temperature
:cos_distance: Boolean for using cosine or Euclidean distance
:returns: A tensor for the pairwise sampli... | cleverhans/loss.py | def masked_pick_probability(x, y, temp, cos_distance):
"""The pairwise sampling probabilities for the elements of x for neighbor
points which share labels.
:param x: a matrix
:param y: a list of labels for each element of x
:param temp: Temperature
:cos_distance: Boolean for using cosine or Eucl... | def masked_pick_probability(x, y, temp, cos_distance):
"""The pairwise sampling probabilities for the elements of x for neighbor
points which share labels.
:param x: a matrix
:param y: a list of labels for each element of x
:param temp: Temperature
:cos_distance: Boolean for using cosine or Eucl... | [
"The",
"pairwise",
"sampling",
"probabilities",
"for",
"the",
"elements",
"of",
"x",
"for",
"neighbor",
"points",
"which",
"share",
"labels",
".",
":",
"param",
"x",
":",
"a",
"matrix",
":",
"param",
"y",
":",
"a",
"list",
"of",
"labels",
"for",
"each",
... | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/loss.py#L453-L464 | [
"def",
"masked_pick_probability",
"(",
"x",
",",
"y",
",",
"temp",
",",
"cos_distance",
")",
":",
"return",
"SNNLCrossEntropy",
".",
"pick_probability",
"(",
"x",
",",
"temp",
",",
"cos_distance",
")",
"*",
"SNNLCrossEntropy",
".",
"same_label_mask",
"(",
"y",... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | SNNLCrossEntropy.SNNL | Soft Nearest Neighbor Loss
:param x: a matrix.
:param y: a list of labels for each element of x.
:param temp: Temperature.
:cos_distance: Boolean for using cosine or Euclidean distance.
:returns: A tensor for the Soft Nearest Neighbor Loss of the points
in x with labels y. | cleverhans/loss.py | def SNNL(x, y, temp, cos_distance):
"""Soft Nearest Neighbor Loss
:param x: a matrix.
:param y: a list of labels for each element of x.
:param temp: Temperature.
:cos_distance: Boolean for using cosine or Euclidean distance.
:returns: A tensor for the Soft Nearest Neighbor Loss of the points
... | def SNNL(x, y, temp, cos_distance):
"""Soft Nearest Neighbor Loss
:param x: a matrix.
:param y: a list of labels for each element of x.
:param temp: Temperature.
:cos_distance: Boolean for using cosine or Euclidean distance.
:returns: A tensor for the Soft Nearest Neighbor Loss of the points
... | [
"Soft",
"Nearest",
"Neighbor",
"Loss",
":",
"param",
"x",
":",
"a",
"matrix",
".",
":",
"param",
"y",
":",
"a",
"list",
"of",
"labels",
"for",
"each",
"element",
"of",
"x",
".",
":",
"param",
"temp",
":",
"Temperature",
".",
":",
"cos_distance",
":",... | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/loss.py#L467-L480 | [
"def",
"SNNL",
"(",
"x",
",",
"y",
",",
"temp",
",",
"cos_distance",
")",
":",
"summed_masked_pick_prob",
"=",
"tf",
".",
"reduce_sum",
"(",
"SNNLCrossEntropy",
".",
"masked_pick_probability",
"(",
"x",
",",
"y",
",",
"temp",
",",
"cos_distance",
")",
",",... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | SNNLCrossEntropy.optimized_temp_SNNL | The optimized variant of Soft Nearest Neighbor Loss. Every time this
tensor is evaluated, the temperature is optimized to minimize the loss
value, this results in more numerically stable calculations of the SNNL.
:param x: a matrix.
:param y: a list of labels for each element of x.
:param initial_te... | cleverhans/loss.py | def optimized_temp_SNNL(x, y, initial_temp, cos_distance):
"""The optimized variant of Soft Nearest Neighbor Loss. Every time this
tensor is evaluated, the temperature is optimized to minimize the loss
value, this results in more numerically stable calculations of the SNNL.
:param x: a matrix.
:para... | def optimized_temp_SNNL(x, y, initial_temp, cos_distance):
"""The optimized variant of Soft Nearest Neighbor Loss. Every time this
tensor is evaluated, the temperature is optimized to minimize the loss
value, this results in more numerically stable calculations of the SNNL.
:param x: a matrix.
:para... | [
"The",
"optimized",
"variant",
"of",
"Soft",
"Nearest",
"Neighbor",
"Loss",
".",
"Every",
"time",
"this",
"tensor",
"is",
"evaluated",
"the",
"temperature",
"is",
"optimized",
"to",
"minimize",
"the",
"loss",
"value",
"this",
"results",
"in",
"more",
"numerica... | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/loss.py#L483-L505 | [
"def",
"optimized_temp_SNNL",
"(",
"x",
",",
"y",
",",
"initial_temp",
",",
"cos_distance",
")",
":",
"t",
"=",
"tf",
".",
"Variable",
"(",
"1",
",",
"dtype",
"=",
"tf",
".",
"float32",
",",
"trainable",
"=",
"False",
",",
"name",
"=",
"\"temp\"",
")... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | show | Display an image.
:param ndarray: The image as an ndarray
:param min_val: The minimum pixel value in the image format
:param max_val: The maximum pixel valie in the image format
If min_val and max_val are not specified, attempts to
infer whether the image is in any of the common ranges:
[0, 1], [-1,... | cleverhans/plot/image.py | def show(ndarray, min_val=None, max_val=None):
"""
Display an image.
:param ndarray: The image as an ndarray
:param min_val: The minimum pixel value in the image format
:param max_val: The maximum pixel valie in the image format
If min_val and max_val are not specified, attempts to
infer whether the i... | def show(ndarray, min_val=None, max_val=None):
"""
Display an image.
:param ndarray: The image as an ndarray
:param min_val: The minimum pixel value in the image format
:param max_val: The maximum pixel valie in the image format
If min_val and max_val are not specified, attempts to
infer whether the i... | [
"Display",
"an",
"image",
".",
":",
"param",
"ndarray",
":",
"The",
"image",
"as",
"an",
"ndarray",
":",
"param",
"min_val",
":",
"The",
"minimum",
"pixel",
"value",
"in",
"the",
"image",
"format",
":",
"param",
"max_val",
":",
"The",
"maximum",
"pixel",... | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/plot/image.py#L13-L29 | [
"def",
"show",
"(",
"ndarray",
",",
"min_val",
"=",
"None",
",",
"max_val",
"=",
"None",
")",
":",
"# Create a temporary file with the suffix '.png'.",
"fd",
",",
"path",
"=",
"mkstemp",
"(",
"suffix",
"=",
"'.png'",
")",
"os",
".",
"close",
"(",
"fd",
")"... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | save | Save an image, represented as an ndarray, to the filesystem
:param path: string, filepath
:param ndarray: The image as an ndarray
:param min_val: The minimum pixel value in the image format
:param max_val: The maximum pixel valie in the image format
If min_val and max_val are not specified, attempts to
... | cleverhans/plot/image.py | def save(path, ndarray, min_val=None, max_val=None):
"""
Save an image, represented as an ndarray, to the filesystem
:param path: string, filepath
:param ndarray: The image as an ndarray
:param min_val: The minimum pixel value in the image format
:param max_val: The maximum pixel valie in the image format
... | def save(path, ndarray, min_val=None, max_val=None):
"""
Save an image, represented as an ndarray, to the filesystem
:param path: string, filepath
:param ndarray: The image as an ndarray
:param min_val: The minimum pixel value in the image format
:param max_val: The maximum pixel valie in the image format
... | [
"Save",
"an",
"image",
"represented",
"as",
"an",
"ndarray",
"to",
"the",
"filesystem",
":",
"param",
"path",
":",
"string",
"filepath",
":",
"param",
"ndarray",
":",
"The",
"image",
"as",
"an",
"ndarray",
":",
"param",
"min_val",
":",
"The",
"minimum",
... | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/plot/image.py#L33-L45 | [
"def",
"save",
"(",
"path",
",",
"ndarray",
",",
"min_val",
"=",
"None",
",",
"max_val",
"=",
"None",
")",
":",
"as_pil",
"(",
"ndarray",
",",
"min_val",
",",
"max_val",
")",
".",
"save",
"(",
"path",
")"
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | as_pil | Converts an ndarray to a PIL image.
:param ndarray: The numpy ndarray to convert
:param min_val: The minimum pixel value in the image format
:param max_val: The maximum pixel valie in the image format
If min_val and max_val are not specified, attempts to
infer whether the image is in any of the common ran... | cleverhans/plot/image.py | def as_pil(ndarray, min_val=None, max_val=None):
"""
Converts an ndarray to a PIL image.
:param ndarray: The numpy ndarray to convert
:param min_val: The minimum pixel value in the image format
:param max_val: The maximum pixel valie in the image format
If min_val and max_val are not specified, attempts t... | def as_pil(ndarray, min_val=None, max_val=None):
"""
Converts an ndarray to a PIL image.
:param ndarray: The numpy ndarray to convert
:param min_val: The minimum pixel value in the image format
:param max_val: The maximum pixel valie in the image format
If min_val and max_val are not specified, attempts t... | [
"Converts",
"an",
"ndarray",
"to",
"a",
"PIL",
"image",
".",
":",
"param",
"ndarray",
":",
"The",
"numpy",
"ndarray",
"to",
"convert",
":",
"param",
"min_val",
":",
"The",
"minimum",
"pixel",
"value",
"in",
"the",
"image",
"format",
":",
"param",
"max_va... | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/plot/image.py#L47-L109 | [
"def",
"as_pil",
"(",
"ndarray",
",",
"min_val",
"=",
"None",
",",
"max_val",
"=",
"None",
")",
":",
"assert",
"isinstance",
"(",
"ndarray",
",",
"np",
".",
"ndarray",
")",
"# rows x cols for grayscale image",
"# rows x cols x channels for color",
"assert",
"ndarr... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | make_grid | Turns a batch of images into one big image.
:param image_batch: ndarray, shape (batch_size, rows, cols, channels)
:returns : a big image containing all `batch_size` images in a grid | cleverhans/plot/image.py | def make_grid(image_batch):
"""
Turns a batch of images into one big image.
:param image_batch: ndarray, shape (batch_size, rows, cols, channels)
:returns : a big image containing all `batch_size` images in a grid
"""
m, ir, ic, ch = image_batch.shape
pad = 3
padded = np.zeros((m, ir + pad * 2, ic + p... | def make_grid(image_batch):
"""
Turns a batch of images into one big image.
:param image_batch: ndarray, shape (batch_size, rows, cols, channels)
:returns : a big image containing all `batch_size` images in a grid
"""
m, ir, ic, ch = image_batch.shape
pad = 3
padded = np.zeros((m, ir + pad * 2, ic + p... | [
"Turns",
"a",
"batch",
"of",
"images",
"into",
"one",
"big",
"image",
".",
":",
"param",
"image_batch",
":",
"ndarray",
"shape",
"(",
"batch_size",
"rows",
"cols",
"channels",
")",
":",
"returns",
":",
"a",
"big",
"image",
"containing",
"all",
"batch_size"... | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/plot/image.py#L111-L140 | [
"def",
"make_grid",
"(",
"image_batch",
")",
":",
"m",
",",
"ir",
",",
"ic",
",",
"ch",
"=",
"image_batch",
".",
"shape",
"pad",
"=",
"3",
"padded",
"=",
"np",
".",
"zeros",
"(",
"(",
"m",
",",
"ir",
"+",
"pad",
"*",
"2",
",",
"ic",
"+",
"pad... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | Attack.generate_np | Generate adversarial examples and return them as a NumPy array.
:param x_val: A NumPy array with the original inputs.
:param **kwargs: optional parameters used by child classes.
:return: A NumPy array holding the adversarial examples. | cleverhans/attacks_tfe.py | def generate_np(self, x_val, **kwargs):
"""
Generate adversarial examples and return them as a NumPy array.
:param x_val: A NumPy array with the original inputs.
:param **kwargs: optional parameters used by child classes.
:return: A NumPy array holding the adversarial examples.
"""
tfe = tf... | def generate_np(self, x_val, **kwargs):
"""
Generate adversarial examples and return them as a NumPy array.
:param x_val: A NumPy array with the original inputs.
:param **kwargs: optional parameters used by child classes.
:return: A NumPy array holding the adversarial examples.
"""
tfe = tf... | [
"Generate",
"adversarial",
"examples",
"and",
"return",
"them",
"as",
"a",
"NumPy",
"array",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks_tfe.py#L57-L68 | [
"def",
"generate_np",
"(",
"self",
",",
"x_val",
",",
"*",
"*",
"kwargs",
")",
":",
"tfe",
"=",
"tf",
".",
"contrib",
".",
"eager",
"x",
"=",
"tfe",
".",
"Variable",
"(",
"x_val",
")",
"adv_x",
"=",
"self",
".",
"generate",
"(",
"x",
",",
"*",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | FastGradientMethod.generate | Generates the adversarial sample for the given input.
:param x: The model's inputs.
:param eps: (optional float) attack step size (input variation)
:param ord: (optional) Order of the norm (mimics NumPy).
Possible values: np.inf, 1 or 2.
:param y: (optional) A tf variable` with the model... | cleverhans/attacks_tfe.py | def generate(self, x, **kwargs):
"""
Generates the adversarial sample for the given input.
:param x: The model's inputs.
:param eps: (optional float) attack step size (input variation)
:param ord: (optional) Order of the norm (mimics NumPy).
Possible values: np.inf, 1 or 2.
:para... | def generate(self, x, **kwargs):
"""
Generates the adversarial sample for the given input.
:param x: The model's inputs.
:param eps: (optional float) attack step size (input variation)
:param ord: (optional) Order of the norm (mimics NumPy).
Possible values: np.inf, 1 or 2.
:para... | [
"Generates",
"the",
"adversarial",
"sample",
"for",
"the",
"given",
"input",
".",
":",
"param",
"x",
":",
"The",
"model",
"s",
"inputs",
".",
":",
"param",
"eps",
":",
"(",
"optional",
"float",
")",
"attack",
"step",
"size",
"(",
"input",
"variation",
... | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks_tfe.py#L104-L126 | [
"def",
"generate",
"(",
"self",
",",
"x",
",",
"*",
"*",
"kwargs",
")",
":",
"# Parse and save attack-specific parameters",
"assert",
"self",
".",
"parse_params",
"(",
"*",
"*",
"kwargs",
")",
"labels",
",",
"_nb_classes",
"=",
"self",
".",
"get_or_guess_label... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | FastGradientMethod.fgm | TensorFlow Eager implementation of the Fast Gradient Method.
:param x: the input variable
:param targeted: Is the attack targeted or untargeted? Untargeted, the
default, will try to make the label incorrect.
Targeted will instead try to move in the direction
... | cleverhans/attacks_tfe.py | def fgm(self, x, labels, targeted=False):
"""
TensorFlow Eager implementation of the Fast Gradient Method.
:param x: the input variable
:param targeted: Is the attack targeted or untargeted? Untargeted, the
default, will try to make the label incorrect.
Targeted... | def fgm(self, x, labels, targeted=False):
"""
TensorFlow Eager implementation of the Fast Gradient Method.
:param x: the input variable
:param targeted: Is the attack targeted or untargeted? Untargeted, the
default, will try to make the label incorrect.
Targeted... | [
"TensorFlow",
"Eager",
"implementation",
"of",
"the",
"Fast",
"Gradient",
"Method",
".",
":",
"param",
"x",
":",
"the",
"input",
"variable",
":",
"param",
"targeted",
":",
"Is",
"the",
"attack",
"targeted",
"or",
"untargeted?",
"Untargeted",
"the",
"default",
... | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks_tfe.py#L128-L159 | [
"def",
"fgm",
"(",
"self",
",",
"x",
",",
"labels",
",",
"targeted",
"=",
"False",
")",
":",
"# Compute loss",
"with",
"tf",
".",
"GradientTape",
"(",
")",
"as",
"tape",
":",
"# input should be watched because it may be",
"# combination of trainable and non-trainabl... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | random_feed_dict | Returns random data to be used with `feed_dict`.
:param rng: A numpy.random.RandomState instance
:param placeholders: List of tensorflow placeholders
:return: A dict mapping placeholders to random numpy values | cleverhans/devtools/mocks.py | def random_feed_dict(rng, placeholders):
"""
Returns random data to be used with `feed_dict`.
:param rng: A numpy.random.RandomState instance
:param placeholders: List of tensorflow placeholders
:return: A dict mapping placeholders to random numpy values
"""
output = {}
for placeholder in placeholders... | def random_feed_dict(rng, placeholders):
"""
Returns random data to be used with `feed_dict`.
:param rng: A numpy.random.RandomState instance
:param placeholders: List of tensorflow placeholders
:return: A dict mapping placeholders to random numpy values
"""
output = {}
for placeholder in placeholders... | [
"Returns",
"random",
"data",
"to",
"be",
"used",
"with",
"feed_dict",
".",
":",
"param",
"rng",
":",
"A",
"numpy",
".",
"random",
".",
"RandomState",
"instance",
":",
"param",
"placeholders",
":",
"List",
"of",
"tensorflow",
"placeholders",
":",
"return",
... | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/devtools/mocks.py#L16-L32 | [
"def",
"random_feed_dict",
"(",
"rng",
",",
"placeholders",
")",
":",
"output",
"=",
"{",
"}",
"for",
"placeholder",
"in",
"placeholders",
":",
"if",
"placeholder",
".",
"dtype",
"!=",
"'float32'",
":",
"raise",
"NotImplementedError",
"(",
")",
"value",
"=",... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | list_files | Returns a list of all files in CleverHans with the given suffix.
Parameters
----------
suffix : str
Returns
-------
file_list : list
A list of all files in CleverHans whose filepath ends with `suffix`. | cleverhans/devtools/list_files.py | def list_files(suffix=""):
"""
Returns a list of all files in CleverHans with the given suffix.
Parameters
----------
suffix : str
Returns
-------
file_list : list
A list of all files in CleverHans whose filepath ends with `suffix`.
"""
cleverhans_path = os.path.abspath(cleverhans.__path__... | def list_files(suffix=""):
"""
Returns a list of all files in CleverHans with the given suffix.
Parameters
----------
suffix : str
Returns
-------
file_list : list
A list of all files in CleverHans whose filepath ends with `suffix`.
"""
cleverhans_path = os.path.abspath(cleverhans.__path__... | [
"Returns",
"a",
"list",
"of",
"all",
"files",
"in",
"CleverHans",
"with",
"the",
"given",
"suffix",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/devtools/list_files.py#L6-L38 | [
"def",
"list_files",
"(",
"suffix",
"=",
"\"\"",
")",
":",
"cleverhans_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"cleverhans",
".",
"__path__",
"[",
"0",
"]",
")",
"# In some environments cleverhans_path does not point to a real directory.",
"# In such case ... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | _list_files | Returns a list of all files ending in `suffix` contained within `path`.
Parameters
----------
path : str
a filepath
suffix : str
Returns
-------
l : list
A list of all files ending in `suffix` contained within `path`.
(If `path` is a file rather than a directory, it is considered
... | cleverhans/devtools/list_files.py | def _list_files(path, suffix=""):
"""
Returns a list of all files ending in `suffix` contained within `path`.
Parameters
----------
path : str
a filepath
suffix : str
Returns
-------
l : list
A list of all files ending in `suffix` contained within `path`.
(If `path` is a file rathe... | def _list_files(path, suffix=""):
"""
Returns a list of all files ending in `suffix` contained within `path`.
Parameters
----------
path : str
a filepath
suffix : str
Returns
-------
l : list
A list of all files ending in `suffix` contained within `path`.
(If `path` is a file rathe... | [
"Returns",
"a",
"list",
"of",
"all",
"files",
"ending",
"in",
"suffix",
"contained",
"within",
"path",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/devtools/list_files.py#L41-L71 | [
"def",
"_list_files",
"(",
"path",
",",
"suffix",
"=",
"\"\"",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"incomplete",
"=",
"os",
".",
"listdir",
"(",
"path",
")",
"complete",
"=",
"[",
"os",
".",
"path",
".",
"join"... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | print_header | Prints header with given text and frame composed of '#' characters. | examples/nips17_adversarial_competition/eval_infra/code/master.py | def print_header(text):
"""Prints header with given text and frame composed of '#' characters."""
print()
print('#'*(len(text)+4))
print('# ' + text + ' #')
print('#'*(len(text)+4))
print() | def print_header(text):
"""Prints header with given text and frame composed of '#' characters."""
print()
print('#'*(len(text)+4))
print('# ' + text + ' #')
print('#'*(len(text)+4))
print() | [
"Prints",
"header",
"with",
"given",
"text",
"and",
"frame",
"composed",
"of",
"#",
"characters",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/master.py#L40-L46 | [
"def",
"print_header",
"(",
"text",
")",
":",
"print",
"(",
")",
"print",
"(",
"'#'",
"*",
"(",
"len",
"(",
"text",
")",
"+",
"4",
")",
")",
"print",
"(",
"'# '",
"+",
"text",
"+",
"' #'",
")",
"print",
"(",
"'#'",
"*",
"(",
"len",
"(",
"text... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | save_dict_to_file | Saves dictionary as CSV file. | examples/nips17_adversarial_competition/eval_infra/code/master.py | def save_dict_to_file(filename, dictionary):
"""Saves dictionary as CSV file."""
with open(filename, 'w') as f:
writer = csv.writer(f)
for k, v in iteritems(dictionary):
writer.writerow([str(k), str(v)]) | def save_dict_to_file(filename, dictionary):
"""Saves dictionary as CSV file."""
with open(filename, 'w') as f:
writer = csv.writer(f)
for k, v in iteritems(dictionary):
writer.writerow([str(k), str(v)]) | [
"Saves",
"dictionary",
"as",
"CSV",
"file",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/master.py#L49-L54 | [
"def",
"save_dict_to_file",
"(",
"filename",
",",
"dictionary",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'w'",
")",
"as",
"f",
":",
"writer",
"=",
"csv",
".",
"writer",
"(",
"f",
")",
"for",
"k",
",",
"v",
"in",
"iteritems",
"(",
"dictionary"... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | main | Main function which runs master. | examples/nips17_adversarial_competition/eval_infra/code/master.py | def main(args):
"""Main function which runs master."""
if args.blacklisted_submissions:
logging.warning('BLACKLISTED SUBMISSIONS: %s',
args.blacklisted_submissions)
if args.limited_dataset:
logging.info('Using limited dataset: 3 batches * 10 images')
max_dataset_num_images = 30
... | def main(args):
"""Main function which runs master."""
if args.blacklisted_submissions:
logging.warning('BLACKLISTED SUBMISSIONS: %s',
args.blacklisted_submissions)
if args.limited_dataset:
logging.info('Using limited dataset: 3 batches * 10 images')
max_dataset_num_images = 30
... | [
"Main",
"function",
"which",
"runs",
"master",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/master.py#L688-L735 | [
"def",
"main",
"(",
"args",
")",
":",
"if",
"args",
".",
"blacklisted_submissions",
":",
"logging",
".",
"warning",
"(",
"'BLACKLISTED SUBMISSIONS: %s'",
",",
"args",
".",
"blacklisted_submissions",
")",
"if",
"args",
".",
"limited_dataset",
":",
"logging",
".",... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | EvaluationMaster.ask_when_work_is_populated | When work is already populated asks whether we should continue.
This method prints warning message that work is populated and asks
whether user wants to continue or not.
Args:
work: instance of WorkPiecesBase
Returns:
True if we should continue and populate datastore, False if we should s... | examples/nips17_adversarial_competition/eval_infra/code/master.py | def ask_when_work_is_populated(self, work):
"""When work is already populated asks whether we should continue.
This method prints warning message that work is populated and asks
whether user wants to continue or not.
Args:
work: instance of WorkPiecesBase
Returns:
True if we should co... | def ask_when_work_is_populated(self, work):
"""When work is already populated asks whether we should continue.
This method prints warning message that work is populated and asks
whether user wants to continue or not.
Args:
work: instance of WorkPiecesBase
Returns:
True if we should co... | [
"When",
"work",
"is",
"already",
"populated",
"asks",
"whether",
"we",
"should",
"continue",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/master.py#L116-L137 | [
"def",
"ask_when_work_is_populated",
"(",
"self",
",",
"work",
")",
":",
"work",
".",
"read_all_from_datastore",
"(",
")",
"if",
"work",
".",
"work",
":",
"print",
"(",
"'Work is already written to datastore.\\n'",
"'If you continue these data will be overwritten and '",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | EvaluationMaster.prepare_attacks | Prepares all data needed for evaluation of attacks. | examples/nips17_adversarial_competition/eval_infra/code/master.py | def prepare_attacks(self):
"""Prepares all data needed for evaluation of attacks."""
print_header('PREPARING ATTACKS DATA')
# verify that attacks data not written yet
if not self.ask_when_work_is_populated(self.attack_work):
return
self.attack_work = eval_lib.AttackWorkPieces(
datastor... | def prepare_attacks(self):
"""Prepares all data needed for evaluation of attacks."""
print_header('PREPARING ATTACKS DATA')
# verify that attacks data not written yet
if not self.ask_when_work_is_populated(self.attack_work):
return
self.attack_work = eval_lib.AttackWorkPieces(
datastor... | [
"Prepares",
"all",
"data",
"needed",
"for",
"evaluation",
"of",
"attacks",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/master.py#L139-L173 | [
"def",
"prepare_attacks",
"(",
"self",
")",
":",
"print_header",
"(",
"'PREPARING ATTACKS DATA'",
")",
"# verify that attacks data not written yet",
"if",
"not",
"self",
".",
"ask_when_work_is_populated",
"(",
"self",
".",
"attack_work",
")",
":",
"return",
"self",
".... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | EvaluationMaster.prepare_defenses | Prepares all data needed for evaluation of defenses. | examples/nips17_adversarial_competition/eval_infra/code/master.py | def prepare_defenses(self):
"""Prepares all data needed for evaluation of defenses."""
print_header('PREPARING DEFENSE DATA')
# verify that defense data not written yet
if not self.ask_when_work_is_populated(self.defense_work):
return
self.defense_work = eval_lib.DefenseWorkPieces(
dat... | def prepare_defenses(self):
"""Prepares all data needed for evaluation of defenses."""
print_header('PREPARING DEFENSE DATA')
# verify that defense data not written yet
if not self.ask_when_work_is_populated(self.defense_work):
return
self.defense_work = eval_lib.DefenseWorkPieces(
dat... | [
"Prepares",
"all",
"data",
"needed",
"for",
"evaluation",
"of",
"defenses",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/master.py#L175-L200 | [
"def",
"prepare_defenses",
"(",
"self",
")",
":",
"print_header",
"(",
"'PREPARING DEFENSE DATA'",
")",
"# verify that defense data not written yet",
"if",
"not",
"self",
".",
"ask_when_work_is_populated",
"(",
"self",
".",
"defense_work",
")",
":",
"return",
"self",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | EvaluationMaster._save_work_results | Saves statistics about each submission.
Saved statistics include score; number of completed and failed batches;
min, max, average and median time needed to run one batch.
Args:
run_stats: dictionary with runtime statistics for submissions,
can be generated by WorkPiecesBase.compute_work_stat... | examples/nips17_adversarial_competition/eval_infra/code/master.py | def _save_work_results(self, run_stats, scores, num_processed_images,
filename):
"""Saves statistics about each submission.
Saved statistics include score; number of completed and failed batches;
min, max, average and median time needed to run one batch.
Args:
run_stats:... | def _save_work_results(self, run_stats, scores, num_processed_images,
filename):
"""Saves statistics about each submission.
Saved statistics include score; number of completed and failed batches;
min, max, average and median time needed to run one batch.
Args:
run_stats:... | [
"Saves",
"statistics",
"about",
"each",
"submission",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/master.py#L202-L243 | [
"def",
"_save_work_results",
"(",
"self",
",",
"run_stats",
",",
"scores",
",",
"num_processed_images",
",",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'w'",
")",
"as",
"f",
":",
"writer",
"=",
"csv",
".",
"writer",
"(",
"f",
")",
"wr... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | EvaluationMaster._save_sorted_results | Saves sorted (by score) results of the evaluation.
Args:
run_stats: dictionary with runtime statistics for submissions,
can be generated by WorkPiecesBase.compute_work_statistics
scores: dictionary mapping submission ids to scores
image_count: dictionary with number of images processed by... | examples/nips17_adversarial_competition/eval_infra/code/master.py | def _save_sorted_results(self, run_stats, scores, image_count, filename):
"""Saves sorted (by score) results of the evaluation.
Args:
run_stats: dictionary with runtime statistics for submissions,
can be generated by WorkPiecesBase.compute_work_statistics
scores: dictionary mapping submissi... | def _save_sorted_results(self, run_stats, scores, image_count, filename):
"""Saves sorted (by score) results of the evaluation.
Args:
run_stats: dictionary with runtime statistics for submissions,
can be generated by WorkPiecesBase.compute_work_statistics
scores: dictionary mapping submissi... | [
"Saves",
"sorted",
"(",
"by",
"score",
")",
"results",
"of",
"the",
"evaluation",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/master.py#L245-L270 | [
"def",
"_save_sorted_results",
"(",
"self",
",",
"run_stats",
",",
"scores",
",",
"image_count",
",",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'w'",
")",
"as",
"f",
":",
"writer",
"=",
"csv",
".",
"writer",
"(",
"f",
")",
"writer",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | EvaluationMaster._read_dataset_metadata | Reads dataset metadata.
Returns:
instance of DatasetMetadata | examples/nips17_adversarial_competition/eval_infra/code/master.py | def _read_dataset_metadata(self):
"""Reads dataset metadata.
Returns:
instance of DatasetMetadata
"""
blob = self.storage_client.get_blob(
'dataset/' + self.dataset_name + '_dataset.csv')
buf = BytesIO()
blob.download_to_file(buf)
buf.seek(0)
return eval_lib.DatasetMetadat... | def _read_dataset_metadata(self):
"""Reads dataset metadata.
Returns:
instance of DatasetMetadata
"""
blob = self.storage_client.get_blob(
'dataset/' + self.dataset_name + '_dataset.csv')
buf = BytesIO()
blob.download_to_file(buf)
buf.seek(0)
return eval_lib.DatasetMetadat... | [
"Reads",
"dataset",
"metadata",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/master.py#L272-L283 | [
"def",
"_read_dataset_metadata",
"(",
"self",
")",
":",
"blob",
"=",
"self",
".",
"storage_client",
".",
"get_blob",
"(",
"'dataset/'",
"+",
"self",
".",
"dataset_name",
"+",
"'_dataset.csv'",
")",
"buf",
"=",
"BytesIO",
"(",
")",
"blob",
".",
"download_to_f... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | EvaluationMaster.compute_results | Computes results (scores, stats, etc...) of competition evaluation.
Results are saved into output directory (self.results_dir).
Also this method saves all intermediate data into output directory as well,
so it can resume computation if it was interrupted for some reason.
This is useful because computat... | examples/nips17_adversarial_competition/eval_infra/code/master.py | def compute_results(self):
"""Computes results (scores, stats, etc...) of competition evaluation.
Results are saved into output directory (self.results_dir).
Also this method saves all intermediate data into output directory as well,
so it can resume computation if it was interrupted for some reason.
... | def compute_results(self):
"""Computes results (scores, stats, etc...) of competition evaluation.
Results are saved into output directory (self.results_dir).
Also this method saves all intermediate data into output directory as well,
so it can resume computation if it was interrupted for some reason.
... | [
"Computes",
"results",
"(",
"scores",
"stats",
"etc",
"...",
")",
"of",
"competition",
"evaluation",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/master.py#L285-L446 | [
"def",
"compute_results",
"(",
"self",
")",
":",
"# read all data",
"logging",
".",
"info",
"(",
"'Reading data from datastore'",
")",
"dataset_meta",
"=",
"self",
".",
"_read_dataset_metadata",
"(",
")",
"self",
".",
"submissions",
".",
"init_from_datastore",
"(",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | EvaluationMaster._show_status_for_work | Shows status for given work pieces.
Args:
work: instance of either AttackWorkPieces or DefenseWorkPieces | examples/nips17_adversarial_competition/eval_infra/code/master.py | def _show_status_for_work(self, work):
"""Shows status for given work pieces.
Args:
work: instance of either AttackWorkPieces or DefenseWorkPieces
"""
work_count = len(work.work)
work_completed = {}
work_completed_count = 0
for v in itervalues(work.work):
if v['is_completed']:
... | def _show_status_for_work(self, work):
"""Shows status for given work pieces.
Args:
work: instance of either AttackWorkPieces or DefenseWorkPieces
"""
work_count = len(work.work)
work_completed = {}
work_completed_count = 0
for v in itervalues(work.work):
if v['is_completed']:
... | [
"Shows",
"status",
"for",
"given",
"work",
"pieces",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/master.py#L448-L477 | [
"def",
"_show_status_for_work",
"(",
"self",
",",
"work",
")",
":",
"work_count",
"=",
"len",
"(",
"work",
".",
"work",
")",
"work_completed",
"=",
"{",
"}",
"work_completed_count",
"=",
"0",
"for",
"v",
"in",
"itervalues",
"(",
"work",
".",
"work",
")",... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | EvaluationMaster._export_work_errors | Saves errors for given work pieces into file.
Args:
work: instance of either AttackWorkPieces or DefenseWorkPieces
output_file: name of the output file | examples/nips17_adversarial_competition/eval_infra/code/master.py | def _export_work_errors(self, work, output_file):
"""Saves errors for given work pieces into file.
Args:
work: instance of either AttackWorkPieces or DefenseWorkPieces
output_file: name of the output file
"""
errors = set()
for v in itervalues(work.work):
if v['is_completed'] and ... | def _export_work_errors(self, work, output_file):
"""Saves errors for given work pieces into file.
Args:
work: instance of either AttackWorkPieces or DefenseWorkPieces
output_file: name of the output file
"""
errors = set()
for v in itervalues(work.work):
if v['is_completed'] and ... | [
"Saves",
"errors",
"for",
"given",
"work",
"pieces",
"into",
"file",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/master.py#L479-L493 | [
"def",
"_export_work_errors",
"(",
"self",
",",
"work",
",",
"output_file",
")",
":",
"errors",
"=",
"set",
"(",
")",
"for",
"v",
"in",
"itervalues",
"(",
"work",
".",
"work",
")",
":",
"if",
"v",
"[",
"'is_completed'",
"]",
"and",
"v",
"[",
"'error'... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | EvaluationMaster.show_status | Shows current status of competition evaluation.
Also this method saves error messages generated by attacks and defenses
into attack_errors.txt and defense_errors.txt. | examples/nips17_adversarial_competition/eval_infra/code/master.py | def show_status(self):
"""Shows current status of competition evaluation.
Also this method saves error messages generated by attacks and defenses
into attack_errors.txt and defense_errors.txt.
"""
print_header('Attack work statistics')
self.attack_work.read_all_from_datastore()
self._show_s... | def show_status(self):
"""Shows current status of competition evaluation.
Also this method saves error messages generated by attacks and defenses
into attack_errors.txt and defense_errors.txt.
"""
print_header('Attack work statistics')
self.attack_work.read_all_from_datastore()
self._show_s... | [
"Shows",
"current",
"status",
"of",
"competition",
"evaluation",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/master.py#L495-L512 | [
"def",
"show_status",
"(",
"self",
")",
":",
"print_header",
"(",
"'Attack work statistics'",
")",
"self",
".",
"attack_work",
".",
"read_all_from_datastore",
"(",
")",
"self",
".",
"_show_status_for_work",
"(",
"self",
".",
"attack_work",
")",
"self",
".",
"_ex... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | EvaluationMaster.cleanup_failed_attacks | Cleans up data of failed attacks. | examples/nips17_adversarial_competition/eval_infra/code/master.py | def cleanup_failed_attacks(self):
"""Cleans up data of failed attacks."""
print_header('Cleaning up failed attacks')
attacks_to_replace = {}
self.attack_work.read_all_from_datastore()
failed_submissions = set()
error_msg = set()
for k, v in iteritems(self.attack_work.work):
if v['error... | def cleanup_failed_attacks(self):
"""Cleans up data of failed attacks."""
print_header('Cleaning up failed attacks')
attacks_to_replace = {}
self.attack_work.read_all_from_datastore()
failed_submissions = set()
error_msg = set()
for k, v in iteritems(self.attack_work.work):
if v['error... | [
"Cleans",
"up",
"data",
"of",
"failed",
"attacks",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/master.py#L514-L544 | [
"def",
"cleanup_failed_attacks",
"(",
"self",
")",
":",
"print_header",
"(",
"'Cleaning up failed attacks'",
")",
"attacks_to_replace",
"=",
"{",
"}",
"self",
".",
"attack_work",
".",
"read_all_from_datastore",
"(",
")",
"failed_submissions",
"=",
"set",
"(",
")",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | EvaluationMaster.cleanup_attacks_with_zero_images | Cleans up data about attacks which generated zero images. | examples/nips17_adversarial_competition/eval_infra/code/master.py | def cleanup_attacks_with_zero_images(self):
"""Cleans up data about attacks which generated zero images."""
print_header('Cleaning up attacks which generated 0 images.')
# find out attack work to cleanup
self.adv_batches.init_from_datastore()
self.attack_work.read_all_from_datastore()
new_attack... | def cleanup_attacks_with_zero_images(self):
"""Cleans up data about attacks which generated zero images."""
print_header('Cleaning up attacks which generated 0 images.')
# find out attack work to cleanup
self.adv_batches.init_from_datastore()
self.attack_work.read_all_from_datastore()
new_attack... | [
"Cleans",
"up",
"data",
"about",
"attacks",
"which",
"generated",
"zero",
"images",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/master.py#L546-L608 | [
"def",
"cleanup_attacks_with_zero_images",
"(",
"self",
")",
":",
"print_header",
"(",
"'Cleaning up attacks which generated 0 images.'",
")",
"# find out attack work to cleanup",
"self",
".",
"adv_batches",
".",
"init_from_datastore",
"(",
")",
"self",
".",
"attack_work",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | EvaluationMaster._cleanup_keys_with_confirmation | Asks confirmation and then deletes entries with keys.
Args:
keys_to_delete: list of datastore keys for which entries should be deleted | examples/nips17_adversarial_competition/eval_infra/code/master.py | def _cleanup_keys_with_confirmation(self, keys_to_delete):
"""Asks confirmation and then deletes entries with keys.
Args:
keys_to_delete: list of datastore keys for which entries should be deleted
"""
print('Round name: ', self.round_name)
print('Number of entities to be deleted: ', len(keys_... | def _cleanup_keys_with_confirmation(self, keys_to_delete):
"""Asks confirmation and then deletes entries with keys.
Args:
keys_to_delete: list of datastore keys for which entries should be deleted
"""
print('Round name: ', self.round_name)
print('Number of entities to be deleted: ', len(keys_... | [
"Asks",
"confirmation",
"and",
"then",
"deletes",
"entries",
"with",
"keys",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/master.py#L610-L649 | [
"def",
"_cleanup_keys_with_confirmation",
"(",
"self",
",",
"keys_to_delete",
")",
":",
"print",
"(",
"'Round name: '",
",",
"self",
".",
"round_name",
")",
"print",
"(",
"'Number of entities to be deleted: '",
",",
"len",
"(",
"keys_to_delete",
")",
")",
"if",
"n... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | EvaluationMaster.cleanup_defenses | Cleans up all data about defense work in current round. | examples/nips17_adversarial_competition/eval_infra/code/master.py | def cleanup_defenses(self):
"""Cleans up all data about defense work in current round."""
print_header('CLEANING UP DEFENSES DATA')
work_ancestor_key = self.datastore_client.key('WorkType', 'AllDefenses')
keys_to_delete = [
e.key
for e in self.datastore_client.query_fetch(kind=u'Classifi... | def cleanup_defenses(self):
"""Cleans up all data about defense work in current round."""
print_header('CLEANING UP DEFENSES DATA')
work_ancestor_key = self.datastore_client.key('WorkType', 'AllDefenses')
keys_to_delete = [
e.key
for e in self.datastore_client.query_fetch(kind=u'Classifi... | [
"Cleans",
"up",
"all",
"data",
"about",
"defense",
"work",
"in",
"current",
"round",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/master.py#L651-L663 | [
"def",
"cleanup_defenses",
"(",
"self",
")",
":",
"print_header",
"(",
"'CLEANING UP DEFENSES DATA'",
")",
"work_ancestor_key",
"=",
"self",
".",
"datastore_client",
".",
"key",
"(",
"'WorkType'",
",",
"'AllDefenses'",
")",
"keys_to_delete",
"=",
"[",
"e",
".",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | EvaluationMaster.cleanup_datastore | Cleans up datastore and deletes all information about current round. | examples/nips17_adversarial_competition/eval_infra/code/master.py | def cleanup_datastore(self):
"""Cleans up datastore and deletes all information about current round."""
print_header('CLEANING UP ENTIRE DATASTORE')
kinds_to_delete = [u'Submission', u'SubmissionType',
u'DatasetImage', u'DatasetBatch',
u'AdversarialImage', u'Adv... | def cleanup_datastore(self):
"""Cleans up datastore and deletes all information about current round."""
print_header('CLEANING UP ENTIRE DATASTORE')
kinds_to_delete = [u'Submission', u'SubmissionType',
u'DatasetImage', u'DatasetBatch',
u'AdversarialImage', u'Adv... | [
"Cleans",
"up",
"datastore",
"and",
"deletes",
"all",
"information",
"about",
"current",
"round",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/master.py#L665-L675 | [
"def",
"cleanup_datastore",
"(",
"self",
")",
":",
"print_header",
"(",
"'CLEANING UP ENTIRE DATASTORE'",
")",
"kinds_to_delete",
"=",
"[",
"u'Submission'",
",",
"u'SubmissionType'",
",",
"u'DatasetImage'",
",",
"u'DatasetBatch'",
",",
"u'AdversarialImage'",
",",
"u'Adv... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | main | Run the sample attack | examples/nips17_adversarial_competition/dev_toolkit/sample_attacks/random_noise/attack_random_noise.py | def main(_):
"""Run the sample attack"""
eps = FLAGS.max_epsilon / 255.0
batch_shape = [FLAGS.batch_size, FLAGS.image_height, FLAGS.image_width, 3]
with tf.Graph().as_default():
x_input = tf.placeholder(tf.float32, shape=batch_shape)
noisy_images = x_input + eps * tf.sign(tf.random_normal(batch_shape))... | def main(_):
"""Run the sample attack"""
eps = FLAGS.max_epsilon / 255.0
batch_shape = [FLAGS.batch_size, FLAGS.image_height, FLAGS.image_width, 3]
with tf.Graph().as_default():
x_input = tf.placeholder(tf.float32, shape=batch_shape)
noisy_images = x_input + eps * tf.sign(tf.random_normal(batch_shape))... | [
"Run",
"the",
"sample",
"attack"
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/sample_attacks/random_noise/attack_random_noise.py#L86-L99 | [
"def",
"main",
"(",
"_",
")",
":",
"eps",
"=",
"FLAGS",
".",
"max_epsilon",
"/",
"255.0",
"batch_shape",
"=",
"[",
"FLAGS",
".",
"batch_size",
",",
"FLAGS",
".",
"image_height",
",",
"FLAGS",
".",
"image_width",
",",
"3",
"]",
"with",
"tf",
".",
"Gra... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | jsma_symbolic | TensorFlow implementation of the JSMA (see https://arxiv.org/abs/1511.07528
for details about the algorithm design choices).
:param x: the input placeholder
:param y_target: the target tensor
:param model: a cleverhans.model.Model object.
:param theta: delta for each feature adjustment
:param gamma: a floa... | cleverhans/attacks/saliency_map_method.py | def jsma_symbolic(x, y_target, model, theta, gamma, clip_min, clip_max):
"""
TensorFlow implementation of the JSMA (see https://arxiv.org/abs/1511.07528
for details about the algorithm design choices).
:param x: the input placeholder
:param y_target: the target tensor
:param model: a cleverhans.model.Model... | def jsma_symbolic(x, y_target, model, theta, gamma, clip_min, clip_max):
"""
TensorFlow implementation of the JSMA (see https://arxiv.org/abs/1511.07528
for details about the algorithm design choices).
:param x: the input placeholder
:param y_target: the target tensor
:param model: a cleverhans.model.Model... | [
"TensorFlow",
"implementation",
"of",
"the",
"JSMA",
"(",
"see",
"https",
":",
"//",
"arxiv",
".",
"org",
"/",
"abs",
"/",
"1511",
".",
"07528",
"for",
"details",
"about",
"the",
"algorithm",
"design",
"choices",
")",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/saliency_map_method.py#L132-L281 | [
"def",
"jsma_symbolic",
"(",
"x",
",",
"y_target",
",",
"model",
",",
"theta",
",",
"gamma",
",",
"clip_min",
",",
"clip_max",
")",
":",
"nb_classes",
"=",
"int",
"(",
"y_target",
".",
"shape",
"[",
"-",
"1",
"]",
".",
"value",
")",
"nb_features",
"=... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | SaliencyMapMethod.generate | Generate symbolic graph for adversarial examples and return.
:param x: The model's symbolic inputs.
:param kwargs: See `parse_params` | cleverhans/attacks/saliency_map_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)
if self.symbolic_impl:
# C... | def generate(self, x, **kwargs):
"""
Generate symbolic graph for adversarial examples and return.
:param x: The model's symbolic inputs.
:param kwargs: See `parse_params`
"""
# Parse and save attack-specific parameters
assert self.parse_params(**kwargs)
if self.symbolic_impl:
# C... | [
"Generate",
"symbolic",
"graph",
"for",
"adversarial",
"examples",
"and",
"return",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/saliency_map_method.py#L44-L90 | [
"def",
"generate",
"(",
"self",
",",
"x",
",",
"*",
"*",
"kwargs",
")",
":",
"# Parse and save attack-specific parameters",
"assert",
"self",
".",
"parse_params",
"(",
"*",
"*",
"kwargs",
")",
"if",
"self",
".",
"symbolic_impl",
":",
"# Create random targets if ... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | SaliencyMapMethod.parse_params | Take in a dictionary of parameters and applies attack-specific checks
before saving them as attributes.
Attack-specific parameters:
:param theta: (optional float) Perturbation introduced to modified
components (can be positive or negative)
:param gamma: (optional float) Maximum perce... | cleverhans/attacks/saliency_map_method.py | def parse_params(self,
theta=1.,
gamma=1.,
clip_min=0.,
clip_max=1.,
y_target=None,
symbolic_impl=True,
**kwargs):
"""
Take in a dictionary of parameters and applies attack-specif... | def parse_params(self,
theta=1.,
gamma=1.,
clip_min=0.,
clip_max=1.,
y_target=None,
symbolic_impl=True,
**kwargs):
"""
Take in a dictionary of parameters and applies attack-specif... | [
"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/saliency_map_method.py#L92-L124 | [
"def",
"parse_params",
"(",
"self",
",",
"theta",
"=",
"1.",
",",
"gamma",
"=",
"1.",
",",
"clip_min",
"=",
"0.",
",",
"clip_max",
"=",
"1.",
",",
"y_target",
"=",
"None",
",",
"symbolic_impl",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"self"... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | make_basic_ngpu | Create a multi-GPU model similar to the basic cnn in the tutorials. | examples/multigpu_advtrain/make_model.py | def make_basic_ngpu(nb_classes=10, input_shape=(None, 28, 28, 1), **kwargs):
"""
Create a multi-GPU model similar to the basic cnn in the tutorials.
"""
model = make_basic_cnn()
layers = model.layers
model = MLPnGPU(nb_classes, layers, input_shape)
return model | def make_basic_ngpu(nb_classes=10, input_shape=(None, 28, 28, 1), **kwargs):
"""
Create a multi-GPU model similar to the basic cnn in the tutorials.
"""
model = make_basic_cnn()
layers = model.layers
model = MLPnGPU(nb_classes, layers, input_shape)
return model | [
"Create",
"a",
"multi",
"-",
"GPU",
"model",
"similar",
"to",
"the",
"basic",
"cnn",
"in",
"the",
"tutorials",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/make_model.py#L27-L35 | [
"def",
"make_basic_ngpu",
"(",
"nb_classes",
"=",
"10",
",",
"input_shape",
"=",
"(",
"None",
",",
"28",
",",
"28",
",",
"1",
")",
",",
"*",
"*",
"kwargs",
")",
":",
"model",
"=",
"make_basic_cnn",
"(",
")",
"layers",
"=",
"model",
".",
"layers",
"... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | make_madry_ngpu | Create a multi-GPU model similar to Madry et al. (arXiv:1706.06083). | examples/multigpu_advtrain/make_model.py | def make_madry_ngpu(nb_classes=10, input_shape=(None, 28, 28, 1), **kwargs):
"""
Create a multi-GPU model similar to Madry et al. (arXiv:1706.06083).
"""
layers = [Conv2DnGPU(32, (5, 5), (1, 1), "SAME"),
ReLU(),
MaxPool((2, 2), (2, 2), "SAME"),
Conv2DnGPU(64, (5, 5), (1, 1), ... | def make_madry_ngpu(nb_classes=10, input_shape=(None, 28, 28, 1), **kwargs):
"""
Create a multi-GPU model similar to Madry et al. (arXiv:1706.06083).
"""
layers = [Conv2DnGPU(32, (5, 5), (1, 1), "SAME"),
ReLU(),
MaxPool((2, 2), (2, 2), "SAME"),
Conv2DnGPU(64, (5, 5), (1, 1), ... | [
"Create",
"a",
"multi",
"-",
"GPU",
"model",
"similar",
"to",
"Madry",
"et",
"al",
".",
"(",
"arXiv",
":",
"1706",
".",
"06083",
")",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/make_model.py#L38-L55 | [
"def",
"make_madry_ngpu",
"(",
"nb_classes",
"=",
"10",
",",
"input_shape",
"=",
"(",
"None",
",",
"28",
",",
"28",
",",
"1",
")",
",",
"*",
"*",
"kwargs",
")",
":",
"layers",
"=",
"[",
"Conv2DnGPU",
"(",
"32",
",",
"(",
"5",
",",
"5",
")",
","... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | ResNetTF._build_model | Build the core model within the graph. | examples/multigpu_advtrain/resnet_tf.py | def _build_model(self, x):
"""Build the core model within the graph."""
with tf.variable_scope('init'):
x = self._conv('init_conv', x, 3, x.shape[3], 16,
self._stride_arr(1))
strides = [1, 2, 2]
activate_before_residual = [True, False, False]
if self.hps.use_bottleneck:
... | def _build_model(self, x):
"""Build the core model within the graph."""
with tf.variable_scope('init'):
x = self._conv('init_conv', x, 3, x.shape[3], 16,
self._stride_arr(1))
strides = [1, 2, 2]
activate_before_residual = [True, False, False]
if self.hps.use_bottleneck:
... | [
"Build",
"the",
"core",
"model",
"within",
"the",
"graph",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/resnet_tf.py#L81-L140 | [
"def",
"_build_model",
"(",
"self",
",",
"x",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"'init'",
")",
":",
"x",
"=",
"self",
".",
"_conv",
"(",
"'init_conv'",
",",
"x",
",",
"3",
",",
"x",
".",
"shape",
"[",
"3",
"]",
",",
"16",
",",... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | ResNetTF.build_cost | Build the graph for cost from the logits if logits are provided.
If predictions are provided, logits are extracted from the operation. | examples/multigpu_advtrain/resnet_tf.py | def build_cost(self, labels, logits):
"""
Build the graph for cost from the logits if logits are provided.
If predictions are provided, logits are extracted from the operation.
"""
op = logits.op
if "softmax" in str(op).lower():
logits, = op.inputs
with tf.variable_scope('costs'):
... | def build_cost(self, labels, logits):
"""
Build the graph for cost from the logits if logits are provided.
If predictions are provided, logits are extracted from the operation.
"""
op = logits.op
if "softmax" in str(op).lower():
logits, = op.inputs
with tf.variable_scope('costs'):
... | [
"Build",
"the",
"graph",
"for",
"cost",
"from",
"the",
"logits",
"if",
"logits",
"are",
"provided",
".",
"If",
"predictions",
"are",
"provided",
"logits",
"are",
"extracted",
"from",
"the",
"operation",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/resnet_tf.py#L142-L158 | [
"def",
"build_cost",
"(",
"self",
",",
"labels",
",",
"logits",
")",
":",
"op",
"=",
"logits",
".",
"op",
"if",
"\"softmax\"",
"in",
"str",
"(",
"op",
")",
".",
"lower",
"(",
")",
":",
"logits",
",",
"=",
"op",
".",
"inputs",
"with",
"tf",
".",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | ResNetTF.build_train_op_from_cost | Build training specific ops for the graph. | examples/multigpu_advtrain/resnet_tf.py | def build_train_op_from_cost(self, cost):
"""Build training specific ops for the graph."""
self.lrn_rate = tf.constant(self.hps.lrn_rate, tf.float32,
name='learning_rate')
self.momentum = tf.constant(self.hps.momentum, tf.float32,
name='momentu... | def build_train_op_from_cost(self, cost):
"""Build training specific ops for the graph."""
self.lrn_rate = tf.constant(self.hps.lrn_rate, tf.float32,
name='learning_rate')
self.momentum = tf.constant(self.hps.momentum, tf.float32,
name='momentu... | [
"Build",
"training",
"specific",
"ops",
"for",
"the",
"graph",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/resnet_tf.py#L160-L187 | [
"def",
"build_train_op_from_cost",
"(",
"self",
",",
"cost",
")",
":",
"self",
".",
"lrn_rate",
"=",
"tf",
".",
"constant",
"(",
"self",
".",
"hps",
".",
"lrn_rate",
",",
"tf",
".",
"float32",
",",
"name",
"=",
"'learning_rate'",
")",
"self",
".",
"mom... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | ResNetTF._layer_norm | Layer normalization. | examples/multigpu_advtrain/resnet_tf.py | def _layer_norm(self, name, x):
"""Layer normalization."""
if self.init_layers:
bn = LayerNorm()
bn.name = name
self.layers += [bn]
else:
bn = self.layers[self.layer_idx]
self.layer_idx += 1
bn.device_name = self.device_name
bn.set_training(self.training)
x = bn.fpr... | def _layer_norm(self, name, x):
"""Layer normalization."""
if self.init_layers:
bn = LayerNorm()
bn.name = name
self.layers += [bn]
else:
bn = self.layers[self.layer_idx]
self.layer_idx += 1
bn.device_name = self.device_name
bn.set_training(self.training)
x = bn.fpr... | [
"Layer",
"normalization",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/resnet_tf.py#L189-L201 | [
"def",
"_layer_norm",
"(",
"self",
",",
"name",
",",
"x",
")",
":",
"if",
"self",
".",
"init_layers",
":",
"bn",
"=",
"LayerNorm",
"(",
")",
"bn",
".",
"name",
"=",
"name",
"self",
".",
"layers",
"+=",
"[",
"bn",
"]",
"else",
":",
"bn",
"=",
"s... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | ResNetTF._residual | Residual unit with 2 sub layers. | examples/multigpu_advtrain/resnet_tf.py | def _residual(self, x, in_filter, out_filter, stride,
activate_before_residual=False):
"""Residual unit with 2 sub layers."""
if activate_before_residual:
with tf.variable_scope('shared_activation'):
x = self._layer_norm('init_bn', x)
x = self._relu(x, self.hps.relu_leakine... | def _residual(self, x, in_filter, out_filter, stride,
activate_before_residual=False):
"""Residual unit with 2 sub layers."""
if activate_before_residual:
with tf.variable_scope('shared_activation'):
x = self._layer_norm('init_bn', x)
x = self._relu(x, self.hps.relu_leakine... | [
"Residual",
"unit",
"with",
"2",
"sub",
"layers",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/resnet_tf.py#L203-L234 | [
"def",
"_residual",
"(",
"self",
",",
"x",
",",
"in_filter",
",",
"out_filter",
",",
"stride",
",",
"activate_before_residual",
"=",
"False",
")",
":",
"if",
"activate_before_residual",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"'shared_activation'",
")",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | ResNetTF._bottleneck_residual | Bottleneck residual unit with 3 sub layers. | examples/multigpu_advtrain/resnet_tf.py | def _bottleneck_residual(self, x, in_filter, out_filter, stride,
activate_before_residual=False):
"""Bottleneck residual unit with 3 sub layers."""
if activate_before_residual:
with tf.variable_scope('common_bn_relu'):
x = self._layer_norm('init_bn', x)
x = self.... | def _bottleneck_residual(self, x, in_filter, out_filter, stride,
activate_before_residual=False):
"""Bottleneck residual unit with 3 sub layers."""
if activate_before_residual:
with tf.variable_scope('common_bn_relu'):
x = self._layer_norm('init_bn', x)
x = self.... | [
"Bottleneck",
"residual",
"unit",
"with",
"3",
"sub",
"layers",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/resnet_tf.py#L236-L271 | [
"def",
"_bottleneck_residual",
"(",
"self",
",",
"x",
",",
"in_filter",
",",
"out_filter",
",",
"stride",
",",
"activate_before_residual",
"=",
"False",
")",
":",
"if",
"activate_before_residual",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"'common_bn_relu'",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | ResNetTF._decay | L2 weight decay loss. | examples/multigpu_advtrain/resnet_tf.py | def _decay(self):
"""L2 weight decay loss."""
if self.decay_cost is not None:
return self.decay_cost
costs = []
if self.device_name is None:
for var in tf.trainable_variables():
if var.op.name.find(r'DW') > 0:
costs.append(tf.nn.l2_loss(var))
else:
for layer in s... | def _decay(self):
"""L2 weight decay loss."""
if self.decay_cost is not None:
return self.decay_cost
costs = []
if self.device_name is None:
for var in tf.trainable_variables():
if var.op.name.find(r'DW') > 0:
costs.append(tf.nn.l2_loss(var))
else:
for layer in s... | [
"L2",
"weight",
"decay",
"loss",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/resnet_tf.py#L273-L291 | [
"def",
"_decay",
"(",
"self",
")",
":",
"if",
"self",
".",
"decay_cost",
"is",
"not",
"None",
":",
"return",
"self",
".",
"decay_cost",
"costs",
"=",
"[",
"]",
"if",
"self",
".",
"device_name",
"is",
"None",
":",
"for",
"var",
"in",
"tf",
".",
"tra... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | ResNetTF._conv | Convolution. | examples/multigpu_advtrain/resnet_tf.py | def _conv(self, name, x, filter_size, in_filters, out_filters, strides):
"""Convolution."""
if self.init_layers:
conv = Conv2DnGPU(out_filters,
(filter_size, filter_size),
strides[1:3], 'SAME', w_name='DW')
conv.name = name
self.layers += [conv]
... | def _conv(self, name, x, filter_size, in_filters, out_filters, strides):
"""Convolution."""
if self.init_layers:
conv = Conv2DnGPU(out_filters,
(filter_size, filter_size),
strides[1:3], 'SAME', w_name='DW')
conv.name = name
self.layers += [conv]
... | [
"Convolution",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/resnet_tf.py#L293-L306 | [
"def",
"_conv",
"(",
"self",
",",
"name",
",",
"x",
",",
"filter_size",
",",
"in_filters",
",",
"out_filters",
",",
"strides",
")",
":",
"if",
"self",
".",
"init_layers",
":",
"conv",
"=",
"Conv2DnGPU",
"(",
"out_filters",
",",
"(",
"filter_size",
",",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | ResNetTF._fully_connected | FullyConnected layer for final output. | examples/multigpu_advtrain/resnet_tf.py | def _fully_connected(self, x, out_dim):
"""FullyConnected layer for final output."""
if self.init_layers:
fc = LinearnGPU(out_dim, w_name='DW')
fc.name = 'logits'
self.layers += [fc]
else:
fc = self.layers[self.layer_idx]
self.layer_idx += 1
fc.device_name = self.device_nam... | def _fully_connected(self, x, out_dim):
"""FullyConnected layer for final output."""
if self.init_layers:
fc = LinearnGPU(out_dim, w_name='DW')
fc.name = 'logits'
self.layers += [fc]
else:
fc = self.layers[self.layer_idx]
self.layer_idx += 1
fc.device_name = self.device_nam... | [
"FullyConnected",
"layer",
"for",
"final",
"output",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/resnet_tf.py#L312-L323 | [
"def",
"_fully_connected",
"(",
"self",
",",
"x",
",",
"out_dim",
")",
":",
"if",
"self",
".",
"init_layers",
":",
"fc",
"=",
"LinearnGPU",
"(",
"out_dim",
",",
"w_name",
"=",
"'DW'",
")",
"fc",
".",
"name",
"=",
"'logits'",
"self",
".",
"layers",
"+... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | read_classification_results | Reads classification results from the file in Cloud Storage.
This method reads file with classification results produced by running
defense on singe batch of adversarial images.
Args:
storage_client: instance of CompetitionStorageClient or None for local file
file_path: path of the file with results
... | examples/nips17_adversarial_competition/eval_infra/code/eval_lib/classification_results.py | def read_classification_results(storage_client, file_path):
"""Reads classification results from the file in Cloud Storage.
This method reads file with classification results produced by running
defense on singe batch of adversarial images.
Args:
storage_client: instance of CompetitionStorageClient or Non... | def read_classification_results(storage_client, file_path):
"""Reads classification results from the file in Cloud Storage.
This method reads file with classification results produced by running
defense on singe batch of adversarial images.
Args:
storage_client: instance of CompetitionStorageClient or Non... | [
"Reads",
"classification",
"results",
"from",
"the",
"file",
"in",
"Cloud",
"Storage",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/classification_results.py#L30-L86 | [
"def",
"read_classification_results",
"(",
"storage_client",
",",
"file_path",
")",
":",
"if",
"storage_client",
":",
"# file on Cloud",
"success",
"=",
"False",
"retry_count",
"=",
"0",
"while",
"retry_count",
"<",
"4",
":",
"try",
":",
"blob",
"=",
"storage_cl... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | analyze_one_classification_result | Reads and analyzes one classification result.
This method reads file with classification result and counts
how many images were classified correctly and incorrectly,
how many times target class was hit and total number of images.
Args:
storage_client: instance of CompetitionStorageClient
file_path: re... | examples/nips17_adversarial_competition/eval_infra/code/eval_lib/classification_results.py | def analyze_one_classification_result(storage_client, file_path,
adv_batch, dataset_batches,
dataset_meta):
"""Reads and analyzes one classification result.
This method reads file with classification result and counts
how many images wer... | def analyze_one_classification_result(storage_client, file_path,
adv_batch, dataset_batches,
dataset_meta):
"""Reads and analyzes one classification result.
This method reads file with classification result and counts
how many images wer... | [
"Reads",
"and",
"analyzes",
"one",
"classification",
"result",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/classification_results.py#L89-L134 | [
"def",
"analyze_one_classification_result",
"(",
"storage_client",
",",
"file_path",
",",
"adv_batch",
",",
"dataset_batches",
",",
"dataset_meta",
")",
":",
"class_result",
"=",
"read_classification_results",
"(",
"storage_client",
",",
"file_path",
")",
"if",
"class_r... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | ResultMatrix.save_to_file | Saves matrix to the file.
Args:
filename: name of the file where to save matrix
remap_dim0: dictionary with mapping row indices to row names which should
be saved to file. If none then indices will be used as names.
remap_dim1: dictionary with mapping column indices to column names which
... | examples/nips17_adversarial_competition/eval_infra/code/eval_lib/classification_results.py | def save_to_file(self, filename, remap_dim0=None, remap_dim1=None):
"""Saves matrix to the file.
Args:
filename: name of the file where to save matrix
remap_dim0: dictionary with mapping row indices to row names which should
be saved to file. If none then indices will be used as names.
... | def save_to_file(self, filename, remap_dim0=None, remap_dim1=None):
"""Saves matrix to the file.
Args:
filename: name of the file where to save matrix
remap_dim0: dictionary with mapping row indices to row names which should
be saved to file. If none then indices will be used as names.
... | [
"Saves",
"matrix",
"to",
"the",
"file",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/classification_results.py#L192-L215 | [
"def",
"save_to_file",
"(",
"self",
",",
"filename",
",",
"remap_dim0",
"=",
"None",
",",
"remap_dim1",
"=",
"None",
")",
":",
"# rows - first index",
"# columns - second index",
"with",
"open",
"(",
"filename",
",",
"'w'",
")",
"as",
"fobj",
":",
"columns",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | ClassificationBatches.init_from_adversarial_batches_write_to_datastore | Populates data from adversarial batches and writes to datastore.
Args:
submissions: instance of CompetitionSubmissions
adv_batches: instance of AversarialBatches | examples/nips17_adversarial_competition/eval_infra/code/eval_lib/classification_results.py | def init_from_adversarial_batches_write_to_datastore(self, submissions,
adv_batches):
"""Populates data from adversarial batches and writes to datastore.
Args:
submissions: instance of CompetitionSubmissions
adv_batches: instance of AversarialB... | def init_from_adversarial_batches_write_to_datastore(self, submissions,
adv_batches):
"""Populates data from adversarial batches and writes to datastore.
Args:
submissions: instance of CompetitionSubmissions
adv_batches: instance of AversarialB... | [
"Populates",
"data",
"from",
"adversarial",
"batches",
"and",
"writes",
"to",
"datastore",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/classification_results.py#L256-L284 | [
"def",
"init_from_adversarial_batches_write_to_datastore",
"(",
"self",
",",
"submissions",
",",
"adv_batches",
")",
":",
"# prepare classification batches",
"idx",
"=",
"0",
"for",
"s_id",
"in",
"iterkeys",
"(",
"submissions",
".",
"defenses",
")",
":",
"for",
"adv... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | ClassificationBatches.init_from_datastore | Initializes data by reading it from the datastore. | examples/nips17_adversarial_competition/eval_infra/code/eval_lib/classification_results.py | def init_from_datastore(self):
"""Initializes data by reading it from the datastore."""
self._data = {}
client = self._datastore_client
for entity in client.query_fetch(kind=KIND_CLASSIFICATION_BATCH):
class_batch_id = entity.key.flat_path[-1]
self.data[class_batch_id] = dict(entity) | def init_from_datastore(self):
"""Initializes data by reading it from the datastore."""
self._data = {}
client = self._datastore_client
for entity in client.query_fetch(kind=KIND_CLASSIFICATION_BATCH):
class_batch_id = entity.key.flat_path[-1]
self.data[class_batch_id] = dict(entity) | [
"Initializes",
"data",
"by",
"reading",
"it",
"from",
"the",
"datastore",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/classification_results.py#L286-L292 | [
"def",
"init_from_datastore",
"(",
"self",
")",
":",
"self",
".",
"_data",
"=",
"{",
"}",
"client",
"=",
"self",
".",
"_datastore_client",
"for",
"entity",
"in",
"client",
".",
"query_fetch",
"(",
"kind",
"=",
"KIND_CLASSIFICATION_BATCH",
")",
":",
"class_ba... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | ClassificationBatches.read_batch_from_datastore | Reads and returns single batch from the datastore. | examples/nips17_adversarial_competition/eval_infra/code/eval_lib/classification_results.py | def read_batch_from_datastore(self, class_batch_id):
"""Reads and returns single batch from the datastore."""
client = self._datastore_client
key = client.key(KIND_CLASSIFICATION_BATCH, class_batch_id)
result = client.get(key)
if result is not None:
return dict(result)
else:
raise Ke... | def read_batch_from_datastore(self, class_batch_id):
"""Reads and returns single batch from the datastore."""
client = self._datastore_client
key = client.key(KIND_CLASSIFICATION_BATCH, class_batch_id)
result = client.get(key)
if result is not None:
return dict(result)
else:
raise Ke... | [
"Reads",
"and",
"returns",
"single",
"batch",
"from",
"the",
"datastore",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/classification_results.py#L294-L303 | [
"def",
"read_batch_from_datastore",
"(",
"self",
",",
"class_batch_id",
")",
":",
"client",
"=",
"self",
".",
"_datastore_client",
"key",
"=",
"client",
".",
"key",
"(",
"KIND_CLASSIFICATION_BATCH",
",",
"class_batch_id",
")",
"result",
"=",
"client",
".",
"get"... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | ClassificationBatches.compute_classification_results | Computes classification results.
Args:
adv_batches: instance of AversarialBatches
dataset_batches: instance of DatasetBatches
dataset_meta: instance of DatasetMetadata
defense_work: instance of DefenseWorkPieces
Returns:
accuracy_matrix, error_matrix, hit_target_class_matrix,
... | examples/nips17_adversarial_competition/eval_infra/code/eval_lib/classification_results.py | def compute_classification_results(self, adv_batches, dataset_batches,
dataset_meta, defense_work=None):
"""Computes classification results.
Args:
adv_batches: instance of AversarialBatches
dataset_batches: instance of DatasetBatches
dataset_meta: instance... | def compute_classification_results(self, adv_batches, dataset_batches,
dataset_meta, defense_work=None):
"""Computes classification results.
Args:
adv_batches: instance of AversarialBatches
dataset_batches: instance of DatasetBatches
dataset_meta: instance... | [
"Computes",
"classification",
"results",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/classification_results.py#L305-L373 | [
"def",
"compute_classification_results",
"(",
"self",
",",
"adv_batches",
",",
"dataset_batches",
",",
"dataset_meta",
",",
"defense_work",
"=",
"None",
")",
":",
"class_batch_to_work",
"=",
"{",
"}",
"if",
"defense_work",
":",
"for",
"v",
"in",
"itervalues",
"(... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | participant_from_submission_path | Parses type of participant based on submission filename.
Args:
submission_path: path to the submission in Google Cloud Storage
Returns:
dict with one element. Element key correspond to type of participant
(team, baseline), element value is ID of the participant.
Raises:
ValueError: is participa... | examples/nips17_adversarial_competition/eval_infra/code/eval_lib/submissions.py | def participant_from_submission_path(submission_path):
"""Parses type of participant based on submission filename.
Args:
submission_path: path to the submission in Google Cloud Storage
Returns:
dict with one element. Element key correspond to type of participant
(team, baseline), element value is ID... | def participant_from_submission_path(submission_path):
"""Parses type of participant based on submission filename.
Args:
submission_path: path to the submission in Google Cloud Storage
Returns:
dict with one element. Element key correspond to type of participant
(team, baseline), element value is ID... | [
"Parses",
"type",
"of",
"participant",
"based",
"on",
"submission",
"filename",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/submissions.py#L35-L61 | [
"def",
"participant_from_submission_path",
"(",
"submission_path",
")",
":",
"basename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"submission_path",
")",
"file_ext",
"=",
"None",
"for",
"e",
"in",
"ALLOWED_EXTENSIONS",
":",
"if",
"basename",
".",
"endswith"... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | CompetitionSubmissions._load_submissions_from_datastore_dir | Loads list of submissions from the directory.
Args:
dir_suffix: suffix of the directory where submissions are stored,
one of the folowing constants: ATTACK_SUBDIR, TARGETED_ATTACK_SUBDIR
or DEFENSE_SUBDIR.
id_pattern: pattern which is used to generate (internal) IDs
for submissi... | examples/nips17_adversarial_competition/eval_infra/code/eval_lib/submissions.py | def _load_submissions_from_datastore_dir(self, dir_suffix, id_pattern):
"""Loads list of submissions from the directory.
Args:
dir_suffix: suffix of the directory where submissions are stored,
one of the folowing constants: ATTACK_SUBDIR, TARGETED_ATTACK_SUBDIR
or DEFENSE_SUBDIR.
id... | def _load_submissions_from_datastore_dir(self, dir_suffix, id_pattern):
"""Loads list of submissions from the directory.
Args:
dir_suffix: suffix of the directory where submissions are stored,
one of the folowing constants: ATTACK_SUBDIR, TARGETED_ATTACK_SUBDIR
or DEFENSE_SUBDIR.
id... | [
"Loads",
"list",
"of",
"submissions",
"from",
"the",
"directory",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/submissions.py#L99-L119 | [
"def",
"_load_submissions_from_datastore_dir",
"(",
"self",
",",
"dir_suffix",
",",
"id_pattern",
")",
":",
"submissions",
"=",
"self",
".",
"_storage_client",
".",
"list_blobs",
"(",
"prefix",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_round_nam... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | CompetitionSubmissions.init_from_storage_write_to_datastore | Init list of sumibssions from Storage and saves them to Datastore.
Should be called only once (typically by master) during evaluation of
the competition. | examples/nips17_adversarial_competition/eval_infra/code/eval_lib/submissions.py | def init_from_storage_write_to_datastore(self):
"""Init list of sumibssions from Storage and saves them to Datastore.
Should be called only once (typically by master) during evaluation of
the competition.
"""
# Load submissions
self._attacks = self._load_submissions_from_datastore_dir(
... | def init_from_storage_write_to_datastore(self):
"""Init list of sumibssions from Storage and saves them to Datastore.
Should be called only once (typically by master) during evaluation of
the competition.
"""
# Load submissions
self._attacks = self._load_submissions_from_datastore_dir(
... | [
"Init",
"list",
"of",
"sumibssions",
"from",
"Storage",
"and",
"saves",
"them",
"to",
"Datastore",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/submissions.py#L121-L134 | [
"def",
"init_from_storage_write_to_datastore",
"(",
"self",
")",
":",
"# Load submissions",
"self",
".",
"_attacks",
"=",
"self",
".",
"_load_submissions_from_datastore_dir",
"(",
"ATTACK_SUBDIR",
",",
"ATTACK_ID_PATTERN",
")",
"self",
".",
"_targeted_attacks",
"=",
"se... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | CompetitionSubmissions._write_to_datastore | Writes all submissions to datastore. | examples/nips17_adversarial_competition/eval_infra/code/eval_lib/submissions.py | def _write_to_datastore(self):
"""Writes all submissions to datastore."""
# Populate datastore
roots_and_submissions = zip([ATTACKS_ENTITY_KEY,
TARGET_ATTACKS_ENTITY_KEY,
DEFENSES_ENTITY_KEY],
[self._attacks,
... | def _write_to_datastore(self):
"""Writes all submissions to datastore."""
# Populate datastore
roots_and_submissions = zip([ATTACKS_ENTITY_KEY,
TARGET_ATTACKS_ENTITY_KEY,
DEFENSES_ENTITY_KEY],
[self._attacks,
... | [
"Writes",
"all",
"submissions",
"to",
"datastore",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/submissions.py#L136-L154 | [
"def",
"_write_to_datastore",
"(",
"self",
")",
":",
"# Populate datastore",
"roots_and_submissions",
"=",
"zip",
"(",
"[",
"ATTACKS_ENTITY_KEY",
",",
"TARGET_ATTACKS_ENTITY_KEY",
",",
"DEFENSES_ENTITY_KEY",
"]",
",",
"[",
"self",
".",
"_attacks",
",",
"self",
".",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | CompetitionSubmissions.init_from_datastore | Init list of submission from Datastore.
Should be called by each worker during initialization. | examples/nips17_adversarial_competition/eval_infra/code/eval_lib/submissions.py | def init_from_datastore(self):
"""Init list of submission from Datastore.
Should be called by each worker during initialization.
"""
self._attacks = {}
self._targeted_attacks = {}
self._defenses = {}
for entity in self._datastore_client.query_fetch(kind=KIND_SUBMISSION):
submission_id... | def init_from_datastore(self):
"""Init list of submission from Datastore.
Should be called by each worker during initialization.
"""
self._attacks = {}
self._targeted_attacks = {}
self._defenses = {}
for entity in self._datastore_client.query_fetch(kind=KIND_SUBMISSION):
submission_id... | [
"Init",
"list",
"of",
"submission",
"from",
"Datastore",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/submissions.py#L156-L177 | [
"def",
"init_from_datastore",
"(",
"self",
")",
":",
"self",
".",
"_attacks",
"=",
"{",
"}",
"self",
".",
"_targeted_attacks",
"=",
"{",
"}",
"self",
".",
"_defenses",
"=",
"{",
"}",
"for",
"entity",
"in",
"self",
".",
"_datastore_client",
".",
"query_fe... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | CompetitionSubmissions.get_all_attack_ids | Returns IDs of all attacks (targeted and non-targeted). | examples/nips17_adversarial_competition/eval_infra/code/eval_lib/submissions.py | def get_all_attack_ids(self):
"""Returns IDs of all attacks (targeted and non-targeted)."""
return list(self.attacks.keys()) + list(self.targeted_attacks.keys()) | def get_all_attack_ids(self):
"""Returns IDs of all attacks (targeted and non-targeted)."""
return list(self.attacks.keys()) + list(self.targeted_attacks.keys()) | [
"Returns",
"IDs",
"of",
"all",
"attacks",
"(",
"targeted",
"and",
"non",
"-",
"targeted",
")",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/submissions.py#L194-L196 | [
"def",
"get_all_attack_ids",
"(",
"self",
")",
":",
"return",
"list",
"(",
"self",
".",
"attacks",
".",
"keys",
"(",
")",
")",
"+",
"list",
"(",
"self",
".",
"targeted_attacks",
".",
"keys",
"(",
")",
")"
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | CompetitionSubmissions.find_by_id | Finds submission by ID.
Args:
submission_id: ID of the submission
Returns:
SubmissionDescriptor with information about submission or None if
submission is not found. | examples/nips17_adversarial_competition/eval_infra/code/eval_lib/submissions.py | def find_by_id(self, submission_id):
"""Finds submission by ID.
Args:
submission_id: ID of the submission
Returns:
SubmissionDescriptor with information about submission or None if
submission is not found.
"""
return self._attacks.get(
submission_id,
self._defense... | def find_by_id(self, submission_id):
"""Finds submission by ID.
Args:
submission_id: ID of the submission
Returns:
SubmissionDescriptor with information about submission or None if
submission is not found.
"""
return self._attacks.get(
submission_id,
self._defense... | [
"Finds",
"submission",
"by",
"ID",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/submissions.py#L198-L212 | [
"def",
"find_by_id",
"(",
"self",
",",
"submission_id",
")",
":",
"return",
"self",
".",
"_attacks",
".",
"get",
"(",
"submission_id",
",",
"self",
".",
"_defenses",
".",
"get",
"(",
"submission_id",
",",
"self",
".",
"_targeted_attacks",
".",
"get",
"(",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | CompetitionSubmissions.get_external_id | Returns human readable submission external ID.
Args:
submission_id: internal submission ID.
Returns:
human readable ID. | examples/nips17_adversarial_competition/eval_infra/code/eval_lib/submissions.py | def get_external_id(self, submission_id):
"""Returns human readable submission external ID.
Args:
submission_id: internal submission ID.
Returns:
human readable ID.
"""
submission = self.find_by_id(submission_id)
if not submission:
return None
if 'team_id' in submission.p... | def get_external_id(self, submission_id):
"""Returns human readable submission external ID.
Args:
submission_id: internal submission ID.
Returns:
human readable ID.
"""
submission = self.find_by_id(submission_id)
if not submission:
return None
if 'team_id' in submission.p... | [
"Returns",
"human",
"readable",
"submission",
"external",
"ID",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/submissions.py#L214-L231 | [
"def",
"get_external_id",
"(",
"self",
",",
"submission_id",
")",
":",
"submission",
"=",
"self",
".",
"find_by_id",
"(",
"submission_id",
")",
"if",
"not",
"submission",
":",
"return",
"None",
"if",
"'team_id'",
"in",
"submission",
".",
"participant_id",
":",... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | SubmissionValidator._prepare_temp_dir | Cleans up and prepare temporary directory. | examples/nips17_adversarial_competition/dev_toolkit/validation_tool/submission_validator_lib.py | def _prepare_temp_dir(self):
"""Cleans up and prepare temporary directory."""
shell_call(['rm', '-rf', os.path.join(self._temp_dir, '*')])
# NOTE: we do not create self._extracted_submission_dir
# this is intentional because self._tmp_extracted_dir or it's subdir
# will be renames into self._extract... | def _prepare_temp_dir(self):
"""Cleans up and prepare temporary directory."""
shell_call(['rm', '-rf', os.path.join(self._temp_dir, '*')])
# NOTE: we do not create self._extracted_submission_dir
# this is intentional because self._tmp_extracted_dir or it's subdir
# will be renames into self._extract... | [
"Cleans",
"up",
"and",
"prepare",
"temporary",
"directory",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/validation_tool/submission_validator_lib.py#L133-L143 | [
"def",
"_prepare_temp_dir",
"(",
"self",
")",
":",
"shell_call",
"(",
"[",
"'rm'",
",",
"'-rf'",
",",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_temp_dir",
",",
"'*'",
")",
"]",
")",
"# NOTE: we do not create self._extracted_submission_dir",
"# this i... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | SubmissionValidator._load_and_verify_metadata | Loads and verifies metadata.
Args:
submission_type: type of the submission
Returns:
dictionaty with metadata or None if metadata not found or invalid | examples/nips17_adversarial_competition/dev_toolkit/validation_tool/submission_validator_lib.py | def _load_and_verify_metadata(self, submission_type):
"""Loads and verifies metadata.
Args:
submission_type: type of the submission
Returns:
dictionaty with metadata or None if metadata not found or invalid
"""
metadata_filename = os.path.join(self._extracted_submission_dir,
... | def _load_and_verify_metadata(self, submission_type):
"""Loads and verifies metadata.
Args:
submission_type: type of the submission
Returns:
dictionaty with metadata or None if metadata not found or invalid
"""
metadata_filename = os.path.join(self._extracted_submission_dir,
... | [
"Loads",
"and",
"verifies",
"metadata",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/validation_tool/submission_validator_lib.py#L204-L245 | [
"def",
"_load_and_verify_metadata",
"(",
"self",
",",
"submission_type",
")",
":",
"metadata_filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_extracted_submission_dir",
",",
"'metadata.json'",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfil... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | SubmissionValidator._run_submission | Runs submission inside Docker container.
Args:
metadata: dictionary with submission metadata
Returns:
True if status code of Docker command was success (i.e. zero),
False otherwise. | examples/nips17_adversarial_competition/dev_toolkit/validation_tool/submission_validator_lib.py | def _run_submission(self, metadata):
"""Runs submission inside Docker container.
Args:
metadata: dictionary with submission metadata
Returns:
True if status code of Docker command was success (i.e. zero),
False otherwise.
"""
if self._use_gpu:
docker_binary = 'nvidia-docker... | def _run_submission(self, metadata):
"""Runs submission inside Docker container.
Args:
metadata: dictionary with submission metadata
Returns:
True if status code of Docker command was success (i.e. zero),
False otherwise.
"""
if self._use_gpu:
docker_binary = 'nvidia-docker... | [
"Runs",
"submission",
"inside",
"Docker",
"container",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/validation_tool/submission_validator_lib.py#L290-L333 | [
"def",
"_run_submission",
"(",
"self",
",",
"metadata",
")",
":",
"if",
"self",
".",
"_use_gpu",
":",
"docker_binary",
"=",
"'nvidia-docker'",
"container_name",
"=",
"metadata",
"[",
"'container_gpu'",
"]",
"else",
":",
"docker_binary",
"=",
"'docker'",
"contain... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | fast_gradient_method | Tensorflow 2.0 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 val... | cleverhans/future/tf2/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):
"""
Tensorflow 2.0 implementation of the Fast Gradient Method.
:param model_fn: a callable that takes an input tensor and returns the model logits.
:param x: input... | def fast_gradient_method(model_fn, x, eps, ord, clip_min=None, clip_max=None, y=None,
targeted=False, sanity_checks=False):
"""
Tensorflow 2.0 implementation of the Fast Gradient Method.
:param model_fn: a callable that takes an input tensor and returns the model logits.
:param x: input... | [
"Tensorflow",
"2",
".",
"0",
"implementation",
"of",
"the",
"Fast",
"Gradient",
"Method",
".",
":",
"param",
"model_fn",
":",
"a",
"callable",
"that",
"takes",
"an",
"input",
"tensor",
"and",
"returns",
"the",
"model",
"logits",
".",
":",
"param",
"x",
"... | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/future/tf2/attacks/fast_gradient_method.py#L7-L59 | [
"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 | compute_gradient | Computes the gradient of the loss with respect to the input tensor.
:param model_fn: a callable that takes an input tensor and returns the model logits.
:param x: input tensor
:param y: Tensor with true labels. If targeted is true, then provide the target label.
:param targeted: bool. Is the attack targeted or... | cleverhans/future/tf2/attacks/fast_gradient_method.py | def compute_gradient(model_fn, x, y, targeted):
"""
Computes the gradient of the loss with respect to the input tensor.
:param model_fn: a callable that takes an input tensor and returns the model logits.
:param x: input tensor
:param y: Tensor with true labels. If targeted is true, then provide the target la... | def compute_gradient(model_fn, x, y, targeted):
"""
Computes the gradient of the loss with respect to the input tensor.
:param model_fn: a callable that takes an input tensor and returns the model logits.
:param x: input tensor
:param y: Tensor with true labels. If targeted is true, then provide the target la... | [
"Computes",
"the",
"gradient",
"of",
"the",
"loss",
"with",
"respect",
"to",
"the",
"input",
"tensor",
".",
":",
"param",
"model_fn",
":",
"a",
"callable",
"that",
"takes",
"an",
"input",
"tensor",
"and",
"returns",
"the",
"model",
"logits",
".",
":",
"p... | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/future/tf2/attacks/fast_gradient_method.py#L66-L87 | [
"def",
"compute_gradient",
"(",
"model_fn",
",",
"x",
",",
"y",
",",
"targeted",
")",
":",
"loss_fn",
"=",
"tf",
".",
"nn",
".",
"sparse_softmax_cross_entropy_with_logits",
"with",
"tf",
".",
"GradientTape",
"(",
")",
"as",
"g",
":",
"g",
".",
"watch",
"... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | optimize_linear | Solves for the optimal input to a linear function under a norm constraint.
Optimal_perturbation = argmax_{eta, ||eta||_{ord} < eps} dot(eta, grad)
:param grad: tf tensor containing a batch of gradients
:param eps: float scalar specifying size of constraint region
:param ord: int specifying order of norm
:re... | cleverhans/future/tf2/attacks/fast_gradient_method.py | def optimize_linear(grad, eps, ord=np.inf):
"""
Solves for the optimal input to a linear function under a norm constraint.
Optimal_perturbation = argmax_{eta, ||eta||_{ord} < eps} dot(eta, grad)
:param grad: tf tensor containing a batch of gradients
:param eps: float scalar specifying size of constraint reg... | def optimize_linear(grad, eps, ord=np.inf):
"""
Solves for the optimal input to a linear function under a norm constraint.
Optimal_perturbation = argmax_{eta, ||eta||_{ord} < eps} dot(eta, grad)
:param grad: tf tensor containing a batch of gradients
:param eps: float scalar specifying size of constraint reg... | [
"Solves",
"for",
"the",
"optimal",
"input",
"to",
"a",
"linear",
"function",
"under",
"a",
"norm",
"constraint",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/future/tf2/attacks/fast_gradient_method.py#L90-L128 | [
"def",
"optimize_linear",
"(",
"grad",
",",
"eps",
",",
"ord",
"=",
"np",
".",
"inf",
")",
":",
"# Convert the iterator returned by `range` into a list.",
"axis",
"=",
"list",
"(",
"range",
"(",
"1",
",",
"len",
"(",
"grad",
".",
"get_shape",
"(",
")",
")"... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | save_pdf | Saves a pdf of the current matplotlib figure.
:param path: str, filepath to save to | cleverhans/plot/save_pdf.py | def save_pdf(path):
"""
Saves a pdf of the current matplotlib figure.
:param path: str, filepath to save to
"""
pp = PdfPages(path)
pp.savefig(pyplot.gcf())
pp.close() | def save_pdf(path):
"""
Saves a pdf of the current matplotlib figure.
:param path: str, filepath to save to
"""
pp = PdfPages(path)
pp.savefig(pyplot.gcf())
pp.close() | [
"Saves",
"a",
"pdf",
"of",
"the",
"current",
"matplotlib",
"figure",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/plot/save_pdf.py#L8-L17 | [
"def",
"save_pdf",
"(",
"path",
")",
":",
"pp",
"=",
"PdfPages",
"(",
"path",
")",
"pp",
".",
"savefig",
"(",
"pyplot",
".",
"gcf",
"(",
")",
")",
"pp",
".",
"close",
"(",
")"
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | clip_eta | Helper function to clip the perturbation to epsilon norm ball.
:param eta: A tensor with the current perturbation.
:param ord: Order of the norm (mimics Numpy).
Possible values: np.inf, 1 or 2.
:param eps: Epsilon, bound of the perturbation. | cleverhans/future/tf2/utils_tf.py | def clip_eta(eta, ord, eps):
"""
Helper function to clip the perturbation to epsilon norm ball.
:param eta: A tensor with the current perturbation.
:param ord: Order of the norm (mimics Numpy).
Possible values: np.inf, 1 or 2.
:param eps: Epsilon, bound of the perturbation.
"""
# Clipping p... | def clip_eta(eta, ord, eps):
"""
Helper function to clip the perturbation to epsilon norm ball.
:param eta: A tensor with the current perturbation.
:param ord: Order of the norm (mimics Numpy).
Possible values: np.inf, 1 or 2.
:param eps: Epsilon, bound of the perturbation.
"""
# Clipping p... | [
"Helper",
"function",
"to",
"clip",
"the",
"perturbation",
"to",
"epsilon",
"norm",
"ball",
".",
":",
"param",
"eta",
":",
"A",
"tensor",
"with",
"the",
"current",
"perturbation",
".",
":",
"param",
"ord",
":",
"Order",
"of",
"the",
"norm",
"(",
"mimics"... | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/future/tf2/utils_tf.py#L5-L33 | [
"def",
"clip_eta",
"(",
"eta",
",",
"ord",
",",
"eps",
")",
":",
"# Clipping perturbation eta to self.ord norm ball",
"if",
"ord",
"not",
"in",
"[",
"np",
".",
"inf",
",",
"1",
",",
"2",
"]",
":",
"raise",
"ValueError",
"(",
"'ord must be np.inf, 1, or 2.'",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | prep_bbox | Define and train a model that simulates the "remote"
black-box oracle described in the original paper.
:param sess: the TF session
:param x: the input placeholder for MNIST
:param y: the ouput placeholder for MNIST
:param x_train: the training data for the oracle
:param y_train: the training labels for the ... | cleverhans_tutorials/mnist_blackbox.py | def prep_bbox(sess, x, y, x_train, y_train, x_test, y_test,
nb_epochs, batch_size, learning_rate,
rng, nb_classes=10, img_rows=28, img_cols=28, nchannels=1):
"""
Define and train a model that simulates the "remote"
black-box oracle described in the original paper.
:param sess: the TF... | def prep_bbox(sess, x, y, x_train, y_train, x_test, y_test,
nb_epochs, batch_size, learning_rate,
rng, nb_classes=10, img_rows=28, img_cols=28, nchannels=1):
"""
Define and train a model that simulates the "remote"
black-box oracle described in the original paper.
:param sess: the TF... | [
"Define",
"and",
"train",
"a",
"model",
"that",
"simulates",
"the",
"remote",
"black",
"-",
"box",
"oracle",
"described",
"in",
"the",
"original",
"paper",
".",
":",
"param",
"sess",
":",
"the",
"TF",
"session",
":",
"param",
"x",
":",
"the",
"input",
... | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans_tutorials/mnist_blackbox.py#L59-L101 | [
"def",
"prep_bbox",
"(",
"sess",
",",
"x",
",",
"y",
",",
"x_train",
",",
"y_train",
",",
"x_test",
",",
"y_test",
",",
"nb_epochs",
",",
"batch_size",
",",
"learning_rate",
",",
"rng",
",",
"nb_classes",
"=",
"10",
",",
"img_rows",
"=",
"28",
",",
"... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | train_sub | This function creates the substitute by alternatively
augmenting the training data and training the substitute.
:param sess: TF session
:param x: input TF placeholder
:param y: output TF placeholder
:param bbox_preds: output of black-box model predictions
:param x_sub: initial substitute training data
:pa... | cleverhans_tutorials/mnist_blackbox.py | def train_sub(sess, x, y, bbox_preds, x_sub, y_sub, nb_classes,
nb_epochs_s, batch_size, learning_rate, data_aug, lmbda,
aug_batch_size, rng, img_rows=28, img_cols=28,
nchannels=1):
"""
This function creates the substitute by alternatively
augmenting the training data and... | def train_sub(sess, x, y, bbox_preds, x_sub, y_sub, nb_classes,
nb_epochs_s, batch_size, learning_rate, data_aug, lmbda,
aug_batch_size, rng, img_rows=28, img_cols=28,
nchannels=1):
"""
This function creates the substitute by alternatively
augmenting the training data and... | [
"This",
"function",
"creates",
"the",
"substitute",
"by",
"alternatively",
"augmenting",
"the",
"training",
"data",
"and",
"training",
"the",
"substitute",
".",
":",
"param",
"sess",
":",
"TF",
"session",
":",
"param",
"x",
":",
"input",
"TF",
"placeholder",
... | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans_tutorials/mnist_blackbox.py#L123-L188 | [
"def",
"train_sub",
"(",
"sess",
",",
"x",
",",
"y",
",",
"bbox_preds",
",",
"x_sub",
",",
"y_sub",
",",
"nb_classes",
",",
"nb_epochs_s",
",",
"batch_size",
",",
"learning_rate",
",",
"data_aug",
",",
"lmbda",
",",
"aug_batch_size",
",",
"rng",
",",
"im... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | mnist_blackbox | MNIST tutorial for the black-box attack from arxiv.org/abs/1602.02697
:param train_start: index of first training set example
:param train_end: index of last training set example
:param test_start: index of first test set example
:param test_end: index of last test set example
:return: a dictionary with:
... | cleverhans_tutorials/mnist_blackbox.py | def mnist_blackbox(train_start=0, train_end=60000, test_start=0,
test_end=10000, nb_classes=NB_CLASSES,
batch_size=BATCH_SIZE, learning_rate=LEARNING_RATE,
nb_epochs=NB_EPOCHS, holdout=HOLDOUT, data_aug=DATA_AUG,
nb_epochs_s=NB_EPOCHS_S, lmbda=... | def mnist_blackbox(train_start=0, train_end=60000, test_start=0,
test_end=10000, nb_classes=NB_CLASSES,
batch_size=BATCH_SIZE, learning_rate=LEARNING_RATE,
nb_epochs=NB_EPOCHS, holdout=HOLDOUT, data_aug=DATA_AUG,
nb_epochs_s=NB_EPOCHS_S, lmbda=... | [
"MNIST",
"tutorial",
"for",
"the",
"black",
"-",
"box",
"attack",
"from",
"arxiv",
".",
"org",
"/",
"abs",
"/",
"1602",
".",
"02697",
":",
"param",
"train_start",
":",
"index",
"of",
"first",
"training",
"set",
"example",
":",
"param",
"train_end",
":",
... | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans_tutorials/mnist_blackbox.py#L191-L284 | [
"def",
"mnist_blackbox",
"(",
"train_start",
"=",
"0",
",",
"train_end",
"=",
"60000",
",",
"test_start",
"=",
"0",
",",
"test_end",
"=",
"10000",
",",
"nb_classes",
"=",
"NB_CLASSES",
",",
"batch_size",
"=",
"BATCH_SIZE",
",",
"learning_rate",
"=",
"LEARNIN... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | random_shift | Pad a single image and then crop to the original size with a random
offset. | cleverhans/augmentation.py | def random_shift(x, pad=(4, 4), mode='REFLECT'):
"""Pad a single image and then crop to the original size with a random
offset."""
assert mode in 'REFLECT SYMMETRIC CONSTANT'.split()
assert x.get_shape().ndims == 3
xp = tf.pad(x, [[pad[0], pad[0]], [pad[1], pad[1]], [0, 0]], mode)
return tf.random_crop(xp, ... | def random_shift(x, pad=(4, 4), mode='REFLECT'):
"""Pad a single image and then crop to the original size with a random
offset."""
assert mode in 'REFLECT SYMMETRIC CONSTANT'.split()
assert x.get_shape().ndims == 3
xp = tf.pad(x, [[pad[0], pad[0]], [pad[1], pad[1]], [0, 0]], mode)
return tf.random_crop(xp, ... | [
"Pad",
"a",
"single",
"image",
"and",
"then",
"crop",
"to",
"the",
"original",
"size",
"with",
"a",
"random",
"offset",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/augmentation.py#L19-L25 | [
"def",
"random_shift",
"(",
"x",
",",
"pad",
"=",
"(",
"4",
",",
"4",
")",
",",
"mode",
"=",
"'REFLECT'",
")",
":",
"assert",
"mode",
"in",
"'REFLECT SYMMETRIC CONSTANT'",
".",
"split",
"(",
")",
"assert",
"x",
".",
"get_shape",
"(",
")",
".",
"ndims... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | batch_augment | Apply dataset augmentation to a batch of exmaples.
:param x: Tensor representing a batch of examples.
:param func: Callable implementing dataset augmentation, operating on
a single image.
:param device: String specifying which device to use. | cleverhans/augmentation.py | def batch_augment(x, func, device='/CPU:0'):
"""
Apply dataset augmentation to a batch of exmaples.
:param x: Tensor representing a batch of examples.
:param func: Callable implementing dataset augmentation, operating on
a single image.
:param device: String specifying which device to use.
"""
with tf... | def batch_augment(x, func, device='/CPU:0'):
"""
Apply dataset augmentation to a batch of exmaples.
:param x: Tensor representing a batch of examples.
:param func: Callable implementing dataset augmentation, operating on
a single image.
:param device: String specifying which device to use.
"""
with tf... | [
"Apply",
"dataset",
"augmentation",
"to",
"a",
"batch",
"of",
"exmaples",
".",
":",
"param",
"x",
":",
"Tensor",
"representing",
"a",
"batch",
"of",
"examples",
".",
":",
"param",
"func",
":",
"Callable",
"implementing",
"dataset",
"augmentation",
"operating",... | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/augmentation.py#L28-L37 | [
"def",
"batch_augment",
"(",
"x",
",",
"func",
",",
"device",
"=",
"'/CPU:0'",
")",
":",
"with",
"tf",
".",
"device",
"(",
"device",
")",
":",
"return",
"tf",
".",
"map_fn",
"(",
"func",
",",
"x",
")"
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | random_crop_and_flip | Augment a batch by randomly cropping and horizontally flipping it. | cleverhans/augmentation.py | def random_crop_and_flip(x, pad_rows=4, pad_cols=4):
"""Augment a batch by randomly cropping and horizontally flipping it."""
rows = tf.shape(x)[1]
cols = tf.shape(x)[2]
channels = x.get_shape()[3]
def _rand_crop_img(img):
"""Randomly crop an individual image"""
return tf.random_crop(img, [rows, cols... | def random_crop_and_flip(x, pad_rows=4, pad_cols=4):
"""Augment a batch by randomly cropping and horizontally flipping it."""
rows = tf.shape(x)[1]
cols = tf.shape(x)[2]
channels = x.get_shape()[3]
def _rand_crop_img(img):
"""Randomly crop an individual image"""
return tf.random_crop(img, [rows, cols... | [
"Augment",
"a",
"batch",
"by",
"randomly",
"cropping",
"and",
"horizontally",
"flipping",
"it",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/augmentation.py#L40-L58 | [
"def",
"random_crop_and_flip",
"(",
"x",
",",
"pad_rows",
"=",
"4",
",",
"pad_cols",
"=",
"4",
")",
":",
"rows",
"=",
"tf",
".",
"shape",
"(",
"x",
")",
"[",
"1",
"]",
"cols",
"=",
"tf",
".",
"shape",
"(",
"x",
")",
"[",
"2",
"]",
"channels",
... | 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_picklable.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=CLEAN_TRAIN,
testing=False,
backprop_through_attack=BACKPRO... | def mnist_tutorial(train_start=0, train_end=60000, test_start=0,
test_end=10000, nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE,
learning_rate=LEARNING_RATE,
clean_train=CLEAN_TRAIN,
testing=False,
backprop_through_attack=BACKPRO... | [
"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_picklable.py#L36-L226 | [
"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 | _project_perturbation | Project `perturbation` onto L-infinity ball of radius `epsilon`.
Also project into hypercube such that the resulting adversarial example
is between clip_min and clip_max, if applicable. | cleverhans/attacks/spsa.py | def _project_perturbation(perturbation, epsilon, input_image, clip_min=None,
clip_max=None):
"""Project `perturbation` onto L-infinity ball of radius `epsilon`.
Also project into hypercube such that the resulting adversarial example
is between clip_min and clip_max, if applicable.
"""
... | def _project_perturbation(perturbation, epsilon, input_image, clip_min=None,
clip_max=None):
"""Project `perturbation` onto L-infinity ball of radius `epsilon`.
Also project into hypercube such that the resulting adversarial example
is between clip_min and clip_max, if applicable.
"""
... | [
"Project",
"perturbation",
"onto",
"L",
"-",
"infinity",
"ball",
"of",
"radius",
"epsilon",
".",
"Also",
"project",
"into",
"hypercube",
"such",
"that",
"the",
"resulting",
"adversarial",
"example",
"is",
"between",
"clip_min",
"and",
"clip_max",
"if",
"applicab... | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/spsa.py#L209-L231 | [
"def",
"_project_perturbation",
"(",
"perturbation",
",",
"epsilon",
",",
"input_image",
",",
"clip_min",
"=",
"None",
",",
"clip_max",
"=",
"None",
")",
":",
"if",
"clip_min",
"is",
"None",
"or",
"clip_max",
"is",
"None",
":",
"raise",
"NotImplementedError",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | margin_logit_loss | Computes difference between logit for `label` and next highest logit.
The loss is high when `label` is unlikely (targeted by default).
This follows the same interface as `loss_fn` for TensorOptimizer and
projected_optimization, i.e. it returns a batch of loss values. | cleverhans/attacks/spsa.py | def margin_logit_loss(model_logits, label, nb_classes=10, num_classes=None):
"""Computes difference between logit for `label` and next highest logit.
The loss is high when `label` is unlikely (targeted by default).
This follows the same interface as `loss_fn` for TensorOptimizer and
projected_optimization, i.e... | def margin_logit_loss(model_logits, label, nb_classes=10, num_classes=None):
"""Computes difference between logit for `label` and next highest logit.
The loss is high when `label` is unlikely (targeted by default).
This follows the same interface as `loss_fn` for TensorOptimizer and
projected_optimization, i.e... | [
"Computes",
"difference",
"between",
"logit",
"for",
"label",
"and",
"next",
"highest",
"logit",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/spsa.py#L444-L473 | [
"def",
"margin_logit_loss",
"(",
"model_logits",
",",
"label",
",",
"nb_classes",
"=",
"10",
",",
"num_classes",
"=",
"None",
")",
":",
"if",
"num_classes",
"is",
"not",
"None",
":",
"warnings",
".",
"warn",
"(",
"\"`num_classes` is depreciated. Switch to `nb_clas... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | spm | TensorFlow implementation of the Spatial Transformation Method.
:return: a tensor for the adversarial example | cleverhans/attacks/spsa.py | def spm(x, model, y=None, n_samples=None, dx_min=-0.1,
dx_max=0.1, n_dxs=5, dy_min=-0.1, dy_max=0.1, n_dys=5,
angle_min=-30, angle_max=30, n_angles=31, black_border_size=0):
"""
TensorFlow implementation of the Spatial Transformation Method.
:return: a tensor for the adversarial example
"""
if... | def spm(x, model, y=None, n_samples=None, dx_min=-0.1,
dx_max=0.1, n_dxs=5, dy_min=-0.1, dy_max=0.1, n_dys=5,
angle_min=-30, angle_max=30, n_angles=31, black_border_size=0):
"""
TensorFlow implementation of the Spatial Transformation Method.
:return: a tensor for the adversarial example
"""
if... | [
"TensorFlow",
"implementation",
"of",
"the",
"Spatial",
"Transformation",
"Method",
".",
":",
"return",
":",
"a",
"tensor",
"for",
"the",
"adversarial",
"example"
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/spsa.py#L524-L581 | [
"def",
"spm",
"(",
"x",
",",
"model",
",",
"y",
"=",
"None",
",",
"n_samples",
"=",
"None",
",",
"dx_min",
"=",
"-",
"0.1",
",",
"dx_max",
"=",
"0.1",
",",
"n_dxs",
"=",
"5",
",",
"dy_min",
"=",
"-",
"0.1",
",",
"dy_max",
"=",
"0.1",
",",
"n_... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | parallel_apply_transformations | Apply image transformations in parallel.
:param transforms: TODO
:param black_border_size: int, size of black border to apply
Returns:
Transformed images | cleverhans/attacks/spsa.py | def parallel_apply_transformations(x, transforms, black_border_size=0):
"""
Apply image transformations in parallel.
:param transforms: TODO
:param black_border_size: int, size of black border to apply
Returns:
Transformed images
"""
transforms = tf.convert_to_tensor(transforms, dtype=tf.float32)
x ... | def parallel_apply_transformations(x, transforms, black_border_size=0):
"""
Apply image transformations in parallel.
:param transforms: TODO
:param black_border_size: int, size of black border to apply
Returns:
Transformed images
"""
transforms = tf.convert_to_tensor(transforms, dtype=tf.float32)
x ... | [
"Apply",
"image",
"transformations",
"in",
"parallel",
".",
":",
"param",
"transforms",
":",
"TODO",
":",
"param",
"black_border_size",
":",
"int",
"size",
"of",
"black",
"border",
"to",
"apply",
"Returns",
":",
"Transformed",
"images"
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/spsa.py#L584-L610 | [
"def",
"parallel_apply_transformations",
"(",
"x",
",",
"transforms",
",",
"black_border_size",
"=",
"0",
")",
":",
"transforms",
"=",
"tf",
".",
"convert_to_tensor",
"(",
"transforms",
",",
"dtype",
"=",
"tf",
".",
"float32",
")",
"x",
"=",
"_apply_black_bord... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | projected_optimization | Generic projected optimization, generalized to work with approximate
gradients. Used for e.g. the SPSA attack.
Args:
:param loss_fn: A callable which takes `input_image` and `label` as
arguments, and returns a batch of loss values. Same
interface as TensorOptimizer.
... | cleverhans/attacks/spsa.py | def projected_optimization(loss_fn,
input_image,
label,
epsilon,
num_steps,
clip_min=None,
clip_max=None,
optimizer=TensorAdam(),
... | def projected_optimization(loss_fn,
input_image,
label,
epsilon,
num_steps,
clip_min=None,
clip_max=None,
optimizer=TensorAdam(),
... | [
"Generic",
"projected",
"optimization",
"generalized",
"to",
"work",
"with",
"approximate",
"gradients",
".",
"Used",
"for",
"e",
".",
"g",
".",
"the",
"SPSA",
"attack",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/spsa.py#L613-L758 | [
"def",
"projected_optimization",
"(",
"loss_fn",
",",
"input_image",
",",
"label",
",",
"epsilon",
",",
"num_steps",
",",
"clip_min",
"=",
"None",
",",
"clip_max",
"=",
"None",
",",
"optimizer",
"=",
"TensorAdam",
"(",
")",
",",
"project_perturbation",
"=",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | SPSA.generate | Generate symbolic graph for adversarial examples.
:param x: The model's symbolic inputs. Must be a batch of size 1.
:param y: A Tensor or None. The index of the correct label.
:param y_target: A Tensor or None. The index of the target label in a
targeted attack.
:param eps: The siz... | cleverhans/attacks/spsa.py | def generate(self,
x,
y=None,
y_target=None,
eps=None,
clip_min=None,
clip_max=None,
nb_iter=None,
is_targeted=None,
early_stop_loss_threshold=None,
learning_rate=DEFAULT... | def generate(self,
x,
y=None,
y_target=None,
eps=None,
clip_min=None,
clip_max=None,
nb_iter=None,
is_targeted=None,
early_stop_loss_threshold=None,
learning_rate=DEFAULT... | [
"Generate",
"symbolic",
"graph",
"for",
"adversarial",
"examples",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/spsa.py#L51-L176 | [
"def",
"generate",
"(",
"self",
",",
"x",
",",
"y",
"=",
"None",
",",
"y_target",
"=",
"None",
",",
"eps",
"=",
"None",
",",
"clip_min",
"=",
"None",
",",
"clip_max",
"=",
"None",
",",
"nb_iter",
"=",
"None",
",",
"is_targeted",
"=",
"None",
",",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | TensorOptimizer._compute_gradients | Compute a new value of `x` to minimize `loss_fn`.
Args:
loss_fn: a callable that takes `x`, a batch of images, and returns
a batch of loss values. `x` will be optimized to minimize
`loss_fn(x)`.
x: A list of Tensors, the values to be updated. This is analogous
to... | cleverhans/attacks/spsa.py | def _compute_gradients(self, loss_fn, x, unused_optim_state):
"""Compute a new value of `x` to minimize `loss_fn`.
Args:
loss_fn: a callable that takes `x`, a batch of images, and returns
a batch of loss values. `x` will be optimized to minimize
`loss_fn(x)`.
x: A list o... | def _compute_gradients(self, loss_fn, x, unused_optim_state):
"""Compute a new value of `x` to minimize `loss_fn`.
Args:
loss_fn: a callable that takes `x`, a batch of images, and returns
a batch of loss values. `x` will be optimized to minimize
`loss_fn(x)`.
x: A list o... | [
"Compute",
"a",
"new",
"value",
"of",
"x",
"to",
"minimize",
"loss_fn",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/spsa.py#L246-L270 | [
"def",
"_compute_gradients",
"(",
"self",
",",
"loss_fn",
",",
"x",
",",
"unused_optim_state",
")",
":",
"# Assumes `x` is a list,",
"# and contains a tensor representing a batch of images",
"assert",
"len",
"(",
"x",
")",
"==",
"1",
"and",
"isinstance",
"(",
"x",
"... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | TensorOptimizer.minimize | Analogous to tf.Optimizer.minimize
:param loss_fn: tf Tensor, representing the loss to minimize
:param x: list of Tensor, analogous to tf.Optimizer's var_list
:param optim_state: A possibly nested dict, containing any optimizer state.
Returns:
new_x: list of Tensor, updated version of `x`
... | cleverhans/attacks/spsa.py | def minimize(self, loss_fn, x, optim_state):
"""
Analogous to tf.Optimizer.minimize
:param loss_fn: tf Tensor, representing the loss to minimize
:param x: list of Tensor, analogous to tf.Optimizer's var_list
:param optim_state: A possibly nested dict, containing any optimizer state.
Returns:
... | def minimize(self, loss_fn, x, optim_state):
"""
Analogous to tf.Optimizer.minimize
:param loss_fn: tf Tensor, representing the loss to minimize
:param x: list of Tensor, analogous to tf.Optimizer's var_list
:param optim_state: A possibly nested dict, containing any optimizer state.
Returns:
... | [
"Analogous",
"to",
"tf",
".",
"Optimizer",
".",
"minimize"
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/spsa.py#L287-L300 | [
"def",
"minimize",
"(",
"self",
",",
"loss_fn",
",",
"x",
",",
"optim_state",
")",
":",
"grads",
"=",
"self",
".",
"_compute_gradients",
"(",
"loss_fn",
",",
"x",
",",
"optim_state",
")",
"return",
"self",
".",
"_apply_gradients",
"(",
"grads",
",",
"x",... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | TensorAdam.init_state | Initialize t, m, and u | cleverhans/attacks/spsa.py | def init_state(self, x):
"""
Initialize t, m, and u
"""
optim_state = {}
optim_state["t"] = 0.
optim_state["m"] = [tf.zeros_like(v) for v in x]
optim_state["u"] = [tf.zeros_like(v) for v in x]
return optim_state | def init_state(self, x):
"""
Initialize t, m, and u
"""
optim_state = {}
optim_state["t"] = 0.
optim_state["m"] = [tf.zeros_like(v) for v in x]
optim_state["u"] = [tf.zeros_like(v) for v in x]
return optim_state | [
"Initialize",
"t",
"m",
"and",
"u"
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/spsa.py#L340-L348 | [
"def",
"init_state",
"(",
"self",
",",
"x",
")",
":",
"optim_state",
"=",
"{",
"}",
"optim_state",
"[",
"\"t\"",
"]",
"=",
"0.",
"optim_state",
"[",
"\"m\"",
"]",
"=",
"[",
"tf",
".",
"zeros_like",
"(",
"v",
")",
"for",
"v",
"in",
"x",
"]",
"opti... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | TensorAdam._apply_gradients | Refer to parent class documentation. | cleverhans/attacks/spsa.py | def _apply_gradients(self, grads, x, optim_state):
"""Refer to parent class documentation."""
new_x = [None] * len(x)
new_optim_state = {
"t": optim_state["t"] + 1.,
"m": [None] * len(x),
"u": [None] * len(x)
}
t = new_optim_state["t"]
for i in xrange(len(x)):
g = g... | def _apply_gradients(self, grads, x, optim_state):
"""Refer to parent class documentation."""
new_x = [None] * len(x)
new_optim_state = {
"t": optim_state["t"] + 1.,
"m": [None] * len(x),
"u": [None] * len(x)
}
t = new_optim_state["t"]
for i in xrange(len(x)):
g = g... | [
"Refer",
"to",
"parent",
"class",
"documentation",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/spsa.py#L350-L371 | [
"def",
"_apply_gradients",
"(",
"self",
",",
"grads",
",",
"x",
",",
"optim_state",
")",
":",
"new_x",
"=",
"[",
"None",
"]",
"*",
"len",
"(",
"x",
")",
"new_optim_state",
"=",
"{",
"\"t\"",
":",
"optim_state",
"[",
"\"t\"",
"]",
"+",
"1.",
",",
"\... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | SPSAAdam._compute_gradients | Compute gradient estimates using SPSA. | cleverhans/attacks/spsa.py | def _compute_gradients(self, loss_fn, x, unused_optim_state):
"""Compute gradient estimates using SPSA."""
# Assumes `x` is a list, containing a [1, H, W, C] image
# If static batch dimension is None, tf.reshape to batch size 1
# so that static shape can be inferred
assert len(x) == 1
static_x_s... | def _compute_gradients(self, loss_fn, x, unused_optim_state):
"""Compute gradient estimates using SPSA."""
# Assumes `x` is a list, containing a [1, H, W, C] image
# If static batch dimension is None, tf.reshape to batch size 1
# so that static shape can be inferred
assert len(x) == 1
static_x_s... | [
"Compute",
"gradient",
"estimates",
"using",
"SPSA",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/spsa.py#L404-L441 | [
"def",
"_compute_gradients",
"(",
"self",
",",
"loss_fn",
",",
"x",
",",
"unused_optim_state",
")",
":",
"# Assumes `x` is a list, containing a [1, H, W, C] image",
"# If static batch dimension is None, tf.reshape to batch size 1",
"# so that static shape can be inferred",
"assert",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | parse_args | Parses command line arguments. | examples/nips17_adversarial_competition/dev_toolkit/run_attacks_and_defenses.py | def parse_args():
"""Parses command line arguments."""
parser = argparse.ArgumentParser(
description='Tool to run attacks and defenses.')
parser.add_argument('--attacks_dir', required=True,
help='Location of all attacks.')
parser.add_argument('--targeted_attacks_dir', required=True,
... | def parse_args():
"""Parses command line arguments."""
parser = argparse.ArgumentParser(
description='Tool to run attacks and defenses.')
parser.add_argument('--attacks_dir', required=True,
help='Location of all attacks.')
parser.add_argument('--targeted_attacks_dir', required=True,
... | [
"Parses",
"command",
"line",
"arguments",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/run_attacks_and_defenses.py#L16-L44 | [
"def",
"parse_args",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Tool to run attacks and defenses.'",
")",
"parser",
".",
"add_argument",
"(",
"'--attacks_dir'",
",",
"required",
"=",
"True",
",",
"help",
"=",
"'Lo... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
train | read_submissions_from_directory | Scans directory and read all submissions.
Args:
dirname: directory to scan.
use_gpu: whether submissions should use GPU. This argument is
used to pick proper Docker container for each submission and create
instance of Attack or Defense class.
Returns:
List with submissions (subclasses of S... | examples/nips17_adversarial_competition/dev_toolkit/run_attacks_and_defenses.py | def read_submissions_from_directory(dirname, use_gpu):
"""Scans directory and read all submissions.
Args:
dirname: directory to scan.
use_gpu: whether submissions should use GPU. This argument is
used to pick proper Docker container for each submission and create
instance of Attack or Defense c... | def read_submissions_from_directory(dirname, use_gpu):
"""Scans directory and read all submissions.
Args:
dirname: directory to scan.
use_gpu: whether submissions should use GPU. This argument is
used to pick proper Docker container for each submission and create
instance of Attack or Defense c... | [
"Scans",
"directory",
"and",
"read",
"all",
"submissions",
"."
] | tensorflow/cleverhans | python | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/run_attacks_and_defenses.py#L121-L158 | [
"def",
"read_submissions_from_directory",
"(",
"dirname",
",",
"use_gpu",
")",
":",
"result",
"=",
"[",
"]",
"for",
"sub_dir",
"in",
"os",
".",
"listdir",
"(",
"dirname",
")",
":",
"submission_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dirname",
"... | 97488e215760547b81afc53f5e5de8ba7da5bd98 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.