INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
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.
Args:
eig_init_vec_val: Start value for eigen value computations
eig_num_iter_val: Number of iterations to run for eigen computations
smooth_val: Value of smoothness parameter
penalty_val: Value of penalty for the current step
learnin... | 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.
Returns:
True if certificate is found
False otherwise | 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.
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 will be saved.
output_dir: directory where to sav... | 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... | 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 ... | 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.
: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`
"""
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
confide... | 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.
:param eta: Tensor
:param ord: np.inf, 1, or 2
:param eps: float | 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 l... | 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.
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 constraint region
:param ord: np.inf, 1, or 2. Order of n... | 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... | 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... |
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.
This function works by running a single MaxConfidence attack on each example,
using SPSA as the underyling optimizer.
This is not intended to be a strong generic attack.
It is intended to be a test to uncover gradient masking.
:param... | 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.
Stop gradient is needed to get the speed-up. This prevents us from
being able to back-prop through the attack.
:param x: A tensor with the input image.
:param y_p: Ground truth ... | 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.
Attack-specific parameters:
:param ngpu: (required int) the number of GPUs available.
:param kwargs: A dictionary of parameters for MadryEtAl attack. | 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 u... | 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: N... | 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: d... | 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.
This function assumes that the work can be parallelized with one worker
device handling one batch of data. If you need multiple devices per
batch, use `batch_eval`.
The tensorflow graph for multiple workers... | 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-devic... | 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.
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 less than batch_size, in this case only
fi... | 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.
:param images_batch: A tensor for an image batch.
:param preproc_func: (optional function) A function that takes in a
tensor and returns a preprocessed input. | 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 other... | 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 s... | 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
... | 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/1706.06083.p... | 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... |
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):
... |
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 | 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 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 | 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... |
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)
... | 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 flo... | 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... | 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... | 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.
Args:
command: command to run as a list of tokens
**kwargs: dirctionary with substitutions
Returns:
whether command was successful, i.e. returned 0 status code
Example of usage:
shell_call(['cp', '${A}', '${B}'], A='src_file', B='dst_file')
wil... | 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.
Args:
dirname: name of the directory
Returns:
True if operation was successfull
If you run something inside Docker container and it writes files, then
these files will be written as root user with restricted permissions.
So to be able to read/modi... | 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... |
Extracts submission and moves it into self._extracted_submission_dir. | 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',
... |
Verifies size of Docker image.
Args:
image_name: name of the Docker image.
Returns:
True if image size is within the limits, False otherwise. | 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_... |
Prepares sample data for the submission.
Args:
submission_type: type of the submission. | def _prepare_sample_data(self, submission_type):
"""Prepares sample data for the submission.
Args:
submission_type: type of the submission.
"""
# write images
images = np.random.randint(0, 256,
size=[BATCH_SIZE, 299, 299, 3], dtype=np.uint8)
for i in range(B... |
Verifies correctness of the submission output.
Args:
submission_type: type of the submission
Returns:
True if output looks valid | def _verify_output(self, submission_type):
"""Verifies correctness of the submission output.
Args:
submission_type: type of the submission
Returns:
True if output looks valid
"""
result = True
if submission_type == 'defense':
try:
image_classification = load_defense_o... |
Validates submission.
Args:
filename: submission filename
Returns:
submission metadata or None if submission is invalid | def validate_submission(self, filename):
"""Validates submission.
Args:
filename: submission filename
Returns:
submission metadata or None if submission is invalid
"""
self._prepare_temp_dir()
# Convert filename to be absolute path, relative path might cause problems
# with mou... |
Save loss in json format | 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')) |
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. | def pairwise_euclid_distance(A, B):
"""Pairwise Euclidean distance between two matrices.
:param A: a matrix.
:param B: a matrix.
:returns: A tensor for the pairwise Euclidean between A and B.
"""
batchA = tf.shape(A)[0]
batchB = tf.shape(B)[0]
sqr_norm_A = tf.reshape(tf.reduce_sum(tf.p... |
Pairwise cosine distance between two matrices.
:param A: a matrix.
:param B: a matrix.
:returns: A tensor for the pairwise cosine between A and B. | def pairwise_cos_distance(A, B):
"""Pairwise cosine distance between two matrices.
:param A: a matrix.
:param B: a matrix.
:returns: A tensor for the pairwise cosine between A and B.
"""
normalized_A = tf.nn.l2_normalize(A, dim=1)
normalized_B = tf.nn.l2_normalize(B, dim=1)
prod = tf.ma... |
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... | def fits(A, B, temp, cos_distance):
"""Exponentiated pairwise distance between each element of A and
all those of B.
:param A: a matrix.
:param B: a matrix.
:param temp: Temperature
:cos_distance: Boolean for using cosine or Euclidean distance.
:returns: A tensor for the exponentiated pairw... |
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... | def pick_probability(x, temp, cos_distance):
"""Row normalized exponentiated pairwise distance between all the elements
of x. Conceptualized as the probability of sampling a neighbor point for
every element of x, proportional to the distance between the points.
:param x: a matrix
:param temp: Temper... |
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. | 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) |
The pairwise sampling probabilities for the elements of x for neighbor
points which share labels.
:param x: a matrix
:param y: a list of labels for each element of x
:param temp: Temperature
:cos_distance: Boolean for using cosine or Euclidean distance
:returns: A tensor for the pairwise sampli... | def masked_pick_probability(x, y, temp, cos_distance):
"""The pairwise sampling probabilities for the elements of x for neighbor
points which share labels.
:param x: a matrix
:param y: a list of labels for each element of x
:param temp: Temperature
:cos_distance: Boolean for using cosine or Eucl... |
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. | 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
... |
The optimized variant of Soft Nearest Neighbor Loss. Every time this
tensor is evaluated, the temperature is optimized to minimize the loss
value, this results in more numerically stable calculations of the SNNL.
:param x: a matrix.
:param y: a list of labels for each element of x.
:param initial_te... | def optimized_temp_SNNL(x, y, initial_temp, cos_distance):
"""The optimized variant of Soft Nearest Neighbor Loss. Every time this
tensor is evaluated, the temperature is optimized to minimize the loss
value, this results in more numerically stable calculations of the SNNL.
:param x: a matrix.
:para... |
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,... | def show(ndarray, min_val=None, max_val=None):
"""
Display an image.
:param ndarray: The image as an ndarray
:param min_val: The minimum pixel value in the image format
:param max_val: The maximum pixel valie in the image format
If min_val and max_val are not specified, attempts to
infer whether the i... |
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
... | 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
... |
Converts an ndarray to a PIL image.
:param ndarray: The numpy ndarray to convert
:param min_val: The minimum pixel value in the image format
:param max_val: The maximum pixel valie in the image format
If min_val and max_val are not specified, attempts to
infer whether the image is in any of the common ran... | def as_pil(ndarray, min_val=None, max_val=None):
"""
Converts an ndarray to a PIL image.
:param ndarray: The numpy ndarray to convert
:param min_val: The minimum pixel value in the image format
:param max_val: The maximum pixel valie in the image format
If min_val and max_val are not specified, attempts t... |
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 | def make_grid(image_batch):
"""
Turns a batch of images into one big image.
:param image_batch: ndarray, shape (batch_size, rows, cols, channels)
:returns : a big image containing all `batch_size` images in a grid
"""
m, ir, ic, ch = image_batch.shape
pad = 3
padded = np.zeros((m, ir + pad * 2, ic + p... |
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. | 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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.