id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
28,500 | tensorflow/cleverhans | cleverhans/experimental/certification/optimization.py | Optimization.run_one_step | def run_one_step(self, eig_init_vec_val, eig_num_iter_val, smooth_val,
penalty_val, learning_rate_val):
"""Run one step of gradient descent for optimization.
Args:
eig_init_vec_val: Start value for eigen value computations
eig_num_iter_val: Number of iterations to run for eigen c... | python | def run_one_step(self, eig_init_vec_val, eig_num_iter_val, smooth_val,
penalty_val, learning_rate_val):
"""Run one step of gradient descent for optimization.
Args:
eig_init_vec_val: Start value for eigen value computations
eig_num_iter_val: Number of iterations to run for eigen c... | [
"def",
"run_one_step",
"(",
"self",
",",
"eig_init_vec_val",
",",
"eig_num_iter_val",
",",
"smooth_val",
",",
"penalty_val",
",",
"learning_rate_val",
")",
":",
"# Running step",
"step_feed_dict",
"=",
"{",
"self",
".",
"eig_init_vec_placeholder",
":",
"eig_init_vec_v... | Run one step of gradient descent for optimization.
Args:
eig_init_vec_val: Start value for eigen value computations
eig_num_iter_val: Number of iterations to run for eigen computations
smooth_val: Value of smoothness parameter
penalty_val: Value of penalty for the current step
learnin... | [
"Run",
"one",
"step",
"of",
"gradient",
"descent",
"for",
"optimization",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/optimization.py#L214-L296 |
28,501 | tensorflow/cleverhans | cleverhans/experimental/certification/optimization.py | Optimization.run_optimization | def run_optimization(self):
"""Run the optimization, call run_one_step with suitable placeholders.
Returns:
True if certificate is found
False otherwise
"""
penalty_val = self.params['init_penalty']
# Don't use smoothing initially - very inaccurate for large dimension
self.smooth_on... | python | def run_optimization(self):
"""Run the optimization, call run_one_step with suitable placeholders.
Returns:
True if certificate is found
False otherwise
"""
penalty_val = self.params['init_penalty']
# Don't use smoothing initially - very inaccurate for large dimension
self.smooth_on... | [
"def",
"run_optimization",
"(",
"self",
")",
":",
"penalty_val",
"=",
"self",
".",
"params",
"[",
"'init_penalty'",
"]",
"# Don't use smoothing initially - very inaccurate for large dimension",
"self",
".",
"smooth_on",
"=",
"False",
"smooth_val",
"=",
"0",
"learning_ra... | Run the optimization, call run_one_step with suitable placeholders.
Returns:
True if certificate is found
False otherwise | [
"Run",
"the",
"optimization",
"call",
"run_one_step",
"with",
"suitable",
"placeholders",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/optimization.py#L298-L347 |
28,502 | tensorflow/cleverhans | examples/nips17_adversarial_competition/dev_toolkit/sample_targeted_attacks/iter_target_class/attack_iter_target_class.py | load_target_class | def load_target_class(input_dir):
"""Loads target classes."""
with tf.gfile.Open(os.path.join(input_dir, 'target_class.csv')) as f:
return {row[0]: int(row[1]) for row in csv.reader(f) if len(row) >= 2} | python | def load_target_class(input_dir):
"""Loads target classes."""
with tf.gfile.Open(os.path.join(input_dir, 'target_class.csv')) as f:
return {row[0]: int(row[1]) for row in csv.reader(f) if len(row) >= 2} | [
"def",
"load_target_class",
"(",
"input_dir",
")",
":",
"with",
"tf",
".",
"gfile",
".",
"Open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"input_dir",
",",
"'target_class.csv'",
")",
")",
"as",
"f",
":",
"return",
"{",
"row",
"[",
"0",
"]",
":",
"... | Loads target classes. | [
"Loads",
"target",
"classes",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/sample_targeted_attacks/iter_target_class/attack_iter_target_class.py#L53-L56 |
28,503 | tensorflow/cleverhans | cleverhans/utils_pytorch.py | clip_eta | def clip_eta(eta, ord, eps):
"""
PyTorch implementation of the clip_eta in utils_tf.
:param eta: Tensor
:param ord: np.inf, 1, or 2
:param eps: float
"""
if ord not in [np.inf, 1, 2]:
raise ValueError('ord must be np.inf, 1, or 2.')
avoid_zero_div = torch.tensor(1e-12, dtype=eta.dtype, device=eta.... | python | def clip_eta(eta, ord, eps):
"""
PyTorch implementation of the clip_eta in utils_tf.
:param eta: Tensor
:param ord: np.inf, 1, or 2
:param eps: float
"""
if ord not in [np.inf, 1, 2]:
raise ValueError('ord must be np.inf, 1, or 2.')
avoid_zero_div = torch.tensor(1e-12, dtype=eta.dtype, device=eta.... | [
"def",
"clip_eta",
"(",
"eta",
",",
"ord",
",",
"eps",
")",
":",
"if",
"ord",
"not",
"in",
"[",
"np",
".",
"inf",
",",
"1",
",",
"2",
"]",
":",
"raise",
"ValueError",
"(",
"'ord must be np.inf, 1, or 2.'",
")",
"avoid_zero_div",
"=",
"torch",
".",
"t... | PyTorch implementation of the clip_eta in utils_tf.
:param eta: Tensor
:param ord: np.inf, 1, or 2
:param eps: float | [
"PyTorch",
"implementation",
"of",
"the",
"clip_eta",
"in",
"utils_tf",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_pytorch.py#L97-L130 |
28,504 | tensorflow/cleverhans | cleverhans/attacks/elastic_net_method.py | EAD.attack | def attack(self, imgs, targets):
"""
Perform the EAD attack on the given instance for the given targets.
If self.targeted is true, then the targets represents the target labels
If self.targeted is false, then targets are the original class labels
"""
batch_size = self.batch_size
r = []
... | python | def attack(self, imgs, targets):
"""
Perform the EAD attack on the given instance for the given targets.
If self.targeted is true, then the targets represents the target labels
If self.targeted is false, then targets are the original class labels
"""
batch_size = self.batch_size
r = []
... | [
"def",
"attack",
"(",
"self",
",",
"imgs",
",",
"targets",
")",
":",
"batch_size",
"=",
"self",
".",
"batch_size",
"r",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"imgs",
")",
"//",
"batch_size",
")",
":",
"_logger",
"."... | Perform the EAD attack on the given instance for the given targets.
If self.targeted is true, then the targets represents the target labels
If self.targeted is false, then targets are the original class labels | [
"Perform",
"the",
"EAD",
"attack",
"on",
"the",
"given",
"instance",
"for",
"the",
"given",
"targets",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/elastic_net_method.py#L374-L404 |
28,505 | tensorflow/cleverhans | examples/nips17_adversarial_competition/dev_toolkit/validation_tool/validate_submission.py | main | def main(args):
"""
Validates the submission.
"""
print_in_box('Validating submission ' + args.submission_filename)
random.seed()
temp_dir = args.temp_dir
delete_temp_dir = False
if not temp_dir:
temp_dir = tempfile.mkdtemp()
logging.info('Created temporary directory: %s', temp_dir)
delete_t... | python | def main(args):
"""
Validates the submission.
"""
print_in_box('Validating submission ' + args.submission_filename)
random.seed()
temp_dir = args.temp_dir
delete_temp_dir = False
if not temp_dir:
temp_dir = tempfile.mkdtemp()
logging.info('Created temporary directory: %s', temp_dir)
delete_t... | [
"def",
"main",
"(",
"args",
")",
":",
"print_in_box",
"(",
"'Validating submission '",
"+",
"args",
".",
"submission_filename",
")",
"random",
".",
"seed",
"(",
")",
"temp_dir",
"=",
"args",
".",
"temp_dir",
"delete_temp_dir",
"=",
"False",
"if",
"not",
"tem... | Validates the submission. | [
"Validates",
"the",
"submission",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/validation_tool/validate_submission.py#L41-L62 |
28,506 | tensorflow/cleverhans | examples/multigpu_advtrain/attacks_multigpu.py | MadryEtAlMultiGPU.attack | def attack(self, x, y_p, **kwargs):
"""
This method creates a symoblic graph of the MadryEtAl attack on
multiple GPUs. The graph is created on the first n GPUs.
Stop gradient is needed to get the speed-up. This prevents us from
being able to back-prop through the attack.
:param x: A tensor wit... | python | def attack(self, x, y_p, **kwargs):
"""
This method creates a symoblic graph of the MadryEtAl attack on
multiple GPUs. The graph is created on the first n GPUs.
Stop gradient is needed to get the speed-up. This prevents us from
being able to back-prop through the attack.
:param x: A tensor wit... | [
"def",
"attack",
"(",
"self",
",",
"x",
",",
"y_p",
",",
"*",
"*",
"kwargs",
")",
":",
"inputs",
"=",
"[",
"]",
"outputs",
"=",
"[",
"]",
"# Create the initial random perturbation",
"device_name",
"=",
"'/gpu:0'",
"self",
".",
"model",
".",
"set_device",
... | This method creates a symoblic graph of the MadryEtAl attack on
multiple GPUs. The graph is created on the first n GPUs.
Stop gradient is needed to get the speed-up. This prevents us from
being able to back-prop through the attack.
:param x: A tensor with the input image.
:param y_p: Ground truth ... | [
"This",
"method",
"creates",
"a",
"symoblic",
"graph",
"of",
"the",
"MadryEtAl",
"attack",
"on",
"multiple",
"GPUs",
".",
"The",
"graph",
"is",
"created",
"on",
"the",
"first",
"n",
"GPUs",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/attacks_multigpu.py#L42-L106 |
28,507 | tensorflow/cleverhans | examples/multigpu_advtrain/attacks_multigpu.py | MadryEtAlMultiGPU.generate_np | def generate_np(self, x_val, **kwargs):
"""
Facilitates testing this attack.
"""
_, feedable, _feedable_types, hash_key = self.construct_variables(kwargs)
if hash_key not in self.graphs:
with tf.variable_scope(None, 'attack_%d' % len(self.graphs)):
# x is a special placeholder we alwa... | python | def generate_np(self, x_val, **kwargs):
"""
Facilitates testing this attack.
"""
_, feedable, _feedable_types, hash_key = self.construct_variables(kwargs)
if hash_key not in self.graphs:
with tf.variable_scope(None, 'attack_%d' % len(self.graphs)):
# x is a special placeholder we alwa... | [
"def",
"generate_np",
"(",
"self",
",",
"x_val",
",",
"*",
"*",
"kwargs",
")",
":",
"_",
",",
"feedable",
",",
"_feedable_types",
",",
"hash_key",
"=",
"self",
".",
"construct_variables",
"(",
"kwargs",
")",
"if",
"hash_key",
"not",
"in",
"self",
".",
... | Facilitates testing this attack. | [
"Facilitates",
"testing",
"this",
"attack",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/attacks_multigpu.py#L108-L134 |
28,508 | tensorflow/cleverhans | cleverhans/evaluation.py | batch_eval | def batch_eval(sess, tf_inputs, tf_outputs, numpy_inputs, batch_size=None,
feed=None,
args=None):
"""
A helper function that computes a tensor on numpy inputs by batches.
This version uses exactly the tensorflow graph constructed by the
caller, so the caller can place specific ops ... | python | def batch_eval(sess, tf_inputs, tf_outputs, numpy_inputs, batch_size=None,
feed=None,
args=None):
"""
A helper function that computes a tensor on numpy inputs by batches.
This version uses exactly the tensorflow graph constructed by the
caller, so the caller can place specific ops ... | [
"def",
"batch_eval",
"(",
"sess",
",",
"tf_inputs",
",",
"tf_outputs",
",",
"numpy_inputs",
",",
"batch_size",
"=",
"None",
",",
"feed",
"=",
"None",
",",
"args",
"=",
"None",
")",
":",
"if",
"args",
"is",
"not",
"None",
":",
"warnings",
".",
"warn",
... | A helper function that computes a tensor on numpy inputs by batches.
This version uses exactly the tensorflow graph constructed by the
caller, so the caller can place specific ops on specific devices
to implement model parallelism.
Most users probably prefer `batch_eval_multi_worker` which maps
a single-devic... | [
"A",
"helper",
"function",
"that",
"computes",
"a",
"tensor",
"on",
"numpy",
"inputs",
"by",
"batches",
".",
"This",
"version",
"uses",
"exactly",
"the",
"tensorflow",
"graph",
"constructed",
"by",
"the",
"caller",
"so",
"the",
"caller",
"can",
"place",
"spe... | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/evaluation.py#L414-L488 |
28,509 | tensorflow/cleverhans | cleverhans/evaluation.py | _check_y | def _check_y(y):
"""
Makes sure a `y` argument is a vliad numpy dataset.
"""
if not isinstance(y, np.ndarray):
raise TypeError("y must be numpy array. Typically y contains "
"the entire test set labels. Got " + str(y) + " of type " + str(type(y))) | python | def _check_y(y):
"""
Makes sure a `y` argument is a vliad numpy dataset.
"""
if not isinstance(y, np.ndarray):
raise TypeError("y must be numpy array. Typically y contains "
"the entire test set labels. Got " + str(y) + " of type " + str(type(y))) | [
"def",
"_check_y",
"(",
"y",
")",
":",
"if",
"not",
"isinstance",
"(",
"y",
",",
"np",
".",
"ndarray",
")",
":",
"raise",
"TypeError",
"(",
"\"y must be numpy array. Typically y contains \"",
"\"the entire test set labels. Got \"",
"+",
"str",
"(",
"y",
")",
"+"... | Makes sure a `y` argument is a vliad numpy dataset. | [
"Makes",
"sure",
"a",
"y",
"argument",
"is",
"a",
"vliad",
"numpy",
"dataset",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/evaluation.py#L726-L732 |
28,510 | tensorflow/cleverhans | examples/multigpu_advtrain/utils.py | preprocess_batch | def preprocess_batch(images_batch, preproc_func=None):
"""
Creates a preprocessing graph for a batch given a function that processes
a single image.
:param images_batch: A tensor for an image batch.
:param preproc_func: (optional function) A function that takes in a
tensor and returns a preprocessed in... | python | def preprocess_batch(images_batch, preproc_func=None):
"""
Creates a preprocessing graph for a batch given a function that processes
a single image.
:param images_batch: A tensor for an image batch.
:param preproc_func: (optional function) A function that takes in a
tensor and returns a preprocessed in... | [
"def",
"preprocess_batch",
"(",
"images_batch",
",",
"preproc_func",
"=",
"None",
")",
":",
"if",
"preproc_func",
"is",
"None",
":",
"return",
"images_batch",
"with",
"tf",
".",
"variable_scope",
"(",
"'preprocess'",
")",
":",
"images_list",
"=",
"tf",
".",
... | Creates a preprocessing graph for a batch given a function that processes
a single image.
:param images_batch: A tensor for an image batch.
:param preproc_func: (optional function) A function that takes in a
tensor and returns a preprocessed input. | [
"Creates",
"a",
"preprocessing",
"graph",
"for",
"a",
"batch",
"given",
"a",
"function",
"that",
"processes",
"a",
"single",
"image",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/utils.py#L5-L25 |
28,511 | tensorflow/cleverhans | cleverhans/model.py | Model.make_params | def make_params(self):
"""
Create all Variables to be returned later by get_params.
By default this is a no-op.
Models that need their fprop to be called for their params to be
created can set `needs_dummy_fprop=True` in the constructor.
"""
if self.needs_dummy_fprop:
if hasattr(self,... | python | def make_params(self):
"""
Create all Variables to be returned later by get_params.
By default this is a no-op.
Models that need their fprop to be called for their params to be
created can set `needs_dummy_fprop=True` in the constructor.
"""
if self.needs_dummy_fprop:
if hasattr(self,... | [
"def",
"make_params",
"(",
"self",
")",
":",
"if",
"self",
".",
"needs_dummy_fprop",
":",
"if",
"hasattr",
"(",
"self",
",",
"\"_dummy_input\"",
")",
":",
"return",
"self",
".",
"_dummy_input",
"=",
"self",
".",
"make_input_placeholder",
"(",
")",
"self",
... | Create all Variables to be returned later by get_params.
By default this is a no-op.
Models that need their fprop to be called for their params to be
created can set `needs_dummy_fprop=True` in the constructor. | [
"Create",
"all",
"Variables",
"to",
"be",
"returned",
"later",
"by",
"get_params",
".",
"By",
"default",
"this",
"is",
"a",
"no",
"-",
"op",
".",
"Models",
"that",
"need",
"their",
"fprop",
"to",
"be",
"called",
"for",
"their",
"params",
"to",
"be",
"c... | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model.py#L152-L164 |
28,512 | tensorflow/cleverhans | cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py | DkNNModel.init_lsh | def init_lsh(self):
"""
Initializes locality-sensitive hashing with FALCONN to find nearest neighbors in training data.
"""
self.query_objects = {
} # contains the object that can be queried to find nearest neighbors at each layer.
# mean of training data representation per layer (that needs to... | python | def init_lsh(self):
"""
Initializes locality-sensitive hashing with FALCONN to find nearest neighbors in training data.
"""
self.query_objects = {
} # contains the object that can be queried to find nearest neighbors at each layer.
# mean of training data representation per layer (that needs to... | [
"def",
"init_lsh",
"(",
"self",
")",
":",
"self",
".",
"query_objects",
"=",
"{",
"}",
"# contains the object that can be queried to find nearest neighbors at each layer.",
"# mean of training data representation per layer (that needs to be substracted before LSH).",
"self",
".",
"ce... | Initializes locality-sensitive hashing with FALCONN to find nearest neighbors in training data. | [
"Initializes",
"locality",
"-",
"sensitive",
"hashing",
"with",
"FALCONN",
"to",
"find",
"nearest",
"neighbors",
"in",
"training",
"data",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py#L88-L132 |
28,513 | tensorflow/cleverhans | cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py | DkNNModel.find_train_knns | def find_train_knns(self, data_activations):
"""
Given a data_activation dictionary that contains a np array with activations for each layer,
find the knns in the training data.
"""
knns_ind = {}
knns_labels = {}
for layer in self.layers:
# Pre-process representations of data to norma... | python | def find_train_knns(self, data_activations):
"""
Given a data_activation dictionary that contains a np array with activations for each layer,
find the knns in the training data.
"""
knns_ind = {}
knns_labels = {}
for layer in self.layers:
# Pre-process representations of data to norma... | [
"def",
"find_train_knns",
"(",
"self",
",",
"data_activations",
")",
":",
"knns_ind",
"=",
"{",
"}",
"knns_labels",
"=",
"{",
"}",
"for",
"layer",
"in",
"self",
".",
"layers",
":",
"# Pre-process representations of data to normalize and remove training data mean.",
"d... | Given a data_activation dictionary that contains a np array with activations for each layer,
find the knns in the training data. | [
"Given",
"a",
"data_activation",
"dictionary",
"that",
"contains",
"a",
"np",
"array",
"with",
"activations",
"for",
"each",
"layer",
"find",
"the",
"knns",
"in",
"the",
"training",
"data",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py#L134-L168 |
28,514 | tensorflow/cleverhans | cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py | DkNNModel.preds_conf_cred | def preds_conf_cred(self, knns_not_in_class):
"""
Given an array of nb_data x nb_classes dimensions, use conformal prediction to compute
the DkNN's prediction, confidence and credibility.
"""
nb_data = knns_not_in_class.shape[0]
preds_knn = np.zeros(nb_data, dtype=np.int32)
confs = np.zeros(... | python | def preds_conf_cred(self, knns_not_in_class):
"""
Given an array of nb_data x nb_classes dimensions, use conformal prediction to compute
the DkNN's prediction, confidence and credibility.
"""
nb_data = knns_not_in_class.shape[0]
preds_knn = np.zeros(nb_data, dtype=np.int32)
confs = np.zeros(... | [
"def",
"preds_conf_cred",
"(",
"self",
",",
"knns_not_in_class",
")",
":",
"nb_data",
"=",
"knns_not_in_class",
".",
"shape",
"[",
"0",
"]",
"preds_knn",
"=",
"np",
".",
"zeros",
"(",
"nb_data",
",",
"dtype",
"=",
"np",
".",
"int32",
")",
"confs",
"=",
... | Given an array of nb_data x nb_classes dimensions, use conformal prediction to compute
the DkNN's prediction, confidence and credibility. | [
"Given",
"an",
"array",
"of",
"nb_data",
"x",
"nb_classes",
"dimensions",
"use",
"conformal",
"prediction",
"to",
"compute",
"the",
"DkNN",
"s",
"prediction",
"confidence",
"and",
"credibility",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py#L192-L214 |
28,515 | tensorflow/cleverhans | cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py | DkNNModel.fprop_np | def fprop_np(self, data_np):
"""
Performs a forward pass through the DkNN on an numpy array of data.
"""
if not self.calibrated:
raise ValueError(
"DkNN needs to be calibrated by calling DkNNModel.calibrate method once before inferring.")
data_activations = self.get_activations(data_... | python | def fprop_np(self, data_np):
"""
Performs a forward pass through the DkNN on an numpy array of data.
"""
if not self.calibrated:
raise ValueError(
"DkNN needs to be calibrated by calling DkNNModel.calibrate method once before inferring.")
data_activations = self.get_activations(data_... | [
"def",
"fprop_np",
"(",
"self",
",",
"data_np",
")",
":",
"if",
"not",
"self",
".",
"calibrated",
":",
"raise",
"ValueError",
"(",
"\"DkNN needs to be calibrated by calling DkNNModel.calibrate method once before inferring.\"",
")",
"data_activations",
"=",
"self",
".",
... | Performs a forward pass through the DkNN on an numpy array of data. | [
"Performs",
"a",
"forward",
"pass",
"through",
"the",
"DkNN",
"on",
"an",
"numpy",
"array",
"of",
"data",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py#L216-L227 |
28,516 | tensorflow/cleverhans | cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py | DkNNModel.fprop | def fprop(self, x):
"""
Performs a forward pass through the DkNN on a TF tensor by wrapping
the fprop_np method.
"""
logits = tf.py_func(self.fprop_np, [x], tf.float32)
return {self.O_LOGITS: logits} | python | def fprop(self, x):
"""
Performs a forward pass through the DkNN on a TF tensor by wrapping
the fprop_np method.
"""
logits = tf.py_func(self.fprop_np, [x], tf.float32)
return {self.O_LOGITS: logits} | [
"def",
"fprop",
"(",
"self",
",",
"x",
")",
":",
"logits",
"=",
"tf",
".",
"py_func",
"(",
"self",
".",
"fprop_np",
",",
"[",
"x",
"]",
",",
"tf",
".",
"float32",
")",
"return",
"{",
"self",
".",
"O_LOGITS",
":",
"logits",
"}"
] | Performs a forward pass through the DkNN on a TF tensor by wrapping
the fprop_np method. | [
"Performs",
"a",
"forward",
"pass",
"through",
"the",
"DkNN",
"on",
"a",
"TF",
"tensor",
"by",
"wrapping",
"the",
"fprop_np",
"method",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py#L229-L235 |
28,517 | tensorflow/cleverhans | cleverhans/model_zoo/madry_lab_challenges/cifar10_model.py | _relu | def _relu(x, leakiness=0.0):
"""Relu, with optional leaky support."""
return tf.where(tf.less(x, 0.0), leakiness * x, x, name='leaky_relu') | python | def _relu(x, leakiness=0.0):
"""Relu, with optional leaky support."""
return tf.where(tf.less(x, 0.0), leakiness * x, x, name='leaky_relu') | [
"def",
"_relu",
"(",
"x",
",",
"leakiness",
"=",
"0.0",
")",
":",
"return",
"tf",
".",
"where",
"(",
"tf",
".",
"less",
"(",
"x",
",",
"0.0",
")",
",",
"leakiness",
"*",
"x",
",",
"x",
",",
"name",
"=",
"'leaky_relu'",
")"
] | Relu, with optional leaky support. | [
"Relu",
"with",
"optional",
"leaky",
"support",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model_zoo/madry_lab_challenges/cifar10_model.py#L292-L294 |
28,518 | tensorflow/cleverhans | cleverhans/experimental/certification/dual_formulation.py | DualFormulation.construct_lanczos_params | def construct_lanczos_params(self):
"""Computes matrices T and V using the Lanczos algorithm.
Args:
k: number of iterations and dimensionality of the tridiagonal matrix
Returns:
eig_vec: eigen vector corresponding to min eigenvalue
"""
# Using autograph to automatically handle
# the... | python | def construct_lanczos_params(self):
"""Computes matrices T and V using the Lanczos algorithm.
Args:
k: number of iterations and dimensionality of the tridiagonal matrix
Returns:
eig_vec: eigen vector corresponding to min eigenvalue
"""
# Using autograph to automatically handle
# the... | [
"def",
"construct_lanczos_params",
"(",
"self",
")",
":",
"# Using autograph to automatically handle",
"# the control flow of minimum_eigen_vector",
"self",
".",
"min_eigen_vec",
"=",
"autograph",
".",
"to_graph",
"(",
"utils",
".",
"tf_lanczos_smallest_eigval",
")",
"def",
... | Computes matrices T and V using the Lanczos algorithm.
Args:
k: number of iterations and dimensionality of the tridiagonal matrix
Returns:
eig_vec: eigen vector corresponding to min eigenvalue | [
"Computes",
"matrices",
"T",
"and",
"V",
"using",
"the",
"Lanczos",
"algorithm",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/dual_formulation.py#L205-L247 |
28,519 | tensorflow/cleverhans | cleverhans/experimental/certification/dual_formulation.py | DualFormulation.set_differentiable_objective | def set_differentiable_objective(self):
"""Function that constructs minimization objective from dual variables."""
# Checking if graphs are already created
if self.vector_g is not None:
return
# Computing the scalar term
bias_sum = 0
for i in range(0, self.nn_params.num_hidden_layers):
... | python | def set_differentiable_objective(self):
"""Function that constructs minimization objective from dual variables."""
# Checking if graphs are already created
if self.vector_g is not None:
return
# Computing the scalar term
bias_sum = 0
for i in range(0, self.nn_params.num_hidden_layers):
... | [
"def",
"set_differentiable_objective",
"(",
"self",
")",
":",
"# Checking if graphs are already created",
"if",
"self",
".",
"vector_g",
"is",
"not",
"None",
":",
"return",
"# Computing the scalar term",
"bias_sum",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"0",
"... | Function that constructs minimization objective from dual variables. | [
"Function",
"that",
"constructs",
"minimization",
"objective",
"from",
"dual",
"variables",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/dual_formulation.py#L249-L298 |
28,520 | tensorflow/cleverhans | cleverhans/experimental/certification/dual_formulation.py | DualFormulation.get_full_psd_matrix | def get_full_psd_matrix(self):
"""Function that returns the tf graph corresponding to the entire matrix M.
Returns:
matrix_h: unrolled version of tf matrix corresponding to H
matrix_m: unrolled tf matrix corresponding to M
"""
if self.matrix_m is not None:
return self.matrix_h, self.m... | python | def get_full_psd_matrix(self):
"""Function that returns the tf graph corresponding to the entire matrix M.
Returns:
matrix_h: unrolled version of tf matrix corresponding to H
matrix_m: unrolled tf matrix corresponding to M
"""
if self.matrix_m is not None:
return self.matrix_h, self.m... | [
"def",
"get_full_psd_matrix",
"(",
"self",
")",
":",
"if",
"self",
".",
"matrix_m",
"is",
"not",
"None",
":",
"return",
"self",
".",
"matrix_h",
",",
"self",
".",
"matrix_m",
"# Computing the matrix term",
"h_columns",
"=",
"[",
"]",
"for",
"i",
"in",
"ran... | Function that returns the tf graph corresponding to the entire matrix M.
Returns:
matrix_h: unrolled version of tf matrix corresponding to H
matrix_m: unrolled tf matrix corresponding to M | [
"Function",
"that",
"returns",
"the",
"tf",
"graph",
"corresponding",
"to",
"the",
"entire",
"matrix",
"M",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/dual_formulation.py#L380-L423 |
28,521 | tensorflow/cleverhans | cleverhans/experimental/certification/dual_formulation.py | DualFormulation.compute_certificate | def compute_certificate(self, current_step, feed_dictionary):
""" Function to compute the certificate based either current value
or dual variables loaded from dual folder """
feed_dict = feed_dictionary.copy()
nu = feed_dict[self.nu]
second_term = self.make_m_psd(nu, feed_dict)
tf.logging.info('... | python | def compute_certificate(self, current_step, feed_dictionary):
""" Function to compute the certificate based either current value
or dual variables loaded from dual folder """
feed_dict = feed_dictionary.copy()
nu = feed_dict[self.nu]
second_term = self.make_m_psd(nu, feed_dict)
tf.logging.info('... | [
"def",
"compute_certificate",
"(",
"self",
",",
"current_step",
",",
"feed_dictionary",
")",
":",
"feed_dict",
"=",
"feed_dictionary",
".",
"copy",
"(",
")",
"nu",
"=",
"feed_dict",
"[",
"self",
".",
"nu",
"]",
"second_term",
"=",
"self",
".",
"make_m_psd",
... | Function to compute the certificate based either current value
or dual variables loaded from dual folder | [
"Function",
"to",
"compute",
"the",
"certificate",
"based",
"either",
"current",
"value",
"or",
"dual",
"variables",
"loaded",
"from",
"dual",
"folder"
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/dual_formulation.py#L483-L521 |
28,522 | tensorflow/cleverhans | examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_submission_lib.py | get_extract_command_template | def get_extract_command_template(filename):
"""Returns extraction command based on the filename extension."""
for k, v in iteritems(EXTRACT_COMMAND):
if filename.endswith(k):
return v
return None | python | def get_extract_command_template(filename):
"""Returns extraction command based on the filename extension."""
for k, v in iteritems(EXTRACT_COMMAND):
if filename.endswith(k):
return v
return None | [
"def",
"get_extract_command_template",
"(",
"filename",
")",
":",
"for",
"k",
",",
"v",
"in",
"iteritems",
"(",
"EXTRACT_COMMAND",
")",
":",
"if",
"filename",
".",
"endswith",
"(",
"k",
")",
":",
"return",
"v",
"return",
"None"
] | Returns extraction command based on the filename extension. | [
"Returns",
"extraction",
"command",
"based",
"on",
"the",
"filename",
"extension",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_submission_lib.py#L45-L50 |
28,523 | tensorflow/cleverhans | examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_submission_lib.py | shell_call | def shell_call(command, **kwargs):
"""Calls shell command with parameter substitution.
Args:
command: command to run as a list of tokens
**kwargs: dirctionary with substitutions
Returns:
whether command was successful, i.e. returned 0 status code
Example of usage:
shell_call(['cp', '${A}', '$... | python | def shell_call(command, **kwargs):
"""Calls shell command with parameter substitution.
Args:
command: command to run as a list of tokens
**kwargs: dirctionary with substitutions
Returns:
whether command was successful, i.e. returned 0 status code
Example of usage:
shell_call(['cp', '${A}', '$... | [
"def",
"shell_call",
"(",
"command",
",",
"*",
"*",
"kwargs",
")",
":",
"command",
"=",
"list",
"(",
"command",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"command",
")",
")",
":",
"m",
"=",
"CMD_VARIABLE_RE",
".",
"match",
"(",
"command",
"[... | Calls shell command with parameter substitution.
Args:
command: command to run as a list of tokens
**kwargs: dirctionary with substitutions
Returns:
whether command was successful, i.e. returned 0 status code
Example of usage:
shell_call(['cp', '${A}', '${B}'], A='src_file', B='dst_file')
wil... | [
"Calls",
"shell",
"command",
"with",
"parameter",
"substitution",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_submission_lib.py#L53-L75 |
28,524 | tensorflow/cleverhans | examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_submission_lib.py | make_directory_writable | def make_directory_writable(dirname):
"""Makes directory readable and writable by everybody.
Args:
dirname: name of the directory
Returns:
True if operation was successfull
If you run something inside Docker container and it writes files, then
these files will be written as root user with restricte... | python | def make_directory_writable(dirname):
"""Makes directory readable and writable by everybody.
Args:
dirname: name of the directory
Returns:
True if operation was successfull
If you run something inside Docker container and it writes files, then
these files will be written as root user with restricte... | [
"def",
"make_directory_writable",
"(",
"dirname",
")",
":",
"retval",
"=",
"shell_call",
"(",
"[",
"'docker'",
",",
"'run'",
",",
"'-v'",
",",
"'{0}:/output_dir'",
".",
"format",
"(",
"dirname",
")",
",",
"'busybox:1.27.2'",
",",
"'chmod'",
",",
"'-R'",
",",... | Makes directory readable and writable by everybody.
Args:
dirname: name of the directory
Returns:
True if operation was successfull
If you run something inside Docker container and it writes files, then
these files will be written as root user with restricted permissions.
So to be able to read/modi... | [
"Makes",
"directory",
"readable",
"and",
"writable",
"by",
"everybody",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_submission_lib.py#L78-L98 |
28,525 | tensorflow/cleverhans | examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_submission_lib.py | SubmissionValidator._extract_submission | 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',
... | python | 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",
")",
":",
"# verify filesize",
"file_size",
"=",
"os",
".",
"path",
".",
"getsize",
"(",
"filename",
")",
"if",
"file_size",
">",
"MAX_SUBMISSION_SIZE_ZIPPED",
":",
"logging",
".",
"error",
"(",
"'Sub... | Extracts submission and moves it into self._extracted_submission_dir. | [
"Extracts",
"submission",
"and",
"moves",
"it",
"into",
"self",
".",
"_extracted_submission_dir",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_submission_lib.py#L148-L194 |
28,526 | tensorflow/cleverhans | examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_submission_lib.py | SubmissionValidator._verify_docker_image_size | 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_... | python | 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",
")",
":",
"shell_call",
"(",
"[",
"'docker'",
",",
"'pull'",
",",
"image_name",
"]",
")",
"try",
":",
"image_size",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"'docker'",
",",
"'inspe... | Verifies size of Docker image.
Args:
image_name: name of the Docker image.
Returns:
True if image size is within the limits, False otherwise. | [
"Verifies",
"size",
"of",
"Docker",
"image",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_submission_lib.py#L247-L267 |
28,527 | tensorflow/cleverhans | examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_submission_lib.py | SubmissionValidator._prepare_sample_data | 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... | python | 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",
")",
":",
"# write images",
"images",
"=",
"np",
".",
"random",
".",
"randint",
"(",
"0",
",",
"256",
",",
"size",
"=",
"[",
"BATCH_SIZE",
",",
"299",
",",
"299",
",",
"3",
"]",
",",
... | Prepares sample data for the submission.
Args:
submission_type: type of the submission. | [
"Prepares",
"sample",
"data",
"for",
"the",
"submission",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_submission_lib.py#L269-L288 |
28,528 | tensorflow/cleverhans | examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_submission_lib.py | SubmissionValidator._verify_output | 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... | python | 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",
")",
":",
"result",
"=",
"True",
"if",
"submission_type",
"==",
"'defense'",
":",
"try",
":",
"image_classification",
"=",
"load_defense_output",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
... | Verifies correctness of the submission output.
Args:
submission_type: type of the submission
Returns:
True if output looks valid | [
"Verifies",
"correctness",
"of",
"the",
"submission",
"output",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_submission_lib.py#L336-L370 |
28,529 | tensorflow/cleverhans | examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_submission_lib.py | SubmissionValidator.validate_submission | 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... | python | 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",
")",
":",
"self",
".",
"_prepare_temp_dir",
"(",
")",
"# Convert filename to be absolute path, relative path might cause problems",
"# with mounting directory in Docker",
"filename",
"=",
"os",
".",
"path",
".",
"a... | Validates submission.
Args:
filename: submission filename
Returns:
submission metadata or None if submission is invalid | [
"Validates",
"submission",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_submission_lib.py#L372-L408 |
28,530 | tensorflow/cleverhans | cleverhans/loss.py | Loss.save | 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')) | python | 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",
")",
":",
"json",
".",
"dump",
"(",
"dict",
"(",
"loss",
"=",
"self",
".",
"__class__",
".",
"__name__",
",",
"params",
"=",
"self",
".",
"hparams",
")",
",",
"open",
"(",
"os",
".",
"path",
".",
"join",
... | Save loss in json format | [
"Save",
"loss",
"in",
"json",
"format"
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/loss.py#L66-L71 |
28,531 | tensorflow/cleverhans | cleverhans/attacks_tfe.py | Attack.generate_np | 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... | python | 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",
")",
":",
"tfe",
"=",
"tf",
".",
"contrib",
".",
"eager",
"x",
"=",
"tfe",
".",
"Variable",
"(",
"x_val",
")",
"adv_x",
"=",
"self",
".",
"generate",
"(",
"x",
",",
"*",
... | 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. | [
"Generate",
"adversarial",
"examples",
"and",
"return",
"them",
"as",
"a",
"NumPy",
"array",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks_tfe.py#L57-L68 |
28,532 | tensorflow/cleverhans | cleverhans/devtools/list_files.py | list_files | 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__... | python | 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",
"=",
"\"\"",
")",
":",
"cleverhans_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"cleverhans",
".",
"__path__",
"[",
"0",
"]",
")",
"# In some environments cleverhans_path does not point to a real directory.",
"# In such case ... | 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`. | [
"Returns",
"a",
"list",
"of",
"all",
"files",
"in",
"CleverHans",
"with",
"the",
"given",
"suffix",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/devtools/list_files.py#L6-L38 |
28,533 | tensorflow/cleverhans | cleverhans/devtools/list_files.py | _list_files | 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... | python | 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",
"=",
"\"\"",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"incomplete",
"=",
"os",
".",
"listdir",
"(",
"path",
")",
"complete",
"=",
"[",
"os",
".",
"path",
".",
"join"... | 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
... | [
"Returns",
"a",
"list",
"of",
"all",
"files",
"ending",
"in",
"suffix",
"contained",
"within",
"path",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/devtools/list_files.py#L41-L71 |
28,534 | tensorflow/cleverhans | examples/nips17_adversarial_competition/eval_infra/code/master.py | save_dict_to_file | 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)]) | python | 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",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'w'",
")",
"as",
"f",
":",
"writer",
"=",
"csv",
".",
"writer",
"(",
"f",
")",
"for",
"k",
",",
"v",
"in",
"iteritems",
"(",
"dictionary"... | Saves dictionary as CSV file. | [
"Saves",
"dictionary",
"as",
"CSV",
"file",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/master.py#L49-L54 |
28,535 | tensorflow/cleverhans | examples/nips17_adversarial_competition/eval_infra/code/master.py | main | 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
... | python | 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",
")",
":",
"if",
"args",
".",
"blacklisted_submissions",
":",
"logging",
".",
"warning",
"(",
"'BLACKLISTED SUBMISSIONS: %s'",
",",
"args",
".",
"blacklisted_submissions",
")",
"if",
"args",
".",
"limited_dataset",
":",
"logging",
".",... | Main function which runs master. | [
"Main",
"function",
"which",
"runs",
"master",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/master.py#L688-L735 |
28,536 | tensorflow/cleverhans | examples/nips17_adversarial_competition/eval_infra/code/master.py | EvaluationMaster.ask_when_work_is_populated | 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... | python | 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",
")",
":",
"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 '",
... | 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... | [
"When",
"work",
"is",
"already",
"populated",
"asks",
"whether",
"we",
"should",
"continue",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/master.py#L116-L137 |
28,537 | tensorflow/cleverhans | examples/nips17_adversarial_competition/eval_infra/code/master.py | EvaluationMaster.prepare_attacks | 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... | python | 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",
")",
":",
"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",
".... | Prepares all data needed for evaluation of attacks. | [
"Prepares",
"all",
"data",
"needed",
"for",
"evaluation",
"of",
"attacks",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/master.py#L139-L173 |
28,538 | tensorflow/cleverhans | examples/nips17_adversarial_competition/eval_infra/code/master.py | EvaluationMaster.prepare_defenses | 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... | python | 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",
")",
":",
"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",
... | Prepares all data needed for evaluation of defenses. | [
"Prepares",
"all",
"data",
"needed",
"for",
"evaluation",
"of",
"defenses",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/master.py#L175-L200 |
28,539 | tensorflow/cleverhans | examples/nips17_adversarial_competition/eval_infra/code/master.py | EvaluationMaster._save_work_results | 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:... | python | 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",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'w'",
")",
"as",
"f",
":",
"writer",
"=",
"csv",
".",
"writer",
"(",
"f",
")",
"wr... | 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... | [
"Saves",
"statistics",
"about",
"each",
"submission",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/master.py#L202-L243 |
28,540 | tensorflow/cleverhans | examples/nips17_adversarial_competition/eval_infra/code/master.py | EvaluationMaster._read_dataset_metadata | 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... | python | 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",
")",
":",
"blob",
"=",
"self",
".",
"storage_client",
".",
"get_blob",
"(",
"'dataset/'",
"+",
"self",
".",
"dataset_name",
"+",
"'_dataset.csv'",
")",
"buf",
"=",
"BytesIO",
"(",
")",
"blob",
".",
"download_to_f... | Reads dataset metadata.
Returns:
instance of DatasetMetadata | [
"Reads",
"dataset",
"metadata",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/master.py#L272-L283 |
28,541 | tensorflow/cleverhans | examples/nips17_adversarial_competition/eval_infra/code/master.py | EvaluationMaster._show_status_for_work | 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']:
... | python | 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",
")",
":",
"work_count",
"=",
"len",
"(",
"work",
".",
"work",
")",
"work_completed",
"=",
"{",
"}",
"work_completed_count",
"=",
"0",
"for",
"v",
"in",
"itervalues",
"(",
"work",
".",
"work",
")",... | Shows status for given work pieces.
Args:
work: instance of either AttackWorkPieces or DefenseWorkPieces | [
"Shows",
"status",
"for",
"given",
"work",
"pieces",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/master.py#L448-L477 |
28,542 | tensorflow/cleverhans | examples/nips17_adversarial_competition/eval_infra/code/master.py | EvaluationMaster._export_work_errors | 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 ... | python | 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",
")",
":",
"errors",
"=",
"set",
"(",
")",
"for",
"v",
"in",
"itervalues",
"(",
"work",
".",
"work",
")",
":",
"if",
"v",
"[",
"'is_completed'",
"]",
"and",
"v",
"[",
"'error'... | Saves errors for given work pieces into file.
Args:
work: instance of either AttackWorkPieces or DefenseWorkPieces
output_file: name of the output file | [
"Saves",
"errors",
"for",
"given",
"work",
"pieces",
"into",
"file",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/master.py#L479-L493 |
28,543 | tensorflow/cleverhans | examples/nips17_adversarial_competition/eval_infra/code/master.py | EvaluationMaster.show_status | 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... | python | 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",
")",
":",
"print_header",
"(",
"'Attack work statistics'",
")",
"self",
".",
"attack_work",
".",
"read_all_from_datastore",
"(",
")",
"self",
".",
"_show_status_for_work",
"(",
"self",
".",
"attack_work",
")",
"self",
".",
"_ex... | 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. | [
"Shows",
"current",
"status",
"of",
"competition",
"evaluation",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/master.py#L495-L512 |
28,544 | tensorflow/cleverhans | examples/nips17_adversarial_competition/eval_infra/code/master.py | EvaluationMaster.cleanup_failed_attacks | 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... | python | 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",
")",
":",
"print_header",
"(",
"'Cleaning up failed attacks'",
")",
"attacks_to_replace",
"=",
"{",
"}",
"self",
".",
"attack_work",
".",
"read_all_from_datastore",
"(",
")",
"failed_submissions",
"=",
"set",
"(",
")",
... | Cleans up data of failed attacks. | [
"Cleans",
"up",
"data",
"of",
"failed",
"attacks",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/master.py#L514-L544 |
28,545 | tensorflow/cleverhans | examples/nips17_adversarial_competition/eval_infra/code/master.py | EvaluationMaster.cleanup_attacks_with_zero_images | 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... | python | 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",
")",
":",
"print_header",
"(",
"'Cleaning up attacks which generated 0 images.'",
")",
"# find out attack work to cleanup",
"self",
".",
"adv_batches",
".",
"init_from_datastore",
"(",
")",
"self",
".",
"attack_work",
... | Cleans up data about attacks which generated zero images. | [
"Cleans",
"up",
"data",
"about",
"attacks",
"which",
"generated",
"zero",
"images",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/master.py#L546-L608 |
28,546 | tensorflow/cleverhans | examples/nips17_adversarial_competition/eval_infra/code/master.py | EvaluationMaster._cleanup_keys_with_confirmation | 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_... | python | 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",
")",
":",
"print",
"(",
"'Round name: '",
",",
"self",
".",
"round_name",
")",
"print",
"(",
"'Number of entities to be deleted: '",
",",
"len",
"(",
"keys_to_delete",
")",
")",
"if",
"n... | Asks confirmation and then deletes entries with keys.
Args:
keys_to_delete: list of datastore keys for which entries should be deleted | [
"Asks",
"confirmation",
"and",
"then",
"deletes",
"entries",
"with",
"keys",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/master.py#L610-L649 |
28,547 | tensorflow/cleverhans | examples/nips17_adversarial_competition/eval_infra/code/master.py | EvaluationMaster.cleanup_defenses | 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... | python | 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",
")",
":",
"print_header",
"(",
"'CLEANING UP DEFENSES DATA'",
")",
"work_ancestor_key",
"=",
"self",
".",
"datastore_client",
".",
"key",
"(",
"'WorkType'",
",",
"'AllDefenses'",
")",
"keys_to_delete",
"=",
"[",
"e",
".",
... | Cleans up all data about defense work in current round. | [
"Cleans",
"up",
"all",
"data",
"about",
"defense",
"work",
"in",
"current",
"round",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/master.py#L651-L663 |
28,548 | tensorflow/cleverhans | examples/nips17_adversarial_competition/eval_infra/code/master.py | EvaluationMaster.cleanup_datastore | 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... | python | 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",
")",
":",
"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. | [
"Cleans",
"up",
"datastore",
"and",
"deletes",
"all",
"information",
"about",
"current",
"round",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/master.py#L665-L675 |
28,549 | tensorflow/cleverhans | examples/multigpu_advtrain/make_model.py | make_basic_ngpu | 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 | python | 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",
")",
":",
"model",
"=",
"make_basic_cnn",
"(",
")",
"layers",
"=",
"model",
".",
"layers",
"... | Create a multi-GPU model similar to the basic cnn in the tutorials. | [
"Create",
"a",
"multi",
"-",
"GPU",
"model",
"similar",
"to",
"the",
"basic",
"cnn",
"in",
"the",
"tutorials",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/make_model.py#L27-L35 |
28,550 | tensorflow/cleverhans | examples/multigpu_advtrain/resnet_tf.py | ResNetTF.build_cost | 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'):
... | python | 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",
")",
":",
"op",
"=",
"logits",
".",
"op",
"if",
"\"softmax\"",
"in",
"str",
"(",
"op",
")",
".",
"lower",
"(",
")",
":",
"logits",
",",
"=",
"op",
".",
"inputs",
"with",
"tf",
".",
... | Build the graph for cost from the logits if logits are provided.
If predictions are provided, logits are extracted from the operation. | [
"Build",
"the",
"graph",
"for",
"cost",
"from",
"the",
"logits",
"if",
"logits",
"are",
"provided",
".",
"If",
"predictions",
"are",
"provided",
"logits",
"are",
"extracted",
"from",
"the",
"operation",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/resnet_tf.py#L142-L158 |
28,551 | tensorflow/cleverhans | examples/multigpu_advtrain/resnet_tf.py | ResNetTF._layer_norm | 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... | python | 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",
")",
":",
"if",
"self",
".",
"init_layers",
":",
"bn",
"=",
"LayerNorm",
"(",
")",
"bn",
".",
"name",
"=",
"name",
"self",
".",
"layers",
"+=",
"[",
"bn",
"]",
"else",
":",
"bn",
"=",
"s... | Layer normalization. | [
"Layer",
"normalization",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/resnet_tf.py#L189-L201 |
28,552 | tensorflow/cleverhans | examples/multigpu_advtrain/resnet_tf.py | ResNetTF._bottleneck_residual | 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.... | python | 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",
")",
":",
"if",
"activate_before_residual",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"'common_bn_relu'",
... | Bottleneck residual unit with 3 sub layers. | [
"Bottleneck",
"residual",
"unit",
"with",
"3",
"sub",
"layers",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/resnet_tf.py#L236-L271 |
28,553 | tensorflow/cleverhans | examples/nips17_adversarial_competition/eval_infra/code/eval_lib/classification_results.py | read_classification_results | 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... | python | 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",
")",
":",
"if",
"storage_client",
":",
"# file on Cloud",
"success",
"=",
"False",
"retry_count",
"=",
"0",
"while",
"retry_count",
"<",
"4",
":",
"try",
":",
"blob",
"=",
"storage_cl... | 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
... | [
"Reads",
"classification",
"results",
"from",
"the",
"file",
"in",
"Cloud",
"Storage",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/classification_results.py#L30-L86 |
28,554 | tensorflow/cleverhans | examples/nips17_adversarial_competition/eval_infra/code/eval_lib/classification_results.py | analyze_one_classification_result | 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... | python | 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",
")",
":",
"class_result",
"=",
"read_classification_results",
"(",
"storage_client",
",",
"file_path",
")",
"if",
"class_r... | 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... | [
"Reads",
"and",
"analyzes",
"one",
"classification",
"result",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/classification_results.py#L89-L134 |
28,555 | tensorflow/cleverhans | examples/nips17_adversarial_competition/eval_infra/code/eval_lib/classification_results.py | ResultMatrix.save_to_file | 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.
... | python | 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",
")",
":",
"# rows - first index",
"# columns - second index",
"with",
"open",
"(",
"filename",
",",
"'w'",
")",
"as",
"fobj",
":",
"columns",
... | 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
... | [
"Saves",
"matrix",
"to",
"the",
"file",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/classification_results.py#L192-L215 |
28,556 | tensorflow/cleverhans | examples/nips17_adversarial_competition/eval_infra/code/eval_lib/classification_results.py | ClassificationBatches.init_from_adversarial_batches_write_to_datastore | 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... | python | 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",
")",
":",
"# prepare classification batches",
"idx",
"=",
"0",
"for",
"s_id",
"in",
"iterkeys",
"(",
"submissions",
".",
"defenses",
")",
":",
"for",
"adv... | Populates data from adversarial batches and writes to datastore.
Args:
submissions: instance of CompetitionSubmissions
adv_batches: instance of AversarialBatches | [
"Populates",
"data",
"from",
"adversarial",
"batches",
"and",
"writes",
"to",
"datastore",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/classification_results.py#L256-L284 |
28,557 | tensorflow/cleverhans | examples/nips17_adversarial_competition/eval_infra/code/eval_lib/classification_results.py | ClassificationBatches.init_from_datastore | 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) | python | 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",
")",
":",
"self",
".",
"_data",
"=",
"{",
"}",
"client",
"=",
"self",
".",
"_datastore_client",
"for",
"entity",
"in",
"client",
".",
"query_fetch",
"(",
"kind",
"=",
"KIND_CLASSIFICATION_BATCH",
")",
":",
"class_ba... | Initializes data by reading it from the datastore. | [
"Initializes",
"data",
"by",
"reading",
"it",
"from",
"the",
"datastore",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/classification_results.py#L286-L292 |
28,558 | tensorflow/cleverhans | examples/nips17_adversarial_competition/eval_infra/code/eval_lib/classification_results.py | ClassificationBatches.read_batch_from_datastore | 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... | python | 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",
")",
":",
"client",
"=",
"self",
".",
"_datastore_client",
"key",
"=",
"client",
".",
"key",
"(",
"KIND_CLASSIFICATION_BATCH",
",",
"class_batch_id",
")",
"result",
"=",
"client",
".",
"get"... | Reads and returns single batch from the datastore. | [
"Reads",
"and",
"returns",
"single",
"batch",
"from",
"the",
"datastore",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/classification_results.py#L294-L303 |
28,559 | tensorflow/cleverhans | examples/nips17_adversarial_competition/eval_infra/code/eval_lib/classification_results.py | ClassificationBatches.compute_classification_results | 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... | python | 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",
")",
":",
"class_batch_to_work",
"=",
"{",
"}",
"if",
"defense_work",
":",
"for",
"v",
"in",
"itervalues",
"(... | 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,
... | [
"Computes",
"classification",
"results",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/classification_results.py#L305-L373 |
28,560 | tensorflow/cleverhans | examples/nips17_adversarial_competition/eval_infra/code/eval_lib/submissions.py | participant_from_submission_path | 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... | python | 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",
")",
":",
"basename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"submission_path",
")",
"file_ext",
"=",
"None",
"for",
"e",
"in",
"ALLOWED_EXTENSIONS",
":",
"if",
"basename",
".",
"endswith"... | 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... | [
"Parses",
"type",
"of",
"participant",
"based",
"on",
"submission",
"filename",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/submissions.py#L35-L61 |
28,561 | tensorflow/cleverhans | examples/nips17_adversarial_competition/eval_infra/code/eval_lib/submissions.py | CompetitionSubmissions._load_submissions_from_datastore_dir | 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... | python | 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",
")",
":",
"submissions",
"=",
"self",
".",
"_storage_client",
".",
"list_blobs",
"(",
"prefix",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_round_nam... | 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... | [
"Loads",
"list",
"of",
"submissions",
"from",
"the",
"directory",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/submissions.py#L99-L119 |
28,562 | tensorflow/cleverhans | examples/nips17_adversarial_competition/eval_infra/code/eval_lib/submissions.py | CompetitionSubmissions.init_from_storage_write_to_datastore | 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(
... | python | 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",
")",
":",
"# Load submissions",
"self",
".",
"_attacks",
"=",
"self",
".",
"_load_submissions_from_datastore_dir",
"(",
"ATTACK_SUBDIR",
",",
"ATTACK_ID_PATTERN",
")",
"self",
".",
"_targeted_attacks",
"=",
"se... | Init list of sumibssions from Storage and saves them to Datastore.
Should be called only once (typically by master) during evaluation of
the competition. | [
"Init",
"list",
"of",
"sumibssions",
"from",
"Storage",
"and",
"saves",
"them",
"to",
"Datastore",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/submissions.py#L121-L134 |
28,563 | tensorflow/cleverhans | examples/nips17_adversarial_competition/eval_infra/code/eval_lib/submissions.py | CompetitionSubmissions._write_to_datastore | 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,
... | python | 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",
")",
":",
"# Populate datastore",
"roots_and_submissions",
"=",
"zip",
"(",
"[",
"ATTACKS_ENTITY_KEY",
",",
"TARGET_ATTACKS_ENTITY_KEY",
",",
"DEFENSES_ENTITY_KEY",
"]",
",",
"[",
"self",
".",
"_attacks",
",",
"self",
".",
... | Writes all submissions to datastore. | [
"Writes",
"all",
"submissions",
"to",
"datastore",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/submissions.py#L136-L154 |
28,564 | tensorflow/cleverhans | examples/nips17_adversarial_competition/eval_infra/code/eval_lib/submissions.py | CompetitionSubmissions.init_from_datastore | 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... | python | 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",
")",
":",
"self",
".",
"_attacks",
"=",
"{",
"}",
"self",
".",
"_targeted_attacks",
"=",
"{",
"}",
"self",
".",
"_defenses",
"=",
"{",
"}",
"for",
"entity",
"in",
"self",
".",
"_datastore_client",
".",
"query_fe... | Init list of submission from Datastore.
Should be called by each worker during initialization. | [
"Init",
"list",
"of",
"submission",
"from",
"Datastore",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/submissions.py#L156-L177 |
28,565 | tensorflow/cleverhans | examples/nips17_adversarial_competition/eval_infra/code/eval_lib/submissions.py | CompetitionSubmissions.find_by_id | 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... | python | 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",
")",
":",
"return",
"self",
".",
"_attacks",
".",
"get",
"(",
"submission_id",
",",
"self",
".",
"_defenses",
".",
"get",
"(",
"submission_id",
",",
"self",
".",
"_targeted_attacks",
".",
"get",
"(",
... | Finds submission by ID.
Args:
submission_id: ID of the submission
Returns:
SubmissionDescriptor with information about submission or None if
submission is not found. | [
"Finds",
"submission",
"by",
"ID",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/submissions.py#L198-L212 |
28,566 | tensorflow/cleverhans | examples/nips17_adversarial_competition/eval_infra/code/eval_lib/submissions.py | CompetitionSubmissions.get_external_id | 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... | python | 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",
")",
":",
"submission",
"=",
"self",
".",
"find_by_id",
"(",
"submission_id",
")",
"if",
"not",
"submission",
":",
"return",
"None",
"if",
"'team_id'",
"in",
"submission",
".",
"participant_id",
":",... | Returns human readable submission external ID.
Args:
submission_id: internal submission ID.
Returns:
human readable ID. | [
"Returns",
"human",
"readable",
"submission",
"external",
"ID",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/submissions.py#L214-L231 |
28,567 | tensorflow/cleverhans | examples/nips17_adversarial_competition/dev_toolkit/validation_tool/submission_validator_lib.py | SubmissionValidator._load_and_verify_metadata | 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,
... | python | 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",
")",
":",
"metadata_filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_extracted_submission_dir",
",",
"'metadata.json'",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfil... | Loads and verifies metadata.
Args:
submission_type: type of the submission
Returns:
dictionaty with metadata or None if metadata not found or invalid | [
"Loads",
"and",
"verifies",
"metadata",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/validation_tool/submission_validator_lib.py#L204-L245 |
28,568 | tensorflow/cleverhans | examples/nips17_adversarial_competition/dev_toolkit/validation_tool/submission_validator_lib.py | SubmissionValidator._run_submission | 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... | python | 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",
")",
":",
"if",
"self",
".",
"_use_gpu",
":",
"docker_binary",
"=",
"'nvidia-docker'",
"container_name",
"=",
"metadata",
"[",
"'container_gpu'",
"]",
"else",
":",
"docker_binary",
"=",
"'docker'",
"contain... | 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. | [
"Runs",
"submission",
"inside",
"Docker",
"container",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/validation_tool/submission_validator_lib.py#L290-L333 |
28,569 | tensorflow/cleverhans | cleverhans/plot/save_pdf.py | save_pdf | 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() | python | 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",
")",
":",
"pp",
"=",
"PdfPages",
"(",
"path",
")",
"pp",
".",
"savefig",
"(",
"pyplot",
".",
"gcf",
"(",
")",
")",
"pp",
".",
"close",
"(",
")"
] | Saves a pdf of the current matplotlib figure.
:param path: str, filepath to save to | [
"Saves",
"a",
"pdf",
"of",
"the",
"current",
"matplotlib",
"figure",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/plot/save_pdf.py#L8-L17 |
28,570 | tensorflow/cleverhans | cleverhans/augmentation.py | random_shift | 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, ... | python | 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'",
")",
":",
"assert",
"mode",
"in",
"'REFLECT SYMMETRIC CONSTANT'",
".",
"split",
"(",
")",
"assert",
"x",
".",
"get_shape",
"(",
")",
".",
"ndims... | Pad a single image and then crop to the original size with a random
offset. | [
"Pad",
"a",
"single",
"image",
"and",
"then",
"crop",
"to",
"the",
"original",
"size",
"with",
"a",
"random",
"offset",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/augmentation.py#L19-L25 |
28,571 | tensorflow/cleverhans | cleverhans/augmentation.py | random_crop_and_flip | 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... | python | 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",
")",
":",
"rows",
"=",
"tf",
".",
"shape",
"(",
"x",
")",
"[",
"1",
"]",
"cols",
"=",
"tf",
".",
"shape",
"(",
"x",
")",
"[",
"2",
"]",
"channels",
... | Augment a batch by randomly cropping and horizontally flipping it. | [
"Augment",
"a",
"batch",
"by",
"randomly",
"cropping",
"and",
"horizontally",
"flipping",
"it",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/augmentation.py#L40-L58 |
28,572 | tensorflow/cleverhans | cleverhans/attacks/spsa.py | _project_perturbation | 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.
"""
... | python | 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",
")",
":",
"if",
"clip_min",
"is",
"None",
"or",
"clip_max",
"is",
"None",
":",
"raise",
"NotImplementedError",
... | 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... | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/spsa.py#L209-L231 |
28,573 | tensorflow/cleverhans | cleverhans/attacks/spsa.py | margin_logit_loss | 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... | python | 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",
")",
":",
"if",
"num_classes",
"is",
"not",
"None",
":",
"warnings",
".",
"warn",
"(",
"\"`num_classes` is depreciated. Switch to `nb_clas... | 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. | [
"Computes",
"difference",
"between",
"logit",
"for",
"label",
"and",
"next",
"highest",
"logit",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/spsa.py#L444-L473 |
28,574 | tensorflow/cleverhans | cleverhans/attacks/spsa.py | TensorOptimizer._compute_gradients | 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... | python | 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",
")",
":",
"# Assumes `x` is a list,",
"# and contains a tensor representing a batch of images",
"assert",
"len",
"(",
"x",
")",
"==",
"1",
"and",
"isinstance",
"(",
"x",
"... | 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... | [
"Compute",
"a",
"new",
"value",
"of",
"x",
"to",
"minimize",
"loss_fn",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/spsa.py#L246-L270 |
28,575 | tensorflow/cleverhans | cleverhans/attacks/spsa.py | TensorOptimizer.minimize | 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:
... | python | 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",
")",
":",
"grads",
"=",
"self",
".",
"_compute_gradients",
"(",
"loss_fn",
",",
"x",
",",
"optim_state",
")",
"return",
"self",
".",
"_apply_gradients",
"(",
"grads",
",",
"x",... | 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`
... | [
"Analogous",
"to",
"tf",
".",
"Optimizer",
".",
"minimize"
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/spsa.py#L287-L300 |
28,576 | tensorflow/cleverhans | cleverhans/attacks/spsa.py | TensorAdam.init_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 | python | 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",
")",
":",
"optim_state",
"=",
"{",
"}",
"optim_state",
"[",
"\"t\"",
"]",
"=",
"0.",
"optim_state",
"[",
"\"m\"",
"]",
"=",
"[",
"tf",
".",
"zeros_like",
"(",
"v",
")",
"for",
"v",
"in",
"x",
"]",
"opti... | Initialize t, m, and u | [
"Initialize",
"t",
"m",
"and",
"u"
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/spsa.py#L340-L348 |
28,577 | tensorflow/cleverhans | cleverhans/attacks/spsa.py | TensorAdam._apply_gradients | 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... | python | 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",
")",
":",
"new_x",
"=",
"[",
"None",
"]",
"*",
"len",
"(",
"x",
")",
"new_optim_state",
"=",
"{",
"\"t\"",
":",
"optim_state",
"[",
"\"t\"",
"]",
"+",
"1.",
",",
"\... | Refer to parent class documentation. | [
"Refer",
"to",
"parent",
"class",
"documentation",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/spsa.py#L350-L371 |
28,578 | tensorflow/cleverhans | cleverhans/attacks/spsa.py | SPSAAdam._compute_gradients | 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... | python | 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",
")",
":",
"# 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",
... | Compute gradient estimates using SPSA. | [
"Compute",
"gradient",
"estimates",
"using",
"SPSA",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/spsa.py#L404-L441 |
28,579 | tensorflow/cleverhans | examples/nips17_adversarial_competition/dev_toolkit/run_attacks_and_defenses.py | read_submissions_from_directory | 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... | python | 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",
")",
":",
"result",
"=",
"[",
"]",
"for",
"sub_dir",
"in",
"os",
".",
"listdir",
"(",
"dirname",
")",
":",
"submission_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dirname",
"... | 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... | [
"Scans",
"directory",
"and",
"read",
"all",
"submissions",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/run_attacks_and_defenses.py#L121-L158 |
28,580 | tensorflow/cleverhans | examples/nips17_adversarial_competition/dev_toolkit/run_attacks_and_defenses.py | load_defense_output | def load_defense_output(filename):
"""Loads output of defense from given file."""
result = {}
with open(filename) as f:
for row in csv.reader(f):
try:
image_filename = row[0]
if image_filename.endswith('.png') or image_filename.endswith('.jpg'):
image_filename = image_filename[... | python | def load_defense_output(filename):
"""Loads output of defense from given file."""
result = {}
with open(filename) as f:
for row in csv.reader(f):
try:
image_filename = row[0]
if image_filename.endswith('.png') or image_filename.endswith('.jpg'):
image_filename = image_filename[... | [
"def",
"load_defense_output",
"(",
"filename",
")",
":",
"result",
"=",
"{",
"}",
"with",
"open",
"(",
"filename",
")",
"as",
"f",
":",
"for",
"row",
"in",
"csv",
".",
"reader",
"(",
"f",
")",
":",
"try",
":",
"image_filename",
"=",
"row",
"[",
"0"... | Loads output of defense from given file. | [
"Loads",
"output",
"of",
"defense",
"from",
"given",
"file",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/run_attacks_and_defenses.py#L328-L341 |
28,581 | tensorflow/cleverhans | examples/nips17_adversarial_competition/dev_toolkit/run_attacks_and_defenses.py | main | def main():
"""Run all attacks against all defenses and compute results.
"""
args = parse_args()
attacks_output_dir = os.path.join(args.intermediate_results_dir,
'attacks_output')
targeted_attacks_output_dir = os.path.join(args.intermediate_results_dir,
... | python | def main():
"""Run all attacks against all defenses and compute results.
"""
args = parse_args()
attacks_output_dir = os.path.join(args.intermediate_results_dir,
'attacks_output')
targeted_attacks_output_dir = os.path.join(args.intermediate_results_dir,
... | [
"def",
"main",
"(",
")",
":",
"args",
"=",
"parse_args",
"(",
")",
"attacks_output_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"args",
".",
"intermediate_results_dir",
",",
"'attacks_output'",
")",
"targeted_attacks_output_dir",
"=",
"os",
".",
"path",
"... | Run all attacks against all defenses and compute results. | [
"Run",
"all",
"attacks",
"against",
"all",
"defenses",
"and",
"compute",
"results",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/run_attacks_and_defenses.py#L468-L547 |
28,582 | tensorflow/cleverhans | examples/nips17_adversarial_competition/dev_toolkit/run_attacks_and_defenses.py | AttacksOutput._load_dataset_clipping | def _load_dataset_clipping(self, dataset_dir, epsilon):
"""Helper method which loads dataset and determines clipping range.
Args:
dataset_dir: location of the dataset.
epsilon: maximum allowed size of adversarial perturbation.
"""
self.dataset_max_clip = {}
self.dataset_min_clip = {}
... | python | def _load_dataset_clipping(self, dataset_dir, epsilon):
"""Helper method which loads dataset and determines clipping range.
Args:
dataset_dir: location of the dataset.
epsilon: maximum allowed size of adversarial perturbation.
"""
self.dataset_max_clip = {}
self.dataset_min_clip = {}
... | [
"def",
"_load_dataset_clipping",
"(",
"self",
",",
"dataset_dir",
",",
"epsilon",
")",
":",
"self",
".",
"dataset_max_clip",
"=",
"{",
"}",
"self",
".",
"dataset_min_clip",
"=",
"{",
"}",
"self",
".",
"_dataset_image_count",
"=",
"0",
"for",
"fname",
"in",
... | Helper method which loads dataset and determines clipping range.
Args:
dataset_dir: location of the dataset.
epsilon: maximum allowed size of adversarial perturbation. | [
"Helper",
"method",
"which",
"loads",
"dataset",
"and",
"determines",
"clipping",
"range",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/run_attacks_and_defenses.py#L191-L214 |
28,583 | tensorflow/cleverhans | examples/nips17_adversarial_competition/dev_toolkit/run_attacks_and_defenses.py | AttacksOutput.clip_and_copy_attack_outputs | def clip_and_copy_attack_outputs(self, attack_name, is_targeted):
"""Clips results of attack and copy it to directory with all images.
Args:
attack_name: name of the attack.
is_targeted: if True then attack is targeted, otherwise non-targeted.
"""
if is_targeted:
self._targeted_attack... | python | def clip_and_copy_attack_outputs(self, attack_name, is_targeted):
"""Clips results of attack and copy it to directory with all images.
Args:
attack_name: name of the attack.
is_targeted: if True then attack is targeted, otherwise non-targeted.
"""
if is_targeted:
self._targeted_attack... | [
"def",
"clip_and_copy_attack_outputs",
"(",
"self",
",",
"attack_name",
",",
"is_targeted",
")",
":",
"if",
"is_targeted",
":",
"self",
".",
"_targeted_attack_names",
".",
"add",
"(",
"attack_name",
")",
"else",
":",
"self",
".",
"_attack_names",
".",
"add",
"... | Clips results of attack and copy it to directory with all images.
Args:
attack_name: name of the attack.
is_targeted: if True then attack is targeted, otherwise non-targeted. | [
"Clips",
"results",
"of",
"attack",
"and",
"copy",
"it",
"to",
"directory",
"with",
"all",
"images",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/run_attacks_and_defenses.py#L216-L254 |
28,584 | tensorflow/cleverhans | examples/nips17_adversarial_competition/dev_toolkit/run_attacks_and_defenses.py | DatasetMetadata.save_target_classes | def save_target_classes(self, filename):
"""Saves target classed for all dataset images into given file."""
with open(filename, 'w') as f:
for k, v in self._target_classes.items():
f.write('{0}.png,{1}\n'.format(k, v)) | python | def save_target_classes(self, filename):
"""Saves target classed for all dataset images into given file."""
with open(filename, 'w') as f:
for k, v in self._target_classes.items():
f.write('{0}.png,{1}\n'.format(k, v)) | [
"def",
"save_target_classes",
"(",
"self",
",",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'w'",
")",
"as",
"f",
":",
"for",
"k",
",",
"v",
"in",
"self",
".",
"_target_classes",
".",
"items",
"(",
")",
":",
"f",
".",
"write",
"(",... | Saves target classed for all dataset images into given file. | [
"Saves",
"target",
"classed",
"for",
"all",
"dataset",
"images",
"into",
"given",
"file",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/run_attacks_and_defenses.py#L321-L325 |
28,585 | tensorflow/cleverhans | cleverhans/attack_bundling.py | single_run_max_confidence_recipe | def single_run_max_confidence_recipe(sess, model, x, y, nb_classes, eps,
clip_min, clip_max, eps_iter, nb_iter,
report_path,
batch_size=BATCH_SIZE,
eps_iter_small=None):
... | python | def single_run_max_confidence_recipe(sess, model, x, y, nb_classes, eps,
clip_min, clip_max, eps_iter, nb_iter,
report_path,
batch_size=BATCH_SIZE,
eps_iter_small=None):
... | [
"def",
"single_run_max_confidence_recipe",
"(",
"sess",
",",
"model",
",",
"x",
",",
"y",
",",
"nb_classes",
",",
"eps",
",",
"clip_min",
",",
"clip_max",
",",
"eps_iter",
",",
"nb_iter",
",",
"report_path",
",",
"batch_size",
"=",
"BATCH_SIZE",
",",
"eps_it... | A reasonable attack bundling recipe for a max norm threat model and
a defender that uses confidence thresholding. This recipe uses both
uniform noise and randomly-initialized PGD targeted attacks.
References:
https://openreview.net/forum?id=H1g0piA9tQ
This version runs each attack (noise, targeted PGD for e... | [
"A",
"reasonable",
"attack",
"bundling",
"recipe",
"for",
"a",
"max",
"norm",
"threat",
"model",
"and",
"a",
"defender",
"that",
"uses",
"confidence",
"thresholding",
".",
"This",
"recipe",
"uses",
"both",
"uniform",
"noise",
"and",
"randomly",
"-",
"initializ... | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attack_bundling.py#L43-L107 |
28,586 | tensorflow/cleverhans | cleverhans/attack_bundling.py | random_search_max_confidence_recipe | def random_search_max_confidence_recipe(sess, model, x, y, eps,
clip_min, clip_max,
report_path, batch_size=BATCH_SIZE,
num_noise_points=10000):
"""Max confidence using random search.
References:... | python | def random_search_max_confidence_recipe(sess, model, x, y, eps,
clip_min, clip_max,
report_path, batch_size=BATCH_SIZE,
num_noise_points=10000):
"""Max confidence using random search.
References:... | [
"def",
"random_search_max_confidence_recipe",
"(",
"sess",
",",
"model",
",",
"x",
",",
"y",
",",
"eps",
",",
"clip_min",
",",
"clip_max",
",",
"report_path",
",",
"batch_size",
"=",
"BATCH_SIZE",
",",
"num_noise_points",
"=",
"10000",
")",
":",
"noise_attack"... | Max confidence using random search.
References:
https://openreview.net/forum?id=H1g0piA9tQ
Describes the max_confidence procedure used for the bundling in this recipe
https://arxiv.org/abs/1802.00420
Describes using random search with 1e5 or more random points to avoid
gradient masking.
:param ses... | [
"Max",
"confidence",
"using",
"random",
"search",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attack_bundling.py#L256-L289 |
28,587 | tensorflow/cleverhans | cleverhans/attack_bundling.py | bundle_attacks | def bundle_attacks(sess, model, x, y, attack_configs, goals, report_path,
attack_batch_size=BATCH_SIZE, eval_batch_size=BATCH_SIZE):
"""
Runs attack bundling.
Users of cleverhans may call this function but are more likely to call
one of the recipes above.
Reference: https://openreview.net/... | python | def bundle_attacks(sess, model, x, y, attack_configs, goals, report_path,
attack_batch_size=BATCH_SIZE, eval_batch_size=BATCH_SIZE):
"""
Runs attack bundling.
Users of cleverhans may call this function but are more likely to call
one of the recipes above.
Reference: https://openreview.net/... | [
"def",
"bundle_attacks",
"(",
"sess",
",",
"model",
",",
"x",
",",
"y",
",",
"attack_configs",
",",
"goals",
",",
"report_path",
",",
"attack_batch_size",
"=",
"BATCH_SIZE",
",",
"eval_batch_size",
"=",
"BATCH_SIZE",
")",
":",
"assert",
"isinstance",
"(",
"s... | Runs attack bundling.
Users of cleverhans may call this function but are more likely to call
one of the recipes above.
Reference: https://openreview.net/forum?id=H1g0piA9tQ
:param sess: tf.session.Session
:param model: cleverhans.model.Model
:param x: numpy array containing clean example inputs to attack
... | [
"Runs",
"attack",
"bundling",
".",
"Users",
"of",
"cleverhans",
"may",
"call",
"this",
"function",
"but",
"are",
"more",
"likely",
"to",
"call",
"one",
"of",
"the",
"recipes",
"above",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attack_bundling.py#L320-L383 |
28,588 | tensorflow/cleverhans | cleverhans/attack_bundling.py | bundle_attacks_with_goal | def bundle_attacks_with_goal(sess, model, x, y, adv_x, attack_configs,
run_counts,
goal, report, report_path,
attack_batch_size=BATCH_SIZE, eval_batch_size=BATCH_SIZE):
"""
Runs attack bundling, working on one specific AttackGoal... | python | def bundle_attacks_with_goal(sess, model, x, y, adv_x, attack_configs,
run_counts,
goal, report, report_path,
attack_batch_size=BATCH_SIZE, eval_batch_size=BATCH_SIZE):
"""
Runs attack bundling, working on one specific AttackGoal... | [
"def",
"bundle_attacks_with_goal",
"(",
"sess",
",",
"model",
",",
"x",
",",
"y",
",",
"adv_x",
",",
"attack_configs",
",",
"run_counts",
",",
"goal",
",",
"report",
",",
"report_path",
",",
"attack_batch_size",
"=",
"BATCH_SIZE",
",",
"eval_batch_size",
"=",
... | Runs attack bundling, working on one specific AttackGoal.
This function is mostly intended to be called by `bundle_attacks`.
Reference: https://openreview.net/forum?id=H1g0piA9tQ
:param sess: tf.session.Session
:param model: cleverhans.model.Model
:param x: numpy array containing clean example inputs to att... | [
"Runs",
"attack",
"bundling",
"working",
"on",
"one",
"specific",
"AttackGoal",
".",
"This",
"function",
"is",
"mostly",
"intended",
"to",
"be",
"called",
"by",
"bundle_attacks",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attack_bundling.py#L385-L425 |
28,589 | tensorflow/cleverhans | cleverhans/attack_bundling.py | run_batch_with_goal | def run_batch_with_goal(sess, model, x, y, adv_x_val, criteria, attack_configs,
run_counts, goal, report, report_path,
attack_batch_size=BATCH_SIZE):
"""
Runs attack bundling on one batch of data.
This function is mostly intended to be called by
`bundle_attacks_wi... | python | def run_batch_with_goal(sess, model, x, y, adv_x_val, criteria, attack_configs,
run_counts, goal, report, report_path,
attack_batch_size=BATCH_SIZE):
"""
Runs attack bundling on one batch of data.
This function is mostly intended to be called by
`bundle_attacks_wi... | [
"def",
"run_batch_with_goal",
"(",
"sess",
",",
"model",
",",
"x",
",",
"y",
",",
"adv_x_val",
",",
"criteria",
",",
"attack_configs",
",",
"run_counts",
",",
"goal",
",",
"report",
",",
"report_path",
",",
"attack_batch_size",
"=",
"BATCH_SIZE",
")",
":",
... | Runs attack bundling on one batch of data.
This function is mostly intended to be called by
`bundle_attacks_with_goal`.
:param sess: tf.session.Session
:param model: cleverhans.model.Model
:param x: numpy array containing clean example inputs to attack
:param y: numpy array containing true labels
:param ... | [
"Runs",
"attack",
"bundling",
"on",
"one",
"batch",
"of",
"data",
".",
"This",
"function",
"is",
"mostly",
"intended",
"to",
"be",
"called",
"by",
"bundle_attacks_with_goal",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attack_bundling.py#L428-L487 |
28,590 | tensorflow/cleverhans | cleverhans/attack_bundling.py | bundle_examples_with_goal | def bundle_examples_with_goal(sess, model, adv_x_list, y, goal,
report_path, batch_size=BATCH_SIZE):
"""
A post-processor version of attack bundling, that chooses the strongest
example from the output of multiple earlier bundling strategies.
:param sess: tf.session.Session
:para... | python | def bundle_examples_with_goal(sess, model, adv_x_list, y, goal,
report_path, batch_size=BATCH_SIZE):
"""
A post-processor version of attack bundling, that chooses the strongest
example from the output of multiple earlier bundling strategies.
:param sess: tf.session.Session
:para... | [
"def",
"bundle_examples_with_goal",
"(",
"sess",
",",
"model",
",",
"adv_x_list",
",",
"y",
",",
"goal",
",",
"report_path",
",",
"batch_size",
"=",
"BATCH_SIZE",
")",
":",
"# Check the input",
"num_attacks",
"=",
"len",
"(",
"adv_x_list",
")",
"assert",
"num_... | A post-processor version of attack bundling, that chooses the strongest
example from the output of multiple earlier bundling strategies.
:param sess: tf.session.Session
:param model: cleverhans.model.Model
:param adv_x_list: list of numpy arrays
Each entry in the list is the output of a previous bundler; i... | [
"A",
"post",
"-",
"processor",
"version",
"of",
"attack",
"bundling",
"that",
"chooses",
"the",
"strongest",
"example",
"from",
"the",
"output",
"of",
"multiple",
"earlier",
"bundling",
"strategies",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attack_bundling.py#L1044-L1110 |
28,591 | tensorflow/cleverhans | cleverhans/attack_bundling.py | spsa_max_confidence_recipe | def spsa_max_confidence_recipe(sess, model, x, y, nb_classes, eps,
clip_min, clip_max, nb_iter,
report_path,
spsa_samples=SPSA.DEFAULT_SPSA_SAMPLES,
spsa_iters=SPSA.DEFAULT_SPSA_ITERS,
... | python | def spsa_max_confidence_recipe(sess, model, x, y, nb_classes, eps,
clip_min, clip_max, nb_iter,
report_path,
spsa_samples=SPSA.DEFAULT_SPSA_SAMPLES,
spsa_iters=SPSA.DEFAULT_SPSA_ITERS,
... | [
"def",
"spsa_max_confidence_recipe",
"(",
"sess",
",",
"model",
",",
"x",
",",
"y",
",",
"nb_classes",
",",
"eps",
",",
"clip_min",
",",
"clip_max",
",",
"nb_iter",
",",
"report_path",
",",
"spsa_samples",
"=",
"SPSA",
".",
"DEFAULT_SPSA_SAMPLES",
",",
"spsa... | Runs the MaxConfidence attack using SPSA as the underlying optimizer.
Even though this runs only one attack, it must be implemented as a bundler
because SPSA supports only batch_size=1. The cleverhans.attacks.MaxConfidence
attack internally multiplies the batch size by nb_classes, so it can't take
SPSA as a ba... | [
"Runs",
"the",
"MaxConfidence",
"attack",
"using",
"SPSA",
"as",
"the",
"underlying",
"optimizer",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attack_bundling.py#L1112-L1156 |
28,592 | tensorflow/cleverhans | cleverhans/attack_bundling.py | AttackGoal.get_criteria | def get_criteria(self, sess, model, advx, y, batch_size=BATCH_SIZE):
"""
Returns a dictionary mapping the name of each criterion to a NumPy
array containing the value of that criterion for each adversarial
example.
Subclasses can add extra criteria by implementing the `extra_criteria`
method.
... | python | def get_criteria(self, sess, model, advx, y, batch_size=BATCH_SIZE):
"""
Returns a dictionary mapping the name of each criterion to a NumPy
array containing the value of that criterion for each adversarial
example.
Subclasses can add extra criteria by implementing the `extra_criteria`
method.
... | [
"def",
"get_criteria",
"(",
"self",
",",
"sess",
",",
"model",
",",
"advx",
",",
"y",
",",
"batch_size",
"=",
"BATCH_SIZE",
")",
":",
"names",
",",
"factory",
"=",
"self",
".",
"extra_criteria",
"(",
")",
"factory",
"=",
"_CriteriaFactory",
"(",
"model",... | Returns a dictionary mapping the name of each criterion to a NumPy
array containing the value of that criterion for each adversarial
example.
Subclasses can add extra criteria by implementing the `extra_criteria`
method.
:param sess: tf.session.Session
:param model: cleverhans.model.Model
:... | [
"Returns",
"a",
"dictionary",
"mapping",
"the",
"name",
"of",
"each",
"criterion",
"to",
"a",
"NumPy",
"array",
"containing",
"the",
"value",
"of",
"that",
"criterion",
"for",
"each",
"adversarial",
"example",
".",
"Subclasses",
"can",
"add",
"extra",
"criteri... | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attack_bundling.py#L532-L554 |
28,593 | tensorflow/cleverhans | cleverhans/attack_bundling.py | AttackGoal.request_examples | def request_examples(self, attack_config, criteria, run_counts, batch_size):
"""
Returns a numpy array of integer example indices to run in the next batch.
"""
raise NotImplementedError(str(type(self)) +
"needs to implement request_examples") | python | def request_examples(self, attack_config, criteria, run_counts, batch_size):
"""
Returns a numpy array of integer example indices to run in the next batch.
"""
raise NotImplementedError(str(type(self)) +
"needs to implement request_examples") | [
"def",
"request_examples",
"(",
"self",
",",
"attack_config",
",",
"criteria",
",",
"run_counts",
",",
"batch_size",
")",
":",
"raise",
"NotImplementedError",
"(",
"str",
"(",
"type",
"(",
"self",
")",
")",
"+",
"\"needs to implement request_examples\"",
")"
] | Returns a numpy array of integer example indices to run in the next batch. | [
"Returns",
"a",
"numpy",
"array",
"of",
"integer",
"example",
"indices",
"to",
"run",
"in",
"the",
"next",
"batch",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attack_bundling.py#L563-L568 |
28,594 | tensorflow/cleverhans | cleverhans/attack_bundling.py | Misclassify.filter | def filter(self, run_counts, criteria):
"""
Return run counts only for examples that are still correctly classified
"""
correctness = criteria['correctness']
assert correctness.dtype == np.bool
filtered_counts = deep_copy(run_counts)
for key in filtered_counts:
filtered_counts[key] = f... | python | def filter(self, run_counts, criteria):
"""
Return run counts only for examples that are still correctly classified
"""
correctness = criteria['correctness']
assert correctness.dtype == np.bool
filtered_counts = deep_copy(run_counts)
for key in filtered_counts:
filtered_counts[key] = f... | [
"def",
"filter",
"(",
"self",
",",
"run_counts",
",",
"criteria",
")",
":",
"correctness",
"=",
"criteria",
"[",
"'correctness'",
"]",
"assert",
"correctness",
".",
"dtype",
"==",
"np",
".",
"bool",
"filtered_counts",
"=",
"deep_copy",
"(",
"run_counts",
")"... | Return run counts only for examples that are still correctly classified | [
"Return",
"run",
"counts",
"only",
"for",
"examples",
"that",
"are",
"still",
"correctly",
"classified"
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attack_bundling.py#L690-L699 |
28,595 | tensorflow/cleverhans | cleverhans/attack_bundling.py | MaxConfidence.filter | def filter(self, run_counts, criteria):
"""
Return the counts for only those examples that are below the threshold
"""
wrong_confidence = criteria['wrong_confidence']
below_t = wrong_confidence <= self.t
filtered_counts = deep_copy(run_counts)
for key in filtered_counts:
filtered_count... | python | def filter(self, run_counts, criteria):
"""
Return the counts for only those examples that are below the threshold
"""
wrong_confidence = criteria['wrong_confidence']
below_t = wrong_confidence <= self.t
filtered_counts = deep_copy(run_counts)
for key in filtered_counts:
filtered_count... | [
"def",
"filter",
"(",
"self",
",",
"run_counts",
",",
"criteria",
")",
":",
"wrong_confidence",
"=",
"criteria",
"[",
"'wrong_confidence'",
"]",
"below_t",
"=",
"wrong_confidence",
"<=",
"self",
".",
"t",
"filtered_counts",
"=",
"deep_copy",
"(",
"run_counts",
... | Return the counts for only those examples that are below the threshold | [
"Return",
"the",
"counts",
"for",
"only",
"those",
"examples",
"that",
"are",
"below",
"the",
"threshold"
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attack_bundling.py#L799-L808 |
28,596 | tensorflow/cleverhans | cleverhans/attacks/bapp.py | clip_image | def clip_image(image, clip_min, clip_max):
""" Clip an image, or an image batch, with upper and lower threshold. """
return np.minimum(np.maximum(clip_min, image), clip_max) | python | def clip_image(image, clip_min, clip_max):
""" Clip an image, or an image batch, with upper and lower threshold. """
return np.minimum(np.maximum(clip_min, image), clip_max) | [
"def",
"clip_image",
"(",
"image",
",",
"clip_min",
",",
"clip_max",
")",
":",
"return",
"np",
".",
"minimum",
"(",
"np",
".",
"maximum",
"(",
"clip_min",
",",
"image",
")",
",",
"clip_max",
")"
] | Clip an image, or an image batch, with upper and lower threshold. | [
"Clip",
"an",
"image",
"or",
"an",
"image",
"batch",
"with",
"upper",
"and",
"lower",
"threshold",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/bapp.py#L353-L355 |
28,597 | tensorflow/cleverhans | cleverhans/attacks/bapp.py | compute_distance | def compute_distance(x_ori, x_pert, constraint='l2'):
""" Compute the distance between two images. """
if constraint == 'l2':
dist = np.linalg.norm(x_ori - x_pert)
elif constraint == 'linf':
dist = np.max(abs(x_ori - x_pert))
return dist | python | def compute_distance(x_ori, x_pert, constraint='l2'):
""" Compute the distance between two images. """
if constraint == 'l2':
dist = np.linalg.norm(x_ori - x_pert)
elif constraint == 'linf':
dist = np.max(abs(x_ori - x_pert))
return dist | [
"def",
"compute_distance",
"(",
"x_ori",
",",
"x_pert",
",",
"constraint",
"=",
"'l2'",
")",
":",
"if",
"constraint",
"==",
"'l2'",
":",
"dist",
"=",
"np",
".",
"linalg",
".",
"norm",
"(",
"x_ori",
"-",
"x_pert",
")",
"elif",
"constraint",
"==",
"'linf... | Compute the distance between two images. | [
"Compute",
"the",
"distance",
"between",
"two",
"images",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/bapp.py#L358-L364 |
28,598 | tensorflow/cleverhans | cleverhans/attacks/bapp.py | approximate_gradient | def approximate_gradient(decision_function, sample, num_evals,
delta, constraint, shape, clip_min, clip_max):
""" Gradient direction estimation """
# Generate random vectors.
noise_shape = [num_evals] + list(shape)
if constraint == 'l2':
rv = np.random.randn(*noise_shape)
elif con... | python | def approximate_gradient(decision_function, sample, num_evals,
delta, constraint, shape, clip_min, clip_max):
""" Gradient direction estimation """
# Generate random vectors.
noise_shape = [num_evals] + list(shape)
if constraint == 'l2':
rv = np.random.randn(*noise_shape)
elif con... | [
"def",
"approximate_gradient",
"(",
"decision_function",
",",
"sample",
",",
"num_evals",
",",
"delta",
",",
"constraint",
",",
"shape",
",",
"clip_min",
",",
"clip_max",
")",
":",
"# Generate random vectors.",
"noise_shape",
"=",
"[",
"num_evals",
"]",
"+",
"li... | Gradient direction estimation | [
"Gradient",
"direction",
"estimation"
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/bapp.py#L366-L399 |
28,599 | tensorflow/cleverhans | cleverhans/attacks/bapp.py | binary_search_batch | def binary_search_batch(original_image, perturbed_images, decision_function,
shape, constraint, theta):
""" Binary search to approach the boundary. """
# Compute distance between each of perturbed image and original image.
dists_post_update = np.array([
compute_distance(
o... | python | def binary_search_batch(original_image, perturbed_images, decision_function,
shape, constraint, theta):
""" Binary search to approach the boundary. """
# Compute distance between each of perturbed image and original image.
dists_post_update = np.array([
compute_distance(
o... | [
"def",
"binary_search_batch",
"(",
"original_image",
",",
"perturbed_images",
",",
"decision_function",
",",
"shape",
",",
"constraint",
",",
"theta",
")",
":",
"# Compute distance between each of perturbed image and original image.",
"dists_post_update",
"=",
"np",
".",
"a... | Binary search to approach the boundary. | [
"Binary",
"search",
"to",
"approach",
"the",
"boundary",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/bapp.py#L417-L468 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.