repo
stringclasses
85 values
path
stringlengths
8
121
func_name
stringlengths
1
82
original_string
stringlengths
112
65.5k
language
stringclasses
1 value
code
stringlengths
112
65.5k
code_tokens
listlengths
20
4.09k
docstring
stringlengths
3
46.3k
docstring_tokens
listlengths
1
564
sha
stringclasses
85 values
url
stringlengths
93
218
partition
stringclasses
1 value
tensorflow/cleverhans
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
train
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
train
tensorflow/cleverhans
cleverhans/experimental/certification/dual_formulation.py
DualFormulation.get_h_product
def get_h_product(self, vector, dtype=None): """Function that provides matrix product interface with PSD matrix. Args: vector: the vector to be multiplied with matrix H Returns: result_product: Matrix product of H and vector """ # Computing the product of matrix_h with beta (input vect...
python
def get_h_product(self, vector, dtype=None): """Function that provides matrix product interface with PSD matrix. Args: vector: the vector to be multiplied with matrix H Returns: result_product: Matrix product of H and vector """ # Computing the product of matrix_h with beta (input vect...
[ "def", "get_h_product", "(", "self", ",", "vector", ",", "dtype", "=", "None", ")", ":", "# Computing the product of matrix_h with beta (input vector)", "# At first layer, h is simply diagonal", "if", "dtype", "is", "None", ":", "dtype", "=", "self", ".", "nn_dtype", ...
Function that provides matrix product interface with PSD matrix. Args: vector: the vector to be multiplied with matrix H Returns: result_product: Matrix product of H and vector
[ "Function", "that", "provides", "matrix", "product", "interface", "with", "PSD", "matrix", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/dual_formulation.py#L300-L350
train
tensorflow/cleverhans
cleverhans/experimental/certification/dual_formulation.py
DualFormulation.get_psd_product
def get_psd_product(self, vector, dtype=None): """Function that provides matrix product interface with PSD matrix. Args: vector: the vector to be multiplied with matrix M Returns: result_product: Matrix product of M and vector """ # For convenience, think of x as [\alpha, \beta] if...
python
def get_psd_product(self, vector, dtype=None): """Function that provides matrix product interface with PSD matrix. Args: vector: the vector to be multiplied with matrix M Returns: result_product: Matrix product of M and vector """ # For convenience, think of x as [\alpha, \beta] if...
[ "def", "get_psd_product", "(", "self", ",", "vector", ",", "dtype", "=", "None", ")", ":", "# For convenience, think of x as [\\alpha, \\beta]", "if", "dtype", "is", "None", ":", "dtype", "=", "self", ".", "nn_dtype", "vector", "=", "tf", ".", "cast", "(", "...
Function that provides matrix product interface with PSD matrix. Args: vector: the vector to be multiplied with matrix M Returns: result_product: Matrix product of M and vector
[ "Function", "that", "provides", "matrix", "product", "interface", "with", "PSD", "matrix", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/dual_formulation.py#L352-L378
train
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
train
tensorflow/cleverhans
cleverhans/experimental/certification/dual_formulation.py
DualFormulation.make_m_psd
def make_m_psd(self, original_nu, feed_dictionary): """Run binary search to find a value for nu that makes M PSD Args: original_nu: starting value of nu to do binary search on feed_dictionary: dictionary of updated lambda variables to feed into M Returns: new_nu: new value of nu """ ...
python
def make_m_psd(self, original_nu, feed_dictionary): """Run binary search to find a value for nu that makes M PSD Args: original_nu: starting value of nu to do binary search on feed_dictionary: dictionary of updated lambda variables to feed into M Returns: new_nu: new value of nu """ ...
[ "def", "make_m_psd", "(", "self", ",", "original_nu", ",", "feed_dictionary", ")", ":", "feed_dict", "=", "feed_dictionary", ".", "copy", "(", ")", "_", ",", "min_eig_val_m", "=", "self", ".", "get_lanczos_eig", "(", "compute_m", "=", "True", ",", "feed_dict...
Run binary search to find a value for nu that makes M PSD Args: original_nu: starting value of nu to do binary search on feed_dictionary: dictionary of updated lambda variables to feed into M Returns: new_nu: new value of nu
[ "Run", "binary", "search", "to", "find", "a", "value", "for", "nu", "that", "makes", "M", "PSD", "Args", ":", "original_nu", ":", "starting", "value", "of", "nu", "to", "do", "binary", "search", "on", "feed_dictionary", ":", "dictionary", "of", "updated", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/dual_formulation.py#L425-L462
train
tensorflow/cleverhans
cleverhans/experimental/certification/dual_formulation.py
DualFormulation.get_lanczos_eig
def get_lanczos_eig(self, compute_m=True, feed_dict=None): """Computes the min eigen value and corresponding vector of matrix M or H using the Lanczos algorithm. Args: compute_m: boolean to determine whether we should compute eig val/vec for M or for H. True for M; False for H. feed_dict...
python
def get_lanczos_eig(self, compute_m=True, feed_dict=None): """Computes the min eigen value and corresponding vector of matrix M or H using the Lanczos algorithm. Args: compute_m: boolean to determine whether we should compute eig val/vec for M or for H. True for M; False for H. feed_dict...
[ "def", "get_lanczos_eig", "(", "self", ",", "compute_m", "=", "True", ",", "feed_dict", "=", "None", ")", ":", "if", "compute_m", ":", "min_eig", ",", "min_vec", "=", "self", ".", "sess", ".", "run", "(", "[", "self", ".", "m_min_eig", ",", "self", "...
Computes the min eigen value and corresponding vector of matrix M or H using the Lanczos algorithm. Args: compute_m: boolean to determine whether we should compute eig val/vec for M or for H. True for M; False for H. feed_dict: dictionary mapping from TF placeholders to values (optional) ...
[ "Computes", "the", "min", "eigen", "value", "and", "corresponding", "vector", "of", "matrix", "M", "or", "H", "using", "the", "Lanczos", "algorithm", ".", "Args", ":", "compute_m", ":", "boolean", "to", "determine", "whether", "we", "should", "compute", "eig...
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/dual_formulation.py#L464-L481
train
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
train
tensorflow/cleverhans
cleverhans/attacks/spatial_transformation_method.py
SpatialTransformationMethod.generate
def generate(self, x, **kwargs): """ Generate symbolic graph for adversarial examples and return. :param x: The model's symbolic inputs. :param kwargs: See `parse_params` """ # Parse and save attack-specific parameters assert self.parse_params(**kwargs) from cleverhans.attacks_tf import...
python
def generate(self, x, **kwargs): """ Generate symbolic graph for adversarial examples and return. :param x: The model's symbolic inputs. :param kwargs: See `parse_params` """ # Parse and save attack-specific parameters assert self.parse_params(**kwargs) from cleverhans.attacks_tf import...
[ "def", "generate", "(", "self", ",", "x", ",", "*", "*", "kwargs", ")", ":", "# Parse and save attack-specific parameters", "assert", "self", ".", "parse_params", "(", "*", "*", "kwargs", ")", "from", "cleverhans", ".", "attacks_tf", "import", "spm", "labels",...
Generate symbolic graph for adversarial examples and return. :param x: The model's symbolic inputs. :param kwargs: See `parse_params`
[ "Generate", "symbolic", "graph", "for", "adversarial", "examples", "and", "return", ".", ":", "param", "x", ":", "The", "model", "s", "symbolic", "inputs", ".", ":", "param", "kwargs", ":", "See", "parse_params" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/spatial_transformation_method.py#L31-L52
train
tensorflow/cleverhans
cleverhans/attacks/spatial_transformation_method.py
SpatialTransformationMethod.parse_params
def parse_params(self, n_samples=None, dx_min=-0.1, dx_max=0.1, n_dxs=2, dy_min=-0.1, dy_max=0.1, n_dys=2, angle_min=-30, angle_max=30, ...
python
def parse_params(self, n_samples=None, dx_min=-0.1, dx_max=0.1, n_dxs=2, dy_min=-0.1, dy_max=0.1, n_dys=2, angle_min=-30, angle_max=30, ...
[ "def", "parse_params", "(", "self", ",", "n_samples", "=", "None", ",", "dx_min", "=", "-", "0.1", ",", "dx_max", "=", "0.1", ",", "n_dxs", "=", "2", ",", "dy_min", "=", "-", "0.1", ",", "dy_max", "=", "0.1", ",", "n_dys", "=", "2", ",", "angle_m...
Take in a dictionary of parameters and applies attack-specific checks before saving them as attributes. :param n_samples: (optional) The number of transformations sampled to construct the attack. Set it to None to run full grid attack. :param dx_min: (optional flo...
[ "Take", "in", "a", "dictionary", "of", "parameters", "and", "applies", "attack", "-", "specific", "checks", "before", "saving", "them", "as", "attributes", ".", ":", "param", "n_samples", ":", "(", "optional", ")", "The", "number", "of", "transformations", "...
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/spatial_transformation_method.py#L54-L106
train
tensorflow/cleverhans
cleverhans/utils_keras.py
conv_2d
def conv_2d(filters, kernel_shape, strides, padding, input_shape=None): """ Defines the right convolutional layer according to the version of Keras that is installed. :param filters: (required integer) the dimensionality of the output space (i.e. the number output of filters in the ...
python
def conv_2d(filters, kernel_shape, strides, padding, input_shape=None): """ Defines the right convolutional layer according to the version of Keras that is installed. :param filters: (required integer) the dimensionality of the output space (i.e. the number output of filters in the ...
[ "def", "conv_2d", "(", "filters", ",", "kernel_shape", ",", "strides", ",", "padding", ",", "input_shape", "=", "None", ")", ":", "if", "input_shape", "is", "not", "None", ":", "return", "Conv2D", "(", "filters", "=", "filters", ",", "kernel_size", "=", ...
Defines the right convolutional layer according to the version of Keras that is installed. :param filters: (required integer) the dimensionality of the output space (i.e. the number output of filters in the convolution) :param kernel_shape: (required tuple or list of 2 integers...
[ "Defines", "the", "right", "convolutional", "layer", "according", "to", "the", "version", "of", "Keras", "that", "is", "installed", ".", ":", "param", "filters", ":", "(", "required", "integer", ")", "the", "dimensionality", "of", "the", "output", "space", "...
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_keras.py#L19-L44
train
tensorflow/cleverhans
cleverhans/utils_keras.py
cnn_model
def cnn_model(logits=False, input_ph=None, img_rows=28, img_cols=28, channels=1, nb_filters=64, nb_classes=10): """ Defines a CNN model using Keras sequential model :param logits: If set to False, returns a Keras model, otherwise will also return logits tensor :param input_ph: Th...
python
def cnn_model(logits=False, input_ph=None, img_rows=28, img_cols=28, channels=1, nb_filters=64, nb_classes=10): """ Defines a CNN model using Keras sequential model :param logits: If set to False, returns a Keras model, otherwise will also return logits tensor :param input_ph: Th...
[ "def", "cnn_model", "(", "logits", "=", "False", ",", "input_ph", "=", "None", ",", "img_rows", "=", "28", ",", "img_cols", "=", "28", ",", "channels", "=", "1", ",", "nb_filters", "=", "64", ",", "nb_classes", "=", "10", ")", ":", "model", "=", "S...
Defines a CNN model using Keras sequential model :param logits: If set to False, returns a Keras model, otherwise will also return logits tensor :param input_ph: The TensorFlow tensor for the input (needed if returning logits) ("ph" stands for placeholder but it...
[ "Defines", "a", "CNN", "model", "using", "Keras", "sequential", "model", ":", "param", "logits", ":", "If", "set", "to", "False", "returns", "a", "Keras", "model", "otherwise", "will", "also", "return", "logits", "tensor", ":", "param", "input_ph", ":", "T...
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_keras.py#L47-L93
train
tensorflow/cleverhans
cleverhans/utils_keras.py
KerasModelWrapper._get_softmax_name
def _get_softmax_name(self): """ Looks for the name of the softmax layer. :return: Softmax layer name """ for layer in self.model.layers: cfg = layer.get_config() if 'activation' in cfg and cfg['activation'] == 'softmax': return layer.name raise Exception("No softmax layers ...
python
def _get_softmax_name(self): """ Looks for the name of the softmax layer. :return: Softmax layer name """ for layer in self.model.layers: cfg = layer.get_config() if 'activation' in cfg and cfg['activation'] == 'softmax': return layer.name raise Exception("No softmax layers ...
[ "def", "_get_softmax_name", "(", "self", ")", ":", "for", "layer", "in", "self", ".", "model", ".", "layers", ":", "cfg", "=", "layer", ".", "get_config", "(", ")", "if", "'activation'", "in", "cfg", "and", "cfg", "[", "'activation'", "]", "==", "'soft...
Looks for the name of the softmax layer. :return: Softmax layer name
[ "Looks", "for", "the", "name", "of", "the", "softmax", "layer", ".", ":", "return", ":", "Softmax", "layer", "name" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_keras.py#L117-L127
train
tensorflow/cleverhans
cleverhans/utils_keras.py
KerasModelWrapper._get_abstract_layer_name
def _get_abstract_layer_name(self): """ Looks for the name of abstracted layer. Usually these layers appears when model is stacked. :return: List of abstracted layers """ abstract_layers = [] for layer in self.model.layers: if 'layers' in layer.get_config(): abstract_layers.app...
python
def _get_abstract_layer_name(self): """ Looks for the name of abstracted layer. Usually these layers appears when model is stacked. :return: List of abstracted layers """ abstract_layers = [] for layer in self.model.layers: if 'layers' in layer.get_config(): abstract_layers.app...
[ "def", "_get_abstract_layer_name", "(", "self", ")", ":", "abstract_layers", "=", "[", "]", "for", "layer", "in", "self", ".", "model", ".", "layers", ":", "if", "'layers'", "in", "layer", ".", "get_config", "(", ")", ":", "abstract_layers", ".", "append",...
Looks for the name of abstracted layer. Usually these layers appears when model is stacked. :return: List of abstracted layers
[ "Looks", "for", "the", "name", "of", "abstracted", "layer", ".", "Usually", "these", "layers", "appears", "when", "model", "is", "stacked", ".", ":", "return", ":", "List", "of", "abstracted", "layers" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_keras.py#L129-L140
train
tensorflow/cleverhans
cleverhans/utils_keras.py
KerasModelWrapper._get_logits_name
def _get_logits_name(self): """ Looks for the name of the layer producing the logits. :return: name of layer producing the logits """ softmax_name = self._get_softmax_name() softmax_layer = self.model.get_layer(softmax_name) if not isinstance(softmax_layer, Activation): # In this case...
python
def _get_logits_name(self): """ Looks for the name of the layer producing the logits. :return: name of layer producing the logits """ softmax_name = self._get_softmax_name() softmax_layer = self.model.get_layer(softmax_name) if not isinstance(softmax_layer, Activation): # In this case...
[ "def", "_get_logits_name", "(", "self", ")", ":", "softmax_name", "=", "self", ".", "_get_softmax_name", "(", ")", "softmax_layer", "=", "self", ".", "model", ".", "get_layer", "(", "softmax_name", ")", "if", "not", "isinstance", "(", "softmax_layer", ",", "...
Looks for the name of the layer producing the logits. :return: name of layer producing the logits
[ "Looks", "for", "the", "name", "of", "the", "layer", "producing", "the", "logits", ".", ":", "return", ":", "name", "of", "layer", "producing", "the", "logits" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_keras.py#L142-L161
train
tensorflow/cleverhans
cleverhans/utils_keras.py
KerasModelWrapper.get_logits
def get_logits(self, x): """ :param x: A symbolic representation of the network input. :return: A symbolic representation of the logits """ logits_name = self._get_logits_name() logits_layer = self.get_layer(x, logits_name) # Need to deal with the case where softmax is part of the # log...
python
def get_logits(self, x): """ :param x: A symbolic representation of the network input. :return: A symbolic representation of the logits """ logits_name = self._get_logits_name() logits_layer = self.get_layer(x, logits_name) # Need to deal with the case where softmax is part of the # log...
[ "def", "get_logits", "(", "self", ",", "x", ")", ":", "logits_name", "=", "self", ".", "_get_logits_name", "(", ")", "logits_layer", "=", "self", ".", "get_layer", "(", "x", ",", "logits_name", ")", "# Need to deal with the case where softmax is part of the", "# l...
:param x: A symbolic representation of the network input. :return: A symbolic representation of the logits
[ ":", "param", "x", ":", "A", "symbolic", "representation", "of", "the", "network", "input", ".", ":", "return", ":", "A", "symbolic", "representation", "of", "the", "logits" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_keras.py#L163-L179
train
tensorflow/cleverhans
cleverhans/utils_keras.py
KerasModelWrapper.get_probs
def get_probs(self, x): """ :param x: A symbolic representation of the network input. :return: A symbolic representation of the probs """ name = self._get_softmax_name() return self.get_layer(x, name)
python
def get_probs(self, x): """ :param x: A symbolic representation of the network input. :return: A symbolic representation of the probs """ name = self._get_softmax_name() return self.get_layer(x, name)
[ "def", "get_probs", "(", "self", ",", "x", ")", ":", "name", "=", "self", ".", "_get_softmax_name", "(", ")", "return", "self", ".", "get_layer", "(", "x", ",", "name", ")" ]
:param x: A symbolic representation of the network input. :return: A symbolic representation of the probs
[ ":", "param", "x", ":", "A", "symbolic", "representation", "of", "the", "network", "input", ".", ":", "return", ":", "A", "symbolic", "representation", "of", "the", "probs" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_keras.py#L181-L188
train
tensorflow/cleverhans
cleverhans/utils_keras.py
KerasModelWrapper.get_layer_names
def get_layer_names(self): """ :return: Names of all the layers kept by Keras """ layer_names = [x.name for x in self.model.layers] return layer_names
python
def get_layer_names(self): """ :return: Names of all the layers kept by Keras """ layer_names = [x.name for x in self.model.layers] return layer_names
[ "def", "get_layer_names", "(", "self", ")", ":", "layer_names", "=", "[", "x", ".", "name", "for", "x", "in", "self", ".", "model", ".", "layers", "]", "return", "layer_names" ]
:return: Names of all the layers kept by Keras
[ ":", "return", ":", "Names", "of", "all", "the", "layers", "kept", "by", "Keras" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_keras.py#L190-L195
train
tensorflow/cleverhans
cleverhans/utils_keras.py
KerasModelWrapper.fprop
def fprop(self, x): """ Exposes all the layers of the model returned by get_layer_names. :param x: A symbolic representation of the network input :return: A dictionary mapping layer names to the symbolic representation of their output. """ if self.keras_model is None: # Get t...
python
def fprop(self, x): """ Exposes all the layers of the model returned by get_layer_names. :param x: A symbolic representation of the network input :return: A dictionary mapping layer names to the symbolic representation of their output. """ if self.keras_model is None: # Get t...
[ "def", "fprop", "(", "self", ",", "x", ")", ":", "if", "self", ".", "keras_model", "is", "None", ":", "# Get the input layer", "new_input", "=", "self", ".", "model", ".", "get_input_at", "(", "0", ")", "# Make a new model that returns each of the layers as output...
Exposes all the layers of the model returned by get_layer_names. :param x: A symbolic representation of the network input :return: A dictionary mapping layer names to the symbolic representation of their output.
[ "Exposes", "all", "the", "layers", "of", "the", "model", "returned", "by", "get_layer_names", ".", ":", "param", "x", ":", "A", "symbolic", "representation", "of", "the", "network", "input", ":", "return", ":", "A", "dictionary", "mapping", "layer", "names",...
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_keras.py#L197-L238
train
tensorflow/cleverhans
cleverhans/utils_keras.py
KerasModelWrapper.get_layer
def get_layer(self, x, layer): """ Expose the hidden features of a model given a layer name. :param x: A symbolic representation of the network input :param layer: The name of the hidden layer to return features at. :return: A symbolic representation of the hidden features :raise: NoSuchLayerErr...
python
def get_layer(self, x, layer): """ Expose the hidden features of a model given a layer name. :param x: A symbolic representation of the network input :param layer: The name of the hidden layer to return features at. :return: A symbolic representation of the hidden features :raise: NoSuchLayerErr...
[ "def", "get_layer", "(", "self", ",", "x", ",", "layer", ")", ":", "# Return the symbolic representation for this layer.", "output", "=", "self", ".", "fprop", "(", "x", ")", "try", ":", "requested", "=", "output", "[", "layer", "]", "except", "KeyError", ":...
Expose the hidden features of a model given a layer name. :param x: A symbolic representation of the network input :param layer: The name of the hidden layer to return features at. :return: A symbolic representation of the hidden features :raise: NoSuchLayerError if `layer` is not in the model.
[ "Expose", "the", "hidden", "features", "of", "a", "model", "given", "a", "layer", "name", ".", ":", "param", "x", ":", "A", "symbolic", "representation", "of", "the", "network", "input", ":", "param", "layer", ":", "The", "name", "of", "the", "hidden", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_keras.py#L240-L254
train
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
train
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
train
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
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_submission_lib.py
SubmissionValidator._prepare_temp_dir
def _prepare_temp_dir(self): """Cleans up and prepare temporary directory.""" if not shell_call(['sudo', 'rm', '-rf', os.path.join(self._temp_dir, '*')]): logging.error('Failed to cleanup temporary directory.') sys.exit(1) # NOTE: we do not create self._extracted_submission_dir # this is int...
python
def _prepare_temp_dir(self): """Cleans up and prepare temporary directory.""" if not shell_call(['sudo', 'rm', '-rf', os.path.join(self._temp_dir, '*')]): logging.error('Failed to cleanup temporary directory.') sys.exit(1) # NOTE: we do not create self._extracted_submission_dir # this is int...
[ "def", "_prepare_temp_dir", "(", "self", ")", ":", "if", "not", "shell_call", "(", "[", "'sudo'", ",", "'rm'", ",", "'-rf'", ",", "os", ".", "path", ".", "join", "(", "self", ".", "_temp_dir", ",", "'*'", ")", "]", ")", ":", "logging", ".", "error"...
Cleans up and prepare temporary directory.
[ "Cleans", "up", "and", "prepare", "temporary", "directory", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_submission_lib.py#L134-L146
train
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
train
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
train
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
train
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
train
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
train
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
train
tensorflow/cleverhans
cleverhans/loss.py
SNNLCrossEntropy.pairwise_euclid_distance
def pairwise_euclid_distance(A, B): """Pairwise Euclidean distance between two matrices. :param A: a matrix. :param B: a matrix. :returns: A tensor for the pairwise Euclidean between A and B. """ batchA = tf.shape(A)[0] batchB = tf.shape(B)[0] sqr_norm_A = tf.reshape(tf.reduce_sum(tf.p...
python
def pairwise_euclid_distance(A, B): """Pairwise Euclidean distance between two matrices. :param A: a matrix. :param B: a matrix. :returns: A tensor for the pairwise Euclidean between A and B. """ batchA = tf.shape(A)[0] batchB = tf.shape(B)[0] sqr_norm_A = tf.reshape(tf.reduce_sum(tf.p...
[ "def", "pairwise_euclid_distance", "(", "A", ",", "B", ")", ":", "batchA", "=", "tf", ".", "shape", "(", "A", ")", "[", "0", "]", "batchB", "=", "tf", ".", "shape", "(", "B", ")", "[", "0", "]", "sqr_norm_A", "=", "tf", ".", "reshape", "(", "tf...
Pairwise Euclidean distance between two matrices. :param A: a matrix. :param B: a matrix. :returns: A tensor for the pairwise Euclidean between A and B.
[ "Pairwise", "Euclidean", "distance", "between", "two", "matrices", ".", ":", "param", "A", ":", "a", "matrix", ".", ":", "param", "B", ":", "a", "matrix", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/loss.py#L376-L392
train
tensorflow/cleverhans
cleverhans/loss.py
SNNLCrossEntropy.pairwise_cos_distance
def pairwise_cos_distance(A, B): """Pairwise cosine distance between two matrices. :param A: a matrix. :param B: a matrix. :returns: A tensor for the pairwise cosine between A and B. """ normalized_A = tf.nn.l2_normalize(A, dim=1) normalized_B = tf.nn.l2_normalize(B, dim=1) prod = tf.ma...
python
def pairwise_cos_distance(A, B): """Pairwise cosine distance between two matrices. :param A: a matrix. :param B: a matrix. :returns: A tensor for the pairwise cosine between A and B. """ normalized_A = tf.nn.l2_normalize(A, dim=1) normalized_B = tf.nn.l2_normalize(B, dim=1) prod = tf.ma...
[ "def", "pairwise_cos_distance", "(", "A", ",", "B", ")", ":", "normalized_A", "=", "tf", ".", "nn", ".", "l2_normalize", "(", "A", ",", "dim", "=", "1", ")", "normalized_B", "=", "tf", ".", "nn", ".", "l2_normalize", "(", "B", ",", "dim", "=", "1",...
Pairwise cosine distance between two matrices. :param A: a matrix. :param B: a matrix. :returns: A tensor for the pairwise cosine between A and B.
[ "Pairwise", "cosine", "distance", "between", "two", "matrices", ".", ":", "param", "A", ":", "a", "matrix", ".", ":", "param", "B", ":", "a", "matrix", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/loss.py#L395-L405
train
tensorflow/cleverhans
cleverhans/loss.py
SNNLCrossEntropy.fits
def fits(A, B, temp, cos_distance): """Exponentiated pairwise distance between each element of A and all those of B. :param A: a matrix. :param B: a matrix. :param temp: Temperature :cos_distance: Boolean for using cosine or Euclidean distance. :returns: A tensor for the exponentiated pairw...
python
def fits(A, B, temp, cos_distance): """Exponentiated pairwise distance between each element of A and all those of B. :param A: a matrix. :param B: a matrix. :param temp: Temperature :cos_distance: Boolean for using cosine or Euclidean distance. :returns: A tensor for the exponentiated pairw...
[ "def", "fits", "(", "A", ",", "B", ",", "temp", ",", "cos_distance", ")", ":", "if", "cos_distance", ":", "distance_matrix", "=", "SNNLCrossEntropy", ".", "pairwise_cos_distance", "(", "A", ",", "B", ")", "else", ":", "distance_matrix", "=", "SNNLCrossEntrop...
Exponentiated pairwise distance between each element of A and all those of B. :param A: a matrix. :param B: a matrix. :param temp: Temperature :cos_distance: Boolean for using cosine or Euclidean distance. :returns: A tensor for the exponentiated pairwise distance between each element and A...
[ "Exponentiated", "pairwise", "distance", "between", "each", "element", "of", "A", "and", "all", "those", "of", "B", ".", ":", "param", "A", ":", "a", "matrix", ".", ":", "param", "B", ":", "a", "matrix", ".", ":", "param", "temp", ":", "Temperature", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/loss.py#L408-L423
train
tensorflow/cleverhans
cleverhans/loss.py
SNNLCrossEntropy.pick_probability
def pick_probability(x, temp, cos_distance): """Row normalized exponentiated pairwise distance between all the elements of x. Conceptualized as the probability of sampling a neighbor point for every element of x, proportional to the distance between the points. :param x: a matrix :param temp: Temper...
python
def pick_probability(x, temp, cos_distance): """Row normalized exponentiated pairwise distance between all the elements of x. Conceptualized as the probability of sampling a neighbor point for every element of x, proportional to the distance between the points. :param x: a matrix :param temp: Temper...
[ "def", "pick_probability", "(", "x", ",", "temp", ",", "cos_distance", ")", ":", "f", "=", "SNNLCrossEntropy", ".", "fits", "(", "x", ",", "x", ",", "temp", ",", "cos_distance", ")", "-", "tf", ".", "eye", "(", "tf", ".", "shape", "(", "x", ")", ...
Row normalized exponentiated pairwise distance between all the elements of x. Conceptualized as the probability of sampling a neighbor point for every element of x, proportional to the distance between the points. :param x: a matrix :param temp: Temperature :cos_distance: Boolean for using cosine or...
[ "Row", "normalized", "exponentiated", "pairwise", "distance", "between", "all", "the", "elements", "of", "x", ".", "Conceptualized", "as", "the", "probability", "of", "sampling", "a", "neighbor", "point", "for", "every", "element", "of", "x", "proportional", "to...
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/loss.py#L426-L440
train
tensorflow/cleverhans
cleverhans/loss.py
SNNLCrossEntropy.same_label_mask
def same_label_mask(y, y2): """Masking matrix such that element i,j is 1 iff y[i] == y2[i]. :param y: a list of labels :param y2: a list of labels :returns: A tensor for the masking matrix. """ return tf.cast(tf.squeeze(tf.equal(y, tf.expand_dims(y2, 1))), tf.float32)
python
def same_label_mask(y, y2): """Masking matrix such that element i,j is 1 iff y[i] == y2[i]. :param y: a list of labels :param y2: a list of labels :returns: A tensor for the masking matrix. """ return tf.cast(tf.squeeze(tf.equal(y, tf.expand_dims(y2, 1))), tf.float32)
[ "def", "same_label_mask", "(", "y", ",", "y2", ")", ":", "return", "tf", ".", "cast", "(", "tf", ".", "squeeze", "(", "tf", ".", "equal", "(", "y", ",", "tf", ".", "expand_dims", "(", "y2", ",", "1", ")", ")", ")", ",", "tf", ".", "float32", ...
Masking matrix such that element i,j is 1 iff y[i] == y2[i]. :param y: a list of labels :param y2: a list of labels :returns: A tensor for the masking matrix.
[ "Masking", "matrix", "such", "that", "element", "i", "j", "is", "1", "iff", "y", "[", "i", "]", "==", "y2", "[", "i", "]", ".", ":", "param", "y", ":", "a", "list", "of", "labels", ":", "param", "y2", ":", "a", "list", "of", "labels" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/loss.py#L443-L450
train
tensorflow/cleverhans
cleverhans/loss.py
SNNLCrossEntropy.masked_pick_probability
def masked_pick_probability(x, y, temp, cos_distance): """The pairwise sampling probabilities for the elements of x for neighbor points which share labels. :param x: a matrix :param y: a list of labels for each element of x :param temp: Temperature :cos_distance: Boolean for using cosine or Eucl...
python
def masked_pick_probability(x, y, temp, cos_distance): """The pairwise sampling probabilities for the elements of x for neighbor points which share labels. :param x: a matrix :param y: a list of labels for each element of x :param temp: Temperature :cos_distance: Boolean for using cosine or Eucl...
[ "def", "masked_pick_probability", "(", "x", ",", "y", ",", "temp", ",", "cos_distance", ")", ":", "return", "SNNLCrossEntropy", ".", "pick_probability", "(", "x", ",", "temp", ",", "cos_distance", ")", "*", "SNNLCrossEntropy", ".", "same_label_mask", "(", "y",...
The pairwise sampling probabilities for the elements of x for neighbor points which share labels. :param x: a matrix :param y: a list of labels for each element of x :param temp: Temperature :cos_distance: Boolean for using cosine or Euclidean distance :returns: A tensor for the pairwise sampli...
[ "The", "pairwise", "sampling", "probabilities", "for", "the", "elements", "of", "x", "for", "neighbor", "points", "which", "share", "labels", ".", ":", "param", "x", ":", "a", "matrix", ":", "param", "y", ":", "a", "list", "of", "labels", "for", "each", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/loss.py#L453-L464
train
tensorflow/cleverhans
cleverhans/loss.py
SNNLCrossEntropy.SNNL
def SNNL(x, y, temp, cos_distance): """Soft Nearest Neighbor Loss :param x: a matrix. :param y: a list of labels for each element of x. :param temp: Temperature. :cos_distance: Boolean for using cosine or Euclidean distance. :returns: A tensor for the Soft Nearest Neighbor Loss of the points ...
python
def SNNL(x, y, temp, cos_distance): """Soft Nearest Neighbor Loss :param x: a matrix. :param y: a list of labels for each element of x. :param temp: Temperature. :cos_distance: Boolean for using cosine or Euclidean distance. :returns: A tensor for the Soft Nearest Neighbor Loss of the points ...
[ "def", "SNNL", "(", "x", ",", "y", ",", "temp", ",", "cos_distance", ")", ":", "summed_masked_pick_prob", "=", "tf", ".", "reduce_sum", "(", "SNNLCrossEntropy", ".", "masked_pick_probability", "(", "x", ",", "y", ",", "temp", ",", "cos_distance", ")", ",",...
Soft Nearest Neighbor Loss :param x: a matrix. :param y: a list of labels for each element of x. :param temp: Temperature. :cos_distance: Boolean for using cosine or Euclidean distance. :returns: A tensor for the Soft Nearest Neighbor Loss of the points in x with labels y.
[ "Soft", "Nearest", "Neighbor", "Loss", ":", "param", "x", ":", "a", "matrix", ".", ":", "param", "y", ":", "a", "list", "of", "labels", "for", "each", "element", "of", "x", ".", ":", "param", "temp", ":", "Temperature", ".", ":", "cos_distance", ":",...
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/loss.py#L467-L480
train
tensorflow/cleverhans
cleverhans/loss.py
SNNLCrossEntropy.optimized_temp_SNNL
def optimized_temp_SNNL(x, y, initial_temp, cos_distance): """The optimized variant of Soft Nearest Neighbor Loss. Every time this tensor is evaluated, the temperature is optimized to minimize the loss value, this results in more numerically stable calculations of the SNNL. :param x: a matrix. :para...
python
def optimized_temp_SNNL(x, y, initial_temp, cos_distance): """The optimized variant of Soft Nearest Neighbor Loss. Every time this tensor is evaluated, the temperature is optimized to minimize the loss value, this results in more numerically stable calculations of the SNNL. :param x: a matrix. :para...
[ "def", "optimized_temp_SNNL", "(", "x", ",", "y", ",", "initial_temp", ",", "cos_distance", ")", ":", "t", "=", "tf", ".", "Variable", "(", "1", ",", "dtype", "=", "tf", ".", "float32", ",", "trainable", "=", "False", ",", "name", "=", "\"temp\"", ")...
The optimized variant of Soft Nearest Neighbor Loss. Every time this tensor is evaluated, the temperature is optimized to minimize the loss value, this results in more numerically stable calculations of the SNNL. :param x: a matrix. :param y: a list of labels for each element of x. :param initial_te...
[ "The", "optimized", "variant", "of", "Soft", "Nearest", "Neighbor", "Loss", ".", "Every", "time", "this", "tensor", "is", "evaluated", "the", "temperature", "is", "optimized", "to", "minimize", "the", "loss", "value", "this", "results", "in", "more", "numerica...
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/loss.py#L483-L505
train
tensorflow/cleverhans
cleverhans/plot/image.py
show
def show(ndarray, min_val=None, max_val=None): """ Display an image. :param ndarray: The image as an ndarray :param min_val: The minimum pixel value in the image format :param max_val: The maximum pixel valie in the image format If min_val and max_val are not specified, attempts to infer whether the i...
python
def show(ndarray, min_val=None, max_val=None): """ Display an image. :param ndarray: The image as an ndarray :param min_val: The minimum pixel value in the image format :param max_val: The maximum pixel valie in the image format If min_val and max_val are not specified, attempts to infer whether the i...
[ "def", "show", "(", "ndarray", ",", "min_val", "=", "None", ",", "max_val", "=", "None", ")", ":", "# Create a temporary file with the suffix '.png'.", "fd", ",", "path", "=", "mkstemp", "(", "suffix", "=", "'.png'", ")", "os", ".", "close", "(", "fd", ")"...
Display an image. :param ndarray: The image as an ndarray :param min_val: The minimum pixel value in the image format :param max_val: The maximum pixel valie in the image format If min_val and max_val are not specified, attempts to infer whether the image is in any of the common ranges: [0, 1], [-1,...
[ "Display", "an", "image", ".", ":", "param", "ndarray", ":", "The", "image", "as", "an", "ndarray", ":", "param", "min_val", ":", "The", "minimum", "pixel", "value", "in", "the", "image", "format", ":", "param", "max_val", ":", "The", "maximum", "pixel",...
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/plot/image.py#L13-L29
train
tensorflow/cleverhans
cleverhans/plot/image.py
save
def save(path, ndarray, min_val=None, max_val=None): """ Save an image, represented as an ndarray, to the filesystem :param path: string, filepath :param ndarray: The image as an ndarray :param min_val: The minimum pixel value in the image format :param max_val: The maximum pixel valie in the image format ...
python
def save(path, ndarray, min_val=None, max_val=None): """ Save an image, represented as an ndarray, to the filesystem :param path: string, filepath :param ndarray: The image as an ndarray :param min_val: The minimum pixel value in the image format :param max_val: The maximum pixel valie in the image format ...
[ "def", "save", "(", "path", ",", "ndarray", ",", "min_val", "=", "None", ",", "max_val", "=", "None", ")", ":", "as_pil", "(", "ndarray", ",", "min_val", ",", "max_val", ")", ".", "save", "(", "path", ")" ]
Save an image, represented as an ndarray, to the filesystem :param path: string, filepath :param ndarray: The image as an ndarray :param min_val: The minimum pixel value in the image format :param max_val: The maximum pixel valie in the image format If min_val and max_val are not specified, attempts to ...
[ "Save", "an", "image", "represented", "as", "an", "ndarray", "to", "the", "filesystem", ":", "param", "path", ":", "string", "filepath", ":", "param", "ndarray", ":", "The", "image", "as", "an", "ndarray", ":", "param", "min_val", ":", "The", "minimum", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/plot/image.py#L33-L45
train
tensorflow/cleverhans
cleverhans/plot/image.py
as_pil
def as_pil(ndarray, min_val=None, max_val=None): """ Converts an ndarray to a PIL image. :param ndarray: The numpy ndarray to convert :param min_val: The minimum pixel value in the image format :param max_val: The maximum pixel valie in the image format If min_val and max_val are not specified, attempts t...
python
def as_pil(ndarray, min_val=None, max_val=None): """ Converts an ndarray to a PIL image. :param ndarray: The numpy ndarray to convert :param min_val: The minimum pixel value in the image format :param max_val: The maximum pixel valie in the image format If min_val and max_val are not specified, attempts t...
[ "def", "as_pil", "(", "ndarray", ",", "min_val", "=", "None", ",", "max_val", "=", "None", ")", ":", "assert", "isinstance", "(", "ndarray", ",", "np", ".", "ndarray", ")", "# rows x cols for grayscale image", "# rows x cols x channels for color", "assert", "ndarr...
Converts an ndarray to a PIL image. :param ndarray: The numpy ndarray to convert :param min_val: The minimum pixel value in the image format :param max_val: The maximum pixel valie in the image format If min_val and max_val are not specified, attempts to infer whether the image is in any of the common ran...
[ "Converts", "an", "ndarray", "to", "a", "PIL", "image", ".", ":", "param", "ndarray", ":", "The", "numpy", "ndarray", "to", "convert", ":", "param", "min_val", ":", "The", "minimum", "pixel", "value", "in", "the", "image", "format", ":", "param", "max_va...
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/plot/image.py#L47-L109
train
tensorflow/cleverhans
cleverhans/plot/image.py
make_grid
def make_grid(image_batch): """ Turns a batch of images into one big image. :param image_batch: ndarray, shape (batch_size, rows, cols, channels) :returns : a big image containing all `batch_size` images in a grid """ m, ir, ic, ch = image_batch.shape pad = 3 padded = np.zeros((m, ir + pad * 2, ic + p...
python
def make_grid(image_batch): """ Turns a batch of images into one big image. :param image_batch: ndarray, shape (batch_size, rows, cols, channels) :returns : a big image containing all `batch_size` images in a grid """ m, ir, ic, ch = image_batch.shape pad = 3 padded = np.zeros((m, ir + pad * 2, ic + p...
[ "def", "make_grid", "(", "image_batch", ")", ":", "m", ",", "ir", ",", "ic", ",", "ch", "=", "image_batch", ".", "shape", "pad", "=", "3", "padded", "=", "np", ".", "zeros", "(", "(", "m", ",", "ir", "+", "pad", "*", "2", ",", "ic", "+", "pad...
Turns a batch of images into one big image. :param image_batch: ndarray, shape (batch_size, rows, cols, channels) :returns : a big image containing all `batch_size` images in a grid
[ "Turns", "a", "batch", "of", "images", "into", "one", "big", "image", ".", ":", "param", "image_batch", ":", "ndarray", "shape", "(", "batch_size", "rows", "cols", "channels", ")", ":", "returns", ":", "a", "big", "image", "containing", "all", "batch_size"...
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/plot/image.py#L111-L140
train
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
train
tensorflow/cleverhans
cleverhans/attacks_tfe.py
FastGradientMethod.generate
def generate(self, x, **kwargs): """ Generates the adversarial sample for the given input. :param x: The model's inputs. :param eps: (optional float) attack step size (input variation) :param ord: (optional) Order of the norm (mimics NumPy). Possible values: np.inf, 1 or 2. :para...
python
def generate(self, x, **kwargs): """ Generates the adversarial sample for the given input. :param x: The model's inputs. :param eps: (optional float) attack step size (input variation) :param ord: (optional) Order of the norm (mimics NumPy). Possible values: np.inf, 1 or 2. :para...
[ "def", "generate", "(", "self", ",", "x", ",", "*", "*", "kwargs", ")", ":", "# Parse and save attack-specific parameters", "assert", "self", ".", "parse_params", "(", "*", "*", "kwargs", ")", "labels", ",", "_nb_classes", "=", "self", ".", "get_or_guess_label...
Generates the adversarial sample for the given input. :param x: The model's inputs. :param eps: (optional float) attack step size (input variation) :param ord: (optional) Order of the norm (mimics NumPy). Possible values: np.inf, 1 or 2. :param y: (optional) A tf variable` with the model...
[ "Generates", "the", "adversarial", "sample", "for", "the", "given", "input", ".", ":", "param", "x", ":", "The", "model", "s", "inputs", ".", ":", "param", "eps", ":", "(", "optional", "float", ")", "attack", "step", "size", "(", "input", "variation", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks_tfe.py#L104-L126
train
tensorflow/cleverhans
cleverhans/attacks_tfe.py
FastGradientMethod.fgm
def fgm(self, x, labels, targeted=False): """ TensorFlow Eager implementation of the Fast Gradient Method. :param x: the input variable :param targeted: Is the attack targeted or untargeted? Untargeted, the default, will try to make the label incorrect. Targeted...
python
def fgm(self, x, labels, targeted=False): """ TensorFlow Eager implementation of the Fast Gradient Method. :param x: the input variable :param targeted: Is the attack targeted or untargeted? Untargeted, the default, will try to make the label incorrect. Targeted...
[ "def", "fgm", "(", "self", ",", "x", ",", "labels", ",", "targeted", "=", "False", ")", ":", "# Compute loss", "with", "tf", ".", "GradientTape", "(", ")", "as", "tape", ":", "# input should be watched because it may be", "# combination of trainable and non-trainabl...
TensorFlow Eager implementation of the Fast Gradient Method. :param x: the input variable :param targeted: Is the attack targeted or untargeted? Untargeted, the default, will try to make the label incorrect. Targeted will instead try to move in the direction ...
[ "TensorFlow", "Eager", "implementation", "of", "the", "Fast", "Gradient", "Method", ".", ":", "param", "x", ":", "the", "input", "variable", ":", "param", "targeted", ":", "Is", "the", "attack", "targeted", "or", "untargeted?", "Untargeted", "the", "default", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks_tfe.py#L128-L159
train
tensorflow/cleverhans
cleverhans/devtools/mocks.py
random_feed_dict
def random_feed_dict(rng, placeholders): """ Returns random data to be used with `feed_dict`. :param rng: A numpy.random.RandomState instance :param placeholders: List of tensorflow placeholders :return: A dict mapping placeholders to random numpy values """ output = {} for placeholder in placeholders...
python
def random_feed_dict(rng, placeholders): """ Returns random data to be used with `feed_dict`. :param rng: A numpy.random.RandomState instance :param placeholders: List of tensorflow placeholders :return: A dict mapping placeholders to random numpy values """ output = {} for placeholder in placeholders...
[ "def", "random_feed_dict", "(", "rng", ",", "placeholders", ")", ":", "output", "=", "{", "}", "for", "placeholder", "in", "placeholders", ":", "if", "placeholder", ".", "dtype", "!=", "'float32'", ":", "raise", "NotImplementedError", "(", ")", "value", "=",...
Returns random data to be used with `feed_dict`. :param rng: A numpy.random.RandomState instance :param placeholders: List of tensorflow placeholders :return: A dict mapping placeholders to random numpy values
[ "Returns", "random", "data", "to", "be", "used", "with", "feed_dict", ".", ":", "param", "rng", ":", "A", "numpy", ".", "random", ".", "RandomState", "instance", ":", "param", "placeholders", ":", "List", "of", "tensorflow", "placeholders", ":", "return", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/devtools/mocks.py#L16-L32
train
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
train
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
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/master.py
print_header
def print_header(text): """Prints header with given text and frame composed of '#' characters.""" print() print('#'*(len(text)+4)) print('# ' + text + ' #') print('#'*(len(text)+4)) print()
python
def print_header(text): """Prints header with given text and frame composed of '#' characters.""" print() print('#'*(len(text)+4)) print('# ' + text + ' #') print('#'*(len(text)+4)) print()
[ "def", "print_header", "(", "text", ")", ":", "print", "(", ")", "print", "(", "'#'", "*", "(", "len", "(", "text", ")", "+", "4", ")", ")", "print", "(", "'# '", "+", "text", "+", "' #'", ")", "print", "(", "'#'", "*", "(", "len", "(", "text...
Prints header with given text and frame composed of '#' characters.
[ "Prints", "header", "with", "given", "text", "and", "frame", "composed", "of", "#", "characters", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/master.py#L40-L46
train
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
train
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
train
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
train
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
train
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
train
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
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/master.py
EvaluationMaster._save_sorted_results
def _save_sorted_results(self, run_stats, scores, image_count, filename): """Saves sorted (by score) results of the evaluation. Args: run_stats: dictionary with runtime statistics for submissions, can be generated by WorkPiecesBase.compute_work_statistics scores: dictionary mapping submissi...
python
def _save_sorted_results(self, run_stats, scores, image_count, filename): """Saves sorted (by score) results of the evaluation. Args: run_stats: dictionary with runtime statistics for submissions, can be generated by WorkPiecesBase.compute_work_statistics scores: dictionary mapping submissi...
[ "def", "_save_sorted_results", "(", "self", ",", "run_stats", ",", "scores", ",", "image_count", ",", "filename", ")", ":", "with", "open", "(", "filename", ",", "'w'", ")", "as", "f", ":", "writer", "=", "csv", ".", "writer", "(", "f", ")", "writer", ...
Saves sorted (by score) results of the evaluation. Args: run_stats: dictionary with runtime statistics for submissions, can be generated by WorkPiecesBase.compute_work_statistics scores: dictionary mapping submission ids to scores image_count: dictionary with number of images processed by...
[ "Saves", "sorted", "(", "by", "score", ")", "results", "of", "the", "evaluation", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/master.py#L245-L270
train
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
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/master.py
EvaluationMaster.compute_results
def compute_results(self): """Computes results (scores, stats, etc...) of competition evaluation. Results are saved into output directory (self.results_dir). Also this method saves all intermediate data into output directory as well, so it can resume computation if it was interrupted for some reason. ...
python
def compute_results(self): """Computes results (scores, stats, etc...) of competition evaluation. Results are saved into output directory (self.results_dir). Also this method saves all intermediate data into output directory as well, so it can resume computation if it was interrupted for some reason. ...
[ "def", "compute_results", "(", "self", ")", ":", "# read all data", "logging", ".", "info", "(", "'Reading data from datastore'", ")", "dataset_meta", "=", "self", ".", "_read_dataset_metadata", "(", ")", "self", ".", "submissions", ".", "init_from_datastore", "(", ...
Computes results (scores, stats, etc...) of competition evaluation. Results are saved into output directory (self.results_dir). Also this method saves all intermediate data into output directory as well, so it can resume computation if it was interrupted for some reason. This is useful because computat...
[ "Computes", "results", "(", "scores", "stats", "etc", "...", ")", "of", "competition", "evaluation", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/master.py#L285-L446
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/dev_toolkit/sample_attacks/random_noise/attack_random_noise.py
main
def main(_): """Run the sample attack""" eps = FLAGS.max_epsilon / 255.0 batch_shape = [FLAGS.batch_size, FLAGS.image_height, FLAGS.image_width, 3] with tf.Graph().as_default(): x_input = tf.placeholder(tf.float32, shape=batch_shape) noisy_images = x_input + eps * tf.sign(tf.random_normal(batch_shape))...
python
def main(_): """Run the sample attack""" eps = FLAGS.max_epsilon / 255.0 batch_shape = [FLAGS.batch_size, FLAGS.image_height, FLAGS.image_width, 3] with tf.Graph().as_default(): x_input = tf.placeholder(tf.float32, shape=batch_shape) noisy_images = x_input + eps * tf.sign(tf.random_normal(batch_shape))...
[ "def", "main", "(", "_", ")", ":", "eps", "=", "FLAGS", ".", "max_epsilon", "/", "255.0", "batch_shape", "=", "[", "FLAGS", ".", "batch_size", ",", "FLAGS", ".", "image_height", ",", "FLAGS", ".", "image_width", ",", "3", "]", "with", "tf", ".", "Gra...
Run the sample attack
[ "Run", "the", "sample", "attack" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/sample_attacks/random_noise/attack_random_noise.py#L86-L99
train
tensorflow/cleverhans
cleverhans/attacks/saliency_map_method.py
jsma_symbolic
def jsma_symbolic(x, y_target, model, theta, gamma, clip_min, clip_max): """ TensorFlow implementation of the JSMA (see https://arxiv.org/abs/1511.07528 for details about the algorithm design choices). :param x: the input placeholder :param y_target: the target tensor :param model: a cleverhans.model.Model...
python
def jsma_symbolic(x, y_target, model, theta, gamma, clip_min, clip_max): """ TensorFlow implementation of the JSMA (see https://arxiv.org/abs/1511.07528 for details about the algorithm design choices). :param x: the input placeholder :param y_target: the target tensor :param model: a cleverhans.model.Model...
[ "def", "jsma_symbolic", "(", "x", ",", "y_target", ",", "model", ",", "theta", ",", "gamma", ",", "clip_min", ",", "clip_max", ")", ":", "nb_classes", "=", "int", "(", "y_target", ".", "shape", "[", "-", "1", "]", ".", "value", ")", "nb_features", "=...
TensorFlow implementation of the JSMA (see https://arxiv.org/abs/1511.07528 for details about the algorithm design choices). :param x: the input placeholder :param y_target: the target tensor :param model: a cleverhans.model.Model object. :param theta: delta for each feature adjustment :param gamma: a floa...
[ "TensorFlow", "implementation", "of", "the", "JSMA", "(", "see", "https", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1511", ".", "07528", "for", "details", "about", "the", "algorithm", "design", "choices", ")", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/saliency_map_method.py#L132-L281
train
tensorflow/cleverhans
cleverhans/attacks/saliency_map_method.py
SaliencyMapMethod.generate
def generate(self, x, **kwargs): """ Generate symbolic graph for adversarial examples and return. :param x: The model's symbolic inputs. :param kwargs: See `parse_params` """ # Parse and save attack-specific parameters assert self.parse_params(**kwargs) if self.symbolic_impl: # C...
python
def generate(self, x, **kwargs): """ Generate symbolic graph for adversarial examples and return. :param x: The model's symbolic inputs. :param kwargs: See `parse_params` """ # Parse and save attack-specific parameters assert self.parse_params(**kwargs) if self.symbolic_impl: # C...
[ "def", "generate", "(", "self", ",", "x", ",", "*", "*", "kwargs", ")", ":", "# Parse and save attack-specific parameters", "assert", "self", ".", "parse_params", "(", "*", "*", "kwargs", ")", "if", "self", ".", "symbolic_impl", ":", "# Create random targets if ...
Generate symbolic graph for adversarial examples and return. :param x: The model's symbolic inputs. :param kwargs: See `parse_params`
[ "Generate", "symbolic", "graph", "for", "adversarial", "examples", "and", "return", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/saliency_map_method.py#L44-L90
train
tensorflow/cleverhans
cleverhans/attacks/saliency_map_method.py
SaliencyMapMethod.parse_params
def parse_params(self, theta=1., gamma=1., clip_min=0., clip_max=1., y_target=None, symbolic_impl=True, **kwargs): """ Take in a dictionary of parameters and applies attack-specif...
python
def parse_params(self, theta=1., gamma=1., clip_min=0., clip_max=1., y_target=None, symbolic_impl=True, **kwargs): """ Take in a dictionary of parameters and applies attack-specif...
[ "def", "parse_params", "(", "self", ",", "theta", "=", "1.", ",", "gamma", "=", "1.", ",", "clip_min", "=", "0.", ",", "clip_max", "=", "1.", ",", "y_target", "=", "None", ",", "symbolic_impl", "=", "True", ",", "*", "*", "kwargs", ")", ":", "self"...
Take in a dictionary of parameters and applies attack-specific checks before saving them as attributes. Attack-specific parameters: :param theta: (optional float) Perturbation introduced to modified components (can be positive or negative) :param gamma: (optional float) Maximum perce...
[ "Take", "in", "a", "dictionary", "of", "parameters", "and", "applies", "attack", "-", "specific", "checks", "before", "saving", "them", "as", "attributes", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/saliency_map_method.py#L92-L124
train
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
train
tensorflow/cleverhans
examples/multigpu_advtrain/make_model.py
make_madry_ngpu
def make_madry_ngpu(nb_classes=10, input_shape=(None, 28, 28, 1), **kwargs): """ Create a multi-GPU model similar to Madry et al. (arXiv:1706.06083). """ layers = [Conv2DnGPU(32, (5, 5), (1, 1), "SAME"), ReLU(), MaxPool((2, 2), (2, 2), "SAME"), Conv2DnGPU(64, (5, 5), (1, 1), ...
python
def make_madry_ngpu(nb_classes=10, input_shape=(None, 28, 28, 1), **kwargs): """ Create a multi-GPU model similar to Madry et al. (arXiv:1706.06083). """ layers = [Conv2DnGPU(32, (5, 5), (1, 1), "SAME"), ReLU(), MaxPool((2, 2), (2, 2), "SAME"), Conv2DnGPU(64, (5, 5), (1, 1), ...
[ "def", "make_madry_ngpu", "(", "nb_classes", "=", "10", ",", "input_shape", "=", "(", "None", ",", "28", ",", "28", ",", "1", ")", ",", "*", "*", "kwargs", ")", ":", "layers", "=", "[", "Conv2DnGPU", "(", "32", ",", "(", "5", ",", "5", ")", ","...
Create a multi-GPU model similar to Madry et al. (arXiv:1706.06083).
[ "Create", "a", "multi", "-", "GPU", "model", "similar", "to", "Madry", "et", "al", ".", "(", "arXiv", ":", "1706", ".", "06083", ")", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/make_model.py#L38-L55
train
tensorflow/cleverhans
examples/multigpu_advtrain/resnet_tf.py
ResNetTF._build_model
def _build_model(self, x): """Build the core model within the graph.""" with tf.variable_scope('init'): x = self._conv('init_conv', x, 3, x.shape[3], 16, self._stride_arr(1)) strides = [1, 2, 2] activate_before_residual = [True, False, False] if self.hps.use_bottleneck: ...
python
def _build_model(self, x): """Build the core model within the graph.""" with tf.variable_scope('init'): x = self._conv('init_conv', x, 3, x.shape[3], 16, self._stride_arr(1)) strides = [1, 2, 2] activate_before_residual = [True, False, False] if self.hps.use_bottleneck: ...
[ "def", "_build_model", "(", "self", ",", "x", ")", ":", "with", "tf", ".", "variable_scope", "(", "'init'", ")", ":", "x", "=", "self", ".", "_conv", "(", "'init_conv'", ",", "x", ",", "3", ",", "x", ".", "shape", "[", "3", "]", ",", "16", ",",...
Build the core model within the graph.
[ "Build", "the", "core", "model", "within", "the", "graph", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/resnet_tf.py#L81-L140
train
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
train
tensorflow/cleverhans
examples/multigpu_advtrain/resnet_tf.py
ResNetTF.build_train_op_from_cost
def build_train_op_from_cost(self, cost): """Build training specific ops for the graph.""" self.lrn_rate = tf.constant(self.hps.lrn_rate, tf.float32, name='learning_rate') self.momentum = tf.constant(self.hps.momentum, tf.float32, name='momentu...
python
def build_train_op_from_cost(self, cost): """Build training specific ops for the graph.""" self.lrn_rate = tf.constant(self.hps.lrn_rate, tf.float32, name='learning_rate') self.momentum = tf.constant(self.hps.momentum, tf.float32, name='momentu...
[ "def", "build_train_op_from_cost", "(", "self", ",", "cost", ")", ":", "self", ".", "lrn_rate", "=", "tf", ".", "constant", "(", "self", ".", "hps", ".", "lrn_rate", ",", "tf", ".", "float32", ",", "name", "=", "'learning_rate'", ")", "self", ".", "mom...
Build training specific ops for the graph.
[ "Build", "training", "specific", "ops", "for", "the", "graph", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/resnet_tf.py#L160-L187
train
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
train
tensorflow/cleverhans
examples/multigpu_advtrain/resnet_tf.py
ResNetTF._residual
def _residual(self, x, in_filter, out_filter, stride, activate_before_residual=False): """Residual unit with 2 sub layers.""" if activate_before_residual: with tf.variable_scope('shared_activation'): x = self._layer_norm('init_bn', x) x = self._relu(x, self.hps.relu_leakine...
python
def _residual(self, x, in_filter, out_filter, stride, activate_before_residual=False): """Residual unit with 2 sub layers.""" if activate_before_residual: with tf.variable_scope('shared_activation'): x = self._layer_norm('init_bn', x) x = self._relu(x, self.hps.relu_leakine...
[ "def", "_residual", "(", "self", ",", "x", ",", "in_filter", ",", "out_filter", ",", "stride", ",", "activate_before_residual", "=", "False", ")", ":", "if", "activate_before_residual", ":", "with", "tf", ".", "variable_scope", "(", "'shared_activation'", ")", ...
Residual unit with 2 sub layers.
[ "Residual", "unit", "with", "2", "sub", "layers", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/resnet_tf.py#L203-L234
train
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
train
tensorflow/cleverhans
examples/multigpu_advtrain/resnet_tf.py
ResNetTF._decay
def _decay(self): """L2 weight decay loss.""" if self.decay_cost is not None: return self.decay_cost costs = [] if self.device_name is None: for var in tf.trainable_variables(): if var.op.name.find(r'DW') > 0: costs.append(tf.nn.l2_loss(var)) else: for layer in s...
python
def _decay(self): """L2 weight decay loss.""" if self.decay_cost is not None: return self.decay_cost costs = [] if self.device_name is None: for var in tf.trainable_variables(): if var.op.name.find(r'DW') > 0: costs.append(tf.nn.l2_loss(var)) else: for layer in s...
[ "def", "_decay", "(", "self", ")", ":", "if", "self", ".", "decay_cost", "is", "not", "None", ":", "return", "self", ".", "decay_cost", "costs", "=", "[", "]", "if", "self", ".", "device_name", "is", "None", ":", "for", "var", "in", "tf", ".", "tra...
L2 weight decay loss.
[ "L2", "weight", "decay", "loss", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/resnet_tf.py#L273-L291
train
tensorflow/cleverhans
examples/multigpu_advtrain/resnet_tf.py
ResNetTF._conv
def _conv(self, name, x, filter_size, in_filters, out_filters, strides): """Convolution.""" if self.init_layers: conv = Conv2DnGPU(out_filters, (filter_size, filter_size), strides[1:3], 'SAME', w_name='DW') conv.name = name self.layers += [conv] ...
python
def _conv(self, name, x, filter_size, in_filters, out_filters, strides): """Convolution.""" if self.init_layers: conv = Conv2DnGPU(out_filters, (filter_size, filter_size), strides[1:3], 'SAME', w_name='DW') conv.name = name self.layers += [conv] ...
[ "def", "_conv", "(", "self", ",", "name", ",", "x", ",", "filter_size", ",", "in_filters", ",", "out_filters", ",", "strides", ")", ":", "if", "self", ".", "init_layers", ":", "conv", "=", "Conv2DnGPU", "(", "out_filters", ",", "(", "filter_size", ",", ...
Convolution.
[ "Convolution", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/resnet_tf.py#L293-L306
train
tensorflow/cleverhans
examples/multigpu_advtrain/resnet_tf.py
ResNetTF._fully_connected
def _fully_connected(self, x, out_dim): """FullyConnected layer for final output.""" if self.init_layers: fc = LinearnGPU(out_dim, w_name='DW') fc.name = 'logits' self.layers += [fc] else: fc = self.layers[self.layer_idx] self.layer_idx += 1 fc.device_name = self.device_nam...
python
def _fully_connected(self, x, out_dim): """FullyConnected layer for final output.""" if self.init_layers: fc = LinearnGPU(out_dim, w_name='DW') fc.name = 'logits' self.layers += [fc] else: fc = self.layers[self.layer_idx] self.layer_idx += 1 fc.device_name = self.device_nam...
[ "def", "_fully_connected", "(", "self", ",", "x", ",", "out_dim", ")", ":", "if", "self", ".", "init_layers", ":", "fc", "=", "LinearnGPU", "(", "out_dim", ",", "w_name", "=", "'DW'", ")", "fc", ".", "name", "=", "'logits'", "self", ".", "layers", "+...
FullyConnected layer for final output.
[ "FullyConnected", "layer", "for", "final", "output", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/resnet_tf.py#L312-L323
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/submissions.py
CompetitionSubmissions.get_all_attack_ids
def get_all_attack_ids(self): """Returns IDs of all attacks (targeted and non-targeted).""" return list(self.attacks.keys()) + list(self.targeted_attacks.keys())
python
def get_all_attack_ids(self): """Returns IDs of all attacks (targeted and non-targeted).""" return list(self.attacks.keys()) + list(self.targeted_attacks.keys())
[ "def", "get_all_attack_ids", "(", "self", ")", ":", "return", "list", "(", "self", ".", "attacks", ".", "keys", "(", ")", ")", "+", "list", "(", "self", ".", "targeted_attacks", ".", "keys", "(", ")", ")" ]
Returns IDs of all attacks (targeted and non-targeted).
[ "Returns", "IDs", "of", "all", "attacks", "(", "targeted", "and", "non", "-", "targeted", ")", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/submissions.py#L194-L196
train
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
train
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
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/dev_toolkit/validation_tool/submission_validator_lib.py
SubmissionValidator._prepare_temp_dir
def _prepare_temp_dir(self): """Cleans up and prepare temporary directory.""" shell_call(['rm', '-rf', os.path.join(self._temp_dir, '*')]) # NOTE: we do not create self._extracted_submission_dir # this is intentional because self._tmp_extracted_dir or it's subdir # will be renames into self._extract...
python
def _prepare_temp_dir(self): """Cleans up and prepare temporary directory.""" shell_call(['rm', '-rf', os.path.join(self._temp_dir, '*')]) # NOTE: we do not create self._extracted_submission_dir # this is intentional because self._tmp_extracted_dir or it's subdir # will be renames into self._extract...
[ "def", "_prepare_temp_dir", "(", "self", ")", ":", "shell_call", "(", "[", "'rm'", ",", "'-rf'", ",", "os", ".", "path", ".", "join", "(", "self", ".", "_temp_dir", ",", "'*'", ")", "]", ")", "# NOTE: we do not create self._extracted_submission_dir", "# this i...
Cleans up and prepare temporary directory.
[ "Cleans", "up", "and", "prepare", "temporary", "directory", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/validation_tool/submission_validator_lib.py#L133-L143
train
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
train
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
train
tensorflow/cleverhans
cleverhans/future/tf2/attacks/fast_gradient_method.py
fast_gradient_method
def fast_gradient_method(model_fn, x, eps, ord, clip_min=None, clip_max=None, y=None, targeted=False, sanity_checks=False): """ Tensorflow 2.0 implementation of the Fast Gradient Method. :param model_fn: a callable that takes an input tensor and returns the model logits. :param x: input...
python
def fast_gradient_method(model_fn, x, eps, ord, clip_min=None, clip_max=None, y=None, targeted=False, sanity_checks=False): """ Tensorflow 2.0 implementation of the Fast Gradient Method. :param model_fn: a callable that takes an input tensor and returns the model logits. :param x: input...
[ "def", "fast_gradient_method", "(", "model_fn", ",", "x", ",", "eps", ",", "ord", ",", "clip_min", "=", "None", ",", "clip_max", "=", "None", ",", "y", "=", "None", ",", "targeted", "=", "False", ",", "sanity_checks", "=", "False", ")", ":", "if", "o...
Tensorflow 2.0 implementation of the Fast Gradient Method. :param model_fn: a callable that takes an input tensor and returns the model logits. :param x: input tensor. :param eps: epsilon (input variation parameter); see https://arxiv.org/abs/1412.6572. :param ord: Order of the norm (mimics NumPy). Possible val...
[ "Tensorflow", "2", ".", "0", "implementation", "of", "the", "Fast", "Gradient", "Method", ".", ":", "param", "model_fn", ":", "a", "callable", "that", "takes", "an", "input", "tensor", "and", "returns", "the", "model", "logits", ".", ":", "param", "x", "...
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/future/tf2/attacks/fast_gradient_method.py#L7-L59
train