INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Calculate the average gradient for each shared variable across all towers. Note that this function provides a synchronization point across all towers. Args: tower_grads: List of lists of ( gradient variable ) tuples. The outer list is over individual gradients. The inner list is over the gradient calculation for each t... | def avg_grads(tower_grads):
"""Calculate the average gradient for each shared variable across all
towers.
Note that this function provides a synchronization point across all towers.
Args:
tower_grads: List of lists of (gradient, variable) tuples. The outer list
is over individual gradients. The inner ... |
Creates the symbolic graph of an adversarial example given the name of an attack. Simplifies creating the symbolic graph of an attack by defining dataset - specific parameters. Dataset - specific default parameters are used unless a different value is given in kwargs. | def create_adv_by_name(model, x, attack_type, sess, dataset, y=None, **kwargs):
"""
Creates the symbolic graph of an adversarial example given the name of
an attack. Simplifies creating the symbolic graph of an attack by defining
dataset-specific parameters.
Dataset-specific default parameters are used unless... |
Log values to standard output and Tensorflow summary. | def log_value(self, tag, val, desc=''):
"""
Log values to standard output and Tensorflow summary.
:param tag: summary tag.
:param val: (required float or numpy array) value to be logged.
:param desc: (optional) additional description to be printed.
"""
logging.info('%s (%s): %.4f' % (desc, ... |
Evaluate the accuracy of the model on adversarial examples | def eval_advs(self, x, y, preds_adv, X_test, Y_test, att_type):
"""
Evaluate the accuracy of the model on adversarial examples
:param x: symbolic input to model.
:param y: symbolic variable for the label.
:param preds_adv: symbolic variable for the prediction on an
adversarial... |
Run the evaluation on multiple attacks. | def eval_multi(self, inc_epoch=True):
"""
Run the evaluation on multiple attacks.
"""
sess = self.sess
preds = self.preds
x = self.x_pre
y = self.y
X_train = self.X_train
Y_train = self.Y_train
X_test = self.X_test
Y_test = self.Y_test
writer = self.writer
self.summa... |
Runs some code that will crash if the GPUs/ GPU driver are suffering from a common bug. This helps to prevent contaminating results in the rest of the library with incorrect calculations. | def run_canary():
"""
Runs some code that will crash if the GPUs / GPU driver are suffering from
a common bug. This helps to prevent contaminating results in the rest of
the library with incorrect calculations.
"""
# Note: please do not edit this function unless you have access to a machine
# with GPUs s... |
Wraps a callable f in a function that warns that the function is deprecated. | def _wrap(f):
"""
Wraps a callable `f` in a function that warns that the function is deprecated.
"""
def wrapper(*args, **kwargs):
"""
Issues a deprecation warning and passes through the arguments.
"""
warnings.warn(str(f) + " is deprecated. Switch to calling the equivalent function in tensorflo... |
This function used to be needed to support tf 1. 4 and early but support for tf 1. 4 and earlier is now dropped.: param op_func: expects the function to handle eg: tf. reduce_sum.: param input_tensor: The tensor to reduce. Should have numeric type.: param axis: The dimensions to reduce. If None ( the default ) reduces ... | def reduce_function(op_func, input_tensor, axis=None, keepdims=None,
name=None, reduction_indices=None):
"""
This function used to be needed to support tf 1.4 and early, but support for tf 1.4 and earlier is now dropped.
:param op_func: expects the function to handle eg: tf.reduce_sum.
:para... |
Wrapper around tf. nn. softmax_cross_entropy_with_logits_v2 to handle deprecated warning | def softmax_cross_entropy_with_logits(sentinel=None,
labels=None,
logits=None,
dim=-1):
"""
Wrapper around tf.nn.softmax_cross_entropy_with_logits_v2 to handle
deprecated warning
"""
# Make sure t... |
Enforces size of perturbation on images and compute hashes for all images. | def enforce_epsilon_and_compute_hash(dataset_batch_dir, adv_dir, output_dir,
epsilon):
"""Enforces size of perturbation on images, and compute hashes for all images.
Args:
dataset_batch_dir: directory with the images of specific dataset batch
adv_dir: directory with gen... |
Downloads dataset organize it by batches and rename images. | def download_dataset(storage_client, image_batches, target_dir,
local_dataset_copy=None):
"""Downloads dataset, organize it by batches and rename images.
Args:
storage_client: instance of the CompetitionStorageClient
image_batches: subclass of ImageBatchesBase with data about images
... |
Saves file with target class for given dataset batch. | def save_target_classes_for_batch(self,
filename,
image_batches,
batch_id):
"""Saves file with target class for given dataset batch.
Args:
filename: output filename
image_batches: instance of... |
Function for min eigen vector using tf s full eigen decomposition. | def tf_min_eig_vec(self):
"""Function for min eigen vector using tf's full eigen decomposition."""
# Full eigen decomposition requires the explicit psd matrix M
_, matrix_m = self.dual_object.get_full_psd_matrix()
[eig_vals, eig_vectors] = tf.self_adjoint_eig(matrix_m)
index = tf.argmin(eig_vals)
... |
Function that returns smoothed version of min eigen vector. | def tf_smooth_eig_vec(self):
"""Function that returns smoothed version of min eigen vector."""
_, matrix_m = self.dual_object.get_full_psd_matrix()
# Easier to think in terms of max so negating the matrix
[eig_vals, eig_vectors] = tf.self_adjoint_eig(-matrix_m)
exp_eig_vals = tf.exp(tf.divide(eig_va... |
Computes the min eigen value and corresponding vector of matrix M. | def get_min_eig_vec_proxy(self, use_tf_eig=False):
"""Computes the min eigen value and corresponding vector of matrix M.
Args:
use_tf_eig: Whether to use tf's default full eigen decomposition
Returns:
eig_vec: Minimum absolute eigen value
eig_val: Corresponding eigen vector
"""
if... |
Computes scipy estimate of min eigenvalue for matrix M. | def get_scipy_eig_vec(self):
"""Computes scipy estimate of min eigenvalue for matrix M.
Returns:
eig_vec: Minimum absolute eigen value
eig_val: Corresponding eigen vector
"""
if not self.params['has_conv']:
matrix_m = self.sess.run(self.dual_object.matrix_m)
min_eig_vec_val, est... |
Create tensorflow op for running one step of descent. | def prepare_for_optimization(self):
"""Create tensorflow op for running one step of descent."""
if self.params['eig_type'] == 'TF':
self.eig_vec_estimate = self.get_min_eig_vec_proxy()
elif self.params['eig_type'] == 'LZS':
self.eig_vec_estimate = self.dual_object.m_min_vec
else:
self.... |
Run one step of gradient descent for optimization. | def run_one_step(self, eig_init_vec_val, eig_num_iter_val, smooth_val,
penalty_val, learning_rate_val):
"""Run one step of gradient descent for optimization.
Args:
eig_init_vec_val: Start value for eigen value computations
eig_num_iter_val: Number of iterations to run for eigen c... |
Run the optimization call run_one_step with suitable placeholders. | def run_optimization(self):
"""Run the optimization, call run_one_step with suitable placeholders.
Returns:
True if certificate is found
False otherwise
"""
penalty_val = self.params['init_penalty']
# Don't use smoothing initially - very inaccurate for large dimension
self.smooth_on... |
Loads target classes. | def load_target_class(input_dir):
"""Loads target classes."""
with tf.gfile.Open(os.path.join(input_dir, 'target_class.csv')) as f:
return {row[0]: int(row[1]) for row in csv.reader(f) if len(row) >= 2} |
Saves images to the output directory. | def save_images(images, filenames, output_dir):
"""Saves images to the output directory.
Args:
images: array with minibatch of images
filenames: list of filenames without path
If number of file names in this list less than number of images in
the minibatch then only first len(filenames) images ... |
Run the sample attack | def main(_):
"""Run the sample attack"""
# Images for inception classifier are normalized to be in [-1, 1] interval,
# eps is a difference between pixels so it should be in [0, 2] interval.
# Renormalizing epsilon from [0, 255] to [0, 2].
eps = 2.0 * FLAGS.max_epsilon / 255.0
alpha = 2.0 * FLAGS.iter_alpha ... |
Applies DeepFool to a batch of inputs: param sess: TF session: param x: The input placeholder: param pred: The model s sorted symbolic output of logits only the top nb_candidate classes are contained: param logits: The model s unnormalized output tensor ( the input to the softmax layer ): param grads: Symbolic gradient... | def deepfool_batch(sess,
x,
pred,
logits,
grads,
X,
nb_candidate,
overshoot,
max_iter,
clip_min,
clip_max,
nb_c... |
TensorFlow implementation of DeepFool. Paper link: see https:// arxiv. org/ pdf/ 1511. 04599. pdf: param sess: TF session: param x: The input placeholder: param predictions: The model s sorted symbolic output of logits only the top nb_candidate classes are contained: param logits: The model s unnormalized output tensor... | def deepfool_attack(sess,
x,
predictions,
logits,
grads,
sample,
nb_candidate,
overshoot,
max_iter,
clip_min,
clip_max,
... |
Generate symbolic graph for adversarial examples and return. | 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`
"""
assert self.sess is not None, \
'Cannot use `generate` when no `sess` was provided'
from cleverhans.utils_tf... |
: param nb_candidate: The number of classes to test against i. e. deepfool only consider nb_candidate classes when attacking ( thus accelerate speed ). The nb_candidate classes are chosen according to the prediction confidence during implementation.: param overshoot: A termination criterion to prevent vanishing updates... | def parse_params(self,
nb_candidate=10,
overshoot=0.02,
max_iter=50,
clip_min=0.,
clip_max=1.,
**kwargs):
"""
:param nb_candidate: The number of classes to test against, i.e.,
... |
PyFunc defined as given by Tensorflow: param func: Custom Function: param inp: Function Inputs: param Tout: Ouput Type of out Custom Function: param stateful: Calculate Gradients when stateful is True: param name: Name of the PyFunction: param grad: Custom Gradient Function: return: | def _py_func_with_gradient(func, inp, Tout, stateful=True, name=None,
grad_func=None):
"""
PyFunc defined as given by Tensorflow
:param func: Custom Function
:param inp: Function Inputs
:param Tout: Ouput Type of out Custom Function
:param stateful: Calculate Gradients when statef... |
Convert a pytorch model into a tensorflow op that allows backprop: param model: A pytorch nn. Module object: param out_dims: The number of output dimensions ( classes ) for the model: return: A model function that maps an input ( tf. Tensor ) to the output of the model ( tf. Tensor ) | def convert_pytorch_model_to_tf(model, out_dims=None):
"""
Convert a pytorch model into a tensorflow op that allows backprop
:param model: A pytorch nn.Module object
:param out_dims: The number of output dimensions (classes) for the model
:return: A model function that maps an input (tf.Tensor) to the
outpu... |
PyTorch implementation of the clip_eta in utils_tf. | def clip_eta(eta, ord, eps):
"""
PyTorch implementation of the clip_eta in utils_tf.
:param eta: Tensor
:param ord: np.inf, 1, or 2
:param eps: float
"""
if ord not in [np.inf, 1, 2]:
raise ValueError('ord must be np.inf, 1, or 2.')
avoid_zero_div = torch.tensor(1e-12, dtype=eta.dtype, device=eta.... |
Get the label to use in generating an adversarial example for x. The kwargs are fed directly from the kwargs of the attack. If y is in kwargs then assume it s an untargeted attack and use that as the label. If y_target is in kwargs and is not none then assume it s a targeted attack and use that as the label. Otherwise ... | def get_or_guess_labels(model, x, **kwargs):
"""
Get the label to use in generating an adversarial example for x.
The kwargs are fed directly from the kwargs of the attack.
If 'y' is in kwargs, then assume it's an untargeted attack and
use that as the label.
If 'y_target' is in kwargs and is not none, then ... |
Solves for the optimal input to a linear function under a norm constraint. | def optimize_linear(grad, eps, ord=np.inf):
"""
Solves for the optimal input to a linear function under a norm constraint.
Optimal_perturbation = argmax_{eta, ||eta||_{ord} < eps} dot(eta, grad)
:param grad: Tensor, shape (N, d_1, ...). Batch of gradients
:param eps: float. Scalar specifying size of constra... |
: param y: ( optional ) A tensor with the true labels for an untargeted attack. If None ( and y_target is None ) then use the original labels the classifier assigns.: param y_target: ( optional ) A tensor with the target labels for a targeted attack.: param beta: Trades off L2 distortion with L1 distortion: higher prod... | def parse_params(self,
y=None,
y_target=None,
beta=1e-2,
decision_rule='EN',
batch_size=1,
confidence=0,
learning_rate=1e-2,
binary_search_steps=9,
m... |
Perform the EAD attack on the given instance for the given targets. | def attack(self, imgs, targets):
"""
Perform the EAD attack on the given instance for the given targets.
If self.targeted is true, then the targets represents the target labels
If self.targeted is false, then targets are the original class labels
"""
batch_size = self.batch_size
r = []
... |
Prints text surrounded by a box made of * s | def print_in_box(text):
"""
Prints `text` surrounded by a box made of *s
"""
print('')
print('*' * (len(text) + 6))
print('** ' + text + ' **')
print('*' * (len(text) + 6))
print('') |
Validates the submission. | def main(args):
"""
Validates the submission.
"""
print_in_box('Validating submission ' + args.submission_filename)
random.seed()
temp_dir = args.temp_dir
delete_temp_dir = False
if not temp_dir:
temp_dir = tempfile.mkdtemp()
logging.info('Created temporary directory: %s', temp_dir)
delete_t... |
Make a confidence report and save it to disk. | def main(argv=None):
"""
Make a confidence report and save it to disk.
"""
try:
_name_of_script, filepath = argv
except ValueError:
raise ValueError(argv)
make_confidence_report(filepath=filepath, test_start=FLAGS.test_start,
test_end=FLAGS.test_end, which_set=FLAGS.which_se... |
Load a saved model gather its predictions and save a confidence report. | def make_confidence_report_spsa(filepath, train_start=TRAIN_START,
train_end=TRAIN_END,
test_start=TEST_START, test_end=TEST_END,
batch_size=BATCH_SIZE, which_set=WHICH_SET,
report_path=REPORT... |
Make a confidence report and save it to disk. | def main(argv=None):
"""
Make a confidence report and save it to disk.
"""
try:
_name_of_script, filepath = argv
except ValueError:
raise ValueError(argv)
make_confidence_report_spsa(filepath=filepath, test_start=FLAGS.test_start,
test_end=FLAGS.test_end,
... |
This method creates a symoblic graph of the MadryEtAl attack on multiple GPUs. The graph is created on the first n GPUs. | def attack(self, x, y_p, **kwargs):
"""
This method creates a symoblic graph of the MadryEtAl attack on
multiple GPUs. The graph is created on the first n GPUs.
Stop gradient is needed to get the speed-up. This prevents us from
being able to back-prop through the attack.
:param x: A tensor wit... |
Facilitates testing this attack. | def generate_np(self, x_val, **kwargs):
"""
Facilitates testing this attack.
"""
_, feedable, _feedable_types, hash_key = self.construct_variables(kwargs)
if hash_key not in self.graphs:
with tf.variable_scope(None, 'attack_%d' % len(self.graphs)):
# x is a special placeholder we alwa... |
Take in a dictionary of parameters and applies attack - specific checks before saving them as attributes. | def parse_params(self, ngpu=1, **kwargs):
"""
Take in a dictionary of parameters and applies attack-specific checks
before saving them as attributes.
Attack-specific parameters:
:param ngpu: (required int) the number of GPUs available.
:param kwargs: A dictionary of parameters for MadryEtAl att... |
Compute the accuracy of a TF model on some data: param sess: TF session to use when training the graph: param model: cleverhans. model. Model instance: param x: numpy array containing input examples ( e. g. MNIST (). x_test ): param y: numpy array containing example labels ( e. g. MNIST (). y_test ): param batch_size: ... | def accuracy(sess, model, x, y, batch_size=None, devices=None, feed=None,
attack=None, attack_params=None):
"""
Compute the accuracy of a TF model on some data
:param sess: TF session to use when training the graph
:param model: cleverhans.model.Model instance
:param x: numpy array containing inp... |
Return the model s classification of the input data and the confidence ( probability ) assigned to each example.: param sess: tf. Session: param model: cleverhans. model. Model: param x: numpy array containing input examples ( e. g. MNIST (). x_test ): param y: numpy array containing true labels ( Needed only if using ... | def class_and_confidence(sess, model, x, y=None, batch_size=None,
devices=None, feed=None, attack=None,
attack_params=None):
"""
Return the model's classification of the input data, and the confidence
(probability) assigned to each example.
:param sess: tf.Sessi... |
Report whether the model is correct and its confidence on each example in a dataset.: param sess: tf. Session: param model: cleverhans. model. Model: param x: numpy array containing input examples ( e. g. MNIST (). x_test ): param y: numpy array containing example labels ( e. g. MNIST (). y_test ): param batch_size: Nu... | def correctness_and_confidence(sess, model, x, y, batch_size=None,
devices=None, feed=None, attack=None,
attack_params=None):
"""
Report whether the model is correct and its confidence on each example in
a dataset.
:param sess: tf.Session
:param mo... |
Run attack on every example in a dataset.: param sess: tf. Session: param model: cleverhans. model. Model: param x: numpy array containing input examples ( e. g. MNIST (). x_test ): param y: numpy array containing example labels ( e. g. MNIST (). y_test ): param attack: cleverhans. attack. Attack: param attack_params: ... | def run_attack(sess, model, x, y, attack, attack_params, batch_size=None,
devices=None, feed=None, pass_y=False):
"""
Run attack on every example in a dataset.
:param sess: tf.Session
:param model: cleverhans.model.Model
:param x: numpy array containing input examples (e.g. MNIST().x_test )
:... |
Generic computation engine for evaluating an expression across a whole dataset divided into batches. | def batch_eval_multi_worker(sess, graph_factory, numpy_inputs, batch_size=None,
devices=None, feed=None):
"""
Generic computation engine for evaluating an expression across a whole
dataset, divided into batches.
This function assumes that the work can be parallelized with one worker... |
A helper function that computes a tensor on numpy inputs by batches. This version uses exactly the tensorflow graph constructed by the caller so the caller can place specific ops on specific devices to implement model parallelism. Most users probably prefer batch_eval_multi_worker which maps a single - device expressio... | def batch_eval(sess, tf_inputs, tf_outputs, numpy_inputs, batch_size=None,
feed=None,
args=None):
"""
A helper function that computes a tensor on numpy inputs by batches.
This version uses exactly the tensorflow graph constructed by the
caller, so the caller can place specific ops ... |
Makes sure a y argument is a vliad numpy dataset. | def _check_y(y):
"""
Makes sure a `y` argument is a vliad numpy dataset.
"""
if not isinstance(y, np.ndarray):
raise TypeError("y must be numpy array. Typically y contains "
"the entire test set labels. Got " + str(y) + " of type " + str(type(y))) |
Read png images from input directory in batches. | def load_images(input_dir, batch_shape):
"""Read png images from input directory in batches.
Args:
input_dir: input directory
batch_shape: shape of minibatch array, i.e. [batch_size, height, width, 3]
Yields:
filenames: list file names without path of each image
Length of this list could be le... |
Run the sample attack | def main(_):
"""Run the sample attack"""
batch_shape = [FLAGS.batch_size, FLAGS.image_height, FLAGS.image_width, 3]
for filenames, images in load_images(FLAGS.input_dir, batch_shape):
save_images(images, filenames, FLAGS.output_dir) |
Creates a preprocessing graph for a batch given a function that processes a single image. | def preprocess_batch(images_batch, preproc_func=None):
"""
Creates a preprocessing graph for a batch given a function that processes
a single image.
:param images_batch: A tensor for an image batch.
:param preproc_func: (optional function) A function that takes in a
tensor and returns a preprocessed in... |
: param x: A symbolic representation ( Tensor ) of the network input: return: A symbolic representation ( Tensor ) of the output logits ( i. e. the values fed as inputs to the softmax layer ). | def get_logits(self, x, **kwargs):
"""
:param x: A symbolic representation (Tensor) of the network input
:return: A symbolic representation (Tensor) of the output logits
(i.e., the values fed as inputs to the softmax layer).
"""
outputs = self.fprop(x, **kwargs)
if self.O_LOGITS in outputs:
... |
: param x: A symbolic representation ( Tensor ) of the network input: return: A symbolic representation ( Tensor ) of the predicted label | def get_predicted_class(self, x, **kwargs):
"""
:param x: A symbolic representation (Tensor) of the network input
:return: A symbolic representation (Tensor) of the predicted label
"""
return tf.argmax(self.get_logits(x, **kwargs), axis=1) |
: param x: A symbolic representation ( Tensor ) of the network input: return: A symbolic representation ( Tensor ) of the output probabilities ( i. e. the output values produced by the softmax layer ). | def get_probs(self, x, **kwargs):
"""
:param x: A symbolic representation (Tensor) of the network input
:return: A symbolic representation (Tensor) of the output
probabilities (i.e., the output values produced by the softmax layer).
"""
d = self.fprop(x, **kwargs)
if self.O_PROBS in d:
... |
Provides access to the model s parameters.: return: A list of all Variables defining the model parameters. | def get_params(self):
"""
Provides access to the model's parameters.
:return: A list of all Variables defining the model parameters.
"""
if hasattr(self, 'params'):
return list(self.params)
# Catch eager execution and assert function overload.
try:
if tf.executing_eagerly():
... |
Create all Variables to be returned later by get_params. By default this is a no - op. Models that need their fprop to be called for their params to be created can set needs_dummy_fprop = True in the constructor. | def make_params(self):
"""
Create all Variables to be returned later by get_params.
By default this is a no-op.
Models that need their fprop to be called for their params to be
created can set `needs_dummy_fprop=True` in the constructor.
"""
if self.needs_dummy_fprop:
if hasattr(self,... |
Return a layer output.: param x: tensor the input to the network.: param layer: str the name of the layer to compute.: param ** kwargs: dict extra optional params to pass to self. fprop.: return: the content of layer layer | def get_layer(self, x, layer, **kwargs):
"""Return a layer output.
:param x: tensor, the input to the network.
:param layer: str, the name of the layer to compute.
:param **kwargs: dict, extra optional params to pass to self.fprop.
:return: the content of layer `layer`
"""
return self.fprop(... |
Takes in confidence values for predictions and correct labels for the data plots a reliability diagram.: param confidence: nb_samples x nb_classes ( e. g. output of softmax ): param labels: vector of nb_samples: param filepath: where to save the diagram: return: | def plot_reliability_diagram(confidence, labels, filepath):
"""
Takes in confidence values for predictions and correct
labels for the data, plots a reliability diagram.
:param confidence: nb_samples x nb_classes (e.g., output of softmax)
:param labels: vector of nb_samples
:param filepath: where to save the... |
Initializes locality - sensitive hashing with FALCONN to find nearest neighbors in training data. | def init_lsh(self):
"""
Initializes locality-sensitive hashing with FALCONN to find nearest neighbors in training data.
"""
self.query_objects = {
} # contains the object that can be queried to find nearest neighbors at each layer.
# mean of training data representation per layer (that needs to... |
Given a data_activation dictionary that contains a np array with activations for each layer find the knns in the training data. | def find_train_knns(self, data_activations):
"""
Given a data_activation dictionary that contains a np array with activations for each layer,
find the knns in the training data.
"""
knns_ind = {}
knns_labels = {}
for layer in self.layers:
# Pre-process representations of data to norma... |
Given an dictionary of nb_data x nb_classes dimension compute the nonconformity of each candidate label for each data point: i. e. the number of knns whose label is different from the candidate label. | def nonconformity(self, knns_labels):
"""
Given an dictionary of nb_data x nb_classes dimension, compute the nonconformity of
each candidate label for each data point: i.e. the number of knns whose label is
different from the candidate label.
"""
nb_data = knns_labels[self.layers[0]].shape[0]
... |
Given an array of nb_data x nb_classes dimensions use conformal prediction to compute the DkNN s prediction confidence and credibility. | def preds_conf_cred(self, knns_not_in_class):
"""
Given an array of nb_data x nb_classes dimensions, use conformal prediction to compute
the DkNN's prediction, confidence and credibility.
"""
nb_data = knns_not_in_class.shape[0]
preds_knn = np.zeros(nb_data, dtype=np.int32)
confs = np.zeros(... |
Performs a forward pass through the DkNN on an numpy array of data. | def fprop_np(self, data_np):
"""
Performs a forward pass through the DkNN on an numpy array of data.
"""
if not self.calibrated:
raise ValueError(
"DkNN needs to be calibrated by calling DkNNModel.calibrate method once before inferring.")
data_activations = self.get_activations(data_... |
Performs a forward pass through the DkNN on a TF tensor by wrapping the fprop_np method. | def fprop(self, x):
"""
Performs a forward pass through the DkNN on a TF tensor by wrapping
the fprop_np method.
"""
logits = tf.py_func(self.fprop_np, [x], tf.float32)
return {self.O_LOGITS: logits} |
Runs the DkNN on holdout data to calibrate the credibility metric.: param cali_data: np array of calibration data.: param cali_labels: np vector of calibration labels. | def calibrate(self, cali_data, cali_labels):
"""
Runs the DkNN on holdout data to calibrate the credibility metric.
:param cali_data: np array of calibration data.
:param cali_labels: np vector of calibration labels.
"""
self.nb_cali = cali_labels.shape[0]
self.cali_activations = self.get_ac... |
MNIST cleverhans tutorial: param nb_epochs: number of epochs to train model: param batch_size: size of training batches: param learning_rate: learning rate for training: return: an AccuracyReport object | def mnist_tutorial(nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE,
train_end=-1, test_end=-1, learning_rate=LEARNING_RATE):
"""
MNIST cleverhans tutorial
:param nb_epochs: number of epochs to train model
:param batch_size: size of training batches
:param learning_rate: learning rate for trainin... |
TensorFlow implementation for apply perturbations to input features based on salency maps: param i: index of first selected feature: param j: index of second selected feature: param X: a matrix containing our input features for our sample: param increase: boolean ; true if we are increasing pixels false otherwise: para... | def apply_perturbations(i, j, X, increase, theta, clip_min, clip_max):
"""
TensorFlow implementation for apply perturbations to input features based
on salency maps
:param i: index of first selected feature
:param j: index of second selected feature
:param X: a matrix containing our input features for our s... |
TensorFlow implementation for computing saliency maps: param grads_target: a matrix containing forward derivatives for the target class: param grads_other: a matrix where every element is the sum of forward derivatives over all non - target classes at that index: param search_domain: the set of input indices that we ar... | def saliency_map(grads_target, grads_other, search_domain, increase):
"""
TensorFlow implementation for computing saliency maps
:param grads_target: a matrix containing forward derivatives for the
target class
:param grads_other: a matrix where every element is the sum of forward
... |
TensorFlow implementation of the foward derivative/ Jacobian: param x: the input placeholder: param grads: the list of TF gradients returned by jacobian_graph (): param target: the target misclassification class: param X: numpy array with sample input: param nb_features: the number of features in the input: return: mat... | def jacobian(sess, x, grads, target, X, nb_features, nb_classes, feed=None):
"""
TensorFlow implementation of the foward derivative / Jacobian
:param x: the input placeholder
:param grads: the list of TF gradients returned by jacobian_graph()
:param target: the target misclassification class
:param X: numpy... |
This class implements either the Basic Iterative Method ( Kurakin et al. 2016 ) when rand_init is set to 0. or the Madry et al. ( 2017 ) method when rand_minmax is larger than 0. Paper link ( Kurakin et al. 2016 ): https:// arxiv. org/ pdf/ 1607. 02533. pdf Paper link ( Madry et al. 2017 ): https:// arxiv. org/ pdf/ 17... | def projected_gradient_descent(model_fn, x, eps, eps_iter, nb_iter, ord,
clip_min=None, clip_max=None, y=None, targeted=False,
rand_init=None, rand_minmax=0.3, sanity_checks=True):
"""
This class implements either the Basic Iterative Method
(Kurakin et... |
Batch normalization. | def _batch_norm(name, x):
"""Batch normalization."""
with tf.name_scope(name):
return tf.contrib.layers.batch_norm(
inputs=x,
decay=.9,
center=True,
scale=True,
activation_fn=None,
updates_collections=None,
is_training=False) |
Residual unit with 2 sub layers. | def _residual(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 = _batch_norm('init_bn', x)
x = _relu(x, 0.1)
orig_x = x
else:
with tf.variabl... |
L2 weight decay loss. | def _decay():
"""L2 weight decay loss."""
costs = []
for var in tf.trainable_variables():
if var.op.name.find('DW') > 0:
costs.append(tf.nn.l2_loss(var))
return tf.add_n(costs) |
Relu with optional leaky support. | def _relu(x, leakiness=0.0):
"""Relu, with optional leaky support."""
return tf.where(tf.less(x, 0.0), leakiness * x, x, name='leaky_relu') |
Build the core model within the graph. | def set_input_shape(self, input_shape):
batch_size, rows, cols, input_channels = input_shape
# assert self.mode == 'train' or self.mode == 'eval'
"""Build the core model within the graph."""
input_shape = list(input_shape)
input_shape[0] = 1
dummy_batch = tf.zeros(input_shape)
dummy_output =... |
Function to create variables for the projected dual object. Function that projects the input dual variables onto the feasible set. Returns: projected_dual: Feasible dual solution corresponding to current dual | def create_projected_dual(self):
"""Function to create variables for the projected dual object.
Function that projects the input dual variables onto the feasible set.
Returns:
projected_dual: Feasible dual solution corresponding to current dual
"""
# TODO: consider whether we can use shallow c... |
Computes matrices T and V using the Lanczos algorithm. | 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... |
Function that constructs minimization objective from dual variables. | 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):
... |
Function that provides matrix product interface with PSD matrix. | def get_h_product(self, vector, dtype=None):
"""Function that provides matrix product interface with PSD matrix.
Args:
vector: the vector to be multiplied with matrix H
Returns:
result_product: Matrix product of H and vector
"""
# Computing the product of matrix_h with beta (input vect... |
Function that provides matrix product interface with PSD matrix. | 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... |
Function that returns the tf graph corresponding to the entire matrix M. | def get_full_psd_matrix(self):
"""Function that returns the tf graph corresponding to the entire matrix M.
Returns:
matrix_h: unrolled version of tf matrix corresponding to H
matrix_m: unrolled tf matrix corresponding to M
"""
if self.matrix_m is not None:
return self.matrix_h, self.m... |
Run binary search to find a value for nu that makes M PSD Args: original_nu: starting value of nu to do binary search on feed_dictionary: dictionary of updated lambda variables to feed into M Returns: new_nu: new value of nu | def make_m_psd(self, original_nu, feed_dictionary):
"""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
"""
... |
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: Corre... | 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... |
Function to compute the certificate based either current value or dual variables loaded from dual folder | 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('... |
Generate symbolic graph for adversarial examples and return.: param x: The model s symbolic inputs.: param kwargs: See parse_params | 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... |
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.: par... | 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,
... |
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... | 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
... |
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: numb... | def cnn_model(logits=False, input_ph=None, img_rows=28, img_cols=28,
channels=1, nb_filters=64, nb_classes=10):
"""
Defines a CNN model using Keras sequential model
:param logits: If set to False, returns a Keras model, otherwise will also
return logits tensor
:param input_ph: Th... |
Looks for the name of the softmax layer.: return: Softmax layer 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 ... |
Looks for the name of abstracted layer. Usually these layers appears when model is stacked.: return: List of abstracted layers | def _get_abstract_layer_name(self):
"""
Looks for the name of abstracted layer.
Usually these layers appears when model is stacked.
:return: List of abstracted layers
"""
abstract_layers = []
for layer in self.model.layers:
if 'layers' in layer.get_config():
abstract_layers.app... |
Looks for the name of the layer producing the logits.: return: name of layer producing the logits | 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... |
: param x: A symbolic representation of the network input.: return: A symbolic representation of the logits | def get_logits(self, x):
"""
:param x: A symbolic representation of the network input.
:return: A symbolic representation of the logits
"""
logits_name = self._get_logits_name()
logits_layer = self.get_layer(x, logits_name)
# Need to deal with the case where softmax is part of the
# log... |
: param x: A symbolic representation of the network input.: return: A symbolic representation of the 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) |
: return: Names of all the layers kept by Keras | 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 |
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. | def fprop(self, x):
"""
Exposes all the layers of the model returned by get_layer_names.
:param x: A symbolic representation of the network input
:return: A dictionary mapping layer names to the symbolic
representation of their output.
"""
if self.keras_model is None:
# Get t... |
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. | def get_layer(self, x, layer):
"""
Expose the hidden features of a model given a layer name.
:param x: A symbolic representation of the network input
:param layer: The name of the hidden layer to return features at.
:return: A symbolic representation of the hidden features
:raise: NoSuchLayerErr... |
Returns extraction command based on the filename extension. | 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 |
Calls shell command with parameter substitution. | 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}', '$... |
Makes directory readable and writable by everybody. | def make_directory_writable(dirname):
"""Makes directory readable and writable by everybody.
Args:
dirname: name of the directory
Returns:
True if operation was successfull
If you run something inside Docker container and it writes files, then
these files will be written as root user with restricte... |
Cleans up and prepare temporary directory. | def _prepare_temp_dir(self):
"""Cleans up and prepare temporary directory."""
if not shell_call(['sudo', 'rm', '-rf', os.path.join(self._temp_dir, '*')]):
logging.error('Failed to cleanup temporary directory.')
sys.exit(1)
# NOTE: we do not create self._extracted_submission_dir
# this is int... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.