repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
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 control flow of minimum_eigen_vector self.min_eigen_vec = autograph.to_graph(utils.tf_lanczos_smallest_eigval) def _m_vector_prod_fn(x): return self.get_psd_product(x, dtype=self.lanczos_dtype) def _h_vector_prod_fn(x): return self.get_h_product(x, dtype=self.lanczos_dtype) # Construct nodes for computing eigenvalue of M self.m_min_vec_estimate = np.zeros(shape=(self.matrix_m_dimension, 1), dtype=np.float64) zeros_m = tf.zeros(shape=(self.matrix_m_dimension, 1), dtype=tf.float64) self.m_min_vec_ph = tf.placeholder_with_default(input=zeros_m, shape=(self.matrix_m_dimension, 1), name='m_min_vec_ph') self.m_min_eig, self.m_min_vec = self.min_eigen_vec(_m_vector_prod_fn, self.matrix_m_dimension, self.m_min_vec_ph, self.lzs_params['max_iter'], dtype=self.lanczos_dtype) self.m_min_eig = tf.cast(self.m_min_eig, self.nn_dtype) self.m_min_vec = tf.cast(self.m_min_vec, self.nn_dtype) self.h_min_vec_estimate = np.zeros(shape=(self.matrix_m_dimension - 1, 1), dtype=np.float64) zeros_h = tf.zeros(shape=(self.matrix_m_dimension - 1, 1), dtype=tf.float64) self.h_min_vec_ph = tf.placeholder_with_default(input=zeros_h, shape=(self.matrix_m_dimension - 1, 1), name='h_min_vec_ph') self.h_min_eig, self.h_min_vec = self.min_eigen_vec(_h_vector_prod_fn, self.matrix_m_dimension-1, self.h_min_vec_ph, self.lzs_params['max_iter'], dtype=self.lanczos_dtype) self.h_min_eig = tf.cast(self.h_min_eig, self.nn_dtype) self.h_min_vec = tf.cast(self.h_min_vec, self.nn_dtype)
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 control flow of minimum_eigen_vector self.min_eigen_vec = autograph.to_graph(utils.tf_lanczos_smallest_eigval) def _m_vector_prod_fn(x): return self.get_psd_product(x, dtype=self.lanczos_dtype) def _h_vector_prod_fn(x): return self.get_h_product(x, dtype=self.lanczos_dtype) # Construct nodes for computing eigenvalue of M self.m_min_vec_estimate = np.zeros(shape=(self.matrix_m_dimension, 1), dtype=np.float64) zeros_m = tf.zeros(shape=(self.matrix_m_dimension, 1), dtype=tf.float64) self.m_min_vec_ph = tf.placeholder_with_default(input=zeros_m, shape=(self.matrix_m_dimension, 1), name='m_min_vec_ph') self.m_min_eig, self.m_min_vec = self.min_eigen_vec(_m_vector_prod_fn, self.matrix_m_dimension, self.m_min_vec_ph, self.lzs_params['max_iter'], dtype=self.lanczos_dtype) self.m_min_eig = tf.cast(self.m_min_eig, self.nn_dtype) self.m_min_vec = tf.cast(self.m_min_vec, self.nn_dtype) self.h_min_vec_estimate = np.zeros(shape=(self.matrix_m_dimension - 1, 1), dtype=np.float64) zeros_h = tf.zeros(shape=(self.matrix_m_dimension - 1, 1), dtype=tf.float64) self.h_min_vec_ph = tf.placeholder_with_default(input=zeros_h, shape=(self.matrix_m_dimension - 1, 1), name='h_min_vec_ph') self.h_min_eig, self.h_min_vec = self.min_eigen_vec(_h_vector_prod_fn, self.matrix_m_dimension-1, self.h_min_vec_ph, self.lzs_params['max_iter'], dtype=self.lanczos_dtype) self.h_min_eig = tf.cast(self.h_min_eig, self.nn_dtype) self.h_min_vec = tf.cast(self.h_min_vec, self.nn_dtype)
[ "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", "_m_vector_prod_fn", "(", "x", ")", ":", "return", "self", ".", "get_psd_product", "(", "x", ",", "dtype", "=", "self", ".", "lanczos_dtype", ")", "def", "_h_vector_prod_fn", "(", "x", ")", ":", "return", "self", ".", "get_h_product", "(", "x", ",", "dtype", "=", "self", ".", "lanczos_dtype", ")", "# Construct nodes for computing eigenvalue of M", "self", ".", "m_min_vec_estimate", "=", "np", ".", "zeros", "(", "shape", "=", "(", "self", ".", "matrix_m_dimension", ",", "1", ")", ",", "dtype", "=", "np", ".", "float64", ")", "zeros_m", "=", "tf", ".", "zeros", "(", "shape", "=", "(", "self", ".", "matrix_m_dimension", ",", "1", ")", ",", "dtype", "=", "tf", ".", "float64", ")", "self", ".", "m_min_vec_ph", "=", "tf", ".", "placeholder_with_default", "(", "input", "=", "zeros_m", ",", "shape", "=", "(", "self", ".", "matrix_m_dimension", ",", "1", ")", ",", "name", "=", "'m_min_vec_ph'", ")", "self", ".", "m_min_eig", ",", "self", ".", "m_min_vec", "=", "self", ".", "min_eigen_vec", "(", "_m_vector_prod_fn", ",", "self", ".", "matrix_m_dimension", ",", "self", ".", "m_min_vec_ph", ",", "self", ".", "lzs_params", "[", "'max_iter'", "]", ",", "dtype", "=", "self", ".", "lanczos_dtype", ")", "self", ".", "m_min_eig", "=", "tf", ".", "cast", "(", "self", ".", "m_min_eig", ",", "self", ".", "nn_dtype", ")", "self", ".", "m_min_vec", "=", "tf", ".", "cast", "(", "self", ".", "m_min_vec", ",", "self", ".", "nn_dtype", ")", "self", ".", "h_min_vec_estimate", "=", "np", ".", "zeros", "(", "shape", "=", "(", "self", ".", "matrix_m_dimension", "-", "1", ",", "1", ")", ",", "dtype", "=", "np", ".", "float64", ")", "zeros_h", "=", "tf", ".", "zeros", "(", "shape", "=", "(", "self", ".", "matrix_m_dimension", "-", "1", ",", "1", ")", ",", "dtype", "=", "tf", ".", "float64", ")", "self", ".", "h_min_vec_ph", "=", "tf", ".", "placeholder_with_default", "(", "input", "=", "zeros_h", ",", "shape", "=", "(", "self", ".", "matrix_m_dimension", "-", "1", ",", "1", ")", ",", "name", "=", "'h_min_vec_ph'", ")", "self", ".", "h_min_eig", ",", "self", ".", "h_min_vec", "=", "self", ".", "min_eigen_vec", "(", "_h_vector_prod_fn", ",", "self", ".", "matrix_m_dimension", "-", "1", ",", "self", ".", "h_min_vec_ph", ",", "self", ".", "lzs_params", "[", "'max_iter'", "]", ",", "dtype", "=", "self", ".", "lanczos_dtype", ")", "self", ".", "h_min_eig", "=", "tf", ".", "cast", "(", "self", ".", "h_min_eig", ",", "self", ".", "nn_dtype", ")", "self", ".", "h_min_vec", "=", "tf", ".", "cast", "(", "self", ".", "h_min_vec", ",", "self", ".", "nn_dtype", ")" ]
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): bias_sum = bias_sum + tf.reduce_sum( tf.multiply(self.nn_params.biases[i], self.lambda_pos[i + 1])) lu_sum = 0 for i in range(0, self.nn_params.num_hidden_layers + 1): lu_sum = lu_sum + tf.reduce_sum( tf.multiply(tf.multiply(self.lower[i], self.upper[i]), self.lambda_lu[i])) self.scalar_f = -bias_sum - lu_sum + self.final_constant # Computing the vector term g_rows = [] for i in range(0, self.nn_params.num_hidden_layers): if i > 0: current_row = (self.lambda_neg[i] + self.lambda_pos[i] - self.nn_params.forward_pass(self.lambda_pos[i+1], i, is_transpose=True) + tf.multiply(self.lower[i]+self.upper[i], self.lambda_lu[i]) + tf.multiply(self.lambda_quad[i], self.nn_params.biases[i-1])) else: current_row = (-self.nn_params.forward_pass(self.lambda_pos[i+1], i, is_transpose=True) + tf.multiply(self.lower[i]+self.upper[i], self.lambda_lu[i])) g_rows.append(current_row) # Term for final linear term g_rows.append((self.lambda_pos[self.nn_params.num_hidden_layers] + self.lambda_neg[self.nn_params.num_hidden_layers] + self.final_linear + tf.multiply((self.lower[self.nn_params.num_hidden_layers]+ self.upper[self.nn_params.num_hidden_layers]), self.lambda_lu[self.nn_params.num_hidden_layers]) + tf.multiply( self.lambda_quad[self.nn_params.num_hidden_layers], self.nn_params.biases[ self.nn_params.num_hidden_layers-1]))) self.vector_g = tf.concat(g_rows, axis=0) self.unconstrained_objective = self.scalar_f + 0.5 * self.nu
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): bias_sum = bias_sum + tf.reduce_sum( tf.multiply(self.nn_params.biases[i], self.lambda_pos[i + 1])) lu_sum = 0 for i in range(0, self.nn_params.num_hidden_layers + 1): lu_sum = lu_sum + tf.reduce_sum( tf.multiply(tf.multiply(self.lower[i], self.upper[i]), self.lambda_lu[i])) self.scalar_f = -bias_sum - lu_sum + self.final_constant # Computing the vector term g_rows = [] for i in range(0, self.nn_params.num_hidden_layers): if i > 0: current_row = (self.lambda_neg[i] + self.lambda_pos[i] - self.nn_params.forward_pass(self.lambda_pos[i+1], i, is_transpose=True) + tf.multiply(self.lower[i]+self.upper[i], self.lambda_lu[i]) + tf.multiply(self.lambda_quad[i], self.nn_params.biases[i-1])) else: current_row = (-self.nn_params.forward_pass(self.lambda_pos[i+1], i, is_transpose=True) + tf.multiply(self.lower[i]+self.upper[i], self.lambda_lu[i])) g_rows.append(current_row) # Term for final linear term g_rows.append((self.lambda_pos[self.nn_params.num_hidden_layers] + self.lambda_neg[self.nn_params.num_hidden_layers] + self.final_linear + tf.multiply((self.lower[self.nn_params.num_hidden_layers]+ self.upper[self.nn_params.num_hidden_layers]), self.lambda_lu[self.nn_params.num_hidden_layers]) + tf.multiply( self.lambda_quad[self.nn_params.num_hidden_layers], self.nn_params.biases[ self.nn_params.num_hidden_layers-1]))) self.vector_g = tf.concat(g_rows, axis=0) self.unconstrained_objective = self.scalar_f + 0.5 * self.nu
[ "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", ",", "self", ".", "nn_params", ".", "num_hidden_layers", ")", ":", "bias_sum", "=", "bias_sum", "+", "tf", ".", "reduce_sum", "(", "tf", ".", "multiply", "(", "self", ".", "nn_params", ".", "biases", "[", "i", "]", ",", "self", ".", "lambda_pos", "[", "i", "+", "1", "]", ")", ")", "lu_sum", "=", "0", "for", "i", "in", "range", "(", "0", ",", "self", ".", "nn_params", ".", "num_hidden_layers", "+", "1", ")", ":", "lu_sum", "=", "lu_sum", "+", "tf", ".", "reduce_sum", "(", "tf", ".", "multiply", "(", "tf", ".", "multiply", "(", "self", ".", "lower", "[", "i", "]", ",", "self", ".", "upper", "[", "i", "]", ")", ",", "self", ".", "lambda_lu", "[", "i", "]", ")", ")", "self", ".", "scalar_f", "=", "-", "bias_sum", "-", "lu_sum", "+", "self", ".", "final_constant", "# Computing the vector term", "g_rows", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "self", ".", "nn_params", ".", "num_hidden_layers", ")", ":", "if", "i", ">", "0", ":", "current_row", "=", "(", "self", ".", "lambda_neg", "[", "i", "]", "+", "self", ".", "lambda_pos", "[", "i", "]", "-", "self", ".", "nn_params", ".", "forward_pass", "(", "self", ".", "lambda_pos", "[", "i", "+", "1", "]", ",", "i", ",", "is_transpose", "=", "True", ")", "+", "tf", ".", "multiply", "(", "self", ".", "lower", "[", "i", "]", "+", "self", ".", "upper", "[", "i", "]", ",", "self", ".", "lambda_lu", "[", "i", "]", ")", "+", "tf", ".", "multiply", "(", "self", ".", "lambda_quad", "[", "i", "]", ",", "self", ".", "nn_params", ".", "biases", "[", "i", "-", "1", "]", ")", ")", "else", ":", "current_row", "=", "(", "-", "self", ".", "nn_params", ".", "forward_pass", "(", "self", ".", "lambda_pos", "[", "i", "+", "1", "]", ",", "i", ",", "is_transpose", "=", "True", ")", "+", "tf", ".", "multiply", "(", "self", ".", "lower", "[", "i", "]", "+", "self", ".", "upper", "[", "i", "]", ",", "self", ".", "lambda_lu", "[", "i", "]", ")", ")", "g_rows", ".", "append", "(", "current_row", ")", "# Term for final linear term", "g_rows", ".", "append", "(", "(", "self", ".", "lambda_pos", "[", "self", ".", "nn_params", ".", "num_hidden_layers", "]", "+", "self", ".", "lambda_neg", "[", "self", ".", "nn_params", ".", "num_hidden_layers", "]", "+", "self", ".", "final_linear", "+", "tf", ".", "multiply", "(", "(", "self", ".", "lower", "[", "self", ".", "nn_params", ".", "num_hidden_layers", "]", "+", "self", ".", "upper", "[", "self", ".", "nn_params", ".", "num_hidden_layers", "]", ")", ",", "self", ".", "lambda_lu", "[", "self", ".", "nn_params", ".", "num_hidden_layers", "]", ")", "+", "tf", ".", "multiply", "(", "self", ".", "lambda_quad", "[", "self", ".", "nn_params", ".", "num_hidden_layers", "]", ",", "self", ".", "nn_params", ".", "biases", "[", "self", ".", "nn_params", ".", "num_hidden_layers", "-", "1", "]", ")", ")", ")", "self", ".", "vector_g", "=", "tf", ".", "concat", "(", "g_rows", ",", "axis", "=", "0", ")", "self", ".", "unconstrained_objective", "=", "self", ".", "scalar_f", "+", "0.5", "*", "self", ".", "nu" ]
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 vector) # At first layer, h is simply diagonal if dtype is None: dtype = self.nn_dtype beta = tf.cast(vector, self.nn_dtype) h_beta_rows = [] for i in range(self.nn_params.num_hidden_layers): # Split beta of this block into [gamma, delta] gamma = beta[self.dual_index[i]:self.dual_index[i + 1]] delta = beta[self.dual_index[i + 1]:self.dual_index[i + 2]] # Expanding the product with diagonal matrices if i == 0: h_beta_rows.append( tf.multiply(2 * self.lambda_lu[i], gamma) - self.nn_params.forward_pass( tf.multiply(self.lambda_quad[i + 1], delta), i, is_transpose=True)) else: h_beta_rows[i] = (h_beta_rows[i] + tf.multiply(self.lambda_quad[i] + self.lambda_lu[i], gamma) - self.nn_params.forward_pass( tf.multiply(self.lambda_quad[i+1], delta), i, is_transpose=True)) new_row = ( tf.multiply(self.lambda_quad[i + 1] + self.lambda_lu[i + 1], delta) - tf.multiply(self.lambda_quad[i + 1], self.nn_params.forward_pass(gamma, i))) h_beta_rows.append(new_row) # Last boundary case h_beta_rows[self.nn_params.num_hidden_layers] = ( h_beta_rows[self.nn_params.num_hidden_layers] + tf.multiply((self.lambda_quad[self.nn_params.num_hidden_layers] + self.lambda_lu[self.nn_params.num_hidden_layers]), delta)) h_beta = tf.concat(h_beta_rows, axis=0) return tf.cast(h_beta, dtype)
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 vector) # At first layer, h is simply diagonal if dtype is None: dtype = self.nn_dtype beta = tf.cast(vector, self.nn_dtype) h_beta_rows = [] for i in range(self.nn_params.num_hidden_layers): # Split beta of this block into [gamma, delta] gamma = beta[self.dual_index[i]:self.dual_index[i + 1]] delta = beta[self.dual_index[i + 1]:self.dual_index[i + 2]] # Expanding the product with diagonal matrices if i == 0: h_beta_rows.append( tf.multiply(2 * self.lambda_lu[i], gamma) - self.nn_params.forward_pass( tf.multiply(self.lambda_quad[i + 1], delta), i, is_transpose=True)) else: h_beta_rows[i] = (h_beta_rows[i] + tf.multiply(self.lambda_quad[i] + self.lambda_lu[i], gamma) - self.nn_params.forward_pass( tf.multiply(self.lambda_quad[i+1], delta), i, is_transpose=True)) new_row = ( tf.multiply(self.lambda_quad[i + 1] + self.lambda_lu[i + 1], delta) - tf.multiply(self.lambda_quad[i + 1], self.nn_params.forward_pass(gamma, i))) h_beta_rows.append(new_row) # Last boundary case h_beta_rows[self.nn_params.num_hidden_layers] = ( h_beta_rows[self.nn_params.num_hidden_layers] + tf.multiply((self.lambda_quad[self.nn_params.num_hidden_layers] + self.lambda_lu[self.nn_params.num_hidden_layers]), delta)) h_beta = tf.concat(h_beta_rows, axis=0) return tf.cast(h_beta, dtype)
[ "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", "beta", "=", "tf", ".", "cast", "(", "vector", ",", "self", ".", "nn_dtype", ")", "h_beta_rows", "=", "[", "]", "for", "i", "in", "range", "(", "self", ".", "nn_params", ".", "num_hidden_layers", ")", ":", "# Split beta of this block into [gamma, delta]", "gamma", "=", "beta", "[", "self", ".", "dual_index", "[", "i", "]", ":", "self", ".", "dual_index", "[", "i", "+", "1", "]", "]", "delta", "=", "beta", "[", "self", ".", "dual_index", "[", "i", "+", "1", "]", ":", "self", ".", "dual_index", "[", "i", "+", "2", "]", "]", "# Expanding the product with diagonal matrices", "if", "i", "==", "0", ":", "h_beta_rows", ".", "append", "(", "tf", ".", "multiply", "(", "2", "*", "self", ".", "lambda_lu", "[", "i", "]", ",", "gamma", ")", "-", "self", ".", "nn_params", ".", "forward_pass", "(", "tf", ".", "multiply", "(", "self", ".", "lambda_quad", "[", "i", "+", "1", "]", ",", "delta", ")", ",", "i", ",", "is_transpose", "=", "True", ")", ")", "else", ":", "h_beta_rows", "[", "i", "]", "=", "(", "h_beta_rows", "[", "i", "]", "+", "tf", ".", "multiply", "(", "self", ".", "lambda_quad", "[", "i", "]", "+", "self", ".", "lambda_lu", "[", "i", "]", ",", "gamma", ")", "-", "self", ".", "nn_params", ".", "forward_pass", "(", "tf", ".", "multiply", "(", "self", ".", "lambda_quad", "[", "i", "+", "1", "]", ",", "delta", ")", ",", "i", ",", "is_transpose", "=", "True", ")", ")", "new_row", "=", "(", "tf", ".", "multiply", "(", "self", ".", "lambda_quad", "[", "i", "+", "1", "]", "+", "self", ".", "lambda_lu", "[", "i", "+", "1", "]", ",", "delta", ")", "-", "tf", ".", "multiply", "(", "self", ".", "lambda_quad", "[", "i", "+", "1", "]", ",", "self", ".", "nn_params", ".", "forward_pass", "(", "gamma", ",", "i", ")", ")", ")", "h_beta_rows", ".", "append", "(", "new_row", ")", "# Last boundary case", "h_beta_rows", "[", "self", ".", "nn_params", ".", "num_hidden_layers", "]", "=", "(", "h_beta_rows", "[", "self", ".", "nn_params", ".", "num_hidden_layers", "]", "+", "tf", ".", "multiply", "(", "(", "self", ".", "lambda_quad", "[", "self", ".", "nn_params", ".", "num_hidden_layers", "]", "+", "self", ".", "lambda_lu", "[", "self", ".", "nn_params", ".", "num_hidden_layers", "]", ")", ",", "delta", ")", ")", "h_beta", "=", "tf", ".", "concat", "(", "h_beta_rows", ",", "axis", "=", "0", ")", "return", "tf", ".", "cast", "(", "h_beta", ",", "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 dtype is None: dtype = self.nn_dtype vector = tf.cast(vector, self.nn_dtype) alpha = tf.reshape(vector[0], shape=[1, 1]) beta = vector[1:] # Computing the product of matrix_h with beta part of vector # At first layer, h is simply diagonal h_beta = self.get_h_product(beta) # Constructing final result using vector_g result = tf.concat( [ alpha * self.nu + tf.reduce_sum(tf.multiply(beta, self.vector_g)), tf.multiply(alpha, self.vector_g) + h_beta ], axis=0) return tf.cast(result, dtype)
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 dtype is None: dtype = self.nn_dtype vector = tf.cast(vector, self.nn_dtype) alpha = tf.reshape(vector[0], shape=[1, 1]) beta = vector[1:] # Computing the product of matrix_h with beta part of vector # At first layer, h is simply diagonal h_beta = self.get_h_product(beta) # Constructing final result using vector_g result = tf.concat( [ alpha * self.nu + tf.reduce_sum(tf.multiply(beta, self.vector_g)), tf.multiply(alpha, self.vector_g) + h_beta ], axis=0) return tf.cast(result, dtype)
[ "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", "(", "vector", ",", "self", ".", "nn_dtype", ")", "alpha", "=", "tf", ".", "reshape", "(", "vector", "[", "0", "]", ",", "shape", "=", "[", "1", ",", "1", "]", ")", "beta", "=", "vector", "[", "1", ":", "]", "# Computing the product of matrix_h with beta part of vector", "# At first layer, h is simply diagonal", "h_beta", "=", "self", ".", "get_h_product", "(", "beta", ")", "# Constructing final result using vector_g", "result", "=", "tf", ".", "concat", "(", "[", "alpha", "*", "self", ".", "nu", "+", "tf", ".", "reduce_sum", "(", "tf", ".", "multiply", "(", "beta", ",", "self", ".", "vector_g", ")", ")", ",", "tf", ".", "multiply", "(", "alpha", ",", "self", ".", "vector_g", ")", "+", "h_beta", "]", ",", "axis", "=", "0", ")", "return", "tf", ".", "cast", "(", "result", ",", "dtype", ")" ]
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.matrix_m # Computing the matrix term h_columns = [] for i in range(self.nn_params.num_hidden_layers + 1): current_col_elems = [] for j in range(i): current_col_elems.append( tf.zeros([self.nn_params.sizes[j], self.nn_params.sizes[i]])) # For the first layer, there is no relu constraint if i == 0: current_col_elems.append(utils.diag(self.lambda_lu[i])) else: current_col_elems.append( utils.diag(self.lambda_lu[i] + self.lambda_quad[i])) if i < self.nn_params.num_hidden_layers: current_col_elems.append(tf.matmul( utils.diag(-1 * self.lambda_quad[i + 1]), self.nn_params.weights[i])) for j in range(i + 2, self.nn_params.num_hidden_layers + 1): current_col_elems.append( tf.zeros([self.nn_params.sizes[j], self.nn_params.sizes[i]])) current_column = tf.concat(current_col_elems, 0) h_columns.append(current_column) self.matrix_h = tf.concat(h_columns, 1) self.matrix_h = (self.matrix_h + tf.transpose(self.matrix_h)) self.matrix_m = tf.concat( [ tf.concat([tf.reshape(self.nu, (1, 1)), tf.transpose(self.vector_g)], axis=1), tf.concat([self.vector_g, self.matrix_h], axis=1) ], axis=0) return self.matrix_h, self.matrix_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.matrix_m # Computing the matrix term h_columns = [] for i in range(self.nn_params.num_hidden_layers + 1): current_col_elems = [] for j in range(i): current_col_elems.append( tf.zeros([self.nn_params.sizes[j], self.nn_params.sizes[i]])) # For the first layer, there is no relu constraint if i == 0: current_col_elems.append(utils.diag(self.lambda_lu[i])) else: current_col_elems.append( utils.diag(self.lambda_lu[i] + self.lambda_quad[i])) if i < self.nn_params.num_hidden_layers: current_col_elems.append(tf.matmul( utils.diag(-1 * self.lambda_quad[i + 1]), self.nn_params.weights[i])) for j in range(i + 2, self.nn_params.num_hidden_layers + 1): current_col_elems.append( tf.zeros([self.nn_params.sizes[j], self.nn_params.sizes[i]])) current_column = tf.concat(current_col_elems, 0) h_columns.append(current_column) self.matrix_h = tf.concat(h_columns, 1) self.matrix_h = (self.matrix_h + tf.transpose(self.matrix_h)) self.matrix_m = tf.concat( [ tf.concat([tf.reshape(self.nu, (1, 1)), tf.transpose(self.vector_g)], axis=1), tf.concat([self.vector_g, self.matrix_h], axis=1) ], axis=0) return self.matrix_h, self.matrix_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", "range", "(", "self", ".", "nn_params", ".", "num_hidden_layers", "+", "1", ")", ":", "current_col_elems", "=", "[", "]", "for", "j", "in", "range", "(", "i", ")", ":", "current_col_elems", ".", "append", "(", "tf", ".", "zeros", "(", "[", "self", ".", "nn_params", ".", "sizes", "[", "j", "]", ",", "self", ".", "nn_params", ".", "sizes", "[", "i", "]", "]", ")", ")", "# For the first layer, there is no relu constraint", "if", "i", "==", "0", ":", "current_col_elems", ".", "append", "(", "utils", ".", "diag", "(", "self", ".", "lambda_lu", "[", "i", "]", ")", ")", "else", ":", "current_col_elems", ".", "append", "(", "utils", ".", "diag", "(", "self", ".", "lambda_lu", "[", "i", "]", "+", "self", ".", "lambda_quad", "[", "i", "]", ")", ")", "if", "i", "<", "self", ".", "nn_params", ".", "num_hidden_layers", ":", "current_col_elems", ".", "append", "(", "tf", ".", "matmul", "(", "utils", ".", "diag", "(", "-", "1", "*", "self", ".", "lambda_quad", "[", "i", "+", "1", "]", ")", ",", "self", ".", "nn_params", ".", "weights", "[", "i", "]", ")", ")", "for", "j", "in", "range", "(", "i", "+", "2", ",", "self", ".", "nn_params", ".", "num_hidden_layers", "+", "1", ")", ":", "current_col_elems", ".", "append", "(", "tf", ".", "zeros", "(", "[", "self", ".", "nn_params", ".", "sizes", "[", "j", "]", ",", "self", ".", "nn_params", ".", "sizes", "[", "i", "]", "]", ")", ")", "current_column", "=", "tf", ".", "concat", "(", "current_col_elems", ",", "0", ")", "h_columns", ".", "append", "(", "current_column", ")", "self", ".", "matrix_h", "=", "tf", ".", "concat", "(", "h_columns", ",", "1", ")", "self", ".", "matrix_h", "=", "(", "self", ".", "matrix_h", "+", "tf", ".", "transpose", "(", "self", ".", "matrix_h", ")", ")", "self", ".", "matrix_m", "=", "tf", ".", "concat", "(", "[", "tf", ".", "concat", "(", "[", "tf", ".", "reshape", "(", "self", ".", "nu", ",", "(", "1", ",", "1", ")", ")", ",", "tf", ".", "transpose", "(", "self", ".", "vector_g", ")", "]", ",", "axis", "=", "1", ")", ",", "tf", ".", "concat", "(", "[", "self", ".", "vector_g", ",", "self", ".", "matrix_h", "]", ",", "axis", "=", "1", ")", "]", ",", "axis", "=", "0", ")", "return", "self", ".", "matrix_h", ",", "self", ".", "matrix_m" ]
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 """ feed_dict = feed_dictionary.copy() _, min_eig_val_m = self.get_lanczos_eig(compute_m=True, feed_dict=feed_dict) lower_nu = original_nu upper_nu = original_nu num_iter = 0 # Find an upper bound on nu while min_eig_val_m - TOL < 0 and num_iter < (MAX_BINARY_SEARCH_ITER / 2): num_iter += 1 upper_nu *= NU_UPDATE_CONSTANT feed_dict.update({self.nu: upper_nu}) _, min_eig_val_m = self.get_lanczos_eig(compute_m=True, feed_dict=feed_dict) final_nu = upper_nu # Perform binary search to find best value of nu while lower_nu <= upper_nu and num_iter < MAX_BINARY_SEARCH_ITER: num_iter += 1 mid_nu = (lower_nu + upper_nu) / 2 feed_dict.update({self.nu: mid_nu}) _, min_eig_val_m = self.get_lanczos_eig(compute_m=True, feed_dict=feed_dict) if min_eig_val_m - TOL < 0: lower_nu = mid_nu else: upper_nu = mid_nu final_nu = upper_nu return final_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 """ feed_dict = feed_dictionary.copy() _, min_eig_val_m = self.get_lanczos_eig(compute_m=True, feed_dict=feed_dict) lower_nu = original_nu upper_nu = original_nu num_iter = 0 # Find an upper bound on nu while min_eig_val_m - TOL < 0 and num_iter < (MAX_BINARY_SEARCH_ITER / 2): num_iter += 1 upper_nu *= NU_UPDATE_CONSTANT feed_dict.update({self.nu: upper_nu}) _, min_eig_val_m = self.get_lanczos_eig(compute_m=True, feed_dict=feed_dict) final_nu = upper_nu # Perform binary search to find best value of nu while lower_nu <= upper_nu and num_iter < MAX_BINARY_SEARCH_ITER: num_iter += 1 mid_nu = (lower_nu + upper_nu) / 2 feed_dict.update({self.nu: mid_nu}) _, min_eig_val_m = self.get_lanczos_eig(compute_m=True, feed_dict=feed_dict) if min_eig_val_m - TOL < 0: lower_nu = mid_nu else: upper_nu = mid_nu final_nu = upper_nu return final_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", "=", "feed_dict", ")", "lower_nu", "=", "original_nu", "upper_nu", "=", "original_nu", "num_iter", "=", "0", "# Find an upper bound on nu", "while", "min_eig_val_m", "-", "TOL", "<", "0", "and", "num_iter", "<", "(", "MAX_BINARY_SEARCH_ITER", "/", "2", ")", ":", "num_iter", "+=", "1", "upper_nu", "*=", "NU_UPDATE_CONSTANT", "feed_dict", ".", "update", "(", "{", "self", ".", "nu", ":", "upper_nu", "}", ")", "_", ",", "min_eig_val_m", "=", "self", ".", "get_lanczos_eig", "(", "compute_m", "=", "True", ",", "feed_dict", "=", "feed_dict", ")", "final_nu", "=", "upper_nu", "# Perform binary search to find best value of nu", "while", "lower_nu", "<=", "upper_nu", "and", "num_iter", "<", "MAX_BINARY_SEARCH_ITER", ":", "num_iter", "+=", "1", "mid_nu", "=", "(", "lower_nu", "+", "upper_nu", ")", "/", "2", "feed_dict", ".", "update", "(", "{", "self", ".", "nu", ":", "mid_nu", "}", ")", "_", ",", "min_eig_val_m", "=", "self", ".", "get_lanczos_eig", "(", "compute_m", "=", "True", ",", "feed_dict", "=", "feed_dict", ")", "if", "min_eig_val_m", "-", "TOL", "<", "0", ":", "lower_nu", "=", "mid_nu", "else", ":", "upper_nu", "=", "mid_nu", "final_nu", "=", "upper_nu", "return", "final_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 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", "lambda", "variables", "to", "feed", "into", "M", "Returns", ":", "new_nu", ":", "new", "value", "of", "nu" ]
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: dictionary mapping from TF placeholders to values (optional) Returns: min_eig_vec: Corresponding eigen vector to min eig val eig_val: Minimum eigen value """ if compute_m: min_eig, min_vec = self.sess.run([self.m_min_eig, self.m_min_vec], feed_dict=feed_dict) else: min_eig, min_vec = self.sess.run([self.h_min_eig, self.h_min_vec], feed_dict=feed_dict) return min_vec, min_eig
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: dictionary mapping from TF placeholders to values (optional) Returns: min_eig_vec: Corresponding eigen vector to min eig val eig_val: Minimum eigen value """ if compute_m: min_eig, min_vec = self.sess.run([self.m_min_eig, self.m_min_vec], feed_dict=feed_dict) else: min_eig, min_vec = self.sess.run([self.h_min_eig, self.h_min_vec], feed_dict=feed_dict) return min_vec, min_eig
[ "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", ".", "m_min_vec", "]", ",", "feed_dict", "=", "feed_dict", ")", "else", ":", "min_eig", ",", "min_vec", "=", "self", ".", "sess", ".", "run", "(", "[", "self", ".", "h_min_eig", ",", "self", ".", "h_min_vec", "]", ",", "feed_dict", "=", "feed_dict", ")", "return", "min_vec", ",", "min_eig" ]
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) Returns: min_eig_vec: Corresponding eigen vector to min eig val eig_val: Minimum eigen value
[ "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", ")", "Returns", ":", "min_eig_vec", ":", "Corresponding", "eigen", "vector", "to", "min", "eig", "val", "eig_val", ":", "Minimum", "eigen", "value" ]
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('Nu after modifying: ' + str(second_term)) feed_dict.update({self.nu: second_term}) computed_certificate = self.sess.run(self.unconstrained_objective, feed_dict=feed_dict) tf.logging.info('Inner step: %d, current value of certificate: %f', current_step, computed_certificate) # Sometimes due to either overflow or instability in inverses, # the returned certificate is large and negative -- keeping a check if LOWER_CERT_BOUND < computed_certificate < 0: _, min_eig_val_m = self.get_lanczos_eig(feed_dict=feed_dict) tf.logging.info('min eig val from lanczos: ' + str(min_eig_val_m)) input_vector_m = tf.placeholder(tf.float32, shape=(self.matrix_m_dimension, 1)) output_vector_m = self.get_psd_product(input_vector_m) def np_vector_prod_fn_m(np_vector): np_vector = np.reshape(np_vector, [-1, 1]) feed_dict.update({input_vector_m:np_vector}) output_np_vector = self.sess.run(output_vector_m, feed_dict=feed_dict) return output_np_vector linear_operator_m = LinearOperator((self.matrix_m_dimension, self.matrix_m_dimension), matvec=np_vector_prod_fn_m) # Performing shift invert scipy operation when eig val estimate is available min_eig_val_m_scipy, _ = eigs(linear_operator_m, k=1, which='SR', tol=TOL) tf.logging.info('min eig val m from scipy: ' + str(min_eig_val_m_scipy)) if min_eig_val_m - TOL > 0: tf.logging.info('Found certificate of robustness!') return True return False
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('Nu after modifying: ' + str(second_term)) feed_dict.update({self.nu: second_term}) computed_certificate = self.sess.run(self.unconstrained_objective, feed_dict=feed_dict) tf.logging.info('Inner step: %d, current value of certificate: %f', current_step, computed_certificate) # Sometimes due to either overflow or instability in inverses, # the returned certificate is large and negative -- keeping a check if LOWER_CERT_BOUND < computed_certificate < 0: _, min_eig_val_m = self.get_lanczos_eig(feed_dict=feed_dict) tf.logging.info('min eig val from lanczos: ' + str(min_eig_val_m)) input_vector_m = tf.placeholder(tf.float32, shape=(self.matrix_m_dimension, 1)) output_vector_m = self.get_psd_product(input_vector_m) def np_vector_prod_fn_m(np_vector): np_vector = np.reshape(np_vector, [-1, 1]) feed_dict.update({input_vector_m:np_vector}) output_np_vector = self.sess.run(output_vector_m, feed_dict=feed_dict) return output_np_vector linear_operator_m = LinearOperator((self.matrix_m_dimension, self.matrix_m_dimension), matvec=np_vector_prod_fn_m) # Performing shift invert scipy operation when eig val estimate is available min_eig_val_m_scipy, _ = eigs(linear_operator_m, k=1, which='SR', tol=TOL) tf.logging.info('min eig val m from scipy: ' + str(min_eig_val_m_scipy)) if min_eig_val_m - TOL > 0: tf.logging.info('Found certificate of robustness!') return True return False
[ "def", "compute_certificate", "(", "self", ",", "current_step", ",", "feed_dictionary", ")", ":", "feed_dict", "=", "feed_dictionary", ".", "copy", "(", ")", "nu", "=", "feed_dict", "[", "self", ".", "nu", "]", "second_term", "=", "self", ".", "make_m_psd", "(", "nu", ",", "feed_dict", ")", "tf", ".", "logging", ".", "info", "(", "'Nu after modifying: '", "+", "str", "(", "second_term", ")", ")", "feed_dict", ".", "update", "(", "{", "self", ".", "nu", ":", "second_term", "}", ")", "computed_certificate", "=", "self", ".", "sess", ".", "run", "(", "self", ".", "unconstrained_objective", ",", "feed_dict", "=", "feed_dict", ")", "tf", ".", "logging", ".", "info", "(", "'Inner step: %d, current value of certificate: %f'", ",", "current_step", ",", "computed_certificate", ")", "# Sometimes due to either overflow or instability in inverses,", "# the returned certificate is large and negative -- keeping a check", "if", "LOWER_CERT_BOUND", "<", "computed_certificate", "<", "0", ":", "_", ",", "min_eig_val_m", "=", "self", ".", "get_lanczos_eig", "(", "feed_dict", "=", "feed_dict", ")", "tf", ".", "logging", ".", "info", "(", "'min eig val from lanczos: '", "+", "str", "(", "min_eig_val_m", ")", ")", "input_vector_m", "=", "tf", ".", "placeholder", "(", "tf", ".", "float32", ",", "shape", "=", "(", "self", ".", "matrix_m_dimension", ",", "1", ")", ")", "output_vector_m", "=", "self", ".", "get_psd_product", "(", "input_vector_m", ")", "def", "np_vector_prod_fn_m", "(", "np_vector", ")", ":", "np_vector", "=", "np", ".", "reshape", "(", "np_vector", ",", "[", "-", "1", ",", "1", "]", ")", "feed_dict", ".", "update", "(", "{", "input_vector_m", ":", "np_vector", "}", ")", "output_np_vector", "=", "self", ".", "sess", ".", "run", "(", "output_vector_m", ",", "feed_dict", "=", "feed_dict", ")", "return", "output_np_vector", "linear_operator_m", "=", "LinearOperator", "(", "(", "self", ".", "matrix_m_dimension", ",", "self", ".", "matrix_m_dimension", ")", ",", "matvec", "=", "np_vector_prod_fn_m", ")", "# Performing shift invert scipy operation when eig val estimate is available", "min_eig_val_m_scipy", ",", "_", "=", "eigs", "(", "linear_operator_m", ",", "k", "=", "1", ",", "which", "=", "'SR'", ",", "tol", "=", "TOL", ")", "tf", ".", "logging", ".", "info", "(", "'min eig val m from scipy: '", "+", "str", "(", "min_eig_val_m_scipy", ")", ")", "if", "min_eig_val_m", "-", "TOL", ">", "0", ":", "tf", ".", "logging", ".", "info", "(", "'Found certificate of robustness!'", ")", "return", "True", "return", "False" ]
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 spm labels, _ = self.get_or_guess_labels(x, kwargs) return spm( x, self.model, y=labels, n_samples=self.n_samples, dx_min=self.dx_min, dx_max=self.dx_max, n_dxs=self.n_dxs, dy_min=self.dy_min, dy_max=self.dy_max, n_dys=self.n_dys, angle_min=self.angle_min, angle_max=self.angle_max, n_angles=self.n_angles, black_border_size=self.black_border_size)
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 spm labels, _ = self.get_or_guess_labels(x, kwargs) return spm( x, self.model, y=labels, n_samples=self.n_samples, dx_min=self.dx_min, dx_max=self.dx_max, n_dxs=self.n_dxs, dy_min=self.dy_min, dy_max=self.dy_max, n_dys=self.n_dys, angle_min=self.angle_min, angle_max=self.angle_max, n_angles=self.n_angles, black_border_size=self.black_border_size)
[ "def", "generate", "(", "self", ",", "x", ",", "*", "*", "kwargs", ")", ":", "# Parse and save attack-specific parameters", "assert", "self", ".", "parse_params", "(", "*", "*", "kwargs", ")", "from", "cleverhans", ".", "attacks_tf", "import", "spm", "labels", ",", "_", "=", "self", ".", "get_or_guess_labels", "(", "x", ",", "kwargs", ")", "return", "spm", "(", "x", ",", "self", ".", "model", ",", "y", "=", "labels", ",", "n_samples", "=", "self", ".", "n_samples", ",", "dx_min", "=", "self", ".", "dx_min", ",", "dx_max", "=", "self", ".", "dx_max", ",", "n_dxs", "=", "self", ".", "n_dxs", ",", "dy_min", "=", "self", ".", "dy_min", ",", "dy_max", "=", "self", ".", "dy_max", ",", "n_dys", "=", "self", ".", "n_dys", ",", "angle_min", "=", "self", ".", "angle_min", ",", "angle_max", "=", "self", ".", "angle_max", ",", "n_angles", "=", "self", ".", "n_angles", ",", "black_border_size", "=", "self", ".", "black_border_size", ")" ]
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, n_angles=6, black_border_size=0, **kwargs): """ 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 float) Minimum translation ratio along x-axis. :param dx_max: (optional float) Maximum translation ratio along x-axis. :param n_dxs: (optional int) Number of discretized translation ratios along x-axis. :param dy_min: (optional float) Minimum translation ratio along y-axis. :param dy_max: (optional float) Maximum translation ratio along y-axis. :param n_dys: (optional int) Number of discretized translation ratios along y-axis. :param angle_min: (optional float) Largest counter-clockwise rotation angle. :param angle_max: (optional float) Largest clockwise rotation angle. :param n_angles: (optional int) Number of discretized angles. :param black_border_size: (optional int) size of the black border in pixels. """ self.n_samples = n_samples self.dx_min = dx_min self.dx_max = dx_max self.n_dxs = n_dxs self.dy_min = dy_min self.dy_max = dy_max self.n_dys = n_dys self.angle_min = angle_min self.angle_max = angle_max self.n_angles = n_angles self.black_border_size = black_border_size if self.dx_min < -1 or self.dy_min < -1 or \ self.dx_max > 1 or self.dy_max > 1: raise ValueError("The value of translation must be bounded " "within [-1, 1]") if len(kwargs.keys()) > 0: warnings.warn("kwargs is unused and will be removed on or after " "2019-04-26.") return True
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, n_angles=6, black_border_size=0, **kwargs): """ 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 float) Minimum translation ratio along x-axis. :param dx_max: (optional float) Maximum translation ratio along x-axis. :param n_dxs: (optional int) Number of discretized translation ratios along x-axis. :param dy_min: (optional float) Minimum translation ratio along y-axis. :param dy_max: (optional float) Maximum translation ratio along y-axis. :param n_dys: (optional int) Number of discretized translation ratios along y-axis. :param angle_min: (optional float) Largest counter-clockwise rotation angle. :param angle_max: (optional float) Largest clockwise rotation angle. :param n_angles: (optional int) Number of discretized angles. :param black_border_size: (optional int) size of the black border in pixels. """ self.n_samples = n_samples self.dx_min = dx_min self.dx_max = dx_max self.n_dxs = n_dxs self.dy_min = dy_min self.dy_max = dy_max self.n_dys = n_dys self.angle_min = angle_min self.angle_max = angle_max self.n_angles = n_angles self.black_border_size = black_border_size if self.dx_min < -1 or self.dy_min < -1 or \ self.dx_max > 1 or self.dy_max > 1: raise ValueError("The value of translation must be bounded " "within [-1, 1]") if len(kwargs.keys()) > 0: warnings.warn("kwargs is unused and will be removed on or after " "2019-04-26.") return True
[ "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", ",", "n_angles", "=", "6", ",", "black_border_size", "=", "0", ",", "*", "*", "kwargs", ")", ":", "self", ".", "n_samples", "=", "n_samples", "self", ".", "dx_min", "=", "dx_min", "self", ".", "dx_max", "=", "dx_max", "self", ".", "n_dxs", "=", "n_dxs", "self", ".", "dy_min", "=", "dy_min", "self", ".", "dy_max", "=", "dy_max", "self", ".", "n_dys", "=", "n_dys", "self", ".", "angle_min", "=", "angle_min", "self", ".", "angle_max", "=", "angle_max", "self", ".", "n_angles", "=", "n_angles", "self", ".", "black_border_size", "=", "black_border_size", "if", "self", ".", "dx_min", "<", "-", "1", "or", "self", ".", "dy_min", "<", "-", "1", "or", "self", ".", "dx_max", ">", "1", "or", "self", ".", "dy_max", ">", "1", ":", "raise", "ValueError", "(", "\"The value of translation must be bounded \"", "\"within [-1, 1]\"", ")", "if", "len", "(", "kwargs", ".", "keys", "(", ")", ")", ">", "0", ":", "warnings", ".", "warn", "(", "\"kwargs is unused and will be removed on or after \"", "\"2019-04-26.\"", ")", "return", "True" ]
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 float) Minimum translation ratio along x-axis. :param dx_max: (optional float) Maximum translation ratio along x-axis. :param n_dxs: (optional int) Number of discretized translation ratios along x-axis. :param dy_min: (optional float) Minimum translation ratio along y-axis. :param dy_max: (optional float) Maximum translation ratio along y-axis. :param n_dys: (optional int) Number of discretized translation ratios along y-axis. :param angle_min: (optional float) Largest counter-clockwise rotation angle. :param angle_max: (optional float) Largest clockwise rotation angle. :param n_angles: (optional int) Number of discretized angles. :param black_border_size: (optional int) size of the black border in pixels.
[ "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", "float", ")", "Minimum", "translation", "ratio", "along", "x", "-", "axis", ".", ":", "param", "dx_max", ":", "(", "optional", "float", ")", "Maximum", "translation", "ratio", "along", "x", "-", "axis", ".", ":", "param", "n_dxs", ":", "(", "optional", "int", ")", "Number", "of", "discretized", "translation", "ratios", "along", "x", "-", "axis", ".", ":", "param", "dy_min", ":", "(", "optional", "float", ")", "Minimum", "translation", "ratio", "along", "y", "-", "axis", ".", ":", "param", "dy_max", ":", "(", "optional", "float", ")", "Maximum", "translation", "ratio", "along", "y", "-", "axis", ".", ":", "param", "n_dys", ":", "(", "optional", "int", ")", "Number", "of", "discretized", "translation", "ratios", "along", "y", "-", "axis", ".", ":", "param", "angle_min", ":", "(", "optional", "float", ")", "Largest", "counter", "-", "clockwise", "rotation", "angle", ".", ":", "param", "angle_max", ":", "(", "optional", "float", ")", "Largest", "clockwise", "rotation", "angle", ".", ":", "param", "n_angles", ":", "(", "optional", "int", ")", "Number", "of", "discretized", "angles", ".", ":", "param", "black_border_size", ":", "(", "optional", "int", ")", "size", "of", "the", "black", "border", "in", "pixels", "." ]
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 convolution) :param kernel_shape: (required tuple or list of 2 integers) specifies the kernel shape of the convolution :param strides: (required tuple or list of 2 integers) specifies the strides of the convolution along the width and height. :param padding: (required string) can be either 'valid' (no padding around input or feature map) or 'same' (pad to ensure that the output feature map size is identical to the layer input) :param input_shape: (optional) give input shape if this is the first layer of the model :return: the Keras layer """ if input_shape is not None: return Conv2D(filters=filters, kernel_size=kernel_shape, strides=strides, padding=padding, input_shape=input_shape) else: return Conv2D(filters=filters, kernel_size=kernel_shape, strides=strides, padding=padding)
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 convolution) :param kernel_shape: (required tuple or list of 2 integers) specifies the kernel shape of the convolution :param strides: (required tuple or list of 2 integers) specifies the strides of the convolution along the width and height. :param padding: (required string) can be either 'valid' (no padding around input or feature map) or 'same' (pad to ensure that the output feature map size is identical to the layer input) :param input_shape: (optional) give input shape if this is the first layer of the model :return: the Keras layer """ if input_shape is not None: return Conv2D(filters=filters, kernel_size=kernel_shape, strides=strides, padding=padding, input_shape=input_shape) else: return Conv2D(filters=filters, kernel_size=kernel_shape, strides=strides, padding=padding)
[ "def", "conv_2d", "(", "filters", ",", "kernel_shape", ",", "strides", ",", "padding", ",", "input_shape", "=", "None", ")", ":", "if", "input_shape", "is", "not", "None", ":", "return", "Conv2D", "(", "filters", "=", "filters", ",", "kernel_size", "=", "kernel_shape", ",", "strides", "=", "strides", ",", "padding", "=", "padding", ",", "input_shape", "=", "input_shape", ")", "else", ":", "return", "Conv2D", "(", "filters", "=", "filters", ",", "kernel_size", "=", "kernel_shape", ",", "strides", "=", "strides", ",", "padding", "=", "padding", ")" ]
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) specifies the kernel shape of the convolution :param strides: (required tuple or list of 2 integers) specifies the strides of the convolution along the width and height. :param padding: (required string) can be either 'valid' (no padding around input or feature map) or 'same' (pad to ensure that the output feature map size is identical to the layer input) :param input_shape: (optional) give input shape if this is the first layer of the model :return: the Keras layer
[ "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", ")", "specifies", "the", "kernel", "shape", "of", "the", "convolution", ":", "param", "strides", ":", "(", "required", "tuple", "or", "list", "of", "2", "integers", ")", "specifies", "the", "strides", "of", "the", "convolution", "along", "the", "width", "and", "height", ".", ":", "param", "padding", ":", "(", "required", "string", ")", "can", "be", "either", "valid", "(", "no", "padding", "around", "input", "or", "feature", "map", ")", "or", "same", "(", "pad", "to", "ensure", "that", "the", "output", "feature", "map", "size", "is", "identical", "to", "the", "layer", "input", ")", ":", "param", "input_shape", ":", "(", "optional", ")", "give", "input", "shape", "if", "this", "is", "the", "first", "layer", "of", "the", "model", ":", "return", ":", "the", "Keras", "layer" ]
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: The TensorFlow tensor for the input (needed if returning logits) ("ph" stands for placeholder but it need not actually be a placeholder) :param img_rows: number of row in the image :param img_cols: number of columns in the image :param channels: number of color channels (e.g., 1 for MNIST) :param nb_filters: number of convolutional filters per layer :param nb_classes: the number of output classes :return: """ model = Sequential() # Define the layers successively (convolution layers are version dependent) if tf.keras.backend.image_data_format() == 'channels_first': input_shape = (channels, img_rows, img_cols) else: assert tf.keras.backend.image_data_format() == 'channels_last' input_shape = (img_rows, img_cols, channels) layers = [conv_2d(nb_filters, (8, 8), (2, 2), "same", input_shape=input_shape), Activation('relu'), conv_2d((nb_filters * 2), (6, 6), (2, 2), "valid"), Activation('relu'), conv_2d((nb_filters * 2), (5, 5), (1, 1), "valid"), Activation('relu'), Flatten(), Dense(nb_classes)] for layer in layers: model.add(layer) if logits: logits_tensor = model(input_ph) model.add(Activation('softmax')) if logits: return model, logits_tensor else: return model
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: The TensorFlow tensor for the input (needed if returning logits) ("ph" stands for placeholder but it need not actually be a placeholder) :param img_rows: number of row in the image :param img_cols: number of columns in the image :param channels: number of color channels (e.g., 1 for MNIST) :param nb_filters: number of convolutional filters per layer :param nb_classes: the number of output classes :return: """ model = Sequential() # Define the layers successively (convolution layers are version dependent) if tf.keras.backend.image_data_format() == 'channels_first': input_shape = (channels, img_rows, img_cols) else: assert tf.keras.backend.image_data_format() == 'channels_last' input_shape = (img_rows, img_cols, channels) layers = [conv_2d(nb_filters, (8, 8), (2, 2), "same", input_shape=input_shape), Activation('relu'), conv_2d((nb_filters * 2), (6, 6), (2, 2), "valid"), Activation('relu'), conv_2d((nb_filters * 2), (5, 5), (1, 1), "valid"), Activation('relu'), Flatten(), Dense(nb_classes)] for layer in layers: model.add(layer) if logits: logits_tensor = model(input_ph) model.add(Activation('softmax')) if logits: return model, logits_tensor else: return model
[ "def", "cnn_model", "(", "logits", "=", "False", ",", "input_ph", "=", "None", ",", "img_rows", "=", "28", ",", "img_cols", "=", "28", ",", "channels", "=", "1", ",", "nb_filters", "=", "64", ",", "nb_classes", "=", "10", ")", ":", "model", "=", "Sequential", "(", ")", "# Define the layers successively (convolution layers are version dependent)", "if", "tf", ".", "keras", ".", "backend", ".", "image_data_format", "(", ")", "==", "'channels_first'", ":", "input_shape", "=", "(", "channels", ",", "img_rows", ",", "img_cols", ")", "else", ":", "assert", "tf", ".", "keras", ".", "backend", ".", "image_data_format", "(", ")", "==", "'channels_last'", "input_shape", "=", "(", "img_rows", ",", "img_cols", ",", "channels", ")", "layers", "=", "[", "conv_2d", "(", "nb_filters", ",", "(", "8", ",", "8", ")", ",", "(", "2", ",", "2", ")", ",", "\"same\"", ",", "input_shape", "=", "input_shape", ")", ",", "Activation", "(", "'relu'", ")", ",", "conv_2d", "(", "(", "nb_filters", "*", "2", ")", ",", "(", "6", ",", "6", ")", ",", "(", "2", ",", "2", ")", ",", "\"valid\"", ")", ",", "Activation", "(", "'relu'", ")", ",", "conv_2d", "(", "(", "nb_filters", "*", "2", ")", ",", "(", "5", ",", "5", ")", ",", "(", "1", ",", "1", ")", ",", "\"valid\"", ")", ",", "Activation", "(", "'relu'", ")", ",", "Flatten", "(", ")", ",", "Dense", "(", "nb_classes", ")", "]", "for", "layer", "in", "layers", ":", "model", ".", "add", "(", "layer", ")", "if", "logits", ":", "logits_tensor", "=", "model", "(", "input_ph", ")", "model", ".", "add", "(", "Activation", "(", "'softmax'", ")", ")", "if", "logits", ":", "return", "model", ",", "logits_tensor", "else", ":", "return", "model" ]
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 need not actually be a placeholder) :param img_rows: number of row in the image :param img_cols: number of columns in the image :param channels: number of color channels (e.g., 1 for MNIST) :param nb_filters: number of convolutional filters per layer :param nb_classes: the number of output classes :return:
[ "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", "need", "not", "actually", "be", "a", "placeholder", ")", ":", "param", "img_rows", ":", "number", "of", "row", "in", "the", "image", ":", "param", "img_cols", ":", "number", "of", "columns", "in", "the", "image", ":", "param", "channels", ":", "number", "of", "color", "channels", "(", "e", ".", "g", ".", "1", "for", "MNIST", ")", ":", "param", "nb_filters", ":", "number", "of", "convolutional", "filters", "per", "layer", ":", "param", "nb_classes", ":", "the", "number", "of", "output", "classes", ":", "return", ":" ]
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 found")
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 found")
[ "def", "_get_softmax_name", "(", "self", ")", ":", "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 found\"", ")" ]
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.append(layer.name) return abstract_layers
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.append(layer.name) return abstract_layers
[ "def", "_get_abstract_layer_name", "(", "self", ")", ":", "abstract_layers", "=", "[", "]", "for", "layer", "in", "self", ".", "model", ".", "layers", ":", "if", "'layers'", "in", "layer", ".", "get_config", "(", ")", ":", "abstract_layers", ".", "append", "(", "layer", ".", "name", ")", "return", "abstract_layers" ]
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, the activation is part of another layer return softmax_name if not hasattr(softmax_layer, '_inbound_nodes'): raise RuntimeError("Please update keras to version >= 2.1.3") node = softmax_layer._inbound_nodes[0] logits_name = node.inbound_layers[0].name return logits_name
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, the activation is part of another layer return softmax_name if not hasattr(softmax_layer, '_inbound_nodes'): raise RuntimeError("Please update keras to version >= 2.1.3") node = softmax_layer._inbound_nodes[0] logits_name = node.inbound_layers[0].name return logits_name
[ "def", "_get_logits_name", "(", "self", ")", ":", "softmax_name", "=", "self", ".", "_get_softmax_name", "(", ")", "softmax_layer", "=", "self", ".", "model", ".", "get_layer", "(", "softmax_name", ")", "if", "not", "isinstance", "(", "softmax_layer", ",", "Activation", ")", ":", "# In this case, the activation is part of another layer", "return", "softmax_name", "if", "not", "hasattr", "(", "softmax_layer", ",", "'_inbound_nodes'", ")", ":", "raise", "RuntimeError", "(", "\"Please update keras to version >= 2.1.3\"", ")", "node", "=", "softmax_layer", ".", "_inbound_nodes", "[", "0", "]", "logits_name", "=", "node", ".", "inbound_layers", "[", "0", "]", ".", "name", "return", "logits_name" ]
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 # logits layer if logits_name == self._get_softmax_name(): softmax_logit_layer = self.get_layer(x, logits_name) # The final op is the softmax. Return its input logits_layer = softmax_logit_layer._op.inputs[0] return logits_layer
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 # logits layer if logits_name == self._get_softmax_name(): softmax_logit_layer = self.get_layer(x, logits_name) # The final op is the softmax. Return its input logits_layer = softmax_logit_layer._op.inputs[0] return logits_layer
[ "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", "# logits layer", "if", "logits_name", "==", "self", ".", "_get_softmax_name", "(", ")", ":", "softmax_logit_layer", "=", "self", ".", "get_layer", "(", "x", ",", "logits_name", ")", "# The final op is the softmax. Return its input", "logits_layer", "=", "softmax_logit_layer", ".", "_op", ".", "inputs", "[", "0", "]", "return", "logits_layer" ]
: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 the input layer new_input = self.model.get_input_at(0) # Make a new model that returns each of the layers as output abstract_layers = self._get_abstract_layer_name() if abstract_layers: warnings.warn( "Abstract layer detected, picking last ouput node as default." "This could happen due to using of stacked model.") layer_outputs = [] # For those abstract model layers, return their last output node as # default. for x_layer in self.model.layers: if x_layer.name not in abstract_layers: layer_outputs.append(x_layer.output) else: layer_outputs.append(x_layer.get_output_at(-1)) self.keras_model = KerasModel(new_input, layer_outputs) # and get the outputs for that model on the input x outputs = self.keras_model(x) # Keras only returns a list for outputs of length >= 1, if the model # is only one layer, wrap a list if len(self.model.layers) == 1: outputs = [outputs] # compute the dict to return fprop_dict = dict(zip(self.get_layer_names(), outputs)) return fprop_dict
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 the input layer new_input = self.model.get_input_at(0) # Make a new model that returns each of the layers as output abstract_layers = self._get_abstract_layer_name() if abstract_layers: warnings.warn( "Abstract layer detected, picking last ouput node as default." "This could happen due to using of stacked model.") layer_outputs = [] # For those abstract model layers, return their last output node as # default. for x_layer in self.model.layers: if x_layer.name not in abstract_layers: layer_outputs.append(x_layer.output) else: layer_outputs.append(x_layer.get_output_at(-1)) self.keras_model = KerasModel(new_input, layer_outputs) # and get the outputs for that model on the input x outputs = self.keras_model(x) # Keras only returns a list for outputs of length >= 1, if the model # is only one layer, wrap a list if len(self.model.layers) == 1: outputs = [outputs] # compute the dict to return fprop_dict = dict(zip(self.get_layer_names(), outputs)) return fprop_dict
[ "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", "abstract_layers", "=", "self", ".", "_get_abstract_layer_name", "(", ")", "if", "abstract_layers", ":", "warnings", ".", "warn", "(", "\"Abstract layer detected, picking last ouput node as default.\"", "\"This could happen due to using of stacked model.\"", ")", "layer_outputs", "=", "[", "]", "# For those abstract model layers, return their last output node as", "# default.", "for", "x_layer", "in", "self", ".", "model", ".", "layers", ":", "if", "x_layer", ".", "name", "not", "in", "abstract_layers", ":", "layer_outputs", ".", "append", "(", "x_layer", ".", "output", ")", "else", ":", "layer_outputs", ".", "append", "(", "x_layer", ".", "get_output_at", "(", "-", "1", ")", ")", "self", ".", "keras_model", "=", "KerasModel", "(", "new_input", ",", "layer_outputs", ")", "# and get the outputs for that model on the input x", "outputs", "=", "self", ".", "keras_model", "(", "x", ")", "# Keras only returns a list for outputs of length >= 1, if the model", "# is only one layer, wrap a list", "if", "len", "(", "self", ".", "model", ".", "layers", ")", "==", "1", ":", "outputs", "=", "[", "outputs", "]", "# compute the dict to return", "fprop_dict", "=", "dict", "(", "zip", "(", "self", ".", "get_layer_names", "(", ")", ",", "outputs", ")", ")", "return", "fprop_dict" ]
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", "to", "the", "symbolic", "representation", "of", "their", "output", "." ]
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: NoSuchLayerError if `layer` is not in the model. """ # Return the symbolic representation for this layer. output = self.fprop(x) try: requested = output[layer] except KeyError: raise NoSuchLayerError() return requested
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: NoSuchLayerError if `layer` is not in the model. """ # Return the symbolic representation for this layer. output = self.fprop(x) try: requested = output[layer] except KeyError: raise NoSuchLayerError() return requested
[ "def", "get_layer", "(", "self", ",", "x", ",", "layer", ")", ":", "# Return the symbolic representation for this layer.", "output", "=", "self", ".", "fprop", "(", "x", ")", "try", ":", "requested", "=", "output", "[", "layer", "]", "except", "KeyError", ":", "raise", "NoSuchLayerError", "(", ")", "return", "requested" ]
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", "layer", "to", "return", "features", "at", ".", ":", "return", ":", "A", "symbolic", "representation", "of", "the", "hidden", "features", ":", "raise", ":", "NoSuchLayerError", "if", "layer", "is", "not", "in", "the", "model", "." ]
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}', '${B}'], A='src_file', B='dst_file') will call shell command: cp src_file dst_file """ command = list(command) for i in range(len(command)): m = CMD_VARIABLE_RE.match(command[i]) if m: var_id = m.group(1) if var_id in kwargs: command[i] = kwargs[var_id] return subprocess.call(command) == 0
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}', '${B}'], A='src_file', B='dst_file') will call shell command: cp src_file dst_file """ command = list(command) for i in range(len(command)): m = CMD_VARIABLE_RE.match(command[i]) if m: var_id = m.group(1) if var_id in kwargs: command[i] = kwargs[var_id] return subprocess.call(command) == 0
[ "def", "shell_call", "(", "command", ",", "*", "*", "kwargs", ")", ":", "command", "=", "list", "(", "command", ")", "for", "i", "in", "range", "(", "len", "(", "command", ")", ")", ":", "m", "=", "CMD_VARIABLE_RE", ".", "match", "(", "command", "[", "i", "]", ")", "if", "m", ":", "var_id", "=", "m", ".", "group", "(", "1", ")", "if", "var_id", "in", "kwargs", ":", "command", "[", "i", "]", "=", "kwargs", "[", "var_id", "]", "return", "subprocess", ".", "call", "(", "command", ")", "==", "0" ]
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') will call shell command: cp src_file dst_file
[ "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 restricted permissions. So to be able to read/modify these files outside of Docker you have to change permissions to be world readable and writable. """ retval = shell_call(['docker', 'run', '-v', '{0}:/output_dir'.format(dirname), 'busybox:1.27.2', 'chmod', '-R', 'a+rwx', '/output_dir']) if not retval: logging.error('Failed to change permissions on directory: %s', dirname) return retval
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 restricted permissions. So to be able to read/modify these files outside of Docker you have to change permissions to be world readable and writable. """ retval = shell_call(['docker', 'run', '-v', '{0}:/output_dir'.format(dirname), 'busybox:1.27.2', 'chmod', '-R', 'a+rwx', '/output_dir']) if not retval: logging.error('Failed to change permissions on directory: %s', dirname) return retval
[ "def", "make_directory_writable", "(", "dirname", ")", ":", "retval", "=", "shell_call", "(", "[", "'docker'", ",", "'run'", ",", "'-v'", ",", "'{0}:/output_dir'", ".", "format", "(", "dirname", ")", ",", "'busybox:1.27.2'", ",", "'chmod'", ",", "'-R'", ",", "'a+rwx'", ",", "'/output_dir'", "]", ")", "if", "not", "retval", ":", "logging", ".", "error", "(", "'Failed to change permissions on directory: %s'", ",", "dirname", ")", "return", "retval" ]
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/modify these files outside of Docker you have to change permissions to be world readable and writable.
[ "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 intentional because self._tmp_extracted_dir or it's subdir # will be renames into self._extracted_submission_dir os.mkdir(self._tmp_extracted_dir) os.mkdir(self._sample_input_dir) os.mkdir(self._sample_output_dir) # make output dir world writable shell_call(['chmod', 'a+rwX', '-R', self._sample_output_dir])
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 intentional because self._tmp_extracted_dir or it's subdir # will be renames into self._extracted_submission_dir os.mkdir(self._tmp_extracted_dir) os.mkdir(self._sample_input_dir) os.mkdir(self._sample_output_dir) # make output dir world writable shell_call(['chmod', 'a+rwX', '-R', self._sample_output_dir])
[ "def", "_prepare_temp_dir", "(", "self", ")", ":", "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 intentional because self._tmp_extracted_dir or it's subdir", "# will be renames into self._extracted_submission_dir", "os", ".", "mkdir", "(", "self", ".", "_tmp_extracted_dir", ")", "os", ".", "mkdir", "(", "self", ".", "_sample_input_dir", ")", "os", ".", "mkdir", "(", "self", ".", "_sample_output_dir", ")", "# make output dir world writable", "shell_call", "(", "[", "'chmod'", ",", "'a+rwX'", ",", "'-R'", ",", "self", ".", "_sample_output_dir", "]", ")" ]
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', file_size, MAX_SUBMISSION_SIZE_ZIPPED) return False # determime archive type exctract_command_tmpl = get_extract_command_template(filename) if not exctract_command_tmpl: logging.error('Input file has to be zip, tar or tar.gz archive; however ' 'found: %s', filename) return False # extract archive submission_dir = os.path.dirname(filename) submission_basename = os.path.basename(filename) logging.info('Extracting archive %s', filename) retval = shell_call( ['docker', 'run', '--network=none', '-v', '{0}:/input_dir'.format(submission_dir), '-v', '{0}:/output_dir'.format(self._tmp_extracted_dir), 'busybox:1.27.2'] + exctract_command_tmpl, src=os.path.join('/input_dir', submission_basename), dst='/output_dir') if not retval: logging.error('Failed to extract submission from file %s', filename) return False if not make_directory_writable(self._tmp_extracted_dir): return False # find submission root root_dir = self._tmp_extracted_dir root_dir_content = [d for d in os.listdir(root_dir) if d != '__MACOSX'] if (len(root_dir_content) == 1 and os.path.isdir(os.path.join(root_dir, root_dir_content[0]))): logging.info('Looks like submission root is in subdirectory "%s" of ' 'the archive', root_dir_content[0]) root_dir = os.path.join(root_dir, root_dir_content[0]) # Move files to self._extracted_submission_dir. # At this point self._extracted_submission_dir does not exist, # so following command will simply rename root_dir into # self._extracted_submission_dir if not shell_call(['mv', root_dir, self._extracted_submission_dir]): logging.error('Can''t move submission files from root directory') return False return True
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', file_size, MAX_SUBMISSION_SIZE_ZIPPED) return False # determime archive type exctract_command_tmpl = get_extract_command_template(filename) if not exctract_command_tmpl: logging.error('Input file has to be zip, tar or tar.gz archive; however ' 'found: %s', filename) return False # extract archive submission_dir = os.path.dirname(filename) submission_basename = os.path.basename(filename) logging.info('Extracting archive %s', filename) retval = shell_call( ['docker', 'run', '--network=none', '-v', '{0}:/input_dir'.format(submission_dir), '-v', '{0}:/output_dir'.format(self._tmp_extracted_dir), 'busybox:1.27.2'] + exctract_command_tmpl, src=os.path.join('/input_dir', submission_basename), dst='/output_dir') if not retval: logging.error('Failed to extract submission from file %s', filename) return False if not make_directory_writable(self._tmp_extracted_dir): return False # find submission root root_dir = self._tmp_extracted_dir root_dir_content = [d for d in os.listdir(root_dir) if d != '__MACOSX'] if (len(root_dir_content) == 1 and os.path.isdir(os.path.join(root_dir, root_dir_content[0]))): logging.info('Looks like submission root is in subdirectory "%s" of ' 'the archive', root_dir_content[0]) root_dir = os.path.join(root_dir, root_dir_content[0]) # Move files to self._extracted_submission_dir. # At this point self._extracted_submission_dir does not exist, # so following command will simply rename root_dir into # self._extracted_submission_dir if not shell_call(['mv', root_dir, self._extracted_submission_dir]): logging.error('Can''t move submission files from root directory') return False return True
[ "def", "_extract_submission", "(", "self", ",", "filename", ")", ":", "# 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'", ",", "file_size", ",", "MAX_SUBMISSION_SIZE_ZIPPED", ")", "return", "False", "# determime archive type", "exctract_command_tmpl", "=", "get_extract_command_template", "(", "filename", ")", "if", "not", "exctract_command_tmpl", ":", "logging", ".", "error", "(", "'Input file has to be zip, tar or tar.gz archive; however '", "'found: %s'", ",", "filename", ")", "return", "False", "# extract archive", "submission_dir", "=", "os", ".", "path", ".", "dirname", "(", "filename", ")", "submission_basename", "=", "os", ".", "path", ".", "basename", "(", "filename", ")", "logging", ".", "info", "(", "'Extracting archive %s'", ",", "filename", ")", "retval", "=", "shell_call", "(", "[", "'docker'", ",", "'run'", ",", "'--network=none'", ",", "'-v'", ",", "'{0}:/input_dir'", ".", "format", "(", "submission_dir", ")", ",", "'-v'", ",", "'{0}:/output_dir'", ".", "format", "(", "self", ".", "_tmp_extracted_dir", ")", ",", "'busybox:1.27.2'", "]", "+", "exctract_command_tmpl", ",", "src", "=", "os", ".", "path", ".", "join", "(", "'/input_dir'", ",", "submission_basename", ")", ",", "dst", "=", "'/output_dir'", ")", "if", "not", "retval", ":", "logging", ".", "error", "(", "'Failed to extract submission from file %s'", ",", "filename", ")", "return", "False", "if", "not", "make_directory_writable", "(", "self", ".", "_tmp_extracted_dir", ")", ":", "return", "False", "# find submission root", "root_dir", "=", "self", ".", "_tmp_extracted_dir", "root_dir_content", "=", "[", "d", "for", "d", "in", "os", ".", "listdir", "(", "root_dir", ")", "if", "d", "!=", "'__MACOSX'", "]", "if", "(", "len", "(", "root_dir_content", ")", "==", "1", "and", "os", ".", "path", ".", "isdir", "(", "os", ".", "path", ".", "join", "(", "root_dir", ",", "root_dir_content", "[", "0", "]", ")", ")", ")", ":", "logging", ".", "info", "(", "'Looks like submission root is in subdirectory \"%s\" of '", "'the archive'", ",", "root_dir_content", "[", "0", "]", ")", "root_dir", "=", "os", ".", "path", ".", "join", "(", "root_dir", ",", "root_dir_content", "[", "0", "]", ")", "# Move files to self._extracted_submission_dir.", "# At this point self._extracted_submission_dir does not exist,", "# so following command will simply rename root_dir into", "# self._extracted_submission_dir", "if", "not", "shell_call", "(", "[", "'mv'", ",", "root_dir", ",", "self", ".", "_extracted_submission_dir", "]", ")", ":", "logging", ".", "error", "(", "'Can'", "'t move submission files from root directory'", ")", "return", "False", "return", "True" ]
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_output( ['docker', 'inspect', '--format={{.Size}}', image_name]).strip() image_size = int(image_size) except (ValueError, subprocess.CalledProcessError) as e: logging.error('Failed to determine docker image size: %s', e) return False logging.info('Size of docker image %s is %d', image_name, image_size) if image_size > MAX_DOCKER_IMAGE_SIZE: logging.error('Image size exceeds limit %d', MAX_DOCKER_IMAGE_SIZE) return image_size <= MAX_DOCKER_IMAGE_SIZE
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_output( ['docker', 'inspect', '--format={{.Size}}', image_name]).strip() image_size = int(image_size) except (ValueError, subprocess.CalledProcessError) as e: logging.error('Failed to determine docker image size: %s', e) return False logging.info('Size of docker image %s is %d', image_name, image_size) if image_size > MAX_DOCKER_IMAGE_SIZE: logging.error('Image size exceeds limit %d', MAX_DOCKER_IMAGE_SIZE) return image_size <= MAX_DOCKER_IMAGE_SIZE
[ "def", "_verify_docker_image_size", "(", "self", ",", "image_name", ")", ":", "shell_call", "(", "[", "'docker'", ",", "'pull'", ",", "image_name", "]", ")", "try", ":", "image_size", "=", "subprocess", ".", "check_output", "(", "[", "'docker'", ",", "'inspect'", ",", "'--format={{.Size}}'", ",", "image_name", "]", ")", ".", "strip", "(", ")", "image_size", "=", "int", "(", "image_size", ")", "except", "(", "ValueError", ",", "subprocess", ".", "CalledProcessError", ")", "as", "e", ":", "logging", ".", "error", "(", "'Failed to determine docker image size: %s'", ",", "e", ")", "return", "False", "logging", ".", "info", "(", "'Size of docker image %s is %d'", ",", "image_name", ",", "image_size", ")", "if", "image_size", ">", "MAX_DOCKER_IMAGE_SIZE", ":", "logging", ".", "error", "(", "'Image size exceeds limit %d'", ",", "MAX_DOCKER_IMAGE_SIZE", ")", "return", "image_size", "<=", "MAX_DOCKER_IMAGE_SIZE" ]
Verifies size of Docker image. Args: image_name: name of the Docker image. Returns: True if image size is within the limits, False otherwise.
[ "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(BATCH_SIZE): Image.fromarray(images[i, :, :, :]).save( os.path.join(self._sample_input_dir, IMAGE_NAME_PATTERN.format(i))) # write target class for targeted attacks if submission_type == 'targeted_attack': target_classes = np.random.randint(1, 1001, size=[BATCH_SIZE]) target_class_filename = os.path.join(self._sample_input_dir, 'target_class.csv') with open(target_class_filename, 'w') as f: for i in range(BATCH_SIZE): f.write((IMAGE_NAME_PATTERN + ',{1}\n').format(i, target_classes[i]))
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(BATCH_SIZE): Image.fromarray(images[i, :, :, :]).save( os.path.join(self._sample_input_dir, IMAGE_NAME_PATTERN.format(i))) # write target class for targeted attacks if submission_type == 'targeted_attack': target_classes = np.random.randint(1, 1001, size=[BATCH_SIZE]) target_class_filename = os.path.join(self._sample_input_dir, 'target_class.csv') with open(target_class_filename, 'w') as f: for i in range(BATCH_SIZE): f.write((IMAGE_NAME_PATTERN + ',{1}\n').format(i, target_classes[i]))
[ "def", "_prepare_sample_data", "(", "self", ",", "submission_type", ")", ":", "# write images", "images", "=", "np", ".", "random", ".", "randint", "(", "0", ",", "256", ",", "size", "=", "[", "BATCH_SIZE", ",", "299", ",", "299", ",", "3", "]", ",", "dtype", "=", "np", ".", "uint8", ")", "for", "i", "in", "range", "(", "BATCH_SIZE", ")", ":", "Image", ".", "fromarray", "(", "images", "[", "i", ",", ":", ",", ":", ",", ":", "]", ")", ".", "save", "(", "os", ".", "path", ".", "join", "(", "self", ".", "_sample_input_dir", ",", "IMAGE_NAME_PATTERN", ".", "format", "(", "i", ")", ")", ")", "# write target class for targeted attacks", "if", "submission_type", "==", "'targeted_attack'", ":", "target_classes", "=", "np", ".", "random", ".", "randint", "(", "1", ",", "1001", ",", "size", "=", "[", "BATCH_SIZE", "]", ")", "target_class_filename", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_sample_input_dir", ",", "'target_class.csv'", ")", "with", "open", "(", "target_class_filename", ",", "'w'", ")", "as", "f", ":", "for", "i", "in", "range", "(", "BATCH_SIZE", ")", ":", "f", ".", "write", "(", "(", "IMAGE_NAME_PATTERN", "+", "',{1}\\n'", ")", ".", "format", "(", "i", ",", "target_classes", "[", "i", "]", ")", ")" ]
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_output( os.path.join(self._sample_output_dir, 'result.csv')) expected_keys = [IMAGE_NAME_PATTERN.format(i) for i in range(BATCH_SIZE)] if set(image_classification.keys()) != set(expected_keys): logging.error('Classification results are not saved for all images') result = False except IOError as e: logging.error('Failed to read defense output file: %s', e) result = False else: for i in range(BATCH_SIZE): image_filename = os.path.join(self._sample_output_dir, IMAGE_NAME_PATTERN.format(i)) try: img = np.array(Image.open(image_filename).convert('RGB')) if list(img.shape) != [299, 299, 3]: logging.error('Invalid image size %s for image %s', str(img.shape), image_filename) result = False except IOError as e: result = False return result
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_output( os.path.join(self._sample_output_dir, 'result.csv')) expected_keys = [IMAGE_NAME_PATTERN.format(i) for i in range(BATCH_SIZE)] if set(image_classification.keys()) != set(expected_keys): logging.error('Classification results are not saved for all images') result = False except IOError as e: logging.error('Failed to read defense output file: %s', e) result = False else: for i in range(BATCH_SIZE): image_filename = os.path.join(self._sample_output_dir, IMAGE_NAME_PATTERN.format(i)) try: img = np.array(Image.open(image_filename).convert('RGB')) if list(img.shape) != [299, 299, 3]: logging.error('Invalid image size %s for image %s', str(img.shape), image_filename) result = False except IOError as e: result = False return result
[ "def", "_verify_output", "(", "self", ",", "submission_type", ")", ":", "result", "=", "True", "if", "submission_type", "==", "'defense'", ":", "try", ":", "image_classification", "=", "load_defense_output", "(", "os", ".", "path", ".", "join", "(", "self", ".", "_sample_output_dir", ",", "'result.csv'", ")", ")", "expected_keys", "=", "[", "IMAGE_NAME_PATTERN", ".", "format", "(", "i", ")", "for", "i", "in", "range", "(", "BATCH_SIZE", ")", "]", "if", "set", "(", "image_classification", ".", "keys", "(", ")", ")", "!=", "set", "(", "expected_keys", ")", ":", "logging", ".", "error", "(", "'Classification results are not saved for all images'", ")", "result", "=", "False", "except", "IOError", "as", "e", ":", "logging", ".", "error", "(", "'Failed to read defense output file: %s'", ",", "e", ")", "result", "=", "False", "else", ":", "for", "i", "in", "range", "(", "BATCH_SIZE", ")", ":", "image_filename", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_sample_output_dir", ",", "IMAGE_NAME_PATTERN", ".", "format", "(", "i", ")", ")", "try", ":", "img", "=", "np", ".", "array", "(", "Image", ".", "open", "(", "image_filename", ")", ".", "convert", "(", "'RGB'", ")", ")", "if", "list", "(", "img", ".", "shape", ")", "!=", "[", "299", ",", "299", ",", "3", "]", ":", "logging", ".", "error", "(", "'Invalid image size %s for image %s'", ",", "str", "(", "img", ".", "shape", ")", ",", "image_filename", ")", "result", "=", "False", "except", "IOError", "as", "e", ":", "result", "=", "False", "return", "result" ]
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 mounting directory in Docker filename = os.path.abspath(filename) # extract submission if not self._extract_submission(filename): return None # verify submission size if not self._verify_submission_size(): return None # Load metadata metadata = self._load_and_verify_metadata() if not metadata: return None submission_type = metadata['type'] # verify docker container size if not self._verify_docker_image_size(metadata['container_gpu']): return None # Try to run submission on sample data self._prepare_sample_data(submission_type) if not self._run_submission(metadata): logging.error('Failure while running submission') return None if not self._verify_output(submission_type): logging.warning('Some of the outputs of your submission are invalid or ' 'missing. You submission still will be evaluation ' 'but you might get lower score.') return metadata
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 mounting directory in Docker filename = os.path.abspath(filename) # extract submission if not self._extract_submission(filename): return None # verify submission size if not self._verify_submission_size(): return None # Load metadata metadata = self._load_and_verify_metadata() if not metadata: return None submission_type = metadata['type'] # verify docker container size if not self._verify_docker_image_size(metadata['container_gpu']): return None # Try to run submission on sample data self._prepare_sample_data(submission_type) if not self._run_submission(metadata): logging.error('Failure while running submission') return None if not self._verify_output(submission_type): logging.warning('Some of the outputs of your submission are invalid or ' 'missing. You submission still will be evaluation ' 'but you might get lower score.') return metadata
[ "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", ".", "abspath", "(", "filename", ")", "# extract submission", "if", "not", "self", ".", "_extract_submission", "(", "filename", ")", ":", "return", "None", "# verify submission size", "if", "not", "self", ".", "_verify_submission_size", "(", ")", ":", "return", "None", "# Load metadata", "metadata", "=", "self", ".", "_load_and_verify_metadata", "(", ")", "if", "not", "metadata", ":", "return", "None", "submission_type", "=", "metadata", "[", "'type'", "]", "# verify docker container size", "if", "not", "self", ".", "_verify_docker_image_size", "(", "metadata", "[", "'container_gpu'", "]", ")", ":", "return", "None", "# Try to run submission on sample data", "self", ".", "_prepare_sample_data", "(", "submission_type", ")", "if", "not", "self", ".", "_run_submission", "(", "metadata", ")", ":", "logging", ".", "error", "(", "'Failure while running submission'", ")", "return", "None", "if", "not", "self", ".", "_verify_output", "(", "submission_type", ")", ":", "logging", ".", "warning", "(", "'Some of the outputs of your submission are invalid or '", "'missing. You submission still will be evaluation '", "'but you might get lower score.'", ")", "return", "metadata" ]
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", "(", "path", ",", "'loss.json'", ")", ",", "'wb'", ")", ")" ]
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.pow(A, 2), 1), [1, batchA]) sqr_norm_B = tf.reshape(tf.reduce_sum(tf.pow(B, 2), 1), [batchB, 1]) inner_prod = tf.matmul(B, A, transpose_b=True) tile_1 = tf.tile(sqr_norm_A, [batchB, 1]) tile_2 = tf.tile(sqr_norm_B, [1, batchA]) return (tile_1 + tile_2 - 2 * inner_prod)
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.pow(A, 2), 1), [1, batchA]) sqr_norm_B = tf.reshape(tf.reduce_sum(tf.pow(B, 2), 1), [batchB, 1]) inner_prod = tf.matmul(B, A, transpose_b=True) tile_1 = tf.tile(sqr_norm_A, [batchB, 1]) tile_2 = tf.tile(sqr_norm_B, [1, batchA]) return (tile_1 + tile_2 - 2 * inner_prod)
[ "def", "pairwise_euclid_distance", "(", "A", ",", "B", ")", ":", "batchA", "=", "tf", ".", "shape", "(", "A", ")", "[", "0", "]", "batchB", "=", "tf", ".", "shape", "(", "B", ")", "[", "0", "]", "sqr_norm_A", "=", "tf", ".", "reshape", "(", "tf", ".", "reduce_sum", "(", "tf", ".", "pow", "(", "A", ",", "2", ")", ",", "1", ")", ",", "[", "1", ",", "batchA", "]", ")", "sqr_norm_B", "=", "tf", ".", "reshape", "(", "tf", ".", "reduce_sum", "(", "tf", ".", "pow", "(", "B", ",", "2", ")", ",", "1", ")", ",", "[", "batchB", ",", "1", "]", ")", "inner_prod", "=", "tf", ".", "matmul", "(", "B", ",", "A", ",", "transpose_b", "=", "True", ")", "tile_1", "=", "tf", ".", "tile", "(", "sqr_norm_A", ",", "[", "batchB", ",", "1", "]", ")", "tile_2", "=", "tf", ".", "tile", "(", "sqr_norm_B", ",", "[", "1", ",", "batchA", "]", ")", "return", "(", "tile_1", "+", "tile_2", "-", "2", "*", "inner_prod", ")" ]
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.matmul(normalized_A, normalized_B, adjoint_b=True) return 1 - prod
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.matmul(normalized_A, normalized_B, adjoint_b=True) return 1 - prod
[ "def", "pairwise_cos_distance", "(", "A", ",", "B", ")", ":", "normalized_A", "=", "tf", ".", "nn", ".", "l2_normalize", "(", "A", ",", "dim", "=", "1", ")", "normalized_B", "=", "tf", ".", "nn", ".", "l2_normalize", "(", "B", ",", "dim", "=", "1", ")", "prod", "=", "tf", ".", "matmul", "(", "normalized_A", ",", "normalized_B", ",", "adjoint_b", "=", "True", ")", "return", "1", "-", "prod" ]
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 pairwise distance between each element and A and all those of B. """ if cos_distance: distance_matrix = SNNLCrossEntropy.pairwise_cos_distance(A, B) else: distance_matrix = SNNLCrossEntropy.pairwise_euclid_distance(A, B) return tf.exp(-(distance_matrix / temp))
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 pairwise distance between each element and A and all those of B. """ if cos_distance: distance_matrix = SNNLCrossEntropy.pairwise_cos_distance(A, B) else: distance_matrix = SNNLCrossEntropy.pairwise_euclid_distance(A, B) return tf.exp(-(distance_matrix / temp))
[ "def", "fits", "(", "A", ",", "B", ",", "temp", ",", "cos_distance", ")", ":", "if", "cos_distance", ":", "distance_matrix", "=", "SNNLCrossEntropy", ".", "pairwise_cos_distance", "(", "A", ",", "B", ")", "else", ":", "distance_matrix", "=", "SNNLCrossEntropy", ".", "pairwise_euclid_distance", "(", "A", ",", "B", ")", "return", "tf", ".", "exp", "(", "-", "(", "distance_matrix", "/", "temp", ")", ")" ]
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 and all those of B.
[ "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", "." ]
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: Temperature :cos_distance: Boolean for using cosine or euclidean distance :returns: A tensor for the row normalized exponentiated pairwise distance between all the elements of x. """ f = SNNLCrossEntropy.fits( x, x, temp, cos_distance) - tf.eye(tf.shape(x)[0]) return f / ( SNNLCrossEntropy.STABILITY_EPS + tf.expand_dims(tf.reduce_sum(f, 1), 1))
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: Temperature :cos_distance: Boolean for using cosine or euclidean distance :returns: A tensor for the row normalized exponentiated pairwise distance between all the elements of x. """ f = SNNLCrossEntropy.fits( x, x, temp, cos_distance) - tf.eye(tf.shape(x)[0]) return f / ( SNNLCrossEntropy.STABILITY_EPS + tf.expand_dims(tf.reduce_sum(f, 1), 1))
[ "def", "pick_probability", "(", "x", ",", "temp", ",", "cos_distance", ")", ":", "f", "=", "SNNLCrossEntropy", ".", "fits", "(", "x", ",", "x", ",", "temp", ",", "cos_distance", ")", "-", "tf", ".", "eye", "(", "tf", ".", "shape", "(", "x", ")", "[", "0", "]", ")", "return", "f", "/", "(", "SNNLCrossEntropy", ".", "STABILITY_EPS", "+", "tf", ".", "expand_dims", "(", "tf", ".", "reduce_sum", "(", "f", ",", "1", ")", ",", "1", ")", ")" ]
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 euclidean distance :returns: A tensor for the row normalized exponentiated pairwise distance between all the elements of 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", "euclidean", "distance" ]
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 Euclidean distance :returns: A tensor for the pairwise sampling probabilities. """ return SNNLCrossEntropy.pick_probability(x, temp, cos_distance) * \ SNNLCrossEntropy.same_label_mask(y, y)
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 Euclidean distance :returns: A tensor for the pairwise sampling probabilities. """ return SNNLCrossEntropy.pick_probability(x, temp, cos_distance) * \ SNNLCrossEntropy.same_label_mask(y, y)
[ "def", "masked_pick_probability", "(", "x", ",", "y", ",", "temp", ",", "cos_distance", ")", ":", "return", "SNNLCrossEntropy", ".", "pick_probability", "(", "x", ",", "temp", ",", "cos_distance", ")", "*", "SNNLCrossEntropy", ".", "same_label_mask", "(", "y", ",", "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 sampling probabilities.
[ "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" ]
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 in x with labels y. """ summed_masked_pick_prob = tf.reduce_sum( SNNLCrossEntropy.masked_pick_probability(x, y, temp, cos_distance), 1) return tf.reduce_mean( -tf.log(SNNLCrossEntropy.STABILITY_EPS + summed_masked_pick_prob))
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 in x with labels y. """ summed_masked_pick_prob = tf.reduce_sum( SNNLCrossEntropy.masked_pick_probability(x, y, temp, cos_distance), 1) return tf.reduce_mean( -tf.log(SNNLCrossEntropy.STABILITY_EPS + summed_masked_pick_prob))
[ "def", "SNNL", "(", "x", ",", "y", ",", "temp", ",", "cos_distance", ")", ":", "summed_masked_pick_prob", "=", "tf", ".", "reduce_sum", "(", "SNNLCrossEntropy", ".", "masked_pick_probability", "(", "x", ",", "y", ",", "temp", ",", "cos_distance", ")", ",", "1", ")", "return", "tf", ".", "reduce_mean", "(", "-", "tf", ".", "log", "(", "SNNLCrossEntropy", ".", "STABILITY_EPS", "+", "summed_masked_pick_prob", ")", ")" ]
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", ":", "Boolean", "for", "using", "cosine", "or", "Euclidean", "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. :param y: a list of labels for each element of x. :param initial_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, optimized for temperature. """ t = tf.Variable(1, dtype=tf.float32, trainable=False, name="temp") def inverse_temp(t): # pylint: disable=missing-docstring # we use inverse_temp because it was observed to be more stable when optimizing. return tf.div(initial_temp, t) ent_loss = SNNLCrossEntropy.SNNL(x, y, inverse_temp(t), cos_distance) updated_t = tf.assign(t, tf.subtract(t, 0.1*tf.gradients(ent_loss, t)[0])) inverse_t = inverse_temp(updated_t) return SNNLCrossEntropy.SNNL(x, y, inverse_t, cos_distance)
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. :param y: a list of labels for each element of x. :param initial_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, optimized for temperature. """ t = tf.Variable(1, dtype=tf.float32, trainable=False, name="temp") def inverse_temp(t): # pylint: disable=missing-docstring # we use inverse_temp because it was observed to be more stable when optimizing. return tf.div(initial_temp, t) ent_loss = SNNLCrossEntropy.SNNL(x, y, inverse_temp(t), cos_distance) updated_t = tf.assign(t, tf.subtract(t, 0.1*tf.gradients(ent_loss, t)[0])) inverse_t = inverse_temp(updated_t) return SNNLCrossEntropy.SNNL(x, y, inverse_t, cos_distance)
[ "def", "optimized_temp_SNNL", "(", "x", ",", "y", ",", "initial_temp", ",", "cos_distance", ")", ":", "t", "=", "tf", ".", "Variable", "(", "1", ",", "dtype", "=", "tf", ".", "float32", ",", "trainable", "=", "False", ",", "name", "=", "\"temp\"", ")", "def", "inverse_temp", "(", "t", ")", ":", "# pylint: disable=missing-docstring", "# we use inverse_temp because it was observed to be more stable when optimizing.", "return", "tf", ".", "div", "(", "initial_temp", ",", "t", ")", "ent_loss", "=", "SNNLCrossEntropy", ".", "SNNL", "(", "x", ",", "y", ",", "inverse_temp", "(", "t", ")", ",", "cos_distance", ")", "updated_t", "=", "tf", ".", "assign", "(", "t", ",", "tf", ".", "subtract", "(", "t", ",", "0.1", "*", "tf", ".", "gradients", "(", "ent_loss", ",", "t", ")", "[", "0", "]", ")", ")", "inverse_t", "=", "inverse_temp", "(", "updated_t", ")", "return", "SNNLCrossEntropy", ".", "SNNL", "(", "x", ",", "y", ",", "inverse_t", ",", "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. :param y: a list of labels for each element of x. :param initial_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, optimized for temperature.
[ "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_temp", ":", "Temperature", ".", ":", "cos_distance", ":", "Boolean", "for", "using", "cosine", "or", "Euclidean", "distance", "." ]
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 image is in any of the common ranges: [0, 1], [-1, 1], [0, 255] This can be ambiguous, so it is better to specify if known. """ # Create a temporary file with the suffix '.png'. fd, path = mkstemp(suffix='.png') os.close(fd) save(path, ndarray, min_val, max_val) shell_call(VIEWER_COMMAND + [path])
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 image is in any of the common ranges: [0, 1], [-1, 1], [0, 255] This can be ambiguous, so it is better to specify if known. """ # Create a temporary file with the suffix '.png'. fd, path = mkstemp(suffix='.png') os.close(fd) save(path, ndarray, min_val, max_val) shell_call(VIEWER_COMMAND + [path])
[ "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", ")", "save", "(", "path", ",", "ndarray", ",", "min_val", ",", "max_val", ")", "shell_call", "(", "VIEWER_COMMAND", "+", "[", "path", "]", ")" ]
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, 1], [0, 255] This can be ambiguous, so it is better to specify if known.
[ "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", "1", "]", "[", "0", "255", "]", "This", "can", "be", "ambiguous", "so", "it", "is", "better", "to", "specify", "if", "known", "." ]
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 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, 1], [0, 255] This can be ambiguous, so it is better to specify if known. """ as_pil(ndarray, min_val, max_val).save(path)
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 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, 1], [0, 255] This can be ambiguous, so it is better to specify if known. """ as_pil(ndarray, min_val, max_val).save(path)
[ "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 infer whether the image is in any of the common ranges: [0, 1], [-1, 1], [0, 255] This can be ambiguous, so it is better to specify if known.
[ "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", "infer", "whether", "the", "image", "is", "in", "any", "of", "the", "common", "ranges", ":", "[", "0", "1", "]", "[", "-", "1", "1", "]", "[", "0", "255", "]", "This", "can", "be", "ambiguous", "so", "it", "is", "better", "to", "specify", "if", "known", "." ]
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 to infer whether the image is in any of the common ranges: [0, 1], [-1, 1], [0, 255] This can be ambiguous, so it is better to specify if known. """ assert isinstance(ndarray, np.ndarray) # rows x cols for grayscale image # rows x cols x channels for color assert ndarray.ndim in [2, 3] if ndarray.ndim == 3: channels = ndarray.shape[2] # grayscale or RGB assert channels in [1, 3] actual_min = ndarray.min() actual_max = ndarray.max() if min_val is not None: assert actual_min >= min_val assert actual_max <= max_val if np.issubdtype(ndarray.dtype, np.floating): if min_val is None: if actual_min < -1.: raise ValueError("Unrecognized range") if actual_min < 0: min_val = -1. else: min_val = 0. if max_val is None: if actual_max > 255.: raise ValueError("Unrecognized range") if actual_max > 1.: max_val = 255. else: max_val = 1. ndarray = (ndarray - min_val) value_range = max_val - min_val ndarray *= (255. / value_range) ndarray = np.cast['uint8'](ndarray) elif 'int' in str(ndarray.dtype): if min_val is not None: assert min_val == 0 else: assert actual_min >= 0. if max_val is not None: assert max_val == 255 else: assert actual_max <= 255. else: raise ValueError("Unrecognized dtype") out = Image.fromarray(ndarray) return out
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 to infer whether the image is in any of the common ranges: [0, 1], [-1, 1], [0, 255] This can be ambiguous, so it is better to specify if known. """ assert isinstance(ndarray, np.ndarray) # rows x cols for grayscale image # rows x cols x channels for color assert ndarray.ndim in [2, 3] if ndarray.ndim == 3: channels = ndarray.shape[2] # grayscale or RGB assert channels in [1, 3] actual_min = ndarray.min() actual_max = ndarray.max() if min_val is not None: assert actual_min >= min_val assert actual_max <= max_val if np.issubdtype(ndarray.dtype, np.floating): if min_val is None: if actual_min < -1.: raise ValueError("Unrecognized range") if actual_min < 0: min_val = -1. else: min_val = 0. if max_val is None: if actual_max > 255.: raise ValueError("Unrecognized range") if actual_max > 1.: max_val = 255. else: max_val = 1. ndarray = (ndarray - min_val) value_range = max_val - min_val ndarray *= (255. / value_range) ndarray = np.cast['uint8'](ndarray) elif 'int' in str(ndarray.dtype): if min_val is not None: assert min_val == 0 else: assert actual_min >= 0. if max_val is not None: assert max_val == 255 else: assert actual_max <= 255. else: raise ValueError("Unrecognized dtype") out = Image.fromarray(ndarray) return out
[ "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", "ndarray", ".", "ndim", "in", "[", "2", ",", "3", "]", "if", "ndarray", ".", "ndim", "==", "3", ":", "channels", "=", "ndarray", ".", "shape", "[", "2", "]", "# grayscale or RGB", "assert", "channels", "in", "[", "1", ",", "3", "]", "actual_min", "=", "ndarray", ".", "min", "(", ")", "actual_max", "=", "ndarray", ".", "max", "(", ")", "if", "min_val", "is", "not", "None", ":", "assert", "actual_min", ">=", "min_val", "assert", "actual_max", "<=", "max_val", "if", "np", ".", "issubdtype", "(", "ndarray", ".", "dtype", ",", "np", ".", "floating", ")", ":", "if", "min_val", "is", "None", ":", "if", "actual_min", "<", "-", "1.", ":", "raise", "ValueError", "(", "\"Unrecognized range\"", ")", "if", "actual_min", "<", "0", ":", "min_val", "=", "-", "1.", "else", ":", "min_val", "=", "0.", "if", "max_val", "is", "None", ":", "if", "actual_max", ">", "255.", ":", "raise", "ValueError", "(", "\"Unrecognized range\"", ")", "if", "actual_max", ">", "1.", ":", "max_val", "=", "255.", "else", ":", "max_val", "=", "1.", "ndarray", "=", "(", "ndarray", "-", "min_val", ")", "value_range", "=", "max_val", "-", "min_val", "ndarray", "*=", "(", "255.", "/", "value_range", ")", "ndarray", "=", "np", ".", "cast", "[", "'uint8'", "]", "(", "ndarray", ")", "elif", "'int'", "in", "str", "(", "ndarray", ".", "dtype", ")", ":", "if", "min_val", "is", "not", "None", ":", "assert", "min_val", "==", "0", "else", ":", "assert", "actual_min", ">=", "0.", "if", "max_val", "is", "not", "None", ":", "assert", "max_val", "==", "255", "else", ":", "assert", "actual_max", "<=", "255.", "else", ":", "raise", "ValueError", "(", "\"Unrecognized dtype\"", ")", "out", "=", "Image", ".", "fromarray", "(", "ndarray", ")", "return", "out" ]
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 ranges: [0, 1], [-1, 1], [0, 255] This can be ambiguous, so it is better to specify if known.
[ "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", "ranges", ":", "[", "0", "1", "]", "[", "-", "1", "1", "]", "[", "0", "255", "]", "This", "can", "be", "ambiguous", "so", "it", "is", "better", "to", "specify", "if", "known", "." ]
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 + pad * 2, ch)) padded[:, pad:-pad, pad:-pad, :] = image_batch m, ir, ic, ch = padded.shape pr = int(np.sqrt(m)) pc = int(np.ceil(float(m) / pr)) extra_m = pr * pc assert extra_m > m padded = np.concatenate((padded, np.zeros((extra_m - m, ir, ic, ch))), axis=0) row_content = np.split(padded, pr) row_content = [np.split(content, pc) for content in row_content] rows = [np.concatenate(content, axis=2) for content in row_content] grid = np.concatenate(rows, axis=1) assert grid.shape[0] == 1, grid.shape grid = grid[0] return grid
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 + pad * 2, ch)) padded[:, pad:-pad, pad:-pad, :] = image_batch m, ir, ic, ch = padded.shape pr = int(np.sqrt(m)) pc = int(np.ceil(float(m) / pr)) extra_m = pr * pc assert extra_m > m padded = np.concatenate((padded, np.zeros((extra_m - m, ir, ic, ch))), axis=0) row_content = np.split(padded, pr) row_content = [np.split(content, pc) for content in row_content] rows = [np.concatenate(content, axis=2) for content in row_content] grid = np.concatenate(rows, axis=1) assert grid.shape[0] == 1, grid.shape grid = grid[0] return grid
[ "def", "make_grid", "(", "image_batch", ")", ":", "m", ",", "ir", ",", "ic", ",", "ch", "=", "image_batch", ".", "shape", "pad", "=", "3", "padded", "=", "np", ".", "zeros", "(", "(", "m", ",", "ir", "+", "pad", "*", "2", ",", "ic", "+", "pad", "*", "2", ",", "ch", ")", ")", "padded", "[", ":", ",", "pad", ":", "-", "pad", ",", "pad", ":", "-", "pad", ",", ":", "]", "=", "image_batch", "m", ",", "ir", ",", "ic", ",", "ch", "=", "padded", ".", "shape", "pr", "=", "int", "(", "np", ".", "sqrt", "(", "m", ")", ")", "pc", "=", "int", "(", "np", ".", "ceil", "(", "float", "(", "m", ")", "/", "pr", ")", ")", "extra_m", "=", "pr", "*", "pc", "assert", "extra_m", ">", "m", "padded", "=", "np", ".", "concatenate", "(", "(", "padded", ",", "np", ".", "zeros", "(", "(", "extra_m", "-", "m", ",", "ir", ",", "ic", ",", "ch", ")", ")", ")", ",", "axis", "=", "0", ")", "row_content", "=", "np", ".", "split", "(", "padded", ",", "pr", ")", "row_content", "=", "[", "np", ".", "split", "(", "content", ",", "pc", ")", "for", "content", "in", "row_content", "]", "rows", "=", "[", "np", ".", "concatenate", "(", "content", ",", "axis", "=", "2", ")", "for", "content", "in", "row_content", "]", "grid", "=", "np", ".", "concatenate", "(", "rows", ",", "axis", "=", "1", ")", "assert", "grid", ".", "shape", "[", "0", "]", "==", "1", ",", "grid", ".", "shape", "grid", "=", "grid", "[", "0", "]", "return", "grid" ]
Turns a batch of images into one big image. :param image_batch: ndarray, shape (batch_size, rows, cols, channels) :returns : a big image containing all `batch_size` images in a grid
[ "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" ]
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.contrib.eager x = tfe.Variable(x_val) adv_x = self.generate(x, **kwargs) return adv_x.numpy()
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.contrib.eager x = tfe.Variable(x_val) adv_x = self.generate(x, **kwargs) return adv_x.numpy()
[ "def", "generate_np", "(", "self", ",", "x_val", ",", "*", "*", "kwargs", ")", ":", "tfe", "=", "tf", ".", "contrib", ".", "eager", "x", "=", "tfe", ".", "Variable", "(", "x_val", ")", "adv_x", "=", "self", ".", "generate", "(", "x", ",", "*", "*", "kwargs", ")", "return", "adv_x", ".", "numpy", "(", ")" ]
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. :param y: (optional) A tf variable` with the model labels. Only provide this parameter if you'd like to use true labels when crafting adversarial samples. Otherwise, model predictions are used as labels to avoid the "label leaking" effect (explained in this paper: https://arxiv.org/abs/1611.01236). Default is None. Labels should be one-hot-encoded. :param y_target: (optional) A tf variable` with the labels to target. Leave y_target=None if y is also set. Labels should be one-hot-encoded. :param clip_min: (optional float) Minimum input component value :param clip_max: (optional float) Maximum input component value """ # Parse and save attack-specific parameters assert self.parse_params(**kwargs) labels, _nb_classes = self.get_or_guess_labels(x, kwargs) return self.fgm(x, labels=labels, targeted=(self.y_target is not None))
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. :param y: (optional) A tf variable` with the model labels. Only provide this parameter if you'd like to use true labels when crafting adversarial samples. Otherwise, model predictions are used as labels to avoid the "label leaking" effect (explained in this paper: https://arxiv.org/abs/1611.01236). Default is None. Labels should be one-hot-encoded. :param y_target: (optional) A tf variable` with the labels to target. Leave y_target=None if y is also set. Labels should be one-hot-encoded. :param clip_min: (optional float) Minimum input component value :param clip_max: (optional float) Maximum input component value """ # Parse and save attack-specific parameters assert self.parse_params(**kwargs) labels, _nb_classes = self.get_or_guess_labels(x, kwargs) return self.fgm(x, labels=labels, targeted=(self.y_target is not None))
[ "def", "generate", "(", "self", ",", "x", ",", "*", "*", "kwargs", ")", ":", "# Parse and save attack-specific parameters", "assert", "self", ".", "parse_params", "(", "*", "*", "kwargs", ")", "labels", ",", "_nb_classes", "=", "self", ".", "get_or_guess_labels", "(", "x", ",", "kwargs", ")", "return", "self", ".", "fgm", "(", "x", ",", "labels", "=", "labels", ",", "targeted", "=", "(", "self", ".", "y_target", "is", "not", "None", ")", ")" ]
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 labels. Only provide this parameter if you'd like to use true labels when crafting adversarial samples. Otherwise, model predictions are used as labels to avoid the "label leaking" effect (explained in this paper: https://arxiv.org/abs/1611.01236). Default is None. Labels should be one-hot-encoded. :param y_target: (optional) A tf variable` with the labels to target. Leave y_target=None if y is also set. Labels should be one-hot-encoded. :param clip_min: (optional float) Minimum input component value :param clip_max: (optional float) Maximum input component value
[ "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", "labels", ".", "Only", "provide", "this", "parameter", "if", "you", "d", "like", "to", "use", "true", "labels", "when", "crafting", "adversarial", "samples", ".", "Otherwise", "model", "predictions", "are", "used", "as", "labels", "to", "avoid", "the", "label", "leaking", "effect", "(", "explained", "in", "this", "paper", ":", "https", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1611", ".", "01236", ")", ".", "Default", "is", "None", ".", "Labels", "should", "be", "one", "-", "hot", "-", "encoded", ".", ":", "param", "y_target", ":", "(", "optional", ")", "A", "tf", "variable", "with", "the", "labels", "to", "target", ".", "Leave", "y_target", "=", "None", "if", "y", "is", "also", "set", ".", "Labels", "should", "be", "one", "-", "hot", "-", "encoded", ".", ":", "param", "clip_min", ":", "(", "optional", "float", ")", "Minimum", "input", "component", "value", ":", "param", "clip_max", ":", "(", "optional", "float", ")", "Maximum", "input", "component", "value" ]
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 will instead try to move in the direction of being more like y. :return: a tensor for the adversarial example """ # Compute loss with tf.GradientTape() as tape: # input should be watched because it may be # combination of trainable and non-trainable variables tape.watch(x) loss_obj = LossCrossEntropy(self.model, smoothing=0.) loss = loss_obj.fprop(x=x, y=labels) if targeted: loss = -loss # Define gradient of loss wrt input grad = tape.gradient(loss, x) optimal_perturbation = attacks.optimize_linear(grad, self.eps, self.ord) # Add perturbation to original example to obtain adversarial example adv_x = x + optimal_perturbation # If clipping is needed # reset all values outside of [clip_min, clip_max] if (self.clip_min is not None) and (self.clip_max is not None): adv_x = tf.clip_by_value(adv_x, self.clip_min, self.clip_max) return adv_x
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 will instead try to move in the direction of being more like y. :return: a tensor for the adversarial example """ # Compute loss with tf.GradientTape() as tape: # input should be watched because it may be # combination of trainable and non-trainable variables tape.watch(x) loss_obj = LossCrossEntropy(self.model, smoothing=0.) loss = loss_obj.fprop(x=x, y=labels) if targeted: loss = -loss # Define gradient of loss wrt input grad = tape.gradient(loss, x) optimal_perturbation = attacks.optimize_linear(grad, self.eps, self.ord) # Add perturbation to original example to obtain adversarial example adv_x = x + optimal_perturbation # If clipping is needed # reset all values outside of [clip_min, clip_max] if (self.clip_min is not None) and (self.clip_max is not None): adv_x = tf.clip_by_value(adv_x, self.clip_min, self.clip_max) return adv_x
[ "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-trainable variables", "tape", ".", "watch", "(", "x", ")", "loss_obj", "=", "LossCrossEntropy", "(", "self", ".", "model", ",", "smoothing", "=", "0.", ")", "loss", "=", "loss_obj", ".", "fprop", "(", "x", "=", "x", ",", "y", "=", "labels", ")", "if", "targeted", ":", "loss", "=", "-", "loss", "# Define gradient of loss wrt input", "grad", "=", "tape", ".", "gradient", "(", "loss", ",", "x", ")", "optimal_perturbation", "=", "attacks", ".", "optimize_linear", "(", "grad", ",", "self", ".", "eps", ",", "self", ".", "ord", ")", "# Add perturbation to original example to obtain adversarial example", "adv_x", "=", "x", "+", "optimal_perturbation", "# If clipping is needed", "# reset all values outside of [clip_min, clip_max]", "if", "(", "self", ".", "clip_min", "is", "not", "None", ")", "and", "(", "self", ".", "clip_max", "is", "not", "None", ")", ":", "adv_x", "=", "tf", ".", "clip_by_value", "(", "adv_x", ",", "self", ".", "clip_min", ",", "self", ".", "clip_max", ")", "return", "adv_x" ]
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 of being more like y. :return: a tensor for the adversarial example
[ "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", "of", "being", "more", "like", "y", ".", ":", "return", ":", "a", "tensor", "for", "the", "adversarial", "example" ]
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: if placeholder.dtype != 'float32': raise NotImplementedError() value = rng.randn(*placeholder.shape).astype('float32') output[placeholder] = value return output
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: if placeholder.dtype != 'float32': raise NotImplementedError() value = rng.randn(*placeholder.shape).astype('float32') output[placeholder] = value return output
[ "def", "random_feed_dict", "(", "rng", ",", "placeholders", ")", ":", "output", "=", "{", "}", "for", "placeholder", "in", "placeholders", ":", "if", "placeholder", ".", "dtype", "!=", "'float32'", ":", "raise", "NotImplementedError", "(", ")", "value", "=", "rng", ".", "randn", "(", "*", "placeholder", ".", "shape", ")", ".", "astype", "(", "'float32'", ")", "output", "[", "placeholder", "]", "=", "value", "return", "output" ]
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", ":", "A", "dict", "mapping", "placeholders", "to", "random", "numpy", "values" ]
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__[0]) # In some environments cleverhans_path does not point to a real directory. # In such case return empty list. if not os.path.isdir(cleverhans_path): return [] repo_path = os.path.abspath(os.path.join(cleverhans_path, os.pardir)) file_list = _list_files(cleverhans_path, suffix) extra_dirs = ['cleverhans_tutorials', 'examples', 'scripts', 'tests_tf', 'tests_pytorch'] for extra_dir in extra_dirs: extra_path = os.path.join(repo_path, extra_dir) if os.path.isdir(extra_path): extra_files = _list_files(extra_path, suffix) extra_files = [os.path.join(os.pardir, path) for path in extra_files] file_list = file_list + extra_files return file_list
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__[0]) # In some environments cleverhans_path does not point to a real directory. # In such case return empty list. if not os.path.isdir(cleverhans_path): return [] repo_path = os.path.abspath(os.path.join(cleverhans_path, os.pardir)) file_list = _list_files(cleverhans_path, suffix) extra_dirs = ['cleverhans_tutorials', 'examples', 'scripts', 'tests_tf', 'tests_pytorch'] for extra_dir in extra_dirs: extra_path = os.path.join(repo_path, extra_dir) if os.path.isdir(extra_path): extra_files = _list_files(extra_path, suffix) extra_files = [os.path.join(os.pardir, path) for path in extra_files] file_list = file_list + extra_files return file_list
[ "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 return empty list.", "if", "not", "os", ".", "path", ".", "isdir", "(", "cleverhans_path", ")", ":", "return", "[", "]", "repo_path", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "cleverhans_path", ",", "os", ".", "pardir", ")", ")", "file_list", "=", "_list_files", "(", "cleverhans_path", ",", "suffix", ")", "extra_dirs", "=", "[", "'cleverhans_tutorials'", ",", "'examples'", ",", "'scripts'", ",", "'tests_tf'", ",", "'tests_pytorch'", "]", "for", "extra_dir", "in", "extra_dirs", ":", "extra_path", "=", "os", ".", "path", ".", "join", "(", "repo_path", ",", "extra_dir", ")", "if", "os", ".", "path", ".", "isdir", "(", "extra_path", ")", ":", "extra_files", "=", "_list_files", "(", "extra_path", ",", "suffix", ")", "extra_files", "=", "[", "os", ".", "path", ".", "join", "(", "os", ".", "pardir", ",", "path", ")", "for", "path", "in", "extra_files", "]", "file_list", "=", "file_list", "+", "extra_files", "return", "file_list" ]
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 rather than a directory, it is considered to "contain" itself) """ if os.path.isdir(path): incomplete = os.listdir(path) complete = [os.path.join(path, entry) for entry in incomplete] lists = [_list_files(subpath, suffix) for subpath in complete] flattened = [] for one_list in lists: for elem in one_list: flattened.append(elem) return flattened else: assert os.path.exists(path), "couldn't find file '%s'" % path if path.endswith(suffix): return [path] return []
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 rather than a directory, it is considered to "contain" itself) """ if os.path.isdir(path): incomplete = os.listdir(path) complete = [os.path.join(path, entry) for entry in incomplete] lists = [_list_files(subpath, suffix) for subpath in complete] flattened = [] for one_list in lists: for elem in one_list: flattened.append(elem) return flattened else: assert os.path.exists(path), "couldn't find file '%s'" % path if path.endswith(suffix): return [path] return []
[ "def", "_list_files", "(", "path", ",", "suffix", "=", "\"\"", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "incomplete", "=", "os", ".", "listdir", "(", "path", ")", "complete", "=", "[", "os", ".", "path", ".", "join", "(", "path", ",", "entry", ")", "for", "entry", "in", "incomplete", "]", "lists", "=", "[", "_list_files", "(", "subpath", ",", "suffix", ")", "for", "subpath", "in", "complete", "]", "flattened", "=", "[", "]", "for", "one_list", "in", "lists", ":", "for", "elem", "in", "one_list", ":", "flattened", ".", "append", "(", "elem", ")", "return", "flattened", "else", ":", "assert", "os", ".", "path", ".", "exists", "(", "path", ")", ",", "\"couldn't find file '%s'\"", "%", "path", "if", "path", ".", "endswith", "(", "suffix", ")", ":", "return", "[", "path", "]", "return", "[", "]" ]
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 to "contain" itself)
[ "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", ")", "+", "4", ")", ")", "print", "(", ")" ]
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", ")", ":", "writer", ".", "writerow", "(", "[", "str", "(", "k", ")", ",", "str", "(", "v", ")", "]", ")" ]
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 batch_size = 10 else: logging.info('Using full dataset. Batch size: %d', DEFAULT_BATCH_SIZE) max_dataset_num_images = None batch_size = DEFAULT_BATCH_SIZE random.seed() print('\nRound: {0}\n'.format(args.round_name)) eval_master = EvaluationMaster( storage_client=eval_lib.CompetitionStorageClient( args.project_id, args.storage_bucket), datastore_client=eval_lib.CompetitionDatastoreClient( args.project_id, args.round_name), round_name=args.round_name, dataset_name=args.dataset_name, blacklisted_submissions=args.blacklisted_submissions, results_dir=args.results_dir, num_defense_shards=args.num_defense_shards, verbose=args.verbose, batch_size=batch_size, max_dataset_num_images=max_dataset_num_images) if args.command == 'attack': eval_master.prepare_attacks() elif args.command == 'defense': eval_master.prepare_defenses() elif args.command == 'cleanup_defenses': eval_master.cleanup_defenses() elif args.command == 'results': eval_master.compute_results() elif args.command == 'status': eval_master.show_status() elif args.command == 'cleanup_datastore': eval_master.cleanup_datastore() elif args.command == 'cleanup_failed_attacks': eval_master.cleanup_failed_attacks() elif args.command == 'cleanup_attacks_with_zero_images': eval_master.cleanup_attacks_with_zero_images() else: print('Invalid command: ', args.command) print('') print(USAGE)
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 batch_size = 10 else: logging.info('Using full dataset. Batch size: %d', DEFAULT_BATCH_SIZE) max_dataset_num_images = None batch_size = DEFAULT_BATCH_SIZE random.seed() print('\nRound: {0}\n'.format(args.round_name)) eval_master = EvaluationMaster( storage_client=eval_lib.CompetitionStorageClient( args.project_id, args.storage_bucket), datastore_client=eval_lib.CompetitionDatastoreClient( args.project_id, args.round_name), round_name=args.round_name, dataset_name=args.dataset_name, blacklisted_submissions=args.blacklisted_submissions, results_dir=args.results_dir, num_defense_shards=args.num_defense_shards, verbose=args.verbose, batch_size=batch_size, max_dataset_num_images=max_dataset_num_images) if args.command == 'attack': eval_master.prepare_attacks() elif args.command == 'defense': eval_master.prepare_defenses() elif args.command == 'cleanup_defenses': eval_master.cleanup_defenses() elif args.command == 'results': eval_master.compute_results() elif args.command == 'status': eval_master.show_status() elif args.command == 'cleanup_datastore': eval_master.cleanup_datastore() elif args.command == 'cleanup_failed_attacks': eval_master.cleanup_failed_attacks() elif args.command == 'cleanup_attacks_with_zero_images': eval_master.cleanup_attacks_with_zero_images() else: print('Invalid command: ', args.command) print('') print(USAGE)
[ "def", "main", "(", "args", ")", ":", "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", "batch_size", "=", "10", "else", ":", "logging", ".", "info", "(", "'Using full dataset. Batch size: %d'", ",", "DEFAULT_BATCH_SIZE", ")", "max_dataset_num_images", "=", "None", "batch_size", "=", "DEFAULT_BATCH_SIZE", "random", ".", "seed", "(", ")", "print", "(", "'\\nRound: {0}\\n'", ".", "format", "(", "args", ".", "round_name", ")", ")", "eval_master", "=", "EvaluationMaster", "(", "storage_client", "=", "eval_lib", ".", "CompetitionStorageClient", "(", "args", ".", "project_id", ",", "args", ".", "storage_bucket", ")", ",", "datastore_client", "=", "eval_lib", ".", "CompetitionDatastoreClient", "(", "args", ".", "project_id", ",", "args", ".", "round_name", ")", ",", "round_name", "=", "args", ".", "round_name", ",", "dataset_name", "=", "args", ".", "dataset_name", ",", "blacklisted_submissions", "=", "args", ".", "blacklisted_submissions", ",", "results_dir", "=", "args", ".", "results_dir", ",", "num_defense_shards", "=", "args", ".", "num_defense_shards", ",", "verbose", "=", "args", ".", "verbose", ",", "batch_size", "=", "batch_size", ",", "max_dataset_num_images", "=", "max_dataset_num_images", ")", "if", "args", ".", "command", "==", "'attack'", ":", "eval_master", ".", "prepare_attacks", "(", ")", "elif", "args", ".", "command", "==", "'defense'", ":", "eval_master", ".", "prepare_defenses", "(", ")", "elif", "args", ".", "command", "==", "'cleanup_defenses'", ":", "eval_master", ".", "cleanup_defenses", "(", ")", "elif", "args", ".", "command", "==", "'results'", ":", "eval_master", ".", "compute_results", "(", ")", "elif", "args", ".", "command", "==", "'status'", ":", "eval_master", ".", "show_status", "(", ")", "elif", "args", ".", "command", "==", "'cleanup_datastore'", ":", "eval_master", ".", "cleanup_datastore", "(", ")", "elif", "args", ".", "command", "==", "'cleanup_failed_attacks'", ":", "eval_master", ".", "cleanup_failed_attacks", "(", ")", "elif", "args", ".", "command", "==", "'cleanup_attacks_with_zero_images'", ":", "eval_master", ".", "cleanup_attacks_with_zero_images", "(", ")", "else", ":", "print", "(", "'Invalid command: '", ",", "args", ".", "command", ")", "print", "(", "''", ")", "print", "(", "USAGE", ")" ]
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 continue and populate datastore, False if we should stop """ 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 ' 'possible corrupted.') inp = input_str('Do you want to continue? ' '(type "yes" without quotes to confirm): ') return inp == 'yes' else: return True
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 continue and populate datastore, False if we should stop """ 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 ' 'possible corrupted.') inp = input_str('Do you want to continue? ' '(type "yes" without quotes to confirm): ') return inp == 'yes' else: return True
[ "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 '", "'possible corrupted.'", ")", "inp", "=", "input_str", "(", "'Do you want to continue? '", "'(type \"yes\" without quotes to confirm): '", ")", "return", "inp", "==", "'yes'", "else", ":", "return", "True" ]
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 stop
[ "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( datastore_client=self.datastore_client) # prepare submissions print_header('Initializing submissions') self.submissions.init_from_storage_write_to_datastore() if self.verbose: print(self.submissions) # prepare dataset batches print_header('Initializing dataset batches') self.dataset_batches.init_from_storage_write_to_datastore( batch_size=self.batch_size, allowed_epsilon=ALLOWED_EPS, skip_image_ids=[], max_num_images=self.max_dataset_num_images) if self.verbose: print(self.dataset_batches) # prepare adversarial batches print_header('Initializing adversarial batches') self.adv_batches.init_from_dataset_and_submissions_write_to_datastore( dataset_batches=self.dataset_batches, attack_submission_ids=self.submissions.get_all_attack_ids()) if self.verbose: print(self.adv_batches) # prepare work pieces print_header('Preparing attack work pieces') self.attack_work.init_from_adversarial_batches(self.adv_batches.data) self.attack_work.write_all_to_datastore() if self.verbose: print(self.attack_work)
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( datastore_client=self.datastore_client) # prepare submissions print_header('Initializing submissions') self.submissions.init_from_storage_write_to_datastore() if self.verbose: print(self.submissions) # prepare dataset batches print_header('Initializing dataset batches') self.dataset_batches.init_from_storage_write_to_datastore( batch_size=self.batch_size, allowed_epsilon=ALLOWED_EPS, skip_image_ids=[], max_num_images=self.max_dataset_num_images) if self.verbose: print(self.dataset_batches) # prepare adversarial batches print_header('Initializing adversarial batches') self.adv_batches.init_from_dataset_and_submissions_write_to_datastore( dataset_batches=self.dataset_batches, attack_submission_ids=self.submissions.get_all_attack_ids()) if self.verbose: print(self.adv_batches) # prepare work pieces print_header('Preparing attack work pieces') self.attack_work.init_from_adversarial_batches(self.adv_batches.data) self.attack_work.write_all_to_datastore() if self.verbose: print(self.attack_work)
[ "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", ".", "attack_work", "=", "eval_lib", ".", "AttackWorkPieces", "(", "datastore_client", "=", "self", ".", "datastore_client", ")", "# prepare submissions", "print_header", "(", "'Initializing submissions'", ")", "self", ".", "submissions", ".", "init_from_storage_write_to_datastore", "(", ")", "if", "self", ".", "verbose", ":", "print", "(", "self", ".", "submissions", ")", "# prepare dataset batches", "print_header", "(", "'Initializing dataset batches'", ")", "self", ".", "dataset_batches", ".", "init_from_storage_write_to_datastore", "(", "batch_size", "=", "self", ".", "batch_size", ",", "allowed_epsilon", "=", "ALLOWED_EPS", ",", "skip_image_ids", "=", "[", "]", ",", "max_num_images", "=", "self", ".", "max_dataset_num_images", ")", "if", "self", ".", "verbose", ":", "print", "(", "self", ".", "dataset_batches", ")", "# prepare adversarial batches", "print_header", "(", "'Initializing adversarial batches'", ")", "self", ".", "adv_batches", ".", "init_from_dataset_and_submissions_write_to_datastore", "(", "dataset_batches", "=", "self", ".", "dataset_batches", ",", "attack_submission_ids", "=", "self", ".", "submissions", ".", "get_all_attack_ids", "(", ")", ")", "if", "self", ".", "verbose", ":", "print", "(", "self", ".", "adv_batches", ")", "# prepare work pieces", "print_header", "(", "'Preparing attack work pieces'", ")", "self", ".", "attack_work", ".", "init_from_adversarial_batches", "(", "self", ".", "adv_batches", ".", "data", ")", "self", ".", "attack_work", ".", "write_all_to_datastore", "(", ")", "if", "self", ".", "verbose", ":", "print", "(", "self", ".", "attack_work", ")" ]
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( datastore_client=self.datastore_client) # load results of attacks self.submissions.init_from_datastore() self.dataset_batches.init_from_datastore() self.adv_batches.init_from_datastore() self.attack_work.read_all_from_datastore() # populate classification results print_header('Initializing classification batches') self.class_batches.init_from_adversarial_batches_write_to_datastore( self.submissions, self.adv_batches) if self.verbose: print(self.class_batches) # populate work pieces print_header('Preparing defense work pieces') self.defense_work.init_from_class_batches( self.class_batches.data, num_shards=self.num_defense_shards) self.defense_work.write_all_to_datastore() if self.verbose: print(self.defense_work)
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( datastore_client=self.datastore_client) # load results of attacks self.submissions.init_from_datastore() self.dataset_batches.init_from_datastore() self.adv_batches.init_from_datastore() self.attack_work.read_all_from_datastore() # populate classification results print_header('Initializing classification batches') self.class_batches.init_from_adversarial_batches_write_to_datastore( self.submissions, self.adv_batches) if self.verbose: print(self.class_batches) # populate work pieces print_header('Preparing defense work pieces') self.defense_work.init_from_class_batches( self.class_batches.data, num_shards=self.num_defense_shards) self.defense_work.write_all_to_datastore() if self.verbose: print(self.defense_work)
[ "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", ".", "defense_work", "=", "eval_lib", ".", "DefenseWorkPieces", "(", "datastore_client", "=", "self", ".", "datastore_client", ")", "# load results of attacks", "self", ".", "submissions", ".", "init_from_datastore", "(", ")", "self", ".", "dataset_batches", ".", "init_from_datastore", "(", ")", "self", ".", "adv_batches", ".", "init_from_datastore", "(", ")", "self", ".", "attack_work", ".", "read_all_from_datastore", "(", ")", "# populate classification results", "print_header", "(", "'Initializing classification batches'", ")", "self", ".", "class_batches", ".", "init_from_adversarial_batches_write_to_datastore", "(", "self", ".", "submissions", ",", "self", ".", "adv_batches", ")", "if", "self", ".", "verbose", ":", "print", "(", "self", ".", "class_batches", ")", "# populate work pieces", "print_header", "(", "'Preparing defense work pieces'", ")", "self", ".", "defense_work", ".", "init_from_class_batches", "(", "self", ".", "class_batches", ".", "data", ",", "num_shards", "=", "self", ".", "num_defense_shards", ")", "self", ".", "defense_work", ".", "write_all_to_datastore", "(", ")", "if", "self", ".", "verbose", ":", "print", "(", "self", ".", "defense_work", ")" ]
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: dictionary with runtime statistics for submissions, can be generated by WorkPiecesBase.compute_work_statistics scores: dictionary mapping submission ids to scores num_processed_images: dictionary with number of successfully processed images by each submission, one of the outputs of ClassificationBatches.compute_classification_results filename: output filename """ with open(filename, 'w') as f: writer = csv.writer(f) writer.writerow( ['SubmissionID', 'ExternalSubmissionId', 'Score', 'CompletedBatches', 'BatchesWithError', 'ProcessedImages', 'MinEvalTime', 'MaxEvalTime', 'MedianEvalTime', 'MeanEvalTime', 'ErrorMsg']) for submission_id in sorted(iterkeys(run_stats)): stat = run_stats.get( submission_id, collections.defaultdict(lambda: float('NaN'))) external_id = self.submissions.get_external_id(submission_id) error_msg = '' while not error_msg and stat['error_messages']: error_msg = stat['error_messages'].pop() if error_msg.startswith('Cant copy adversarial batch locally'): error_msg = '' writer.writerow([ submission_id, external_id, scores.get(submission_id, None), stat['completed'], stat['num_errors'], num_processed_images.get(submission_id, None), stat['min_eval_time'], stat['max_eval_time'], stat['median_eval_time'], stat['mean_eval_time'], error_msg ])
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: dictionary with runtime statistics for submissions, can be generated by WorkPiecesBase.compute_work_statistics scores: dictionary mapping submission ids to scores num_processed_images: dictionary with number of successfully processed images by each submission, one of the outputs of ClassificationBatches.compute_classification_results filename: output filename """ with open(filename, 'w') as f: writer = csv.writer(f) writer.writerow( ['SubmissionID', 'ExternalSubmissionId', 'Score', 'CompletedBatches', 'BatchesWithError', 'ProcessedImages', 'MinEvalTime', 'MaxEvalTime', 'MedianEvalTime', 'MeanEvalTime', 'ErrorMsg']) for submission_id in sorted(iterkeys(run_stats)): stat = run_stats.get( submission_id, collections.defaultdict(lambda: float('NaN'))) external_id = self.submissions.get_external_id(submission_id) error_msg = '' while not error_msg and stat['error_messages']: error_msg = stat['error_messages'].pop() if error_msg.startswith('Cant copy adversarial batch locally'): error_msg = '' writer.writerow([ submission_id, external_id, scores.get(submission_id, None), stat['completed'], stat['num_errors'], num_processed_images.get(submission_id, None), stat['min_eval_time'], stat['max_eval_time'], stat['median_eval_time'], stat['mean_eval_time'], error_msg ])
[ "def", "_save_work_results", "(", "self", ",", "run_stats", ",", "scores", ",", "num_processed_images", ",", "filename", ")", ":", "with", "open", "(", "filename", ",", "'w'", ")", "as", "f", ":", "writer", "=", "csv", ".", "writer", "(", "f", ")", "writer", ".", "writerow", "(", "[", "'SubmissionID'", ",", "'ExternalSubmissionId'", ",", "'Score'", ",", "'CompletedBatches'", ",", "'BatchesWithError'", ",", "'ProcessedImages'", ",", "'MinEvalTime'", ",", "'MaxEvalTime'", ",", "'MedianEvalTime'", ",", "'MeanEvalTime'", ",", "'ErrorMsg'", "]", ")", "for", "submission_id", "in", "sorted", "(", "iterkeys", "(", "run_stats", ")", ")", ":", "stat", "=", "run_stats", ".", "get", "(", "submission_id", ",", "collections", ".", "defaultdict", "(", "lambda", ":", "float", "(", "'NaN'", ")", ")", ")", "external_id", "=", "self", ".", "submissions", ".", "get_external_id", "(", "submission_id", ")", "error_msg", "=", "''", "while", "not", "error_msg", "and", "stat", "[", "'error_messages'", "]", ":", "error_msg", "=", "stat", "[", "'error_messages'", "]", ".", "pop", "(", ")", "if", "error_msg", ".", "startswith", "(", "'Cant copy adversarial batch locally'", ")", ":", "error_msg", "=", "''", "writer", ".", "writerow", "(", "[", "submission_id", ",", "external_id", ",", "scores", ".", "get", "(", "submission_id", ",", "None", ")", ",", "stat", "[", "'completed'", "]", ",", "stat", "[", "'num_errors'", "]", ",", "num_processed_images", ".", "get", "(", "submission_id", ",", "None", ")", ",", "stat", "[", "'min_eval_time'", "]", ",", "stat", "[", "'max_eval_time'", "]", ",", "stat", "[", "'median_eval_time'", "]", ",", "stat", "[", "'mean_eval_time'", "]", ",", "error_msg", "]", ")" ]
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_statistics scores: dictionary mapping submission ids to scores num_processed_images: dictionary with number of successfully processed images by each submission, one of the outputs of ClassificationBatches.compute_classification_results filename: output filename
[ "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 submission ids to scores image_count: dictionary with number of images processed by submission filename: output filename """ with open(filename, 'w') as f: writer = csv.writer(f) writer.writerow(['SubmissionID', 'ExternalTeamId', 'Score', 'MedianTime', 'ImageCount']) def get_second(x): """Returns second entry of a list/tuple""" return x[1] for s_id, score in sorted(iteritems(scores), key=get_second, reverse=True): external_id = self.submissions.get_external_id(s_id) stat = run_stats.get( s_id, collections.defaultdict(lambda: float('NaN'))) writer.writerow([s_id, external_id, score, stat['median_eval_time'], image_count[s_id]])
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 submission ids to scores image_count: dictionary with number of images processed by submission filename: output filename """ with open(filename, 'w') as f: writer = csv.writer(f) writer.writerow(['SubmissionID', 'ExternalTeamId', 'Score', 'MedianTime', 'ImageCount']) def get_second(x): """Returns second entry of a list/tuple""" return x[1] for s_id, score in sorted(iteritems(scores), key=get_second, reverse=True): external_id = self.submissions.get_external_id(s_id) stat = run_stats.get( s_id, collections.defaultdict(lambda: float('NaN'))) writer.writerow([s_id, external_id, score, stat['median_eval_time'], image_count[s_id]])
[ "def", "_save_sorted_results", "(", "self", ",", "run_stats", ",", "scores", ",", "image_count", ",", "filename", ")", ":", "with", "open", "(", "filename", ",", "'w'", ")", "as", "f", ":", "writer", "=", "csv", ".", "writer", "(", "f", ")", "writer", ".", "writerow", "(", "[", "'SubmissionID'", ",", "'ExternalTeamId'", ",", "'Score'", ",", "'MedianTime'", ",", "'ImageCount'", "]", ")", "def", "get_second", "(", "x", ")", ":", "\"\"\"Returns second entry of a list/tuple\"\"\"", "return", "x", "[", "1", "]", "for", "s_id", ",", "score", "in", "sorted", "(", "iteritems", "(", "scores", ")", ",", "key", "=", "get_second", ",", "reverse", "=", "True", ")", ":", "external_id", "=", "self", ".", "submissions", ".", "get_external_id", "(", "s_id", ")", "stat", "=", "run_stats", ".", "get", "(", "s_id", ",", "collections", ".", "defaultdict", "(", "lambda", ":", "float", "(", "'NaN'", ")", ")", ")", "writer", ".", "writerow", "(", "[", "s_id", ",", "external_id", ",", "score", ",", "stat", "[", "'median_eval_time'", "]", ",", "image_count", "[", "s_id", "]", "]", ")" ]
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 submission filename: output filename
[ "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.DatasetMetadata(buf)
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.DatasetMetadata(buf)
[ "def", "_read_dataset_metadata", "(", "self", ")", ":", "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", ".", "DatasetMetadata", "(", "buf", ")" ]
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. This is useful because computatin of resuls could take many minutes. """ # read all data logging.info('Reading data from datastore') dataset_meta = self._read_dataset_metadata() self.submissions.init_from_datastore() self.dataset_batches.init_from_datastore() self.adv_batches.init_from_datastore() self.attack_work.read_all_from_datastore() if os.path.exists(os.path.join(self.results_dir, 'defense_work.dump')): with open(os.path.join(self.results_dir, 'defense_work.dump')) as f: self.defense_work.deserialize(f) else: self.defense_work.read_all_from_datastore() with open(os.path.join(self.results_dir, 'defense_work.dump'), 'w') as f: self.defense_work.serialize(f) if os.path.exists(os.path.join(self.results_dir, 'class_batches.dump')): with open(os.path.join(self.results_dir, 'class_batches.dump')) as f: self.class_batches.deserialize(f) else: self.class_batches.init_from_datastore() with open(os.path.join(self.results_dir, 'class_batches.dump'), 'w') as f: self.class_batches.serialize(f) # process data logging.info('Processing classification results') count_adv_images = self.adv_batches.count_generated_adv_examples() intermediate_files = ['acc_matrix.dump', 'error_matrix.dump', 'hit_tc_matrix.dump', 'classified_images_count.dump'] if all([os.path.exists(os.path.join(self.results_dir, fname)) for fname in intermediate_files]): with open(os.path.join(self.results_dir, 'acc_matrix.dump')) as f: acc_matrix = pickle.load(f) with open(os.path.join(self.results_dir, 'error_matrix.dump')) as f: error_matrix = pickle.load(f) with open(os.path.join(self.results_dir, 'hit_tc_matrix.dump')) as f: hit_tc_matrix = pickle.load(f) with open(os.path.join(self.results_dir, 'classified_images_count.dump')) as f: classified_images_count = pickle.load(f) else: acc_matrix, error_matrix, hit_tc_matrix, classified_images_count = ( self.class_batches.compute_classification_results( self.adv_batches, self.dataset_batches, dataset_meta, self.defense_work)) with open(os.path.join(self.results_dir, 'acc_matrix.dump'), 'w') as f: pickle.dump(acc_matrix, f) with open(os.path.join(self.results_dir, 'error_matrix.dump'), 'w') as f: pickle.dump(error_matrix, f) with open(os.path.join(self.results_dir, 'hit_tc_matrix.dump'), 'w') as f: pickle.dump(hit_tc_matrix, f) with open(os.path.join(self.results_dir, 'classified_images_count.dump'), 'w') as f: pickle.dump(classified_images_count, f) # compute attacks and defenses which will be used for scoring logging.info('Computing attacks and defenses which are used for scoring') expected_num_adv_images = self.dataset_batches.count_num_images() attacks_to_use = [k for k, v in iteritems(count_adv_images) if ((v == expected_num_adv_images) and (k not in self.blacklisted_submissions))] total_num_adversarial = sum(itervalues(count_adv_images)) defenses_to_use = [k for k, v in iteritems(classified_images_count) if ((v == total_num_adversarial) and (k not in self.blacklisted_submissions))] logging.info('Expected number of adversarial images: %d', expected_num_adv_images) logging.info('Number of attacks to use to score defenses: %d', len(attacks_to_use)) logging.info('Expected number of classification predictions: %d', total_num_adversarial) logging.info('Number of defenses to use to score attacks: %d', len(defenses_to_use)) save_dict_to_file(os.path.join(self.results_dir, 'count_adv_images.csv'), count_adv_images) save_dict_to_file(os.path.join(self.results_dir, 'classified_images_count.csv'), classified_images_count) # compute scores logging.info('Computing scores') attack_scores = defaultdict(lambda: 0) targeted_attack_scores = defaultdict(lambda: 0) defense_scores = defaultdict(lambda: 0) for defense_id in acc_matrix.dim0: for attack_id in acc_matrix.dim1: if attack_id in attacks_to_use: defense_scores[defense_id] += acc_matrix[defense_id, attack_id] if defense_id in defenses_to_use: if attack_id in self.submissions.targeted_attacks: targeted_attack_scores[attack_id] += ( hit_tc_matrix[defense_id, attack_id]) else: attack_scores[attack_id] += error_matrix[defense_id, attack_id] # negate results of blacklisted submissions for s_id in self.blacklisted_submissions: if s_id in defense_scores: defense_scores[s_id] = -defense_scores[s_id] if s_id in attack_scores: attack_scores[s_id] = -attack_scores[s_id] if s_id in targeted_attack_scores: targeted_attack_scores[s_id] = -targeted_attack_scores[s_id] # save results logging.info('Saving results') all_attack_stats = self.attack_work.compute_work_statistics() nontargeted_attack_stats = {k: v for k, v in iteritems(all_attack_stats) if k in self.submissions.attacks} targeted_attack_stats = {k: v for k, v in iteritems(all_attack_stats) if k in self.submissions.targeted_attacks} defense_stats = self.defense_work.compute_work_statistics() self._save_work_results( nontargeted_attack_stats, attack_scores, count_adv_images, os.path.join(self.results_dir, 'attack_results.csv')) self._save_work_results( targeted_attack_stats, targeted_attack_scores, count_adv_images, os.path.join(self.results_dir, 'targeted_attack_results.csv')) self._save_work_results( defense_stats, defense_scores, classified_images_count, os.path.join(self.results_dir, 'defense_results.csv')) self._save_sorted_results( nontargeted_attack_stats, attack_scores, count_adv_images, os.path.join(self.results_dir, 'sorted_attack_results.csv')) self._save_sorted_results( targeted_attack_stats, targeted_attack_scores, count_adv_images, os.path.join(self.results_dir, 'sorted_target_attack_results.csv')) self._save_sorted_results( defense_stats, defense_scores, classified_images_count, os.path.join(self.results_dir, 'sorted_defense_results.csv')) defense_id_to_name = {k: self.submissions.get_external_id(k) for k in iterkeys(self.submissions.defenses)} attack_id_to_name = {k: self.submissions.get_external_id(k) for k in self.submissions.get_all_attack_ids()} acc_matrix.save_to_file( os.path.join(self.results_dir, 'accuracy_matrix.csv'), remap_dim0=defense_id_to_name, remap_dim1=attack_id_to_name) error_matrix.save_to_file( os.path.join(self.results_dir, 'error_matrix.csv'), remap_dim0=defense_id_to_name, remap_dim1=attack_id_to_name) hit_tc_matrix.save_to_file( os.path.join(self.results_dir, 'hit_target_class_matrix.csv'), remap_dim0=defense_id_to_name, remap_dim1=attack_id_to_name) save_dict_to_file(os.path.join(self.results_dir, 'defense_id_to_name.csv'), defense_id_to_name) save_dict_to_file(os.path.join(self.results_dir, 'attack_id_to_name.csv'), attack_id_to_name)
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. This is useful because computatin of resuls could take many minutes. """ # read all data logging.info('Reading data from datastore') dataset_meta = self._read_dataset_metadata() self.submissions.init_from_datastore() self.dataset_batches.init_from_datastore() self.adv_batches.init_from_datastore() self.attack_work.read_all_from_datastore() if os.path.exists(os.path.join(self.results_dir, 'defense_work.dump')): with open(os.path.join(self.results_dir, 'defense_work.dump')) as f: self.defense_work.deserialize(f) else: self.defense_work.read_all_from_datastore() with open(os.path.join(self.results_dir, 'defense_work.dump'), 'w') as f: self.defense_work.serialize(f) if os.path.exists(os.path.join(self.results_dir, 'class_batches.dump')): with open(os.path.join(self.results_dir, 'class_batches.dump')) as f: self.class_batches.deserialize(f) else: self.class_batches.init_from_datastore() with open(os.path.join(self.results_dir, 'class_batches.dump'), 'w') as f: self.class_batches.serialize(f) # process data logging.info('Processing classification results') count_adv_images = self.adv_batches.count_generated_adv_examples() intermediate_files = ['acc_matrix.dump', 'error_matrix.dump', 'hit_tc_matrix.dump', 'classified_images_count.dump'] if all([os.path.exists(os.path.join(self.results_dir, fname)) for fname in intermediate_files]): with open(os.path.join(self.results_dir, 'acc_matrix.dump')) as f: acc_matrix = pickle.load(f) with open(os.path.join(self.results_dir, 'error_matrix.dump')) as f: error_matrix = pickle.load(f) with open(os.path.join(self.results_dir, 'hit_tc_matrix.dump')) as f: hit_tc_matrix = pickle.load(f) with open(os.path.join(self.results_dir, 'classified_images_count.dump')) as f: classified_images_count = pickle.load(f) else: acc_matrix, error_matrix, hit_tc_matrix, classified_images_count = ( self.class_batches.compute_classification_results( self.adv_batches, self.dataset_batches, dataset_meta, self.defense_work)) with open(os.path.join(self.results_dir, 'acc_matrix.dump'), 'w') as f: pickle.dump(acc_matrix, f) with open(os.path.join(self.results_dir, 'error_matrix.dump'), 'w') as f: pickle.dump(error_matrix, f) with open(os.path.join(self.results_dir, 'hit_tc_matrix.dump'), 'w') as f: pickle.dump(hit_tc_matrix, f) with open(os.path.join(self.results_dir, 'classified_images_count.dump'), 'w') as f: pickle.dump(classified_images_count, f) # compute attacks and defenses which will be used for scoring logging.info('Computing attacks and defenses which are used for scoring') expected_num_adv_images = self.dataset_batches.count_num_images() attacks_to_use = [k for k, v in iteritems(count_adv_images) if ((v == expected_num_adv_images) and (k not in self.blacklisted_submissions))] total_num_adversarial = sum(itervalues(count_adv_images)) defenses_to_use = [k for k, v in iteritems(classified_images_count) if ((v == total_num_adversarial) and (k not in self.blacklisted_submissions))] logging.info('Expected number of adversarial images: %d', expected_num_adv_images) logging.info('Number of attacks to use to score defenses: %d', len(attacks_to_use)) logging.info('Expected number of classification predictions: %d', total_num_adversarial) logging.info('Number of defenses to use to score attacks: %d', len(defenses_to_use)) save_dict_to_file(os.path.join(self.results_dir, 'count_adv_images.csv'), count_adv_images) save_dict_to_file(os.path.join(self.results_dir, 'classified_images_count.csv'), classified_images_count) # compute scores logging.info('Computing scores') attack_scores = defaultdict(lambda: 0) targeted_attack_scores = defaultdict(lambda: 0) defense_scores = defaultdict(lambda: 0) for defense_id in acc_matrix.dim0: for attack_id in acc_matrix.dim1: if attack_id in attacks_to_use: defense_scores[defense_id] += acc_matrix[defense_id, attack_id] if defense_id in defenses_to_use: if attack_id in self.submissions.targeted_attacks: targeted_attack_scores[attack_id] += ( hit_tc_matrix[defense_id, attack_id]) else: attack_scores[attack_id] += error_matrix[defense_id, attack_id] # negate results of blacklisted submissions for s_id in self.blacklisted_submissions: if s_id in defense_scores: defense_scores[s_id] = -defense_scores[s_id] if s_id in attack_scores: attack_scores[s_id] = -attack_scores[s_id] if s_id in targeted_attack_scores: targeted_attack_scores[s_id] = -targeted_attack_scores[s_id] # save results logging.info('Saving results') all_attack_stats = self.attack_work.compute_work_statistics() nontargeted_attack_stats = {k: v for k, v in iteritems(all_attack_stats) if k in self.submissions.attacks} targeted_attack_stats = {k: v for k, v in iteritems(all_attack_stats) if k in self.submissions.targeted_attacks} defense_stats = self.defense_work.compute_work_statistics() self._save_work_results( nontargeted_attack_stats, attack_scores, count_adv_images, os.path.join(self.results_dir, 'attack_results.csv')) self._save_work_results( targeted_attack_stats, targeted_attack_scores, count_adv_images, os.path.join(self.results_dir, 'targeted_attack_results.csv')) self._save_work_results( defense_stats, defense_scores, classified_images_count, os.path.join(self.results_dir, 'defense_results.csv')) self._save_sorted_results( nontargeted_attack_stats, attack_scores, count_adv_images, os.path.join(self.results_dir, 'sorted_attack_results.csv')) self._save_sorted_results( targeted_attack_stats, targeted_attack_scores, count_adv_images, os.path.join(self.results_dir, 'sorted_target_attack_results.csv')) self._save_sorted_results( defense_stats, defense_scores, classified_images_count, os.path.join(self.results_dir, 'sorted_defense_results.csv')) defense_id_to_name = {k: self.submissions.get_external_id(k) for k in iterkeys(self.submissions.defenses)} attack_id_to_name = {k: self.submissions.get_external_id(k) for k in self.submissions.get_all_attack_ids()} acc_matrix.save_to_file( os.path.join(self.results_dir, 'accuracy_matrix.csv'), remap_dim0=defense_id_to_name, remap_dim1=attack_id_to_name) error_matrix.save_to_file( os.path.join(self.results_dir, 'error_matrix.csv'), remap_dim0=defense_id_to_name, remap_dim1=attack_id_to_name) hit_tc_matrix.save_to_file( os.path.join(self.results_dir, 'hit_target_class_matrix.csv'), remap_dim0=defense_id_to_name, remap_dim1=attack_id_to_name) save_dict_to_file(os.path.join(self.results_dir, 'defense_id_to_name.csv'), defense_id_to_name) save_dict_to_file(os.path.join(self.results_dir, 'attack_id_to_name.csv'), attack_id_to_name)
[ "def", "compute_results", "(", "self", ")", ":", "# read all data", "logging", ".", "info", "(", "'Reading data from datastore'", ")", "dataset_meta", "=", "self", ".", "_read_dataset_metadata", "(", ")", "self", ".", "submissions", ".", "init_from_datastore", "(", ")", "self", ".", "dataset_batches", ".", "init_from_datastore", "(", ")", "self", ".", "adv_batches", ".", "init_from_datastore", "(", ")", "self", ".", "attack_work", ".", "read_all_from_datastore", "(", ")", "if", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "self", ".", "results_dir", ",", "'defense_work.dump'", ")", ")", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "self", ".", "results_dir", ",", "'defense_work.dump'", ")", ")", "as", "f", ":", "self", ".", "defense_work", ".", "deserialize", "(", "f", ")", "else", ":", "self", ".", "defense_work", ".", "read_all_from_datastore", "(", ")", "with", "open", "(", "os", ".", "path", ".", "join", "(", "self", ".", "results_dir", ",", "'defense_work.dump'", ")", ",", "'w'", ")", "as", "f", ":", "self", ".", "defense_work", ".", "serialize", "(", "f", ")", "if", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "self", ".", "results_dir", ",", "'class_batches.dump'", ")", ")", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "self", ".", "results_dir", ",", "'class_batches.dump'", ")", ")", "as", "f", ":", "self", ".", "class_batches", ".", "deserialize", "(", "f", ")", "else", ":", "self", ".", "class_batches", ".", "init_from_datastore", "(", ")", "with", "open", "(", "os", ".", "path", ".", "join", "(", "self", ".", "results_dir", ",", "'class_batches.dump'", ")", ",", "'w'", ")", "as", "f", ":", "self", ".", "class_batches", ".", "serialize", "(", "f", ")", "# process data", "logging", ".", "info", "(", "'Processing classification results'", ")", "count_adv_images", "=", "self", ".", "adv_batches", ".", "count_generated_adv_examples", "(", ")", "intermediate_files", "=", "[", "'acc_matrix.dump'", ",", "'error_matrix.dump'", ",", "'hit_tc_matrix.dump'", ",", "'classified_images_count.dump'", "]", "if", "all", "(", "[", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "self", ".", "results_dir", ",", "fname", ")", ")", "for", "fname", "in", "intermediate_files", "]", ")", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "self", ".", "results_dir", ",", "'acc_matrix.dump'", ")", ")", "as", "f", ":", "acc_matrix", "=", "pickle", ".", "load", "(", "f", ")", "with", "open", "(", "os", ".", "path", ".", "join", "(", "self", ".", "results_dir", ",", "'error_matrix.dump'", ")", ")", "as", "f", ":", "error_matrix", "=", "pickle", ".", "load", "(", "f", ")", "with", "open", "(", "os", ".", "path", ".", "join", "(", "self", ".", "results_dir", ",", "'hit_tc_matrix.dump'", ")", ")", "as", "f", ":", "hit_tc_matrix", "=", "pickle", ".", "load", "(", "f", ")", "with", "open", "(", "os", ".", "path", ".", "join", "(", "self", ".", "results_dir", ",", "'classified_images_count.dump'", ")", ")", "as", "f", ":", "classified_images_count", "=", "pickle", ".", "load", "(", "f", ")", "else", ":", "acc_matrix", ",", "error_matrix", ",", "hit_tc_matrix", ",", "classified_images_count", "=", "(", "self", ".", "class_batches", ".", "compute_classification_results", "(", "self", ".", "adv_batches", ",", "self", ".", "dataset_batches", ",", "dataset_meta", ",", "self", ".", "defense_work", ")", ")", "with", "open", "(", "os", ".", "path", ".", "join", "(", "self", ".", "results_dir", ",", "'acc_matrix.dump'", ")", ",", "'w'", ")", "as", "f", ":", "pickle", ".", "dump", "(", "acc_matrix", ",", "f", ")", "with", "open", "(", "os", ".", "path", ".", "join", "(", "self", ".", "results_dir", ",", "'error_matrix.dump'", ")", ",", "'w'", ")", "as", "f", ":", "pickle", ".", "dump", "(", "error_matrix", ",", "f", ")", "with", "open", "(", "os", ".", "path", ".", "join", "(", "self", ".", "results_dir", ",", "'hit_tc_matrix.dump'", ")", ",", "'w'", ")", "as", "f", ":", "pickle", ".", "dump", "(", "hit_tc_matrix", ",", "f", ")", "with", "open", "(", "os", ".", "path", ".", "join", "(", "self", ".", "results_dir", ",", "'classified_images_count.dump'", ")", ",", "'w'", ")", "as", "f", ":", "pickle", ".", "dump", "(", "classified_images_count", ",", "f", ")", "# compute attacks and defenses which will be used for scoring", "logging", ".", "info", "(", "'Computing attacks and defenses which are used for scoring'", ")", "expected_num_adv_images", "=", "self", ".", "dataset_batches", ".", "count_num_images", "(", ")", "attacks_to_use", "=", "[", "k", "for", "k", ",", "v", "in", "iteritems", "(", "count_adv_images", ")", "if", "(", "(", "v", "==", "expected_num_adv_images", ")", "and", "(", "k", "not", "in", "self", ".", "blacklisted_submissions", ")", ")", "]", "total_num_adversarial", "=", "sum", "(", "itervalues", "(", "count_adv_images", ")", ")", "defenses_to_use", "=", "[", "k", "for", "k", ",", "v", "in", "iteritems", "(", "classified_images_count", ")", "if", "(", "(", "v", "==", "total_num_adversarial", ")", "and", "(", "k", "not", "in", "self", ".", "blacklisted_submissions", ")", ")", "]", "logging", ".", "info", "(", "'Expected number of adversarial images: %d'", ",", "expected_num_adv_images", ")", "logging", ".", "info", "(", "'Number of attacks to use to score defenses: %d'", ",", "len", "(", "attacks_to_use", ")", ")", "logging", ".", "info", "(", "'Expected number of classification predictions: %d'", ",", "total_num_adversarial", ")", "logging", ".", "info", "(", "'Number of defenses to use to score attacks: %d'", ",", "len", "(", "defenses_to_use", ")", ")", "save_dict_to_file", "(", "os", ".", "path", ".", "join", "(", "self", ".", "results_dir", ",", "'count_adv_images.csv'", ")", ",", "count_adv_images", ")", "save_dict_to_file", "(", "os", ".", "path", ".", "join", "(", "self", ".", "results_dir", ",", "'classified_images_count.csv'", ")", ",", "classified_images_count", ")", "# compute scores", "logging", ".", "info", "(", "'Computing scores'", ")", "attack_scores", "=", "defaultdict", "(", "lambda", ":", "0", ")", "targeted_attack_scores", "=", "defaultdict", "(", "lambda", ":", "0", ")", "defense_scores", "=", "defaultdict", "(", "lambda", ":", "0", ")", "for", "defense_id", "in", "acc_matrix", ".", "dim0", ":", "for", "attack_id", "in", "acc_matrix", ".", "dim1", ":", "if", "attack_id", "in", "attacks_to_use", ":", "defense_scores", "[", "defense_id", "]", "+=", "acc_matrix", "[", "defense_id", ",", "attack_id", "]", "if", "defense_id", "in", "defenses_to_use", ":", "if", "attack_id", "in", "self", ".", "submissions", ".", "targeted_attacks", ":", "targeted_attack_scores", "[", "attack_id", "]", "+=", "(", "hit_tc_matrix", "[", "defense_id", ",", "attack_id", "]", ")", "else", ":", "attack_scores", "[", "attack_id", "]", "+=", "error_matrix", "[", "defense_id", ",", "attack_id", "]", "# negate results of blacklisted submissions", "for", "s_id", "in", "self", ".", "blacklisted_submissions", ":", "if", "s_id", "in", "defense_scores", ":", "defense_scores", "[", "s_id", "]", "=", "-", "defense_scores", "[", "s_id", "]", "if", "s_id", "in", "attack_scores", ":", "attack_scores", "[", "s_id", "]", "=", "-", "attack_scores", "[", "s_id", "]", "if", "s_id", "in", "targeted_attack_scores", ":", "targeted_attack_scores", "[", "s_id", "]", "=", "-", "targeted_attack_scores", "[", "s_id", "]", "# save results", "logging", ".", "info", "(", "'Saving results'", ")", "all_attack_stats", "=", "self", ".", "attack_work", ".", "compute_work_statistics", "(", ")", "nontargeted_attack_stats", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", "iteritems", "(", "all_attack_stats", ")", "if", "k", "in", "self", ".", "submissions", ".", "attacks", "}", "targeted_attack_stats", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", "iteritems", "(", "all_attack_stats", ")", "if", "k", "in", "self", ".", "submissions", ".", "targeted_attacks", "}", "defense_stats", "=", "self", ".", "defense_work", ".", "compute_work_statistics", "(", ")", "self", ".", "_save_work_results", "(", "nontargeted_attack_stats", ",", "attack_scores", ",", "count_adv_images", ",", "os", ".", "path", ".", "join", "(", "self", ".", "results_dir", ",", "'attack_results.csv'", ")", ")", "self", ".", "_save_work_results", "(", "targeted_attack_stats", ",", "targeted_attack_scores", ",", "count_adv_images", ",", "os", ".", "path", ".", "join", "(", "self", ".", "results_dir", ",", "'targeted_attack_results.csv'", ")", ")", "self", ".", "_save_work_results", "(", "defense_stats", ",", "defense_scores", ",", "classified_images_count", ",", "os", ".", "path", ".", "join", "(", "self", ".", "results_dir", ",", "'defense_results.csv'", ")", ")", "self", ".", "_save_sorted_results", "(", "nontargeted_attack_stats", ",", "attack_scores", ",", "count_adv_images", ",", "os", ".", "path", ".", "join", "(", "self", ".", "results_dir", ",", "'sorted_attack_results.csv'", ")", ")", "self", ".", "_save_sorted_results", "(", "targeted_attack_stats", ",", "targeted_attack_scores", ",", "count_adv_images", ",", "os", ".", "path", ".", "join", "(", "self", ".", "results_dir", ",", "'sorted_target_attack_results.csv'", ")", ")", "self", ".", "_save_sorted_results", "(", "defense_stats", ",", "defense_scores", ",", "classified_images_count", ",", "os", ".", "path", ".", "join", "(", "self", ".", "results_dir", ",", "'sorted_defense_results.csv'", ")", ")", "defense_id_to_name", "=", "{", "k", ":", "self", ".", "submissions", ".", "get_external_id", "(", "k", ")", "for", "k", "in", "iterkeys", "(", "self", ".", "submissions", ".", "defenses", ")", "}", "attack_id_to_name", "=", "{", "k", ":", "self", ".", "submissions", ".", "get_external_id", "(", "k", ")", "for", "k", "in", "self", ".", "submissions", ".", "get_all_attack_ids", "(", ")", "}", "acc_matrix", ".", "save_to_file", "(", "os", ".", "path", ".", "join", "(", "self", ".", "results_dir", ",", "'accuracy_matrix.csv'", ")", ",", "remap_dim0", "=", "defense_id_to_name", ",", "remap_dim1", "=", "attack_id_to_name", ")", "error_matrix", ".", "save_to_file", "(", "os", ".", "path", ".", "join", "(", "self", ".", "results_dir", ",", "'error_matrix.csv'", ")", ",", "remap_dim0", "=", "defense_id_to_name", ",", "remap_dim1", "=", "attack_id_to_name", ")", "hit_tc_matrix", ".", "save_to_file", "(", "os", ".", "path", ".", "join", "(", "self", ".", "results_dir", ",", "'hit_target_class_matrix.csv'", ")", ",", "remap_dim0", "=", "defense_id_to_name", ",", "remap_dim1", "=", "attack_id_to_name", ")", "save_dict_to_file", "(", "os", ".", "path", ".", "join", "(", "self", ".", "results_dir", ",", "'defense_id_to_name.csv'", ")", ",", "defense_id_to_name", ")", "save_dict_to_file", "(", "os", ".", "path", ".", "join", "(", "self", ".", "results_dir", ",", "'attack_id_to_name.csv'", ")", ",", "attack_id_to_name", ")" ]
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 computatin of resuls could take many minutes.
[ "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']: work_completed_count += 1 worker_id = v['claimed_worker_id'] if worker_id not in work_completed: work_completed[worker_id] = { 'completed_count': 0, 'last_update': 0.0, } work_completed[worker_id]['completed_count'] += 1 work_completed[worker_id]['last_update'] = max( work_completed[worker_id]['last_update'], v['claimed_worker_start_time']) print('Completed {0}/{1} work'.format(work_completed_count, work_count)) for k in sorted(iterkeys(work_completed)): last_update_time = time.strftime( '%Y-%m-%d %H:%M:%S', time.localtime(work_completed[k]['last_update'])) print('Worker {0}: completed {1} last claimed work at {2}'.format( k, work_completed[k]['completed_count'], last_update_time))
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']: work_completed_count += 1 worker_id = v['claimed_worker_id'] if worker_id not in work_completed: work_completed[worker_id] = { 'completed_count': 0, 'last_update': 0.0, } work_completed[worker_id]['completed_count'] += 1 work_completed[worker_id]['last_update'] = max( work_completed[worker_id]['last_update'], v['claimed_worker_start_time']) print('Completed {0}/{1} work'.format(work_completed_count, work_count)) for k in sorted(iterkeys(work_completed)): last_update_time = time.strftime( '%Y-%m-%d %H:%M:%S', time.localtime(work_completed[k]['last_update'])) print('Worker {0}: completed {1} last claimed work at {2}'.format( k, work_completed[k]['completed_count'], last_update_time))
[ "def", "_show_status_for_work", "(", "self", ",", "work", ")", ":", "work_count", "=", "len", "(", "work", ".", "work", ")", "work_completed", "=", "{", "}", "work_completed_count", "=", "0", "for", "v", "in", "itervalues", "(", "work", ".", "work", ")", ":", "if", "v", "[", "'is_completed'", "]", ":", "work_completed_count", "+=", "1", "worker_id", "=", "v", "[", "'claimed_worker_id'", "]", "if", "worker_id", "not", "in", "work_completed", ":", "work_completed", "[", "worker_id", "]", "=", "{", "'completed_count'", ":", "0", ",", "'last_update'", ":", "0.0", ",", "}", "work_completed", "[", "worker_id", "]", "[", "'completed_count'", "]", "+=", "1", "work_completed", "[", "worker_id", "]", "[", "'last_update'", "]", "=", "max", "(", "work_completed", "[", "worker_id", "]", "[", "'last_update'", "]", ",", "v", "[", "'claimed_worker_start_time'", "]", ")", "print", "(", "'Completed {0}/{1} work'", ".", "format", "(", "work_completed_count", ",", "work_count", ")", ")", "for", "k", "in", "sorted", "(", "iterkeys", "(", "work_completed", ")", ")", ":", "last_update_time", "=", "time", ".", "strftime", "(", "'%Y-%m-%d %H:%M:%S'", ",", "time", ".", "localtime", "(", "work_completed", "[", "k", "]", "[", "'last_update'", "]", ")", ")", "print", "(", "'Worker {0}: completed {1} last claimed work at {2}'", ".", "format", "(", "k", ",", "work_completed", "[", "k", "]", "[", "'completed_count'", "]", ",", "last_update_time", ")", ")" ]
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 v['error'] is not None: errors.add(v['error']) with open(output_file, 'w') as f: for e in sorted(errors): f.write(e) f.write('\n')
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 v['error'] is not None: errors.add(v['error']) with open(output_file, 'w') as f: for e in sorted(errors): f.write(e) f.write('\n')
[ "def", "_export_work_errors", "(", "self", ",", "work", ",", "output_file", ")", ":", "errors", "=", "set", "(", ")", "for", "v", "in", "itervalues", "(", "work", ".", "work", ")", ":", "if", "v", "[", "'is_completed'", "]", "and", "v", "[", "'error'", "]", "is", "not", "None", ":", "errors", ".", "add", "(", "v", "[", "'error'", "]", ")", "with", "open", "(", "output_file", ",", "'w'", ")", "as", "f", ":", "for", "e", "in", "sorted", "(", "errors", ")", ":", "f", ".", "write", "(", "e", ")", "f", ".", "write", "(", "'\\n'", ")" ]
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_status_for_work(self.attack_work) self._export_work_errors( self.attack_work, os.path.join(self.results_dir, 'attack_errors.txt')) print_header('Defense work statistics') self.defense_work.read_all_from_datastore() self._show_status_for_work(self.defense_work) self._export_work_errors( self.defense_work, os.path.join(self.results_dir, 'defense_errors.txt'))
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_status_for_work(self.attack_work) self._export_work_errors( self.attack_work, os.path.join(self.results_dir, 'attack_errors.txt')) print_header('Defense work statistics') self.defense_work.read_all_from_datastore() self._show_status_for_work(self.defense_work) self._export_work_errors( self.defense_work, os.path.join(self.results_dir, 'defense_errors.txt'))
[ "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", ".", "_export_work_errors", "(", "self", ".", "attack_work", ",", "os", ".", "path", ".", "join", "(", "self", ".", "results_dir", ",", "'attack_errors.txt'", ")", ")", "print_header", "(", "'Defense work statistics'", ")", "self", ".", "defense_work", ".", "read_all_from_datastore", "(", ")", "self", ".", "_show_status_for_work", "(", "self", ".", "defense_work", ")", "self", ".", "_export_work_errors", "(", "self", ".", "defense_work", ",", "os", ".", "path", ".", "join", "(", "self", ".", "results_dir", ",", "'defense_errors.txt'", ")", ")" ]
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'] is not None: attacks_to_replace[k] = dict(v) failed_submissions.add(v['submission_id']) error_msg.add(v['error']) attacks_to_replace[k].update( { 'claimed_worker_id': None, 'claimed_worker_start_time': None, 'is_completed': False, 'error': None, 'elapsed_time': None, }) self.attack_work.replace_work(attacks_to_replace) print('Affected submissions:') print(' '.join(sorted(failed_submissions))) print('Error messages:') print(' '.join(sorted(error_msg))) print('') inp = input_str('Are you sure? (type "yes" without quotes to confirm): ') if inp != 'yes': return self.attack_work.write_all_to_datastore() print('Work cleaned up')
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'] is not None: attacks_to_replace[k] = dict(v) failed_submissions.add(v['submission_id']) error_msg.add(v['error']) attacks_to_replace[k].update( { 'claimed_worker_id': None, 'claimed_worker_start_time': None, 'is_completed': False, 'error': None, 'elapsed_time': None, }) self.attack_work.replace_work(attacks_to_replace) print('Affected submissions:') print(' '.join(sorted(failed_submissions))) print('Error messages:') print(' '.join(sorted(error_msg))) print('') inp = input_str('Are you sure? (type "yes" without quotes to confirm): ') if inp != 'yes': return self.attack_work.write_all_to_datastore() print('Work cleaned up')
[ "def", "cleanup_failed_attacks", "(", "self", ")", ":", "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'", "]", "is", "not", "None", ":", "attacks_to_replace", "[", "k", "]", "=", "dict", "(", "v", ")", "failed_submissions", ".", "add", "(", "v", "[", "'submission_id'", "]", ")", "error_msg", ".", "add", "(", "v", "[", "'error'", "]", ")", "attacks_to_replace", "[", "k", "]", ".", "update", "(", "{", "'claimed_worker_id'", ":", "None", ",", "'claimed_worker_start_time'", ":", "None", ",", "'is_completed'", ":", "False", ",", "'error'", ":", "None", ",", "'elapsed_time'", ":", "None", ",", "}", ")", "self", ".", "attack_work", ".", "replace_work", "(", "attacks_to_replace", ")", "print", "(", "'Affected submissions:'", ")", "print", "(", "' '", ".", "join", "(", "sorted", "(", "failed_submissions", ")", ")", ")", "print", "(", "'Error messages:'", ")", "print", "(", "' '", ".", "join", "(", "sorted", "(", "error_msg", ")", ")", ")", "print", "(", "''", ")", "inp", "=", "input_str", "(", "'Are you sure? (type \"yes\" without quotes to confirm): '", ")", "if", "inp", "!=", "'yes'", ":", "return", "self", ".", "attack_work", ".", "write_all_to_datastore", "(", ")", "print", "(", "'Work cleaned up'", ")" ]
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_work = {} affected_adversarial_batches = set() for work_id, work in iteritems(self.attack_work.work): adv_batch_id = work['output_adversarial_batch_id'] img_count_adv_batch = len(self.adv_batches.data[adv_batch_id]['images']) if (img_count_adv_batch < 100) and (work['elapsed_time'] < 500): affected_adversarial_batches.add(adv_batch_id) new_attack_work[work_id] = dict(work) new_attack_work[work_id].update( { 'claimed_worker_id': None, 'claimed_worker_start_time': None, 'is_completed': False, 'error': None, 'elapsed_time': None, }) self.attack_work.replace_work(new_attack_work) print_header('Changes in attack works:') print(self.attack_work) # build list of classification batches self.class_batches.init_from_datastore() affected_class_batches = set() for k, v in iteritems(self.class_batches.data): if v['adversarial_batch_id'] in affected_adversarial_batches: affected_class_batches.add(k) # cleanup defense work on affected batches self.defense_work.read_all_from_datastore() new_defense_work = {} for k, v in iteritems(self.defense_work.work): if v['output_classification_batch_id'] in affected_class_batches: new_defense_work[k] = dict(v) new_defense_work[k].update( { 'claimed_worker_id': None, 'claimed_worker_start_time': None, 'is_completed': False, 'error': None, 'elapsed_time': None, 'stat_correct': None, 'stat_error': None, 'stat_target_class': None, 'stat_num_images': None, }) self.defense_work.replace_work(new_defense_work) print_header('Changes in defense works:') print(self.defense_work) print('') print('Total number of affected attack work: ', len(self.attack_work)) print('Total number of affected defense work: ', len(self.defense_work)) inp = input_str('Are you sure? (type "yes" without quotes to confirm): ') if inp != 'yes': return print('Writing attacks work') self.attack_work.write_all_to_datastore() print('Writing defenses work') self.defense_work.write_all_to_datastore() print('Done!')
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_work = {} affected_adversarial_batches = set() for work_id, work in iteritems(self.attack_work.work): adv_batch_id = work['output_adversarial_batch_id'] img_count_adv_batch = len(self.adv_batches.data[adv_batch_id]['images']) if (img_count_adv_batch < 100) and (work['elapsed_time'] < 500): affected_adversarial_batches.add(adv_batch_id) new_attack_work[work_id] = dict(work) new_attack_work[work_id].update( { 'claimed_worker_id': None, 'claimed_worker_start_time': None, 'is_completed': False, 'error': None, 'elapsed_time': None, }) self.attack_work.replace_work(new_attack_work) print_header('Changes in attack works:') print(self.attack_work) # build list of classification batches self.class_batches.init_from_datastore() affected_class_batches = set() for k, v in iteritems(self.class_batches.data): if v['adversarial_batch_id'] in affected_adversarial_batches: affected_class_batches.add(k) # cleanup defense work on affected batches self.defense_work.read_all_from_datastore() new_defense_work = {} for k, v in iteritems(self.defense_work.work): if v['output_classification_batch_id'] in affected_class_batches: new_defense_work[k] = dict(v) new_defense_work[k].update( { 'claimed_worker_id': None, 'claimed_worker_start_time': None, 'is_completed': False, 'error': None, 'elapsed_time': None, 'stat_correct': None, 'stat_error': None, 'stat_target_class': None, 'stat_num_images': None, }) self.defense_work.replace_work(new_defense_work) print_header('Changes in defense works:') print(self.defense_work) print('') print('Total number of affected attack work: ', len(self.attack_work)) print('Total number of affected defense work: ', len(self.defense_work)) inp = input_str('Are you sure? (type "yes" without quotes to confirm): ') if inp != 'yes': return print('Writing attacks work') self.attack_work.write_all_to_datastore() print('Writing defenses work') self.defense_work.write_all_to_datastore() print('Done!')
[ "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", ".", "read_all_from_datastore", "(", ")", "new_attack_work", "=", "{", "}", "affected_adversarial_batches", "=", "set", "(", ")", "for", "work_id", ",", "work", "in", "iteritems", "(", "self", ".", "attack_work", ".", "work", ")", ":", "adv_batch_id", "=", "work", "[", "'output_adversarial_batch_id'", "]", "img_count_adv_batch", "=", "len", "(", "self", ".", "adv_batches", ".", "data", "[", "adv_batch_id", "]", "[", "'images'", "]", ")", "if", "(", "img_count_adv_batch", "<", "100", ")", "and", "(", "work", "[", "'elapsed_time'", "]", "<", "500", ")", ":", "affected_adversarial_batches", ".", "add", "(", "adv_batch_id", ")", "new_attack_work", "[", "work_id", "]", "=", "dict", "(", "work", ")", "new_attack_work", "[", "work_id", "]", ".", "update", "(", "{", "'claimed_worker_id'", ":", "None", ",", "'claimed_worker_start_time'", ":", "None", ",", "'is_completed'", ":", "False", ",", "'error'", ":", "None", ",", "'elapsed_time'", ":", "None", ",", "}", ")", "self", ".", "attack_work", ".", "replace_work", "(", "new_attack_work", ")", "print_header", "(", "'Changes in attack works:'", ")", "print", "(", "self", ".", "attack_work", ")", "# build list of classification batches", "self", ".", "class_batches", ".", "init_from_datastore", "(", ")", "affected_class_batches", "=", "set", "(", ")", "for", "k", ",", "v", "in", "iteritems", "(", "self", ".", "class_batches", ".", "data", ")", ":", "if", "v", "[", "'adversarial_batch_id'", "]", "in", "affected_adversarial_batches", ":", "affected_class_batches", ".", "add", "(", "k", ")", "# cleanup defense work on affected batches", "self", ".", "defense_work", ".", "read_all_from_datastore", "(", ")", "new_defense_work", "=", "{", "}", "for", "k", ",", "v", "in", "iteritems", "(", "self", ".", "defense_work", ".", "work", ")", ":", "if", "v", "[", "'output_classification_batch_id'", "]", "in", "affected_class_batches", ":", "new_defense_work", "[", "k", "]", "=", "dict", "(", "v", ")", "new_defense_work", "[", "k", "]", ".", "update", "(", "{", "'claimed_worker_id'", ":", "None", ",", "'claimed_worker_start_time'", ":", "None", ",", "'is_completed'", ":", "False", ",", "'error'", ":", "None", ",", "'elapsed_time'", ":", "None", ",", "'stat_correct'", ":", "None", ",", "'stat_error'", ":", "None", ",", "'stat_target_class'", ":", "None", ",", "'stat_num_images'", ":", "None", ",", "}", ")", "self", ".", "defense_work", ".", "replace_work", "(", "new_defense_work", ")", "print_header", "(", "'Changes in defense works:'", ")", "print", "(", "self", ".", "defense_work", ")", "print", "(", "''", ")", "print", "(", "'Total number of affected attack work: '", ",", "len", "(", "self", ".", "attack_work", ")", ")", "print", "(", "'Total number of affected defense work: '", ",", "len", "(", "self", ".", "defense_work", ")", ")", "inp", "=", "input_str", "(", "'Are you sure? (type \"yes\" without quotes to confirm): '", ")", "if", "inp", "!=", "'yes'", ":", "return", "print", "(", "'Writing attacks work'", ")", "self", ".", "attack_work", ".", "write_all_to_datastore", "(", ")", "print", "(", "'Writing defenses work'", ")", "self", ".", "defense_work", ".", "write_all_to_datastore", "(", ")", "print", "(", "'Done!'", ")" ]
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_to_delete)) if not keys_to_delete: return if self.verbose: print('Entities to delete:') idx = 0 prev_key_prefix = None dots_printed_after_same_prefix = False for k in keys_to_delete: if idx >= 20: print(' ...') print(' ...') break key_prefix = (k.flat_path[0:1] if k.flat_path[0] in [u'SubmissionType', u'WorkType'] else k.flat_path[0]) if prev_key_prefix == key_prefix: if not dots_printed_after_same_prefix: print(' ...') dots_printed_after_same_prefix = True else: print(' ', k) dots_printed_after_same_prefix = False idx += 1 prev_key_prefix = key_prefix print() inp = input_str('Are you sure? (type "yes" without quotes to confirm): ') if inp != 'yes': return with self.datastore_client.no_transact_batch() as batch: for k in keys_to_delete: batch.delete(k) print('Data deleted')
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_to_delete)) if not keys_to_delete: return if self.verbose: print('Entities to delete:') idx = 0 prev_key_prefix = None dots_printed_after_same_prefix = False for k in keys_to_delete: if idx >= 20: print(' ...') print(' ...') break key_prefix = (k.flat_path[0:1] if k.flat_path[0] in [u'SubmissionType', u'WorkType'] else k.flat_path[0]) if prev_key_prefix == key_prefix: if not dots_printed_after_same_prefix: print(' ...') dots_printed_after_same_prefix = True else: print(' ', k) dots_printed_after_same_prefix = False idx += 1 prev_key_prefix = key_prefix print() inp = input_str('Are you sure? (type "yes" without quotes to confirm): ') if inp != 'yes': return with self.datastore_client.no_transact_batch() as batch: for k in keys_to_delete: batch.delete(k) print('Data deleted')
[ "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", "not", "keys_to_delete", ":", "return", "if", "self", ".", "verbose", ":", "print", "(", "'Entities to delete:'", ")", "idx", "=", "0", "prev_key_prefix", "=", "None", "dots_printed_after_same_prefix", "=", "False", "for", "k", "in", "keys_to_delete", ":", "if", "idx", ">=", "20", ":", "print", "(", "' ...'", ")", "print", "(", "' ...'", ")", "break", "key_prefix", "=", "(", "k", ".", "flat_path", "[", "0", ":", "1", "]", "if", "k", ".", "flat_path", "[", "0", "]", "in", "[", "u'SubmissionType'", ",", "u'WorkType'", "]", "else", "k", ".", "flat_path", "[", "0", "]", ")", "if", "prev_key_prefix", "==", "key_prefix", ":", "if", "not", "dots_printed_after_same_prefix", ":", "print", "(", "' ...'", ")", "dots_printed_after_same_prefix", "=", "True", "else", ":", "print", "(", "' '", ",", "k", ")", "dots_printed_after_same_prefix", "=", "False", "idx", "+=", "1", "prev_key_prefix", "=", "key_prefix", "print", "(", ")", "inp", "=", "input_str", "(", "'Are you sure? (type \"yes\" without quotes to confirm): '", ")", "if", "inp", "!=", "'yes'", ":", "return", "with", "self", ".", "datastore_client", ".", "no_transact_batch", "(", ")", "as", "batch", ":", "for", "k", "in", "keys_to_delete", ":", "batch", ".", "delete", "(", "k", ")", "print", "(", "'Data deleted'", ")" ]
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'ClassificationBatch') ] + [ e.key for e in self.datastore_client.query_fetch(kind=u'Work', ancestor=work_ancestor_key) ] self._cleanup_keys_with_confirmation(keys_to_delete)
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'ClassificationBatch') ] + [ e.key for e in self.datastore_client.query_fetch(kind=u'Work', ancestor=work_ancestor_key) ] self._cleanup_keys_with_confirmation(keys_to_delete)
[ "def", "cleanup_defenses", "(", "self", ")", ":", "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'ClassificationBatch'", ")", "]", "+", "[", "e", ".", "key", "for", "e", "in", "self", ".", "datastore_client", ".", "query_fetch", "(", "kind", "=", "u'Work'", ",", "ancestor", "=", "work_ancestor_key", ")", "]", "self", ".", "_cleanup_keys_with_confirmation", "(", "keys_to_delete", ")" ]
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'AdversarialBatch', u'Work', u'WorkType', u'ClassificationBatch'] keys_to_delete = [e.key for k in kinds_to_delete for e in self.datastore_client.query_fetch(kind=k)] self._cleanup_keys_with_confirmation(keys_to_delete)
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'AdversarialBatch', u'Work', u'WorkType', u'ClassificationBatch'] keys_to_delete = [e.key for k in kinds_to_delete for e in self.datastore_client.query_fetch(kind=k)] self._cleanup_keys_with_confirmation(keys_to_delete)
[ "def", "cleanup_datastore", "(", "self", ")", ":", "print_header", "(", "'CLEANING UP ENTIRE DATASTORE'", ")", "kinds_to_delete", "=", "[", "u'Submission'", ",", "u'SubmissionType'", ",", "u'DatasetImage'", ",", "u'DatasetBatch'", ",", "u'AdversarialImage'", ",", "u'AdversarialBatch'", ",", "u'Work'", ",", "u'WorkType'", ",", "u'ClassificationBatch'", "]", "keys_to_delete", "=", "[", "e", ".", "key", "for", "k", "in", "kinds_to_delete", "for", "e", "in", "self", ".", "datastore_client", ".", "query_fetch", "(", "kind", "=", "k", ")", "]", "self", ".", "_cleanup_keys_with_confirmation", "(", "keys_to_delete", ")" ]
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)) x_output = tf.clip_by_value(noisy_images, 0.0, 1.0) with tf.Session(FLAGS.master) as sess: for filenames, images in load_images(FLAGS.input_dir, batch_shape): out_images = sess.run(x_output, feed_dict={x_input: images}) save_images(out_images, filenames, FLAGS.output_dir)
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)) x_output = tf.clip_by_value(noisy_images, 0.0, 1.0) with tf.Session(FLAGS.master) as sess: for filenames, images in load_images(FLAGS.input_dir, batch_shape): out_images = sess.run(x_output, feed_dict={x_input: images}) save_images(out_images, filenames, FLAGS.output_dir)
[ "def", "main", "(", "_", ")", ":", "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", ")", ")", "x_output", "=", "tf", ".", "clip_by_value", "(", "noisy_images", ",", "0.0", ",", "1.0", ")", "with", "tf", ".", "Session", "(", "FLAGS", ".", "master", ")", "as", "sess", ":", "for", "filenames", ",", "images", "in", "load_images", "(", "FLAGS", ".", "input_dir", ",", "batch_shape", ")", ":", "out_images", "=", "sess", ".", "run", "(", "x_output", ",", "feed_dict", "=", "{", "x_input", ":", "images", "}", ")", "save_images", "(", "out_images", ",", "filenames", ",", "FLAGS", ".", "output_dir", ")" ]
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 object. :param theta: delta for each feature adjustment :param gamma: a float between 0 - 1 indicating the maximum distortion percentage :param clip_min: minimum value for components of the example returned :param clip_max: maximum value for components of the example returned :return: a tensor for the adversarial example """ nb_classes = int(y_target.shape[-1].value) nb_features = int(np.product(x.shape[1:]).value) if x.dtype == tf.float32 and y_target.dtype == tf.int64: y_target = tf.cast(y_target, tf.int32) if x.dtype == tf.float32 and y_target.dtype == tf.float64: warnings.warn("Downcasting labels---this should be harmless unless" " they are smoothed") y_target = tf.cast(y_target, tf.float32) max_iters = np.floor(nb_features * gamma / 2) increase = bool(theta > 0) tmp = np.ones((nb_features, nb_features), int) np.fill_diagonal(tmp, 0) zero_diagonal = tf.constant(tmp, tf_dtype) # Compute our initial search domain. We optimize the initial search domain # by removing all features that are already at their maximum values (if # increasing input features---otherwise, at their minimum value). if increase: search_domain = tf.reshape( tf.cast(x < clip_max, tf_dtype), [-1, nb_features]) else: search_domain = tf.reshape( tf.cast(x > clip_min, tf_dtype), [-1, nb_features]) # Loop variables # x_in: the tensor that holds the latest adversarial outputs that are in # progress. # y_in: the tensor for target labels # domain_in: the tensor that holds the latest search domain # cond_in: the boolean tensor to show if more iteration is needed for # generating adversarial samples def condition(x_in, y_in, domain_in, i_in, cond_in): # Repeat the loop until we have achieved misclassification or # reaches the maximum iterations return tf.logical_and(tf.less(i_in, max_iters), cond_in) # Same loop variables as above def body(x_in, y_in, domain_in, i_in, cond_in): # Create graph for model logits and predictions logits = model.get_logits(x_in) preds = tf.nn.softmax(logits) preds_onehot = tf.one_hot(tf.argmax(preds, axis=1), depth=nb_classes) # create the Jacobian graph list_derivatives = [] for class_ind in xrange(nb_classes): derivatives = tf.gradients(logits[:, class_ind], x_in) list_derivatives.append(derivatives[0]) grads = tf.reshape( tf.stack(list_derivatives), shape=[nb_classes, -1, nb_features]) # Compute the Jacobian components # To help with the computation later, reshape the target_class # and other_class to [nb_classes, -1, 1]. # The last dimention is added to allow broadcasting later. target_class = tf.reshape( tf.transpose(y_in, perm=[1, 0]), shape=[nb_classes, -1, 1]) other_classes = tf.cast(tf.not_equal(target_class, 1), tf_dtype) grads_target = reduce_sum(grads * target_class, axis=0) grads_other = reduce_sum(grads * other_classes, axis=0) # Remove the already-used input features from the search space # Subtract 2 times the maximum value from those value so that # they won't be picked later increase_coef = (4 * int(increase) - 2) \ * tf.cast(tf.equal(domain_in, 0), tf_dtype) target_tmp = grads_target target_tmp -= increase_coef \ * reduce_max(tf.abs(grads_target), axis=1, keepdims=True) target_sum = tf.reshape(target_tmp, shape=[-1, nb_features, 1]) \ + tf.reshape(target_tmp, shape=[-1, 1, nb_features]) other_tmp = grads_other other_tmp += increase_coef \ * reduce_max(tf.abs(grads_other), axis=1, keepdims=True) other_sum = tf.reshape(other_tmp, shape=[-1, nb_features, 1]) \ + tf.reshape(other_tmp, shape=[-1, 1, nb_features]) # Create a mask to only keep features that match conditions if increase: scores_mask = ((target_sum > 0) & (other_sum < 0)) else: scores_mask = ((target_sum < 0) & (other_sum > 0)) # Create a 2D numpy array of scores for each pair of candidate features scores = tf.cast(scores_mask, tf_dtype) \ * (-target_sum * other_sum) * zero_diagonal # Extract the best two pixels best = tf.argmax( tf.reshape(scores, shape=[-1, nb_features * nb_features]), axis=1) p1 = tf.mod(best, nb_features) p2 = tf.floordiv(best, nb_features) p1_one_hot = tf.one_hot(p1, depth=nb_features) p2_one_hot = tf.one_hot(p2, depth=nb_features) # Check if more modification is needed for each sample mod_not_done = tf.equal(reduce_sum(y_in * preds_onehot, axis=1), 0) cond = mod_not_done & (reduce_sum(domain_in, axis=1) >= 2) # Update the search domain cond_float = tf.reshape(tf.cast(cond, tf_dtype), shape=[-1, 1]) to_mod = (p1_one_hot + p2_one_hot) * cond_float domain_out = domain_in - to_mod # Apply the modification to the images to_mod_reshape = tf.reshape( to_mod, shape=([-1] + x_in.shape[1:].as_list())) if increase: x_out = tf.minimum(clip_max, x_in + to_mod_reshape * theta) else: x_out = tf.maximum(clip_min, x_in - to_mod_reshape * theta) # Increase the iterator, and check if all misclassifications are done i_out = tf.add(i_in, 1) cond_out = reduce_any(cond) return x_out, y_in, domain_out, i_out, cond_out # Run loop to do JSMA x_adv, _, _, _, _ = tf.while_loop( condition, body, [x, y_target, search_domain, 0, True], parallel_iterations=1) return x_adv
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 object. :param theta: delta for each feature adjustment :param gamma: a float between 0 - 1 indicating the maximum distortion percentage :param clip_min: minimum value for components of the example returned :param clip_max: maximum value for components of the example returned :return: a tensor for the adversarial example """ nb_classes = int(y_target.shape[-1].value) nb_features = int(np.product(x.shape[1:]).value) if x.dtype == tf.float32 and y_target.dtype == tf.int64: y_target = tf.cast(y_target, tf.int32) if x.dtype == tf.float32 and y_target.dtype == tf.float64: warnings.warn("Downcasting labels---this should be harmless unless" " they are smoothed") y_target = tf.cast(y_target, tf.float32) max_iters = np.floor(nb_features * gamma / 2) increase = bool(theta > 0) tmp = np.ones((nb_features, nb_features), int) np.fill_diagonal(tmp, 0) zero_diagonal = tf.constant(tmp, tf_dtype) # Compute our initial search domain. We optimize the initial search domain # by removing all features that are already at their maximum values (if # increasing input features---otherwise, at their minimum value). if increase: search_domain = tf.reshape( tf.cast(x < clip_max, tf_dtype), [-1, nb_features]) else: search_domain = tf.reshape( tf.cast(x > clip_min, tf_dtype), [-1, nb_features]) # Loop variables # x_in: the tensor that holds the latest adversarial outputs that are in # progress. # y_in: the tensor for target labels # domain_in: the tensor that holds the latest search domain # cond_in: the boolean tensor to show if more iteration is needed for # generating adversarial samples def condition(x_in, y_in, domain_in, i_in, cond_in): # Repeat the loop until we have achieved misclassification or # reaches the maximum iterations return tf.logical_and(tf.less(i_in, max_iters), cond_in) # Same loop variables as above def body(x_in, y_in, domain_in, i_in, cond_in): # Create graph for model logits and predictions logits = model.get_logits(x_in) preds = tf.nn.softmax(logits) preds_onehot = tf.one_hot(tf.argmax(preds, axis=1), depth=nb_classes) # create the Jacobian graph list_derivatives = [] for class_ind in xrange(nb_classes): derivatives = tf.gradients(logits[:, class_ind], x_in) list_derivatives.append(derivatives[0]) grads = tf.reshape( tf.stack(list_derivatives), shape=[nb_classes, -1, nb_features]) # Compute the Jacobian components # To help with the computation later, reshape the target_class # and other_class to [nb_classes, -1, 1]. # The last dimention is added to allow broadcasting later. target_class = tf.reshape( tf.transpose(y_in, perm=[1, 0]), shape=[nb_classes, -1, 1]) other_classes = tf.cast(tf.not_equal(target_class, 1), tf_dtype) grads_target = reduce_sum(grads * target_class, axis=0) grads_other = reduce_sum(grads * other_classes, axis=0) # Remove the already-used input features from the search space # Subtract 2 times the maximum value from those value so that # they won't be picked later increase_coef = (4 * int(increase) - 2) \ * tf.cast(tf.equal(domain_in, 0), tf_dtype) target_tmp = grads_target target_tmp -= increase_coef \ * reduce_max(tf.abs(grads_target), axis=1, keepdims=True) target_sum = tf.reshape(target_tmp, shape=[-1, nb_features, 1]) \ + tf.reshape(target_tmp, shape=[-1, 1, nb_features]) other_tmp = grads_other other_tmp += increase_coef \ * reduce_max(tf.abs(grads_other), axis=1, keepdims=True) other_sum = tf.reshape(other_tmp, shape=[-1, nb_features, 1]) \ + tf.reshape(other_tmp, shape=[-1, 1, nb_features]) # Create a mask to only keep features that match conditions if increase: scores_mask = ((target_sum > 0) & (other_sum < 0)) else: scores_mask = ((target_sum < 0) & (other_sum > 0)) # Create a 2D numpy array of scores for each pair of candidate features scores = tf.cast(scores_mask, tf_dtype) \ * (-target_sum * other_sum) * zero_diagonal # Extract the best two pixels best = tf.argmax( tf.reshape(scores, shape=[-1, nb_features * nb_features]), axis=1) p1 = tf.mod(best, nb_features) p2 = tf.floordiv(best, nb_features) p1_one_hot = tf.one_hot(p1, depth=nb_features) p2_one_hot = tf.one_hot(p2, depth=nb_features) # Check if more modification is needed for each sample mod_not_done = tf.equal(reduce_sum(y_in * preds_onehot, axis=1), 0) cond = mod_not_done & (reduce_sum(domain_in, axis=1) >= 2) # Update the search domain cond_float = tf.reshape(tf.cast(cond, tf_dtype), shape=[-1, 1]) to_mod = (p1_one_hot + p2_one_hot) * cond_float domain_out = domain_in - to_mod # Apply the modification to the images to_mod_reshape = tf.reshape( to_mod, shape=([-1] + x_in.shape[1:].as_list())) if increase: x_out = tf.minimum(clip_max, x_in + to_mod_reshape * theta) else: x_out = tf.maximum(clip_min, x_in - to_mod_reshape * theta) # Increase the iterator, and check if all misclassifications are done i_out = tf.add(i_in, 1) cond_out = reduce_any(cond) return x_out, y_in, domain_out, i_out, cond_out # Run loop to do JSMA x_adv, _, _, _, _ = tf.while_loop( condition, body, [x, y_target, search_domain, 0, True], parallel_iterations=1) return x_adv
[ "def", "jsma_symbolic", "(", "x", ",", "y_target", ",", "model", ",", "theta", ",", "gamma", ",", "clip_min", ",", "clip_max", ")", ":", "nb_classes", "=", "int", "(", "y_target", ".", "shape", "[", "-", "1", "]", ".", "value", ")", "nb_features", "=", "int", "(", "np", ".", "product", "(", "x", ".", "shape", "[", "1", ":", "]", ")", ".", "value", ")", "if", "x", ".", "dtype", "==", "tf", ".", "float32", "and", "y_target", ".", "dtype", "==", "tf", ".", "int64", ":", "y_target", "=", "tf", ".", "cast", "(", "y_target", ",", "tf", ".", "int32", ")", "if", "x", ".", "dtype", "==", "tf", ".", "float32", "and", "y_target", ".", "dtype", "==", "tf", ".", "float64", ":", "warnings", ".", "warn", "(", "\"Downcasting labels---this should be harmless unless\"", "\" they are smoothed\"", ")", "y_target", "=", "tf", ".", "cast", "(", "y_target", ",", "tf", ".", "float32", ")", "max_iters", "=", "np", ".", "floor", "(", "nb_features", "*", "gamma", "/", "2", ")", "increase", "=", "bool", "(", "theta", ">", "0", ")", "tmp", "=", "np", ".", "ones", "(", "(", "nb_features", ",", "nb_features", ")", ",", "int", ")", "np", ".", "fill_diagonal", "(", "tmp", ",", "0", ")", "zero_diagonal", "=", "tf", ".", "constant", "(", "tmp", ",", "tf_dtype", ")", "# Compute our initial search domain. We optimize the initial search domain", "# by removing all features that are already at their maximum values (if", "# increasing input features---otherwise, at their minimum value).", "if", "increase", ":", "search_domain", "=", "tf", ".", "reshape", "(", "tf", ".", "cast", "(", "x", "<", "clip_max", ",", "tf_dtype", ")", ",", "[", "-", "1", ",", "nb_features", "]", ")", "else", ":", "search_domain", "=", "tf", ".", "reshape", "(", "tf", ".", "cast", "(", "x", ">", "clip_min", ",", "tf_dtype", ")", ",", "[", "-", "1", ",", "nb_features", "]", ")", "# Loop variables", "# x_in: the tensor that holds the latest adversarial outputs that are in", "# progress.", "# y_in: the tensor for target labels", "# domain_in: the tensor that holds the latest search domain", "# cond_in: the boolean tensor to show if more iteration is needed for", "# generating adversarial samples", "def", "condition", "(", "x_in", ",", "y_in", ",", "domain_in", ",", "i_in", ",", "cond_in", ")", ":", "# Repeat the loop until we have achieved misclassification or", "# reaches the maximum iterations", "return", "tf", ".", "logical_and", "(", "tf", ".", "less", "(", "i_in", ",", "max_iters", ")", ",", "cond_in", ")", "# Same loop variables as above", "def", "body", "(", "x_in", ",", "y_in", ",", "domain_in", ",", "i_in", ",", "cond_in", ")", ":", "# Create graph for model logits and predictions", "logits", "=", "model", ".", "get_logits", "(", "x_in", ")", "preds", "=", "tf", ".", "nn", ".", "softmax", "(", "logits", ")", "preds_onehot", "=", "tf", ".", "one_hot", "(", "tf", ".", "argmax", "(", "preds", ",", "axis", "=", "1", ")", ",", "depth", "=", "nb_classes", ")", "# create the Jacobian graph", "list_derivatives", "=", "[", "]", "for", "class_ind", "in", "xrange", "(", "nb_classes", ")", ":", "derivatives", "=", "tf", ".", "gradients", "(", "logits", "[", ":", ",", "class_ind", "]", ",", "x_in", ")", "list_derivatives", ".", "append", "(", "derivatives", "[", "0", "]", ")", "grads", "=", "tf", ".", "reshape", "(", "tf", ".", "stack", "(", "list_derivatives", ")", ",", "shape", "=", "[", "nb_classes", ",", "-", "1", ",", "nb_features", "]", ")", "# Compute the Jacobian components", "# To help with the computation later, reshape the target_class", "# and other_class to [nb_classes, -1, 1].", "# The last dimention is added to allow broadcasting later.", "target_class", "=", "tf", ".", "reshape", "(", "tf", ".", "transpose", "(", "y_in", ",", "perm", "=", "[", "1", ",", "0", "]", ")", ",", "shape", "=", "[", "nb_classes", ",", "-", "1", ",", "1", "]", ")", "other_classes", "=", "tf", ".", "cast", "(", "tf", ".", "not_equal", "(", "target_class", ",", "1", ")", ",", "tf_dtype", ")", "grads_target", "=", "reduce_sum", "(", "grads", "*", "target_class", ",", "axis", "=", "0", ")", "grads_other", "=", "reduce_sum", "(", "grads", "*", "other_classes", ",", "axis", "=", "0", ")", "# Remove the already-used input features from the search space", "# Subtract 2 times the maximum value from those value so that", "# they won't be picked later", "increase_coef", "=", "(", "4", "*", "int", "(", "increase", ")", "-", "2", ")", "*", "tf", ".", "cast", "(", "tf", ".", "equal", "(", "domain_in", ",", "0", ")", ",", "tf_dtype", ")", "target_tmp", "=", "grads_target", "target_tmp", "-=", "increase_coef", "*", "reduce_max", "(", "tf", ".", "abs", "(", "grads_target", ")", ",", "axis", "=", "1", ",", "keepdims", "=", "True", ")", "target_sum", "=", "tf", ".", "reshape", "(", "target_tmp", ",", "shape", "=", "[", "-", "1", ",", "nb_features", ",", "1", "]", ")", "+", "tf", ".", "reshape", "(", "target_tmp", ",", "shape", "=", "[", "-", "1", ",", "1", ",", "nb_features", "]", ")", "other_tmp", "=", "grads_other", "other_tmp", "+=", "increase_coef", "*", "reduce_max", "(", "tf", ".", "abs", "(", "grads_other", ")", ",", "axis", "=", "1", ",", "keepdims", "=", "True", ")", "other_sum", "=", "tf", ".", "reshape", "(", "other_tmp", ",", "shape", "=", "[", "-", "1", ",", "nb_features", ",", "1", "]", ")", "+", "tf", ".", "reshape", "(", "other_tmp", ",", "shape", "=", "[", "-", "1", ",", "1", ",", "nb_features", "]", ")", "# Create a mask to only keep features that match conditions", "if", "increase", ":", "scores_mask", "=", "(", "(", "target_sum", ">", "0", ")", "&", "(", "other_sum", "<", "0", ")", ")", "else", ":", "scores_mask", "=", "(", "(", "target_sum", "<", "0", ")", "&", "(", "other_sum", ">", "0", ")", ")", "# Create a 2D numpy array of scores for each pair of candidate features", "scores", "=", "tf", ".", "cast", "(", "scores_mask", ",", "tf_dtype", ")", "*", "(", "-", "target_sum", "*", "other_sum", ")", "*", "zero_diagonal", "# Extract the best two pixels", "best", "=", "tf", ".", "argmax", "(", "tf", ".", "reshape", "(", "scores", ",", "shape", "=", "[", "-", "1", ",", "nb_features", "*", "nb_features", "]", ")", ",", "axis", "=", "1", ")", "p1", "=", "tf", ".", "mod", "(", "best", ",", "nb_features", ")", "p2", "=", "tf", ".", "floordiv", "(", "best", ",", "nb_features", ")", "p1_one_hot", "=", "tf", ".", "one_hot", "(", "p1", ",", "depth", "=", "nb_features", ")", "p2_one_hot", "=", "tf", ".", "one_hot", "(", "p2", ",", "depth", "=", "nb_features", ")", "# Check if more modification is needed for each sample", "mod_not_done", "=", "tf", ".", "equal", "(", "reduce_sum", "(", "y_in", "*", "preds_onehot", ",", "axis", "=", "1", ")", ",", "0", ")", "cond", "=", "mod_not_done", "&", "(", "reduce_sum", "(", "domain_in", ",", "axis", "=", "1", ")", ">=", "2", ")", "# Update the search domain", "cond_float", "=", "tf", ".", "reshape", "(", "tf", ".", "cast", "(", "cond", ",", "tf_dtype", ")", ",", "shape", "=", "[", "-", "1", ",", "1", "]", ")", "to_mod", "=", "(", "p1_one_hot", "+", "p2_one_hot", ")", "*", "cond_float", "domain_out", "=", "domain_in", "-", "to_mod", "# Apply the modification to the images", "to_mod_reshape", "=", "tf", ".", "reshape", "(", "to_mod", ",", "shape", "=", "(", "[", "-", "1", "]", "+", "x_in", ".", "shape", "[", "1", ":", "]", ".", "as_list", "(", ")", ")", ")", "if", "increase", ":", "x_out", "=", "tf", ".", "minimum", "(", "clip_max", ",", "x_in", "+", "to_mod_reshape", "*", "theta", ")", "else", ":", "x_out", "=", "tf", ".", "maximum", "(", "clip_min", ",", "x_in", "-", "to_mod_reshape", "*", "theta", ")", "# Increase the iterator, and check if all misclassifications are done", "i_out", "=", "tf", ".", "add", "(", "i_in", ",", "1", ")", "cond_out", "=", "reduce_any", "(", "cond", ")", "return", "x_out", ",", "y_in", ",", "domain_out", ",", "i_out", ",", "cond_out", "# Run loop to do JSMA", "x_adv", ",", "_", ",", "_", ",", "_", ",", "_", "=", "tf", ".", "while_loop", "(", "condition", ",", "body", ",", "[", "x", ",", "y_target", ",", "search_domain", ",", "0", ",", "True", "]", ",", "parallel_iterations", "=", "1", ")", "return", "x_adv" ]
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 float between 0 - 1 indicating the maximum distortion percentage :param clip_min: minimum value for components of the example returned :param clip_max: maximum value for components of the example returned :return: a tensor for the adversarial example
[ "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: # Create random targets if y_target not provided if self.y_target is None: from random import randint def random_targets(gt): result = gt.copy() nb_s = gt.shape[0] nb_classes = gt.shape[1] for i in range(nb_s): result[i, :] = np.roll(result[i, :], randint(1, nb_classes - 1)) return result labels, nb_classes = self.get_or_guess_labels(x, kwargs) self.y_target = tf.py_func(random_targets, [labels], self.tf_dtype) self.y_target.set_shape([None, nb_classes]) x_adv = jsma_symbolic( x, model=self.model, y_target=self.y_target, theta=self.theta, gamma=self.gamma, clip_min=self.clip_min, clip_max=self.clip_max) else: raise NotImplementedError("The jsma_batch function has been removed." " The symbolic_impl argument to SaliencyMapMethod will be removed" " on 2019-07-18 or after. Any code that depends on the non-symbolic" " implementation of the JSMA should be revised. Consider using" " SaliencyMapMethod.generate_np() instead.") return x_adv
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: # Create random targets if y_target not provided if self.y_target is None: from random import randint def random_targets(gt): result = gt.copy() nb_s = gt.shape[0] nb_classes = gt.shape[1] for i in range(nb_s): result[i, :] = np.roll(result[i, :], randint(1, nb_classes - 1)) return result labels, nb_classes = self.get_or_guess_labels(x, kwargs) self.y_target = tf.py_func(random_targets, [labels], self.tf_dtype) self.y_target.set_shape([None, nb_classes]) x_adv = jsma_symbolic( x, model=self.model, y_target=self.y_target, theta=self.theta, gamma=self.gamma, clip_min=self.clip_min, clip_max=self.clip_max) else: raise NotImplementedError("The jsma_batch function has been removed." " The symbolic_impl argument to SaliencyMapMethod will be removed" " on 2019-07-18 or after. Any code that depends on the non-symbolic" " implementation of the JSMA should be revised. Consider using" " SaliencyMapMethod.generate_np() instead.") return x_adv
[ "def", "generate", "(", "self", ",", "x", ",", "*", "*", "kwargs", ")", ":", "# Parse and save attack-specific parameters", "assert", "self", ".", "parse_params", "(", "*", "*", "kwargs", ")", "if", "self", ".", "symbolic_impl", ":", "# Create random targets if y_target not provided", "if", "self", ".", "y_target", "is", "None", ":", "from", "random", "import", "randint", "def", "random_targets", "(", "gt", ")", ":", "result", "=", "gt", ".", "copy", "(", ")", "nb_s", "=", "gt", ".", "shape", "[", "0", "]", "nb_classes", "=", "gt", ".", "shape", "[", "1", "]", "for", "i", "in", "range", "(", "nb_s", ")", ":", "result", "[", "i", ",", ":", "]", "=", "np", ".", "roll", "(", "result", "[", "i", ",", ":", "]", ",", "randint", "(", "1", ",", "nb_classes", "-", "1", ")", ")", "return", "result", "labels", ",", "nb_classes", "=", "self", ".", "get_or_guess_labels", "(", "x", ",", "kwargs", ")", "self", ".", "y_target", "=", "tf", ".", "py_func", "(", "random_targets", ",", "[", "labels", "]", ",", "self", ".", "tf_dtype", ")", "self", ".", "y_target", ".", "set_shape", "(", "[", "None", ",", "nb_classes", "]", ")", "x_adv", "=", "jsma_symbolic", "(", "x", ",", "model", "=", "self", ".", "model", ",", "y_target", "=", "self", ".", "y_target", ",", "theta", "=", "self", ".", "theta", ",", "gamma", "=", "self", ".", "gamma", ",", "clip_min", "=", "self", ".", "clip_min", ",", "clip_max", "=", "self", ".", "clip_max", ")", "else", ":", "raise", "NotImplementedError", "(", "\"The jsma_batch function has been removed.\"", "\" The symbolic_impl argument to SaliencyMapMethod will be removed\"", "\" on 2019-07-18 or after. Any code that depends on the non-symbolic\"", "\" implementation of the JSMA should be revised. Consider using\"", "\" SaliencyMapMethod.generate_np() instead.\"", ")", "return", "x_adv" ]
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-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 percentage of perturbed features :param clip_min: (optional float) Minimum component value for clipping :param clip_max: (optional float) Maximum component value for clipping :param y_target: (optional) Target tensor if the attack is targeted """ self.theta = theta self.gamma = gamma self.clip_min = clip_min self.clip_max = clip_max self.y_target = y_target self.symbolic_impl = symbolic_impl if len(kwargs.keys()) > 0: warnings.warn("kwargs is unused and will be removed on or after " "2019-04-26.") return True
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-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 percentage of perturbed features :param clip_min: (optional float) Minimum component value for clipping :param clip_max: (optional float) Maximum component value for clipping :param y_target: (optional) Target tensor if the attack is targeted """ self.theta = theta self.gamma = gamma self.clip_min = clip_min self.clip_max = clip_max self.y_target = y_target self.symbolic_impl = symbolic_impl if len(kwargs.keys()) > 0: warnings.warn("kwargs is unused and will be removed on or after " "2019-04-26.") return True
[ "def", "parse_params", "(", "self", ",", "theta", "=", "1.", ",", "gamma", "=", "1.", ",", "clip_min", "=", "0.", ",", "clip_max", "=", "1.", ",", "y_target", "=", "None", ",", "symbolic_impl", "=", "True", ",", "*", "*", "kwargs", ")", ":", "self", ".", "theta", "=", "theta", "self", ".", "gamma", "=", "gamma", "self", ".", "clip_min", "=", "clip_min", "self", ".", "clip_max", "=", "clip_max", "self", ".", "y_target", "=", "y_target", "self", ".", "symbolic_impl", "=", "symbolic_impl", "if", "len", "(", "kwargs", ".", "keys", "(", ")", ")", ">", "0", ":", "warnings", ".", "warn", "(", "\"kwargs is unused and will be removed on or after \"", "\"2019-04-26.\"", ")", "return", "True" ]
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 percentage of perturbed features :param clip_min: (optional float) Minimum component value for clipping :param clip_max: (optional float) Maximum component value for clipping :param y_target: (optional) Target tensor if the attack is targeted
[ "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", "model", "=", "MLPnGPU", "(", "nb_classes", ",", "layers", ",", "input_shape", ")", "return", "model" ]
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), "SAME"), ReLU(), MaxPool((2, 2), (2, 2), "SAME"), Flatten(), LinearnGPU(1024), ReLU(), LinearnGPU(nb_classes), Softmax()] model = MLPnGPU(nb_classes, layers, input_shape) return model
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), "SAME"), ReLU(), MaxPool((2, 2), (2, 2), "SAME"), Flatten(), LinearnGPU(1024), ReLU(), LinearnGPU(nb_classes), Softmax()] model = MLPnGPU(nb_classes, layers, input_shape) return model
[ "def", "make_madry_ngpu", "(", "nb_classes", "=", "10", ",", "input_shape", "=", "(", "None", ",", "28", ",", "28", ",", "1", ")", ",", "*", "*", "kwargs", ")", ":", "layers", "=", "[", "Conv2DnGPU", "(", "32", ",", "(", "5", ",", "5", ")", ",", "(", "1", ",", "1", ")", ",", "\"SAME\"", ")", ",", "ReLU", "(", ")", ",", "MaxPool", "(", "(", "2", ",", "2", ")", ",", "(", "2", ",", "2", ")", ",", "\"SAME\"", ")", ",", "Conv2DnGPU", "(", "64", ",", "(", "5", ",", "5", ")", ",", "(", "1", ",", "1", ")", ",", "\"SAME\"", ")", ",", "ReLU", "(", ")", ",", "MaxPool", "(", "(", "2", ",", "2", ")", ",", "(", "2", ",", "2", ")", ",", "\"SAME\"", ")", ",", "Flatten", "(", ")", ",", "LinearnGPU", "(", "1024", ")", ",", "ReLU", "(", ")", ",", "LinearnGPU", "(", "nb_classes", ")", ",", "Softmax", "(", ")", "]", "model", "=", "MLPnGPU", "(", "nb_classes", ",", "layers", ",", "input_shape", ")", "return", "model" ]
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: res_func = self._bottleneck_residual filters = [16, 64, 128, 256] else: res_func = self._residual filters = [16, 16, 32, 64] # Uncomment the following codes to use w28-10 wide residual # network. # It is more memory efficient than very deep residual network and # has # comparably good performance. # https://arxiv.org/pdf/1605.07146v1.pdf # filters = [16, 160, 320, 640] # Update hps.num_residual_units to 4 with tf.variable_scope('unit_1_0'): x = res_func(x, filters[0], filters[1], self._stride_arr(strides[0]), activate_before_residual[0]) for i in six.moves.range(1, self.hps.num_residual_units): with tf.variable_scope('unit_1_%d' % i): x = res_func(x, filters[1], filters[1], self._stride_arr(1), False) with tf.variable_scope('unit_2_0'): x = res_func(x, filters[1], filters[2], self._stride_arr(strides[1]), activate_before_residual[1]) for i in six.moves.range(1, self.hps.num_residual_units): with tf.variable_scope('unit_2_%d' % i): x = res_func(x, filters[2], filters[2], self._stride_arr(1), False) with tf.variable_scope('unit_3_0'): x = res_func(x, filters[2], filters[3], self._stride_arr(strides[2]), activate_before_residual[2]) for i in six.moves.range(1, self.hps.num_residual_units): with tf.variable_scope('unit_3_%d' % i): x = res_func(x, filters[3], filters[3], self._stride_arr(1), False) with tf.variable_scope('unit_last'): x = self._layer_norm('final_bn', x) x = self._relu(x, self.hps.relu_leakiness) x = self._global_avg_pool(x) with tf.variable_scope('logit'): logits = self._fully_connected(x, self.hps.nb_classes) predictions = tf.nn.softmax(logits) return logits, predictions
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: res_func = self._bottleneck_residual filters = [16, 64, 128, 256] else: res_func = self._residual filters = [16, 16, 32, 64] # Uncomment the following codes to use w28-10 wide residual # network. # It is more memory efficient than very deep residual network and # has # comparably good performance. # https://arxiv.org/pdf/1605.07146v1.pdf # filters = [16, 160, 320, 640] # Update hps.num_residual_units to 4 with tf.variable_scope('unit_1_0'): x = res_func(x, filters[0], filters[1], self._stride_arr(strides[0]), activate_before_residual[0]) for i in six.moves.range(1, self.hps.num_residual_units): with tf.variable_scope('unit_1_%d' % i): x = res_func(x, filters[1], filters[1], self._stride_arr(1), False) with tf.variable_scope('unit_2_0'): x = res_func(x, filters[1], filters[2], self._stride_arr(strides[1]), activate_before_residual[1]) for i in six.moves.range(1, self.hps.num_residual_units): with tf.variable_scope('unit_2_%d' % i): x = res_func(x, filters[2], filters[2], self._stride_arr(1), False) with tf.variable_scope('unit_3_0'): x = res_func(x, filters[2], filters[3], self._stride_arr(strides[2]), activate_before_residual[2]) for i in six.moves.range(1, self.hps.num_residual_units): with tf.variable_scope('unit_3_%d' % i): x = res_func(x, filters[3], filters[3], self._stride_arr(1), False) with tf.variable_scope('unit_last'): x = self._layer_norm('final_bn', x) x = self._relu(x, self.hps.relu_leakiness) x = self._global_avg_pool(x) with tf.variable_scope('logit'): logits = self._fully_connected(x, self.hps.nb_classes) predictions = tf.nn.softmax(logits) return logits, predictions
[ "def", "_build_model", "(", "self", ",", "x", ")", ":", "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", ":", "res_func", "=", "self", ".", "_bottleneck_residual", "filters", "=", "[", "16", ",", "64", ",", "128", ",", "256", "]", "else", ":", "res_func", "=", "self", ".", "_residual", "filters", "=", "[", "16", ",", "16", ",", "32", ",", "64", "]", "# Uncomment the following codes to use w28-10 wide residual", "# network.", "# It is more memory efficient than very deep residual network and", "# has", "# comparably good performance.", "# https://arxiv.org/pdf/1605.07146v1.pdf", "# filters = [16, 160, 320, 640]", "# Update hps.num_residual_units to 4", "with", "tf", ".", "variable_scope", "(", "'unit_1_0'", ")", ":", "x", "=", "res_func", "(", "x", ",", "filters", "[", "0", "]", ",", "filters", "[", "1", "]", ",", "self", ".", "_stride_arr", "(", "strides", "[", "0", "]", ")", ",", "activate_before_residual", "[", "0", "]", ")", "for", "i", "in", "six", ".", "moves", ".", "range", "(", "1", ",", "self", ".", "hps", ".", "num_residual_units", ")", ":", "with", "tf", ".", "variable_scope", "(", "'unit_1_%d'", "%", "i", ")", ":", "x", "=", "res_func", "(", "x", ",", "filters", "[", "1", "]", ",", "filters", "[", "1", "]", ",", "self", ".", "_stride_arr", "(", "1", ")", ",", "False", ")", "with", "tf", ".", "variable_scope", "(", "'unit_2_0'", ")", ":", "x", "=", "res_func", "(", "x", ",", "filters", "[", "1", "]", ",", "filters", "[", "2", "]", ",", "self", ".", "_stride_arr", "(", "strides", "[", "1", "]", ")", ",", "activate_before_residual", "[", "1", "]", ")", "for", "i", "in", "six", ".", "moves", ".", "range", "(", "1", ",", "self", ".", "hps", ".", "num_residual_units", ")", ":", "with", "tf", ".", "variable_scope", "(", "'unit_2_%d'", "%", "i", ")", ":", "x", "=", "res_func", "(", "x", ",", "filters", "[", "2", "]", ",", "filters", "[", "2", "]", ",", "self", ".", "_stride_arr", "(", "1", ")", ",", "False", ")", "with", "tf", ".", "variable_scope", "(", "'unit_3_0'", ")", ":", "x", "=", "res_func", "(", "x", ",", "filters", "[", "2", "]", ",", "filters", "[", "3", "]", ",", "self", ".", "_stride_arr", "(", "strides", "[", "2", "]", ")", ",", "activate_before_residual", "[", "2", "]", ")", "for", "i", "in", "six", ".", "moves", ".", "range", "(", "1", ",", "self", ".", "hps", ".", "num_residual_units", ")", ":", "with", "tf", ".", "variable_scope", "(", "'unit_3_%d'", "%", "i", ")", ":", "x", "=", "res_func", "(", "x", ",", "filters", "[", "3", "]", ",", "filters", "[", "3", "]", ",", "self", ".", "_stride_arr", "(", "1", ")", ",", "False", ")", "with", "tf", ".", "variable_scope", "(", "'unit_last'", ")", ":", "x", "=", "self", ".", "_layer_norm", "(", "'final_bn'", ",", "x", ")", "x", "=", "self", ".", "_relu", "(", "x", ",", "self", ".", "hps", ".", "relu_leakiness", ")", "x", "=", "self", ".", "_global_avg_pool", "(", "x", ")", "with", "tf", ".", "variable_scope", "(", "'logit'", ")", ":", "logits", "=", "self", ".", "_fully_connected", "(", "x", ",", "self", ".", "hps", ".", "nb_classes", ")", "predictions", "=", "tf", ".", "nn", ".", "softmax", "(", "logits", ")", "return", "logits", ",", "predictions" ]
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'): xent = tf.nn.softmax_cross_entropy_with_logits( logits=logits, labels=labels) cost = tf.reduce_mean(xent, name='xent') cost += self._decay() cost = cost return cost
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'): xent = tf.nn.softmax_cross_entropy_with_logits( logits=logits, labels=labels) cost = tf.reduce_mean(xent, name='xent') cost += self._decay() cost = cost return cost
[ "def", "build_cost", "(", "self", ",", "labels", ",", "logits", ")", ":", "op", "=", "logits", ".", "op", "if", "\"softmax\"", "in", "str", "(", "op", ")", ".", "lower", "(", ")", ":", "logits", ",", "=", "op", ".", "inputs", "with", "tf", ".", "variable_scope", "(", "'costs'", ")", ":", "xent", "=", "tf", ".", "nn", ".", "softmax_cross_entropy_with_logits", "(", "logits", "=", "logits", ",", "labels", "=", "labels", ")", "cost", "=", "tf", ".", "reduce_mean", "(", "xent", ",", "name", "=", "'xent'", ")", "cost", "+=", "self", ".", "_decay", "(", ")", "cost", "=", "cost", "return", "cost" ]
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='momentum') trainable_variables = tf.trainable_variables() grads = tf.gradients(cost, trainable_variables) devs = {v.device for v in trainable_variables} assert len(devs) == 1, ('There should be no trainable variables' ' on any device other than the last GPU.') optimizer = tf.train.MomentumOptimizer(self.lrn_rate, self.momentum) gv_pairs = zip(grads, trainable_variables) gv_pairs = [gv for gv in gv_pairs if gv[0] is not None] devs = {gv[1].device for gv in gv_pairs} assert len(devs) == 1, ('There should be no gradients wrt' ' vars on other GPUs.') apply_op = optimizer.apply_gradients( gv_pairs, global_step=self.global_step, name='train_step') train_ops = [apply_op] train_op = tf.group(*train_ops) return train_op
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='momentum') trainable_variables = tf.trainable_variables() grads = tf.gradients(cost, trainable_variables) devs = {v.device for v in trainable_variables} assert len(devs) == 1, ('There should be no trainable variables' ' on any device other than the last GPU.') optimizer = tf.train.MomentumOptimizer(self.lrn_rate, self.momentum) gv_pairs = zip(grads, trainable_variables) gv_pairs = [gv for gv in gv_pairs if gv[0] is not None] devs = {gv[1].device for gv in gv_pairs} assert len(devs) == 1, ('There should be no gradients wrt' ' vars on other GPUs.') apply_op = optimizer.apply_gradients( gv_pairs, global_step=self.global_step, name='train_step') train_ops = [apply_op] train_op = tf.group(*train_ops) return train_op
[ "def", "build_train_op_from_cost", "(", "self", ",", "cost", ")", ":", "self", ".", "lrn_rate", "=", "tf", ".", "constant", "(", "self", ".", "hps", ".", "lrn_rate", ",", "tf", ".", "float32", ",", "name", "=", "'learning_rate'", ")", "self", ".", "momentum", "=", "tf", ".", "constant", "(", "self", ".", "hps", ".", "momentum", ",", "tf", ".", "float32", ",", "name", "=", "'momentum'", ")", "trainable_variables", "=", "tf", ".", "trainable_variables", "(", ")", "grads", "=", "tf", ".", "gradients", "(", "cost", ",", "trainable_variables", ")", "devs", "=", "{", "v", ".", "device", "for", "v", "in", "trainable_variables", "}", "assert", "len", "(", "devs", ")", "==", "1", ",", "(", "'There should be no trainable variables'", "' on any device other than the last GPU.'", ")", "optimizer", "=", "tf", ".", "train", ".", "MomentumOptimizer", "(", "self", ".", "lrn_rate", ",", "self", ".", "momentum", ")", "gv_pairs", "=", "zip", "(", "grads", ",", "trainable_variables", ")", "gv_pairs", "=", "[", "gv", "for", "gv", "in", "gv_pairs", "if", "gv", "[", "0", "]", "is", "not", "None", "]", "devs", "=", "{", "gv", "[", "1", "]", ".", "device", "for", "gv", "in", "gv_pairs", "}", "assert", "len", "(", "devs", ")", "==", "1", ",", "(", "'There should be no gradients wrt'", "' vars on other GPUs.'", ")", "apply_op", "=", "optimizer", ".", "apply_gradients", "(", "gv_pairs", ",", "global_step", "=", "self", ".", "global_step", ",", "name", "=", "'train_step'", ")", "train_ops", "=", "[", "apply_op", "]", "train_op", "=", "tf", ".", "group", "(", "*", "train_ops", ")", "return", "train_op" ]
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.fprop(x) return x
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.fprop(x) return x
[ "def", "_layer_norm", "(", "self", ",", "name", ",", "x", ")", ":", "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", ".", "fprop", "(", "x", ")", "return", "x" ]
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_leakiness) orig_x = x else: with tf.variable_scope('residual_only_activation'): orig_x = x x = self._layer_norm('init_bn', x) x = self._relu(x, self.hps.relu_leakiness) with tf.variable_scope('sub1'): x = self._conv('conv1', x, 3, in_filter, out_filter, stride) with tf.variable_scope('sub2'): x = self._layer_norm('bn2', x) x = self._relu(x, self.hps.relu_leakiness) x = self._conv('conv2', x, 3, out_filter, out_filter, [1, 1, 1, 1]) with tf.variable_scope('sub_add'): if in_filter != out_filter: orig_x = tf.nn.avg_pool(orig_x, stride, stride, 'VALID') orig_x = tf.pad( orig_x, [[0, 0], [0, 0], [0, 0], [(out_filter - in_filter) // 2, (out_filter - in_filter) // 2]]) x += orig_x return x
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_leakiness) orig_x = x else: with tf.variable_scope('residual_only_activation'): orig_x = x x = self._layer_norm('init_bn', x) x = self._relu(x, self.hps.relu_leakiness) with tf.variable_scope('sub1'): x = self._conv('conv1', x, 3, in_filter, out_filter, stride) with tf.variable_scope('sub2'): x = self._layer_norm('bn2', x) x = self._relu(x, self.hps.relu_leakiness) x = self._conv('conv2', x, 3, out_filter, out_filter, [1, 1, 1, 1]) with tf.variable_scope('sub_add'): if in_filter != out_filter: orig_x = tf.nn.avg_pool(orig_x, stride, stride, 'VALID') orig_x = tf.pad( orig_x, [[0, 0], [0, 0], [0, 0], [(out_filter - in_filter) // 2, (out_filter - in_filter) // 2]]) x += orig_x return x
[ "def", "_residual", "(", "self", ",", "x", ",", "in_filter", ",", "out_filter", ",", "stride", ",", "activate_before_residual", "=", "False", ")", ":", "if", "activate_before_residual", ":", "with", "tf", ".", "variable_scope", "(", "'shared_activation'", ")", ":", "x", "=", "self", ".", "_layer_norm", "(", "'init_bn'", ",", "x", ")", "x", "=", "self", ".", "_relu", "(", "x", ",", "self", ".", "hps", ".", "relu_leakiness", ")", "orig_x", "=", "x", "else", ":", "with", "tf", ".", "variable_scope", "(", "'residual_only_activation'", ")", ":", "orig_x", "=", "x", "x", "=", "self", ".", "_layer_norm", "(", "'init_bn'", ",", "x", ")", "x", "=", "self", ".", "_relu", "(", "x", ",", "self", ".", "hps", ".", "relu_leakiness", ")", "with", "tf", ".", "variable_scope", "(", "'sub1'", ")", ":", "x", "=", "self", ".", "_conv", "(", "'conv1'", ",", "x", ",", "3", ",", "in_filter", ",", "out_filter", ",", "stride", ")", "with", "tf", ".", "variable_scope", "(", "'sub2'", ")", ":", "x", "=", "self", ".", "_layer_norm", "(", "'bn2'", ",", "x", ")", "x", "=", "self", ".", "_relu", "(", "x", ",", "self", ".", "hps", ".", "relu_leakiness", ")", "x", "=", "self", ".", "_conv", "(", "'conv2'", ",", "x", ",", "3", ",", "out_filter", ",", "out_filter", ",", "[", "1", ",", "1", ",", "1", ",", "1", "]", ")", "with", "tf", ".", "variable_scope", "(", "'sub_add'", ")", ":", "if", "in_filter", "!=", "out_filter", ":", "orig_x", "=", "tf", ".", "nn", ".", "avg_pool", "(", "orig_x", ",", "stride", ",", "stride", ",", "'VALID'", ")", "orig_x", "=", "tf", ".", "pad", "(", "orig_x", ",", "[", "[", "0", ",", "0", "]", ",", "[", "0", ",", "0", "]", ",", "[", "0", ",", "0", "]", ",", "[", "(", "out_filter", "-", "in_filter", ")", "//", "2", ",", "(", "out_filter", "-", "in_filter", ")", "//", "2", "]", "]", ")", "x", "+=", "orig_x", "return", "x" ]
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._relu(x, self.hps.relu_leakiness) orig_x = x else: with tf.variable_scope('residual_bn_relu'): orig_x = x x = self._layer_norm('init_bn', x) x = self._relu(x, self.hps.relu_leakiness) with tf.variable_scope('sub1'): x = self._conv('conv1', x, 1, in_filter, out_filter / 4, stride) with tf.variable_scope('sub2'): x = self._layer_norm('bn2', x) x = self._relu(x, self.hps.relu_leakiness) x = self._conv('conv2', x, 3, out_filter / 4, out_filter / 4, [1, 1, 1, 1]) with tf.variable_scope('sub3'): x = self._layer_norm('bn3', x) x = self._relu(x, self.hps.relu_leakiness) x = self._conv('conv3', x, 1, out_filter / 4, out_filter, [1, 1, 1, 1]) with tf.variable_scope('sub_add'): if in_filter != out_filter: orig_x = self._conv('project', orig_x, 1, in_filter, out_filter, stride) x += orig_x return x
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._relu(x, self.hps.relu_leakiness) orig_x = x else: with tf.variable_scope('residual_bn_relu'): orig_x = x x = self._layer_norm('init_bn', x) x = self._relu(x, self.hps.relu_leakiness) with tf.variable_scope('sub1'): x = self._conv('conv1', x, 1, in_filter, out_filter / 4, stride) with tf.variable_scope('sub2'): x = self._layer_norm('bn2', x) x = self._relu(x, self.hps.relu_leakiness) x = self._conv('conv2', x, 3, out_filter / 4, out_filter / 4, [1, 1, 1, 1]) with tf.variable_scope('sub3'): x = self._layer_norm('bn3', x) x = self._relu(x, self.hps.relu_leakiness) x = self._conv('conv3', x, 1, out_filter / 4, out_filter, [1, 1, 1, 1]) with tf.variable_scope('sub_add'): if in_filter != out_filter: orig_x = self._conv('project', orig_x, 1, in_filter, out_filter, stride) x += orig_x return x
[ "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'", ")", ":", "x", "=", "self", ".", "_layer_norm", "(", "'init_bn'", ",", "x", ")", "x", "=", "self", ".", "_relu", "(", "x", ",", "self", ".", "hps", ".", "relu_leakiness", ")", "orig_x", "=", "x", "else", ":", "with", "tf", ".", "variable_scope", "(", "'residual_bn_relu'", ")", ":", "orig_x", "=", "x", "x", "=", "self", ".", "_layer_norm", "(", "'init_bn'", ",", "x", ")", "x", "=", "self", ".", "_relu", "(", "x", ",", "self", ".", "hps", ".", "relu_leakiness", ")", "with", "tf", ".", "variable_scope", "(", "'sub1'", ")", ":", "x", "=", "self", ".", "_conv", "(", "'conv1'", ",", "x", ",", "1", ",", "in_filter", ",", "out_filter", "/", "4", ",", "stride", ")", "with", "tf", ".", "variable_scope", "(", "'sub2'", ")", ":", "x", "=", "self", ".", "_layer_norm", "(", "'bn2'", ",", "x", ")", "x", "=", "self", ".", "_relu", "(", "x", ",", "self", ".", "hps", ".", "relu_leakiness", ")", "x", "=", "self", ".", "_conv", "(", "'conv2'", ",", "x", ",", "3", ",", "out_filter", "/", "4", ",", "out_filter", "/", "4", ",", "[", "1", ",", "1", ",", "1", ",", "1", "]", ")", "with", "tf", ".", "variable_scope", "(", "'sub3'", ")", ":", "x", "=", "self", ".", "_layer_norm", "(", "'bn3'", ",", "x", ")", "x", "=", "self", ".", "_relu", "(", "x", ",", "self", ".", "hps", ".", "relu_leakiness", ")", "x", "=", "self", ".", "_conv", "(", "'conv3'", ",", "x", ",", "1", ",", "out_filter", "/", "4", ",", "out_filter", ",", "[", "1", ",", "1", ",", "1", ",", "1", "]", ")", "with", "tf", ".", "variable_scope", "(", "'sub_add'", ")", ":", "if", "in_filter", "!=", "out_filter", ":", "orig_x", "=", "self", ".", "_conv", "(", "'project'", ",", "orig_x", ",", "1", ",", "in_filter", ",", "out_filter", ",", "stride", ")", "x", "+=", "orig_x", "return", "x" ]
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 self.layers: for var in layer.params_device[self.device_name].values(): if (isinstance(var, tf.Variable) and var.op.name.find(r'DW') > 0): costs.append(tf.nn.l2_loss(var)) self.decay_cost = tf.multiply(self.hps.weight_decay_rate, tf.add_n(costs)) return self.decay_cost
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 self.layers: for var in layer.params_device[self.device_name].values(): if (isinstance(var, tf.Variable) and var.op.name.find(r'DW') > 0): costs.append(tf.nn.l2_loss(var)) self.decay_cost = tf.multiply(self.hps.weight_decay_rate, tf.add_n(costs)) return self.decay_cost
[ "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", ".", "trainable_variables", "(", ")", ":", "if", "var", ".", "op", ".", "name", ".", "find", "(", "r'DW'", ")", ">", "0", ":", "costs", ".", "append", "(", "tf", ".", "nn", ".", "l2_loss", "(", "var", ")", ")", "else", ":", "for", "layer", "in", "self", ".", "layers", ":", "for", "var", "in", "layer", ".", "params_device", "[", "self", ".", "device_name", "]", ".", "values", "(", ")", ":", "if", "(", "isinstance", "(", "var", ",", "tf", ".", "Variable", ")", "and", "var", ".", "op", ".", "name", ".", "find", "(", "r'DW'", ")", ">", "0", ")", ":", "costs", ".", "append", "(", "tf", ".", "nn", ".", "l2_loss", "(", "var", ")", ")", "self", ".", "decay_cost", "=", "tf", ".", "multiply", "(", "self", ".", "hps", ".", "weight_decay_rate", ",", "tf", ".", "add_n", "(", "costs", ")", ")", "return", "self", ".", "decay_cost" ]
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] else: conv = self.layers[self.layer_idx] self.layer_idx += 1 conv.device_name = self.device_name conv.set_training(self.training) return conv.fprop(x)
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] else: conv = self.layers[self.layer_idx] self.layer_idx += 1 conv.device_name = self.device_name conv.set_training(self.training) return conv.fprop(x)
[ "def", "_conv", "(", "self", ",", "name", ",", "x", ",", "filter_size", ",", "in_filters", ",", "out_filters", ",", "strides", ")", ":", "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", "]", "else", ":", "conv", "=", "self", ".", "layers", "[", "self", ".", "layer_idx", "]", "self", ".", "layer_idx", "+=", "1", "conv", ".", "device_name", "=", "self", ".", "device_name", "conv", ".", "set_training", "(", "self", ".", "training", ")", "return", "conv", ".", "fprop", "(", "x", ")" ]
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_name fc.set_training(self.training) return fc.fprop(x)
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_name fc.set_training(self.training) return fc.fprop(x)
[ "def", "_fully_connected", "(", "self", ",", "x", ",", "out_dim", ")", ":", "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_name", "fc", ".", "set_training", "(", "self", ".", "training", ")", "return", "fc", ".", "fprop", "(", "x", ")" ]
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 None for local file file_path: path of the file with results Returns: dictionary where keys are image names or IDs and values are classification labels """ if storage_client: # file on Cloud success = False retry_count = 0 while retry_count < 4: try: blob = storage_client.get_blob(file_path) if not blob: return {} if blob.size > MAX_ALLOWED_CLASSIFICATION_RESULT_SIZE: logging.warning('Skipping classification result because it''s too ' 'big: %d bytes for %s', blob.size, file_path) return None buf = BytesIO() blob.download_to_file(buf) buf.seek(0) success = True break except Exception: retry_count += 1 time.sleep(5) if not success: return None else: # local file try: with open(file_path, 'rb') as f: buf = BytesIO(f.read()) except IOError: return None result = {} if PY3: buf = StringIO(buf.read().decode('UTF-8')) for row in csv.reader(buf): try: image_filename = row[0] if image_filename.endswith('.png') or image_filename.endswith('.jpg'): image_filename = image_filename[:image_filename.rfind('.')] label = int(row[1]) except (IndexError, ValueError): continue result[image_filename] = label return result
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 None for local file file_path: path of the file with results Returns: dictionary where keys are image names or IDs and values are classification labels """ if storage_client: # file on Cloud success = False retry_count = 0 while retry_count < 4: try: blob = storage_client.get_blob(file_path) if not blob: return {} if blob.size > MAX_ALLOWED_CLASSIFICATION_RESULT_SIZE: logging.warning('Skipping classification result because it''s too ' 'big: %d bytes for %s', blob.size, file_path) return None buf = BytesIO() blob.download_to_file(buf) buf.seek(0) success = True break except Exception: retry_count += 1 time.sleep(5) if not success: return None else: # local file try: with open(file_path, 'rb') as f: buf = BytesIO(f.read()) except IOError: return None result = {} if PY3: buf = StringIO(buf.read().decode('UTF-8')) for row in csv.reader(buf): try: image_filename = row[0] if image_filename.endswith('.png') or image_filename.endswith('.jpg'): image_filename = image_filename[:image_filename.rfind('.')] label = int(row[1]) except (IndexError, ValueError): continue result[image_filename] = label return result
[ "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_client", ".", "get_blob", "(", "file_path", ")", "if", "not", "blob", ":", "return", "{", "}", "if", "blob", ".", "size", ">", "MAX_ALLOWED_CLASSIFICATION_RESULT_SIZE", ":", "logging", ".", "warning", "(", "'Skipping classification result because it'", "'s too '", "'big: %d bytes for %s'", ",", "blob", ".", "size", ",", "file_path", ")", "return", "None", "buf", "=", "BytesIO", "(", ")", "blob", ".", "download_to_file", "(", "buf", ")", "buf", ".", "seek", "(", "0", ")", "success", "=", "True", "break", "except", "Exception", ":", "retry_count", "+=", "1", "time", ".", "sleep", "(", "5", ")", "if", "not", "success", ":", "return", "None", "else", ":", "# local file", "try", ":", "with", "open", "(", "file_path", ",", "'rb'", ")", "as", "f", ":", "buf", "=", "BytesIO", "(", "f", ".", "read", "(", ")", ")", "except", "IOError", ":", "return", "None", "result", "=", "{", "}", "if", "PY3", ":", "buf", "=", "StringIO", "(", "buf", ".", "read", "(", ")", ".", "decode", "(", "'UTF-8'", ")", ")", "for", "row", "in", "csv", ".", "reader", "(", "buf", ")", ":", "try", ":", "image_filename", "=", "row", "[", "0", "]", "if", "image_filename", ".", "endswith", "(", "'.png'", ")", "or", "image_filename", ".", "endswith", "(", "'.jpg'", ")", ":", "image_filename", "=", "image_filename", "[", ":", "image_filename", ".", "rfind", "(", "'.'", ")", "]", "label", "=", "int", "(", "row", "[", "1", "]", ")", "except", "(", "IndexError", ",", "ValueError", ")", ":", "continue", "result", "[", "image_filename", "]", "=", "label", "return", "result" ]
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 Returns: dictionary where keys are image names or IDs and values are classification labels
[ "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 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: result file path adv_batch: AversarialBatches.data[adv_batch_id] adv_batch_id is stored in each ClassificationBatch entity dataset_batches: instance of DatasetBatches dataset_meta: instance of DatasetMetadata Returns: Tuple of (count_correctly_classified, count_errors, count_hit_target_class, num_images) """ class_result = read_classification_results(storage_client, file_path) if class_result is None: return 0, 0, 0, 0 adv_images = adv_batch['images'] dataset_batch_images = ( dataset_batches.data[adv_batch['dataset_batch_id']]['images']) count_correctly_classified = 0 count_errors = 0 count_hit_target_class = 0 num_images = 0 for adv_img_id, label in iteritems(class_result): if adv_img_id not in adv_images: continue num_images += 1 clean_image_id = adv_images[adv_img_id]['clean_image_id'] dataset_image_id = ( dataset_batch_images[clean_image_id]['dataset_image_id']) if label == dataset_meta.get_true_label(dataset_image_id): count_correctly_classified += 1 else: count_errors += 1 if label == dataset_meta.get_target_class(dataset_image_id): count_hit_target_class += 1 return (count_correctly_classified, count_errors, count_hit_target_class, num_images)
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 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: result file path adv_batch: AversarialBatches.data[adv_batch_id] adv_batch_id is stored in each ClassificationBatch entity dataset_batches: instance of DatasetBatches dataset_meta: instance of DatasetMetadata Returns: Tuple of (count_correctly_classified, count_errors, count_hit_target_class, num_images) """ class_result = read_classification_results(storage_client, file_path) if class_result is None: return 0, 0, 0, 0 adv_images = adv_batch['images'] dataset_batch_images = ( dataset_batches.data[adv_batch['dataset_batch_id']]['images']) count_correctly_classified = 0 count_errors = 0 count_hit_target_class = 0 num_images = 0 for adv_img_id, label in iteritems(class_result): if adv_img_id not in adv_images: continue num_images += 1 clean_image_id = adv_images[adv_img_id]['clean_image_id'] dataset_image_id = ( dataset_batch_images[clean_image_id]['dataset_image_id']) if label == dataset_meta.get_true_label(dataset_image_id): count_correctly_classified += 1 else: count_errors += 1 if label == dataset_meta.get_target_class(dataset_image_id): count_hit_target_class += 1 return (count_correctly_classified, count_errors, count_hit_target_class, num_images)
[ "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_result", "is", "None", ":", "return", "0", ",", "0", ",", "0", ",", "0", "adv_images", "=", "adv_batch", "[", "'images'", "]", "dataset_batch_images", "=", "(", "dataset_batches", ".", "data", "[", "adv_batch", "[", "'dataset_batch_id'", "]", "]", "[", "'images'", "]", ")", "count_correctly_classified", "=", "0", "count_errors", "=", "0", "count_hit_target_class", "=", "0", "num_images", "=", "0", "for", "adv_img_id", ",", "label", "in", "iteritems", "(", "class_result", ")", ":", "if", "adv_img_id", "not", "in", "adv_images", ":", "continue", "num_images", "+=", "1", "clean_image_id", "=", "adv_images", "[", "adv_img_id", "]", "[", "'clean_image_id'", "]", "dataset_image_id", "=", "(", "dataset_batch_images", "[", "clean_image_id", "]", "[", "'dataset_image_id'", "]", ")", "if", "label", "==", "dataset_meta", ".", "get_true_label", "(", "dataset_image_id", ")", ":", "count_correctly_classified", "+=", "1", "else", ":", "count_errors", "+=", "1", "if", "label", "==", "dataset_meta", ".", "get_target_class", "(", "dataset_image_id", ")", ":", "count_hit_target_class", "+=", "1", "return", "(", "count_correctly_classified", ",", "count_errors", ",", "count_hit_target_class", ",", "num_images", ")" ]
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: result file path adv_batch: AversarialBatches.data[adv_batch_id] adv_batch_id is stored in each ClassificationBatch entity dataset_batches: instance of DatasetBatches dataset_meta: instance of DatasetMetadata Returns: Tuple of (count_correctly_classified, count_errors, count_hit_target_class, num_images)
[ "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. remap_dim1: dictionary with mapping column indices to column names which should be saved to file. If none then indices will be used as names. """ # rows - first index # columns - second index with open(filename, 'w') as fobj: columns = list(sorted(self._dim1)) for col in columns: fobj.write(',') fobj.write(str(remap_dim1[col] if remap_dim1 else col)) fobj.write('\n') for row in sorted(self._dim0): fobj.write(str(remap_dim0[row] if remap_dim0 else row)) for col in columns: fobj.write(',') fobj.write(str(self[row, col])) fobj.write('\n')
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. remap_dim1: dictionary with mapping column indices to column names which should be saved to file. If none then indices will be used as names. """ # rows - first index # columns - second index with open(filename, 'w') as fobj: columns = list(sorted(self._dim1)) for col in columns: fobj.write(',') fobj.write(str(remap_dim1[col] if remap_dim1 else col)) fobj.write('\n') for row in sorted(self._dim0): fobj.write(str(remap_dim0[row] if remap_dim0 else row)) for col in columns: fobj.write(',') fobj.write(str(self[row, col])) fobj.write('\n')
[ "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", "=", "list", "(", "sorted", "(", "self", ".", "_dim1", ")", ")", "for", "col", "in", "columns", ":", "fobj", ".", "write", "(", "','", ")", "fobj", ".", "write", "(", "str", "(", "remap_dim1", "[", "col", "]", "if", "remap_dim1", "else", "col", ")", ")", "fobj", ".", "write", "(", "'\\n'", ")", "for", "row", "in", "sorted", "(", "self", ".", "_dim0", ")", ":", "fobj", ".", "write", "(", "str", "(", "remap_dim0", "[", "row", "]", "if", "remap_dim0", "else", "row", ")", ")", "for", "col", "in", "columns", ":", "fobj", ".", "write", "(", "','", ")", "fobj", ".", "write", "(", "str", "(", "self", "[", "row", ",", "col", "]", ")", ")", "fobj", ".", "write", "(", "'\\n'", ")" ]
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 should be saved to file. If none then indices will be used as names.
[ "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 AversarialBatches """ # prepare classification batches idx = 0 for s_id in iterkeys(submissions.defenses): for adv_id in iterkeys(adv_batches.data): class_batch_id = CLASSIFICATION_BATCH_ID_PATTERN.format(idx) idx += 1 self.data[class_batch_id] = { 'adversarial_batch_id': adv_id, 'submission_id': s_id, 'result_path': os.path.join( self._round_name, CLASSIFICATION_BATCHES_SUBDIR, s_id + '_' + adv_id + '.csv') } # save them to datastore client = self._datastore_client with client.no_transact_batch() as batch: for key, value in iteritems(self.data): entity = client.entity(client.key(KIND_CLASSIFICATION_BATCH, key)) entity.update(value) batch.put(entity)
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 AversarialBatches """ # prepare classification batches idx = 0 for s_id in iterkeys(submissions.defenses): for adv_id in iterkeys(adv_batches.data): class_batch_id = CLASSIFICATION_BATCH_ID_PATTERN.format(idx) idx += 1 self.data[class_batch_id] = { 'adversarial_batch_id': adv_id, 'submission_id': s_id, 'result_path': os.path.join( self._round_name, CLASSIFICATION_BATCHES_SUBDIR, s_id + '_' + adv_id + '.csv') } # save them to datastore client = self._datastore_client with client.no_transact_batch() as batch: for key, value in iteritems(self.data): entity = client.entity(client.key(KIND_CLASSIFICATION_BATCH, key)) entity.update(value) batch.put(entity)
[ "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_id", "in", "iterkeys", "(", "adv_batches", ".", "data", ")", ":", "class_batch_id", "=", "CLASSIFICATION_BATCH_ID_PATTERN", ".", "format", "(", "idx", ")", "idx", "+=", "1", "self", ".", "data", "[", "class_batch_id", "]", "=", "{", "'adversarial_batch_id'", ":", "adv_id", ",", "'submission_id'", ":", "s_id", ",", "'result_path'", ":", "os", ".", "path", ".", "join", "(", "self", ".", "_round_name", ",", "CLASSIFICATION_BATCHES_SUBDIR", ",", "s_id", "+", "'_'", "+", "adv_id", "+", "'.csv'", ")", "}", "# save them to datastore", "client", "=", "self", ".", "_datastore_client", "with", "client", ".", "no_transact_batch", "(", ")", "as", "batch", ":", "for", "key", ",", "value", "in", "iteritems", "(", "self", ".", "data", ")", ":", "entity", "=", "client", ".", "entity", "(", "client", ".", "key", "(", "KIND_CLASSIFICATION_BATCH", ",", "key", ")", ")", "entity", ".", "update", "(", "value", ")", "batch", ".", "put", "(", "entity", ")" ]
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_batch_id", "=", "entity", ".", "key", ".", "flat_path", "[", "-", "1", "]", "self", ".", "data", "[", "class_batch_id", "]", "=", "dict", "(", "entity", ")" ]
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 KeyError( 'Key {0} not found in the datastore'.format(key.flat_path))
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 KeyError( 'Key {0} not found in the datastore'.format(key.flat_path))
[ "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", "(", "key", ")", "if", "result", "is", "not", "None", ":", "return", "dict", "(", "result", ")", "else", ":", "raise", "KeyError", "(", "'Key {0} not found in the datastore'", ".", "format", "(", "key", ".", "flat_path", ")", ")" ]
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 of DatasetMetadata defense_work: instance of DefenseWorkPieces Returns: accuracy_matrix, error_matrix, hit_target_class_matrix, processed_images_count """ class_batch_to_work = {} if defense_work: for v in itervalues(defense_work.work): class_batch_to_work[v['output_classification_batch_id']] = v # accuracy_matrix[defense_id, attack_id] = num correctly classified accuracy_matrix = ResultMatrix() # error_matrix[defense_id, attack_id] = num misclassfied error_matrix = ResultMatrix() # hit_target_class_matrix[defense_id, attack_id] = num hit target class hit_target_class_matrix = ResultMatrix() # processed_images_count[defense_id] = num processed images by defense processed_images_count = {} total_count = len(self.data) processed_count = 0 logging.info('Processing %d files with classification results', len(self.data)) for k, v in iteritems(self.data): if processed_count % 100 == 0: logging.info('Processed %d out of %d classification results', processed_count, total_count) processed_count += 1 defense_id = v['submission_id'] adv_batch = adv_batches.data[v['adversarial_batch_id']] attack_id = adv_batch['submission_id'] work_item = class_batch_to_work.get(k) required_work_stats = ['stat_correct', 'stat_error', 'stat_target_class', 'stat_num_images'] if work_item and work_item['error']: # ignore batches with error continue if work_item and all(work_item.get(i) is not None for i in required_work_stats): count_correctly_classified = work_item['stat_correct'] count_errors = work_item['stat_error'] count_hit_target_class = work_item['stat_target_class'] num_images = work_item['stat_num_images'] else: logging.warning('Recomputing accuracy for classification batch %s', k) (count_correctly_classified, count_errors, count_hit_target_class, num_images) = analyze_one_classification_result( self._storage_client, v['result_path'], adv_batch, dataset_batches, dataset_meta) # update accuracy and hit target class accuracy_matrix[defense_id, attack_id] += count_correctly_classified error_matrix[defense_id, attack_id] += count_errors hit_target_class_matrix[defense_id, attack_id] += count_hit_target_class # update number of processed images processed_images_count[defense_id] = ( processed_images_count.get(defense_id, 0) + num_images) return (accuracy_matrix, error_matrix, hit_target_class_matrix, processed_images_count)
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 of DatasetMetadata defense_work: instance of DefenseWorkPieces Returns: accuracy_matrix, error_matrix, hit_target_class_matrix, processed_images_count """ class_batch_to_work = {} if defense_work: for v in itervalues(defense_work.work): class_batch_to_work[v['output_classification_batch_id']] = v # accuracy_matrix[defense_id, attack_id] = num correctly classified accuracy_matrix = ResultMatrix() # error_matrix[defense_id, attack_id] = num misclassfied error_matrix = ResultMatrix() # hit_target_class_matrix[defense_id, attack_id] = num hit target class hit_target_class_matrix = ResultMatrix() # processed_images_count[defense_id] = num processed images by defense processed_images_count = {} total_count = len(self.data) processed_count = 0 logging.info('Processing %d files with classification results', len(self.data)) for k, v in iteritems(self.data): if processed_count % 100 == 0: logging.info('Processed %d out of %d classification results', processed_count, total_count) processed_count += 1 defense_id = v['submission_id'] adv_batch = adv_batches.data[v['adversarial_batch_id']] attack_id = adv_batch['submission_id'] work_item = class_batch_to_work.get(k) required_work_stats = ['stat_correct', 'stat_error', 'stat_target_class', 'stat_num_images'] if work_item and work_item['error']: # ignore batches with error continue if work_item and all(work_item.get(i) is not None for i in required_work_stats): count_correctly_classified = work_item['stat_correct'] count_errors = work_item['stat_error'] count_hit_target_class = work_item['stat_target_class'] num_images = work_item['stat_num_images'] else: logging.warning('Recomputing accuracy for classification batch %s', k) (count_correctly_classified, count_errors, count_hit_target_class, num_images) = analyze_one_classification_result( self._storage_client, v['result_path'], adv_batch, dataset_batches, dataset_meta) # update accuracy and hit target class accuracy_matrix[defense_id, attack_id] += count_correctly_classified error_matrix[defense_id, attack_id] += count_errors hit_target_class_matrix[defense_id, attack_id] += count_hit_target_class # update number of processed images processed_images_count[defense_id] = ( processed_images_count.get(defense_id, 0) + num_images) return (accuracy_matrix, error_matrix, hit_target_class_matrix, processed_images_count)
[ "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", "(", "defense_work", ".", "work", ")", ":", "class_batch_to_work", "[", "v", "[", "'output_classification_batch_id'", "]", "]", "=", "v", "# accuracy_matrix[defense_id, attack_id] = num correctly classified", "accuracy_matrix", "=", "ResultMatrix", "(", ")", "# error_matrix[defense_id, attack_id] = num misclassfied", "error_matrix", "=", "ResultMatrix", "(", ")", "# hit_target_class_matrix[defense_id, attack_id] = num hit target class", "hit_target_class_matrix", "=", "ResultMatrix", "(", ")", "# processed_images_count[defense_id] = num processed images by defense", "processed_images_count", "=", "{", "}", "total_count", "=", "len", "(", "self", ".", "data", ")", "processed_count", "=", "0", "logging", ".", "info", "(", "'Processing %d files with classification results'", ",", "len", "(", "self", ".", "data", ")", ")", "for", "k", ",", "v", "in", "iteritems", "(", "self", ".", "data", ")", ":", "if", "processed_count", "%", "100", "==", "0", ":", "logging", ".", "info", "(", "'Processed %d out of %d classification results'", ",", "processed_count", ",", "total_count", ")", "processed_count", "+=", "1", "defense_id", "=", "v", "[", "'submission_id'", "]", "adv_batch", "=", "adv_batches", ".", "data", "[", "v", "[", "'adversarial_batch_id'", "]", "]", "attack_id", "=", "adv_batch", "[", "'submission_id'", "]", "work_item", "=", "class_batch_to_work", ".", "get", "(", "k", ")", "required_work_stats", "=", "[", "'stat_correct'", ",", "'stat_error'", ",", "'stat_target_class'", ",", "'stat_num_images'", "]", "if", "work_item", "and", "work_item", "[", "'error'", "]", ":", "# ignore batches with error", "continue", "if", "work_item", "and", "all", "(", "work_item", ".", "get", "(", "i", ")", "is", "not", "None", "for", "i", "in", "required_work_stats", ")", ":", "count_correctly_classified", "=", "work_item", "[", "'stat_correct'", "]", "count_errors", "=", "work_item", "[", "'stat_error'", "]", "count_hit_target_class", "=", "work_item", "[", "'stat_target_class'", "]", "num_images", "=", "work_item", "[", "'stat_num_images'", "]", "else", ":", "logging", ".", "warning", "(", "'Recomputing accuracy for classification batch %s'", ",", "k", ")", "(", "count_correctly_classified", ",", "count_errors", ",", "count_hit_target_class", ",", "num_images", ")", "=", "analyze_one_classification_result", "(", "self", ".", "_storage_client", ",", "v", "[", "'result_path'", "]", ",", "adv_batch", ",", "dataset_batches", ",", "dataset_meta", ")", "# update accuracy and hit target class", "accuracy_matrix", "[", "defense_id", ",", "attack_id", "]", "+=", "count_correctly_classified", "error_matrix", "[", "defense_id", ",", "attack_id", "]", "+=", "count_errors", "hit_target_class_matrix", "[", "defense_id", ",", "attack_id", "]", "+=", "count_hit_target_class", "# update number of processed images", "processed_images_count", "[", "defense_id", "]", "=", "(", "processed_images_count", ".", "get", "(", "defense_id", ",", "0", ")", "+", "num_images", ")", "return", "(", "accuracy_matrix", ",", "error_matrix", ",", "hit_target_class_matrix", ",", "processed_images_count", ")" ]
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, processed_images_count
[ "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 of the participant. Raises: ValueError: is participant can't be determined based on submission path. """ basename = os.path.basename(submission_path) file_ext = None for e in ALLOWED_EXTENSIONS: if basename.endswith(e): file_ext = e break if not file_ext: raise ValueError('Invalid submission path: ' + submission_path) basename = basename[:-len(file_ext)] if basename.isdigit(): return {'team_id': int(basename)} if basename.startswith('baseline_'): return {'baseline_id': basename[len('baseline_'):]} raise ValueError('Invalid submission path: ' + submission_path)
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 of the participant. Raises: ValueError: is participant can't be determined based on submission path. """ basename = os.path.basename(submission_path) file_ext = None for e in ALLOWED_EXTENSIONS: if basename.endswith(e): file_ext = e break if not file_ext: raise ValueError('Invalid submission path: ' + submission_path) basename = basename[:-len(file_ext)] if basename.isdigit(): return {'team_id': int(basename)} if basename.startswith('baseline_'): return {'baseline_id': basename[len('baseline_'):]} raise ValueError('Invalid submission path: ' + submission_path)
[ "def", "participant_from_submission_path", "(", "submission_path", ")", ":", "basename", "=", "os", ".", "path", ".", "basename", "(", "submission_path", ")", "file_ext", "=", "None", "for", "e", "in", "ALLOWED_EXTENSIONS", ":", "if", "basename", ".", "endswith", "(", "e", ")", ":", "file_ext", "=", "e", "break", "if", "not", "file_ext", ":", "raise", "ValueError", "(", "'Invalid submission path: '", "+", "submission_path", ")", "basename", "=", "basename", "[", ":", "-", "len", "(", "file_ext", ")", "]", "if", "basename", ".", "isdigit", "(", ")", ":", "return", "{", "'team_id'", ":", "int", "(", "basename", ")", "}", "if", "basename", ".", "startswith", "(", "'baseline_'", ")", ":", "return", "{", "'baseline_id'", ":", "basename", "[", "len", "(", "'baseline_'", ")", ":", "]", "}", "raise", "ValueError", "(", "'Invalid 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 of the participant. Raises: ValueError: is participant can't be determined based on submission path.
[ "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_pattern: pattern which is used to generate (internal) IDs for submissins. One of the following constants: ATTACK_ID_PATTERN, TARGETED_ATTACK_ID_PATTERN or DEFENSE_ID_PATTERN. Returns: dictionary with all found submissions """ submissions = self._storage_client.list_blobs( prefix=os.path.join(self._round_name, dir_suffix)) return { id_pattern.format(idx): SubmissionDescriptor( path=s, participant_id=participant_from_submission_path(s)) for idx, s in enumerate(submissions) }
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_pattern: pattern which is used to generate (internal) IDs for submissins. One of the following constants: ATTACK_ID_PATTERN, TARGETED_ATTACK_ID_PATTERN or DEFENSE_ID_PATTERN. Returns: dictionary with all found submissions """ submissions = self._storage_client.list_blobs( prefix=os.path.join(self._round_name, dir_suffix)) return { id_pattern.format(idx): SubmissionDescriptor( path=s, participant_id=participant_from_submission_path(s)) for idx, s in enumerate(submissions) }
[ "def", "_load_submissions_from_datastore_dir", "(", "self", ",", "dir_suffix", ",", "id_pattern", ")", ":", "submissions", "=", "self", ".", "_storage_client", ".", "list_blobs", "(", "prefix", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_round_name", ",", "dir_suffix", ")", ")", "return", "{", "id_pattern", ".", "format", "(", "idx", ")", ":", "SubmissionDescriptor", "(", "path", "=", "s", ",", "participant_id", "=", "participant_from_submission_path", "(", "s", ")", ")", "for", "idx", ",", "s", "in", "enumerate", "(", "submissions", ")", "}" ]
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 submissins. One of the following constants: ATTACK_ID_PATTERN, TARGETED_ATTACK_ID_PATTERN or DEFENSE_ID_PATTERN. Returns: dictionary with all found submissions
[ "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( ATTACK_SUBDIR, ATTACK_ID_PATTERN) self._targeted_attacks = self._load_submissions_from_datastore_dir( TARGETED_ATTACK_SUBDIR, TARGETED_ATTACK_ID_PATTERN) self._defenses = self._load_submissions_from_datastore_dir( DEFENSE_SUBDIR, DEFENSE_ID_PATTERN) self._write_to_datastore()
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( ATTACK_SUBDIR, ATTACK_ID_PATTERN) self._targeted_attacks = self._load_submissions_from_datastore_dir( TARGETED_ATTACK_SUBDIR, TARGETED_ATTACK_ID_PATTERN) self._defenses = self._load_submissions_from_datastore_dir( DEFENSE_SUBDIR, DEFENSE_ID_PATTERN) self._write_to_datastore()
[ "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", "=", "self", ".", "_load_submissions_from_datastore_dir", "(", "TARGETED_ATTACK_SUBDIR", ",", "TARGETED_ATTACK_ID_PATTERN", ")", "self", ".", "_defenses", "=", "self", ".", "_load_submissions_from_datastore_dir", "(", "DEFENSE_SUBDIR", ",", "DEFENSE_ID_PATTERN", ")", "self", ".", "_write_to_datastore", "(", ")" ]
Init list of sumibssions from Storage and saves them to Datastore. Should be called only once (typically by master) during evaluation of the competition.
[ "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, self._targeted_attacks, self._defenses]) client = self._datastore_client with client.no_transact_batch() as batch: for root_key, submissions in roots_and_submissions: batch.put(client.entity(client.key(*root_key))) for k, v in iteritems(submissions): entity = client.entity(client.key( *(root_key + [KIND_SUBMISSION, k]))) entity['submission_path'] = v.path entity.update(participant_from_submission_path(v.path)) batch.put(entity)
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, self._targeted_attacks, self._defenses]) client = self._datastore_client with client.no_transact_batch() as batch: for root_key, submissions in roots_and_submissions: batch.put(client.entity(client.key(*root_key))) for k, v in iteritems(submissions): entity = client.entity(client.key( *(root_key + [KIND_SUBMISSION, k]))) entity['submission_path'] = v.path entity.update(participant_from_submission_path(v.path)) batch.put(entity)
[ "def", "_write_to_datastore", "(", "self", ")", ":", "# Populate datastore", "roots_and_submissions", "=", "zip", "(", "[", "ATTACKS_ENTITY_KEY", ",", "TARGET_ATTACKS_ENTITY_KEY", ",", "DEFENSES_ENTITY_KEY", "]", ",", "[", "self", ".", "_attacks", ",", "self", ".", "_targeted_attacks", ",", "self", ".", "_defenses", "]", ")", "client", "=", "self", ".", "_datastore_client", "with", "client", ".", "no_transact_batch", "(", ")", "as", "batch", ":", "for", "root_key", ",", "submissions", "in", "roots_and_submissions", ":", "batch", ".", "put", "(", "client", ".", "entity", "(", "client", ".", "key", "(", "*", "root_key", ")", ")", ")", "for", "k", ",", "v", "in", "iteritems", "(", "submissions", ")", ":", "entity", "=", "client", ".", "entity", "(", "client", ".", "key", "(", "*", "(", "root_key", "+", "[", "KIND_SUBMISSION", ",", "k", "]", ")", ")", ")", "entity", "[", "'submission_path'", "]", "=", "v", ".", "path", "entity", ".", "update", "(", "participant_from_submission_path", "(", "v", ".", "path", ")", ")", "batch", ".", "put", "(", "entity", ")" ]
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 = entity.key.flat_path[-1] submission_path = entity['submission_path'] participant_id = {k: entity[k] for k in ['team_id', 'baseline_id'] if k in entity} submission_descr = SubmissionDescriptor(path=submission_path, participant_id=participant_id) if list(entity.key.flat_path[0:2]) == ATTACKS_ENTITY_KEY: self._attacks[submission_id] = submission_descr elif list(entity.key.flat_path[0:2]) == TARGET_ATTACKS_ENTITY_KEY: self._targeted_attacks[submission_id] = submission_descr elif list(entity.key.flat_path[0:2]) == DEFENSES_ENTITY_KEY: self._defenses[submission_id] = submission_descr
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 = entity.key.flat_path[-1] submission_path = entity['submission_path'] participant_id = {k: entity[k] for k in ['team_id', 'baseline_id'] if k in entity} submission_descr = SubmissionDescriptor(path=submission_path, participant_id=participant_id) if list(entity.key.flat_path[0:2]) == ATTACKS_ENTITY_KEY: self._attacks[submission_id] = submission_descr elif list(entity.key.flat_path[0:2]) == TARGET_ATTACKS_ENTITY_KEY: self._targeted_attacks[submission_id] = submission_descr elif list(entity.key.flat_path[0:2]) == DEFENSES_ENTITY_KEY: self._defenses[submission_id] = submission_descr
[ "def", "init_from_datastore", "(", "self", ")", ":", "self", ".", "_attacks", "=", "{", "}", "self", ".", "_targeted_attacks", "=", "{", "}", "self", ".", "_defenses", "=", "{", "}", "for", "entity", "in", "self", ".", "_datastore_client", ".", "query_fetch", "(", "kind", "=", "KIND_SUBMISSION", ")", ":", "submission_id", "=", "entity", ".", "key", ".", "flat_path", "[", "-", "1", "]", "submission_path", "=", "entity", "[", "'submission_path'", "]", "participant_id", "=", "{", "k", ":", "entity", "[", "k", "]", "for", "k", "in", "[", "'team_id'", ",", "'baseline_id'", "]", "if", "k", "in", "entity", "}", "submission_descr", "=", "SubmissionDescriptor", "(", "path", "=", "submission_path", ",", "participant_id", "=", "participant_id", ")", "if", "list", "(", "entity", ".", "key", ".", "flat_path", "[", "0", ":", "2", "]", ")", "==", "ATTACKS_ENTITY_KEY", ":", "self", ".", "_attacks", "[", "submission_id", "]", "=", "submission_descr", "elif", "list", "(", "entity", ".", "key", ".", "flat_path", "[", "0", ":", "2", "]", ")", "==", "TARGET_ATTACKS_ENTITY_KEY", ":", "self", ".", "_targeted_attacks", "[", "submission_id", "]", "=", "submission_descr", "elif", "list", "(", "entity", ".", "key", ".", "flat_path", "[", "0", ":", "2", "]", ")", "==", "DEFENSES_ENTITY_KEY", ":", "self", ".", "_defenses", "[", "submission_id", "]", "=", "submission_descr" ]
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._defenses.get( submission_id, self._targeted_attacks.get(submission_id, None)))
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._defenses.get( submission_id, self._targeted_attacks.get(submission_id, None)))
[ "def", "find_by_id", "(", "self", ",", "submission_id", ")", ":", "return", "self", ".", "_attacks", ".", "get", "(", "submission_id", ",", "self", ".", "_defenses", ".", "get", "(", "submission_id", ",", "self", ".", "_targeted_attacks", ".", "get", "(", "submission_id", ",", "None", ")", ")", ")" ]
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.participant_id: return submission.participant_id['team_id'] elif 'baseline_id' in submission.participant_id: return 'baseline_' + submission.participant_id['baseline_id'] else: return ''
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.participant_id: return submission.participant_id['team_id'] elif 'baseline_id' in submission.participant_id: return 'baseline_' + submission.participant_id['baseline_id'] else: return ''
[ "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", ":", "return", "submission", ".", "participant_id", "[", "'team_id'", "]", "elif", "'baseline_id'", "in", "submission", ".", "participant_id", ":", "return", "'baseline_'", "+", "submission", ".", "participant_id", "[", "'baseline_id'", "]", "else", ":", "return", "''" ]
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._extracted_submission_dir os.mkdir(self._tmp_extracted_dir) os.mkdir(self._sample_input_dir) os.mkdir(self._sample_output_dir) # make output dir world writable shell_call(['chmod', 'a+rwX', '-R', self._sample_output_dir])
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._extracted_submission_dir os.mkdir(self._tmp_extracted_dir) os.mkdir(self._sample_input_dir) os.mkdir(self._sample_output_dir) # make output dir world writable shell_call(['chmod', 'a+rwX', '-R', self._sample_output_dir])
[ "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 is intentional because self._tmp_extracted_dir or it's subdir", "# will be renames into self._extracted_submission_dir", "os", ".", "mkdir", "(", "self", ".", "_tmp_extracted_dir", ")", "os", ".", "mkdir", "(", "self", ".", "_sample_input_dir", ")", "os", ".", "mkdir", "(", "self", ".", "_sample_output_dir", ")", "# make output dir world writable", "shell_call", "(", "[", "'chmod'", ",", "'a+rwX'", ",", "'-R'", ",", "self", ".", "_sample_output_dir", "]", ")" ]
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, 'metadata.json') if not os.path.isfile(metadata_filename): logging.error('metadata.json not found') return None try: with open(metadata_filename, 'r') as f: metadata = json.load(f) except IOError as e: logging.error('Failed to load metadata: %s', e) return None for field_name in REQUIRED_METADATA_JSON_FIELDS: if field_name not in metadata: logging.error('Field %s not found in metadata', field_name) return None # Verify submission type if submission_type != metadata['type']: logging.error('Invalid submission type in metadata, expected "%s", ' 'actual "%s"', submission_type, metadata['type']) return None # Check submission entry point entry_point = metadata['entry_point'] if not os.path.isfile(os.path.join(self._extracted_submission_dir, entry_point)): logging.error('Entry point not found: %s', entry_point) return None if not entry_point.endswith('.sh'): logging.warning('Entry point is not an .sh script. ' 'This is not necessarily a problem, but if submission ' 'won''t run double check entry point first: %s', entry_point) # Metadata verified return metadata
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, 'metadata.json') if not os.path.isfile(metadata_filename): logging.error('metadata.json not found') return None try: with open(metadata_filename, 'r') as f: metadata = json.load(f) except IOError as e: logging.error('Failed to load metadata: %s', e) return None for field_name in REQUIRED_METADATA_JSON_FIELDS: if field_name not in metadata: logging.error('Field %s not found in metadata', field_name) return None # Verify submission type if submission_type != metadata['type']: logging.error('Invalid submission type in metadata, expected "%s", ' 'actual "%s"', submission_type, metadata['type']) return None # Check submission entry point entry_point = metadata['entry_point'] if not os.path.isfile(os.path.join(self._extracted_submission_dir, entry_point)): logging.error('Entry point not found: %s', entry_point) return None if not entry_point.endswith('.sh'): logging.warning('Entry point is not an .sh script. ' 'This is not necessarily a problem, but if submission ' 'won''t run double check entry point first: %s', entry_point) # Metadata verified return metadata
[ "def", "_load_and_verify_metadata", "(", "self", ",", "submission_type", ")", ":", "metadata_filename", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_extracted_submission_dir", ",", "'metadata.json'", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "metadata_filename", ")", ":", "logging", ".", "error", "(", "'metadata.json not found'", ")", "return", "None", "try", ":", "with", "open", "(", "metadata_filename", ",", "'r'", ")", "as", "f", ":", "metadata", "=", "json", ".", "load", "(", "f", ")", "except", "IOError", "as", "e", ":", "logging", ".", "error", "(", "'Failed to load metadata: %s'", ",", "e", ")", "return", "None", "for", "field_name", "in", "REQUIRED_METADATA_JSON_FIELDS", ":", "if", "field_name", "not", "in", "metadata", ":", "logging", ".", "error", "(", "'Field %s not found in metadata'", ",", "field_name", ")", "return", "None", "# Verify submission type", "if", "submission_type", "!=", "metadata", "[", "'type'", "]", ":", "logging", ".", "error", "(", "'Invalid submission type in metadata, expected \"%s\", '", "'actual \"%s\"'", ",", "submission_type", ",", "metadata", "[", "'type'", "]", ")", "return", "None", "# Check submission entry point", "entry_point", "=", "metadata", "[", "'entry_point'", "]", "if", "not", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "self", ".", "_extracted_submission_dir", ",", "entry_point", ")", ")", ":", "logging", ".", "error", "(", "'Entry point not found: %s'", ",", "entry_point", ")", "return", "None", "if", "not", "entry_point", ".", "endswith", "(", "'.sh'", ")", ":", "logging", ".", "warning", "(", "'Entry point is not an .sh script. '", "'This is not necessarily a problem, but if submission '", "'won'", "'t run double check entry point first: %s'", ",", "entry_point", ")", "# Metadata verified", "return", "metadata" ]
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' container_name = metadata['container_gpu'] else: docker_binary = 'docker' container_name = metadata['container'] if metadata['type'] == 'defense': cmd = [docker_binary, 'run', '--network=none', '-m=24g', '-v', '{0}:/input_images:ro'.format(self._sample_input_dir), '-v', '{0}:/output_data'.format(self._sample_output_dir), '-v', '{0}:/code'.format(self._extracted_submission_dir), '-w', '/code', container_name, './' + metadata['entry_point'], '/input_images', '/output_data/result.csv'] else: epsilon = np.random.choice(ALLOWED_EPS) cmd = [docker_binary, 'run', '--network=none', '-m=24g', '-v', '{0}:/input_images:ro'.format(self._sample_input_dir), '-v', '{0}:/output_images'.format(self._sample_output_dir), '-v', '{0}:/code'.format(self._extracted_submission_dir), '-w', '/code', container_name, './' + metadata['entry_point'], '/input_images', '/output_images', str(epsilon)] logging.info('Command to run submission: %s', ' '.join(cmd)) return shell_call(cmd)
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' container_name = metadata['container_gpu'] else: docker_binary = 'docker' container_name = metadata['container'] if metadata['type'] == 'defense': cmd = [docker_binary, 'run', '--network=none', '-m=24g', '-v', '{0}:/input_images:ro'.format(self._sample_input_dir), '-v', '{0}:/output_data'.format(self._sample_output_dir), '-v', '{0}:/code'.format(self._extracted_submission_dir), '-w', '/code', container_name, './' + metadata['entry_point'], '/input_images', '/output_data/result.csv'] else: epsilon = np.random.choice(ALLOWED_EPS) cmd = [docker_binary, 'run', '--network=none', '-m=24g', '-v', '{0}:/input_images:ro'.format(self._sample_input_dir), '-v', '{0}:/output_images'.format(self._sample_output_dir), '-v', '{0}:/code'.format(self._extracted_submission_dir), '-w', '/code', container_name, './' + metadata['entry_point'], '/input_images', '/output_images', str(epsilon)] logging.info('Command to run submission: %s', ' '.join(cmd)) return shell_call(cmd)
[ "def", "_run_submission", "(", "self", ",", "metadata", ")", ":", "if", "self", ".", "_use_gpu", ":", "docker_binary", "=", "'nvidia-docker'", "container_name", "=", "metadata", "[", "'container_gpu'", "]", "else", ":", "docker_binary", "=", "'docker'", "container_name", "=", "metadata", "[", "'container'", "]", "if", "metadata", "[", "'type'", "]", "==", "'defense'", ":", "cmd", "=", "[", "docker_binary", ",", "'run'", ",", "'--network=none'", ",", "'-m=24g'", ",", "'-v'", ",", "'{0}:/input_images:ro'", ".", "format", "(", "self", ".", "_sample_input_dir", ")", ",", "'-v'", ",", "'{0}:/output_data'", ".", "format", "(", "self", ".", "_sample_output_dir", ")", ",", "'-v'", ",", "'{0}:/code'", ".", "format", "(", "self", ".", "_extracted_submission_dir", ")", ",", "'-w'", ",", "'/code'", ",", "container_name", ",", "'./'", "+", "metadata", "[", "'entry_point'", "]", ",", "'/input_images'", ",", "'/output_data/result.csv'", "]", "else", ":", "epsilon", "=", "np", ".", "random", ".", "choice", "(", "ALLOWED_EPS", ")", "cmd", "=", "[", "docker_binary", ",", "'run'", ",", "'--network=none'", ",", "'-m=24g'", ",", "'-v'", ",", "'{0}:/input_images:ro'", ".", "format", "(", "self", ".", "_sample_input_dir", ")", ",", "'-v'", ",", "'{0}:/output_images'", ".", "format", "(", "self", ".", "_sample_output_dir", ")", ",", "'-v'", ",", "'{0}:/code'", ".", "format", "(", "self", ".", "_extracted_submission_dir", ")", ",", "'-w'", ",", "'/code'", ",", "container_name", ",", "'./'", "+", "metadata", "[", "'entry_point'", "]", ",", "'/input_images'", ",", "'/output_images'", ",", "str", "(", "epsilon", ")", "]", "logging", ".", "info", "(", "'Command to run submission: %s'", ",", "' '", ".", "join", "(", "cmd", ")", ")", "return", "shell_call", "(", "cmd", ")" ]
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 tensor. :param eps: epsilon (input variation parameter); see https://arxiv.org/abs/1412.6572. :param ord: Order of the norm (mimics NumPy). Possible values: np.inf, 1 or 2. :param clip_min: (optional) float. Minimum float value for adversarial example components. :param clip_max: (optional) float. Maximum float value for adversarial example components. :param y: (optional) Tensor with true labels. If targeted is true, then provide the target label. Otherwise, only provide this parameter if you'd like to use true labels when crafting adversarial samples. Otherwise, model predictions are used as labels to avoid the "label leaking" effect (explained in this paper: https://arxiv.org/abs/1611.01236). Default is None. :param targeted: (optional) bool. 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 of being more like y. :param sanity_checks: bool, if True, include asserts (Turn them off to use less runtime / memory or for unit tests that intentionally pass strange input) :return: a tensor for the adversarial example """ if ord not in [np.inf, 1, 2]: raise ValueError("Norm order must be either np.inf, 1, or 2.") asserts = [] # If a data range was specified, check that the input was in that range if clip_min is not None: asserts.append(tf.math.greater_equal(x, clip_min)) if clip_max is not None: asserts.append(tf.math.less_equal(x, clip_max)) if y is None: # Using model predictions as ground truth to avoid label leaking y = tf.argmax(model_fn(x), 1) grad = compute_gradient(model_fn, x, y, targeted) optimal_perturbation = optimize_linear(grad, eps, ord) # Add perturbation to original example to obtain adversarial example adv_x = x + optimal_perturbation # If clipping is needed, reset all values outside of [clip_min, clip_max] if (clip_min is not None) or (clip_max is not None): # We don't currently support one-sided clipping assert clip_min is not None and clip_max is not None adv_x = tf.clip_by_value(adv_x, clip_min, clip_max) if sanity_checks: assert np.all(asserts) return adv_x
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 tensor. :param eps: epsilon (input variation parameter); see https://arxiv.org/abs/1412.6572. :param ord: Order of the norm (mimics NumPy). Possible values: np.inf, 1 or 2. :param clip_min: (optional) float. Minimum float value for adversarial example components. :param clip_max: (optional) float. Maximum float value for adversarial example components. :param y: (optional) Tensor with true labels. If targeted is true, then provide the target label. Otherwise, only provide this parameter if you'd like to use true labels when crafting adversarial samples. Otherwise, model predictions are used as labels to avoid the "label leaking" effect (explained in this paper: https://arxiv.org/abs/1611.01236). Default is None. :param targeted: (optional) bool. 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 of being more like y. :param sanity_checks: bool, if True, include asserts (Turn them off to use less runtime / memory or for unit tests that intentionally pass strange input) :return: a tensor for the adversarial example """ if ord not in [np.inf, 1, 2]: raise ValueError("Norm order must be either np.inf, 1, or 2.") asserts = [] # If a data range was specified, check that the input was in that range if clip_min is not None: asserts.append(tf.math.greater_equal(x, clip_min)) if clip_max is not None: asserts.append(tf.math.less_equal(x, clip_max)) if y is None: # Using model predictions as ground truth to avoid label leaking y = tf.argmax(model_fn(x), 1) grad = compute_gradient(model_fn, x, y, targeted) optimal_perturbation = optimize_linear(grad, eps, ord) # Add perturbation to original example to obtain adversarial example adv_x = x + optimal_perturbation # If clipping is needed, reset all values outside of [clip_min, clip_max] if (clip_min is not None) or (clip_max is not None): # We don't currently support one-sided clipping assert clip_min is not None and clip_max is not None adv_x = tf.clip_by_value(adv_x, clip_min, clip_max) if sanity_checks: assert np.all(asserts) return adv_x
[ "def", "fast_gradient_method", "(", "model_fn", ",", "x", ",", "eps", ",", "ord", ",", "clip_min", "=", "None", ",", "clip_max", "=", "None", ",", "y", "=", "None", ",", "targeted", "=", "False", ",", "sanity_checks", "=", "False", ")", ":", "if", "ord", "not", "in", "[", "np", ".", "inf", ",", "1", ",", "2", "]", ":", "raise", "ValueError", "(", "\"Norm order must be either np.inf, 1, or 2.\"", ")", "asserts", "=", "[", "]", "# If a data range was specified, check that the input was in that range", "if", "clip_min", "is", "not", "None", ":", "asserts", ".", "append", "(", "tf", ".", "math", ".", "greater_equal", "(", "x", ",", "clip_min", ")", ")", "if", "clip_max", "is", "not", "None", ":", "asserts", ".", "append", "(", "tf", ".", "math", ".", "less_equal", "(", "x", ",", "clip_max", ")", ")", "if", "y", "is", "None", ":", "# Using model predictions as ground truth to avoid label leaking", "y", "=", "tf", ".", "argmax", "(", "model_fn", "(", "x", ")", ",", "1", ")", "grad", "=", "compute_gradient", "(", "model_fn", ",", "x", ",", "y", ",", "targeted", ")", "optimal_perturbation", "=", "optimize_linear", "(", "grad", ",", "eps", ",", "ord", ")", "# Add perturbation to original example to obtain adversarial example", "adv_x", "=", "x", "+", "optimal_perturbation", "# If clipping is needed, reset all values outside of [clip_min, clip_max]", "if", "(", "clip_min", "is", "not", "None", ")", "or", "(", "clip_max", "is", "not", "None", ")", ":", "# We don't currently support one-sided clipping", "assert", "clip_min", "is", "not", "None", "and", "clip_max", "is", "not", "None", "adv_x", "=", "tf", ".", "clip_by_value", "(", "adv_x", ",", "clip_min", ",", "clip_max", ")", "if", "sanity_checks", ":", "assert", "np", ".", "all", "(", "asserts", ")", "return", "adv_x" ]
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 values: np.inf, 1 or 2. :param clip_min: (optional) float. Minimum float value for adversarial example components. :param clip_max: (optional) float. Maximum float value for adversarial example components. :param y: (optional) Tensor with true labels. If targeted is true, then provide the target label. Otherwise, only provide this parameter if you'd like to use true labels when crafting adversarial samples. Otherwise, model predictions are used as labels to avoid the "label leaking" effect (explained in this paper: https://arxiv.org/abs/1611.01236). Default is None. :param targeted: (optional) bool. 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 of being more like y. :param sanity_checks: bool, if True, include asserts (Turn them off to use less runtime / memory or for unit tests that intentionally pass strange input) :return: a tensor for the adversarial example
[ "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", "values", ":", "np", ".", "inf", "1", "or", "2", ".", ":", "param", "clip_min", ":", "(", "optional", ")", "float", ".", "Minimum", "float", "value", "for", "adversarial", "example", "components", ".", ":", "param", "clip_max", ":", "(", "optional", ")", "float", ".", "Maximum", "float", "value", "for", "adversarial", "example", "components", ".", ":", "param", "y", ":", "(", "optional", ")", "Tensor", "with", "true", "labels", ".", "If", "targeted", "is", "true", "then", "provide", "the", "target", "label", ".", "Otherwise", "only", "provide", "this", "parameter", "if", "you", "d", "like", "to", "use", "true", "labels", "when", "crafting", "adversarial", "samples", ".", "Otherwise", "model", "predictions", "are", "used", "as", "labels", "to", "avoid", "the", "label", "leaking", "effect", "(", "explained", "in", "this", "paper", ":", "https", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1611", ".", "01236", ")", ".", "Default", "is", "None", ".", ":", "param", "targeted", ":", "(", "optional", ")", "bool", ".", "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", "of", "being", "more", "like", "y", ".", ":", "param", "sanity_checks", ":", "bool", "if", "True", "include", "asserts", "(", "Turn", "them", "off", "to", "use", "less", "runtime", "/", "memory", "or", "for", "unit", "tests", "that", "intentionally", "pass", "strange", "input", ")", ":", "return", ":", "a", "tensor", "for", "the", "adversarial", "example" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/future/tf2/attacks/fast_gradient_method.py#L7-L59
train