Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def generate(self, x, **kwargs):
assert self.sess is not None, \
'Cannot use `generate` when no `sess` was provided'
from cleverhans.utils_tf import jacobian_graph
# Parse and save attack-specific parameters
assert self.parse_params(**kwargs)
... | [
"\n Generate symbolic graph for adversarial examples and return.\n\n :param x: The model's symbolic inputs.\n :param kwargs: See `parse_params`\n ",
"deepfool function for py_func"
] |
Please provide a description of the function:def parse_params(self,
nb_candidate=10,
overshoot=0.02,
max_iter=50,
clip_min=0.,
clip_max=1.,
**kwargs):
self.nb_candidate = nb_candidate
self.over... | [
"\n :param nb_candidate: The number of classes to test against, i.e.,\n deepfool only consider nb_candidate classes when\n attacking(thus accelerate speed). The nb_candidate\n classes are chosen according to the prediction\n ... |
Please provide a description of the function:def _py_func_with_gradient(func, inp, Tout, stateful=True, name=None,
grad_func=None):
# Generate random name in order to avoid conflicts with inbuilt names
rnd_name = 'PyFuncGrad-' + '%0x' % getrandbits(30 * 4)
# Register Tensorflow Grad... | [
"\n PyFunc defined as given by Tensorflow\n :param func: Custom Function\n :param inp: Function Inputs\n :param Tout: Ouput Type of out Custom Function\n :param stateful: Calculate Gradients when stateful is True\n :param name: Name of the PyFunction\n :param grad: Custom Gradient Function\n :return:\n "
] |
Please provide a description of the function:def convert_pytorch_model_to_tf(model, out_dims=None):
warnings.warn("convert_pytorch_model_to_tf is deprecated, switch to"
+ " dedicated PyTorch support provided by CleverHans v4.")
torch_state = {
'logits': None,
'x': None,
}
if not ... | [
"\n Convert a pytorch model into a tensorflow op that allows backprop\n :param model: A pytorch nn.Module object\n :param out_dims: The number of output dimensions (classes) for the model\n :return: A model function that maps an input (tf.Tensor) to the\n output of the model (tf.Tensor)\n ",
"TODO: write th... |
Please provide a description of the function:def clip_eta(eta, ord, eps):
if ord not in [np.inf, 1, 2]:
raise ValueError('ord must be np.inf, 1, or 2.')
avoid_zero_div = torch.tensor(1e-12, dtype=eta.dtype, device=eta.device)
reduc_ind = list(range(1, len(eta.size())))
if ord == np.inf:
eta = torch.... | [
"\n PyTorch implementation of the clip_eta in utils_tf.\n\n :param eta: Tensor\n :param ord: np.inf, 1, or 2\n :param eps: float\n "
] |
Please provide a description of the function:def get_or_guess_labels(model, x, **kwargs):
if 'y' in kwargs and 'y_target' in kwargs:
raise ValueError("Can not set both 'y' and 'y_target'.")
if 'y' in kwargs:
labels = kwargs['y']
elif 'y_target' in kwargs and kwargs['y_target'] is not None:
labels =... | [
"\n Get the label to use in generating an adversarial example for x.\n The kwargs are fed directly from the kwargs of the attack.\n If 'y' is in kwargs, then assume it's an untargeted attack and\n use that as the label.\n If 'y_target' is in kwargs and is not none, then assume it's a\n targeted attack and use... |
Please provide a description of the function:def optimize_linear(grad, eps, ord=np.inf):
red_ind = list(range(1, len(grad.size())))
avoid_zero_div = torch.tensor(1e-12, dtype=grad.dtype, device=grad.device)
if ord == np.inf:
# Take sign of gradient
optimal_perturbation = torch.sign(grad)
elif ord ==... | [
"\n Solves for the optimal input to a linear function under a norm constraint.\n\n Optimal_perturbation = argmax_{eta, ||eta||_{ord} < eps} dot(eta, grad)\n\n :param grad: Tensor, shape (N, d_1, ...). Batch of gradients\n :param eps: float. Scalar specifying size of constraint region\n :param ord: np.inf, 1, o... |
Please provide a description of the function:def parse_params(self,
y=None,
y_target=None,
beta=1e-2,
decision_rule='EN',
batch_size=1,
confidence=0,
learning_rate=1e-2,
... | [
"\n :param y: (optional) A tensor with the true labels for an untargeted\n attack. If None (and y_target is None) then use the\n original labels the classifier assigns.\n :param y_target: (optional) A tensor with the target labels for a\n targeted attack.\n :param bet... |
Please provide a description of the function:def attack(self, imgs, targets):
batch_size = self.batch_size
r = []
for i in range(0, len(imgs) // batch_size):
_logger.debug(
("Running EAD attack on instance %s of %s",
i * batch_size, len(imgs)))
r.extend(
self... | [
"\n Perform the EAD attack on the given instance for the given targets.\n\n If self.targeted is true, then the targets represents the target labels\n If self.targeted is false, then targets are the original class labels\n "
] |
Please provide a description of the function:def print_in_box(text):
print('')
print('*' * (len(text) + 6))
print('** ' + text + ' **')
print('*' * (len(text) + 6))
print('') | [
"\n Prints `text` surrounded by a box made of *s\n "
] |
Please provide a description of the function:def main(args):
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)
... | [
"\n Validates the submission.\n "
] |
Please provide a description of the function:def main(argv=None):
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_set,
... | [
"\n Make a confidence report and save it to disk.\n "
] |
Please provide a description of the function: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,
... | [
"\n Load a saved model, gather its predictions, and save a confidence report.\n\n\n This function works by running a single MaxConfidence attack on each example,\n using SPSA as the underyling optimizer.\n This is not intended to be a strong generic attack.\n It is intended to be a test to uncover gradient mas... |
Please provide a description of the function:def main(argv=None):
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,
... | [
"\n Make a confidence report and save it to disk.\n "
] |
Please provide a description of the function:def attack(self, x, y_p, **kwargs):
inputs = []
outputs = []
# Create the initial random perturbation
device_name = '/gpu:0'
self.model.set_device(device_name)
with tf.device(device_name):
with tf.variable_scope('init_rand'):
if se... | [
"\n This method creates a symoblic graph of the MadryEtAl attack on\n multiple GPUs. The graph is created on the first n GPUs.\n\n Stop gradient is needed to get the speed-up. This prevents us from\n being able to back-prop through the attack.\n\n :param x: A tensor with the input image.\n :param ... |
Please provide a description of the function:def generate_np(self, x_val, **kwargs):
_, 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 always ... | [
"\n Facilitates testing this attack.\n "
] |
Please provide a description of the function:def parse_params(self, ngpu=1, **kwargs):
return_status = super(MadryEtAlMultiGPU, self).parse_params(**kwargs)
self.ngpu = ngpu
return return_status | [
"\n Take in a dictionary of parameters and applies attack-specific checks\n before saving them as attributes.\n\n Attack-specific parameters:\n :param ngpu: (required int) the number of GPUs available.\n :param kwargs: A dictionary of parameters for MadryEtAl attack.\n "
] |
Please provide a description of the function:def accuracy(sess, model, x, y, batch_size=None, devices=None, feed=None,
attack=None, attack_params=None):
_check_x(x)
_check_y(y)
if x.shape[0] != y.shape[0]:
raise ValueError("Number of input examples and labels do not match.")
factory = _Cor... | [
"\n Compute the accuracy of a TF model on some data\n :param sess: TF session to use when training the graph\n :param model: cleverhans.model.Model instance\n :param x: numpy array containing input examples (e.g. MNIST().x_test )\n :param y: numpy array containing example labels (e.g. MNIST().y_test )\n :para... |
Please provide a description of the function:def class_and_confidence(sess, model, x, y=None, batch_size=None,
devices=None, feed=None, attack=None,
attack_params=None):
_check_x(x)
inputs = [x]
if attack is not None:
inputs.append(y)
_check_y(y)
i... | [
"\n Return the model's classification of the input data, and the confidence\n (probability) assigned to each example.\n :param sess: tf.Session\n :param model: cleverhans.model.Model\n :param x: numpy array containing input examples (e.g. MNIST().x_test )\n :param y: numpy array containing true labels\n (N... |
Please provide a description of the function:def correctness_and_confidence(sess, model, x, y, batch_size=None,
devices=None, feed=None, attack=None,
attack_params=None):
_check_x(x)
_check_y(y)
if x.shape[0] != y.shape[0]:
raise ValueError("Nu... | [
"\n Report whether the model is correct and its confidence on each example in\n a dataset.\n :param sess: tf.Session\n :param model: cleverhans.model.Model\n :param x: numpy array containing input examples (e.g. MNIST().x_test )\n :param y: numpy array containing example labels (e.g. MNIST().y_test )\n :para... |
Please provide a description of the function:def run_attack(sess, model, x, y, attack, attack_params, batch_size=None,
devices=None, feed=None, pass_y=False):
_check_x(x)
_check_y(y)
factory = _AttackFactory(model, attack, attack_params, pass_y)
out, = batch_eval_multi_worker(sess, factory,... | [
"\n Run attack on every example in a dataset.\n :param sess: tf.Session\n :param model: cleverhans.model.Model\n :param x: numpy array containing input examples (e.g. MNIST().x_test )\n :param y: numpy array containing example labels (e.g. MNIST().y_test )\n :param attack: cleverhans.attack.Attack\n :param a... |
Please provide a description of the function:def batch_eval_multi_worker(sess, graph_factory, numpy_inputs, batch_size=None,
devices=None, feed=None):
canary.run_canary()
global _batch_eval_multi_worker_cache
devices = infer_devices(devices)
if batch_size is None:
# For big ... | [
"\n Generic computation engine for evaluating an expression across a whole\n dataset, divided into batches.\n\n This function assumes that the work can be parallelized with one worker\n device handling one batch of data. If you need multiple devices per\n batch, use `batch_eval`.\n\n The tensorflow graph for ... |
Please provide a description of the function:def batch_eval(sess, tf_inputs, tf_outputs, numpy_inputs, batch_size=None,
feed=None,
args=None):
if args is not None:
warnings.warn("`args` is deprecated and will be removed on or "
"after 2019-03-09. Pass `batch_siz... | [
"\n A helper function that computes a tensor on numpy inputs by batches.\n This version uses exactly the tensorflow graph constructed by the\n caller, so the caller can place specific ops on specific devices\n to implement model parallelism.\n Most users probably prefer `batch_eval_multi_worker` which maps\n ... |
Please provide a description of the function:def _check_y(y):
if not isinstance(y, np.ndarray):
raise TypeError("y must be numpy array. Typically y contains "
"the entire test set labels. Got " + str(y) + " of type " + str(type(y))) | [
"\n Makes sure a `y` argument is a vliad numpy dataset.\n "
] |
Please provide a description of the function:def load_images(input_dir, batch_shape):
images = np.zeros(batch_shape)
filenames = []
idx = 0
batch_size = batch_shape[0]
for filepath in tf.gfile.Glob(os.path.join(input_dir, '*.png')):
with tf.gfile.Open(filepath) as f:
images[idx, :, :, :] = imread... | [
"Read png images from input directory in batches.\n\n Args:\n input_dir: input directory\n batch_shape: shape of minibatch array, i.e. [batch_size, height, width, 3]\n\n Yields:\n filenames: list file names without path of each image\n Length of this list could be less than batch_size, in this case ... |
Please provide a description of the function:def main(_):
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) | [
"Run the sample attack"
] |
Please provide a description of the function:def preprocess_batch(images_batch, preproc_func=None):
if preproc_func is None:
return images_batch
with tf.variable_scope('preprocess'):
images_list = tf.split(images_batch, int(images_batch.shape[0]))
result_list = []
for img in images_list:
r... | [
"\n Creates a preprocessing graph for a batch given a function that processes\n a single image.\n\n :param images_batch: A tensor for an image batch.\n :param preproc_func: (optional function) A function that takes in a\n tensor and returns a preprocessed input.\n "
] |
Please provide a description of the function:def get_logits(self, x, **kwargs):
outputs = self.fprop(x, **kwargs)
if self.O_LOGITS in outputs:
return outputs[self.O_LOGITS]
raise NotImplementedError(str(type(self)) + "must implement `get_logits`"
" or must define a "... | [
"\n :param x: A symbolic representation (Tensor) of the network input\n :return: A symbolic representation (Tensor) of the output logits\n (i.e., the values fed as inputs to the softmax layer).\n "
] |
Please provide a description of the function:def get_predicted_class(self, x, **kwargs):
return tf.argmax(self.get_logits(x, **kwargs), axis=1) | [
"\n :param x: A symbolic representation (Tensor) of the network input\n :return: A symbolic representation (Tensor) of the predicted label\n "
] |
Please provide a description of the function:def get_probs(self, x, **kwargs):
d = self.fprop(x, **kwargs)
if self.O_PROBS in d:
output = d[self.O_PROBS]
min_prob = tf.reduce_min(output)
max_prob = tf.reduce_max(output)
asserts = [utils_tf.assert_greater_equal(min_prob,
... | [
"\n :param x: A symbolic representation (Tensor) of the network input\n :return: A symbolic representation (Tensor) of the output\n probabilities (i.e., the output values produced by the softmax layer).\n "
] |
Please provide a description of the function:def get_params(self):
if hasattr(self, 'params'):
return list(self.params)
# Catch eager execution and assert function overload.
try:
if tf.executing_eagerly():
raise NotImplementedError("For Eager execution - get_params "
... | [
"\n Provides access to the model's parameters.\n :return: A list of all Variables defining the model parameters.\n "
] |
Please provide a description of the function:def make_params(self):
if self.needs_dummy_fprop:
if hasattr(self, "_dummy_input"):
return
self._dummy_input = self.make_input_placeholder()
self.fprop(self._dummy_input) | [
"\n Create all Variables to be returned later by get_params.\n By default this is a no-op.\n Models that need their fprop to be called for their params to be\n created can set `needs_dummy_fprop=True` in the constructor.\n "
] |
Please provide a description of the function:def get_layer(self, x, layer, **kwargs):
return self.fprop(x, **kwargs)[layer] | [
"Return a layer output.\n :param x: tensor, the input to the network.\n :param layer: str, the name of the layer to compute.\n :param **kwargs: dict, extra optional params to pass to self.fprop.\n :return: the content of layer `layer`\n "
] |
Please provide a description of the function:def plot_reliability_diagram(confidence, labels, filepath):
assert len(confidence.shape) == 2
assert len(labels.shape) == 1
assert confidence.shape[0] == labels.shape[0]
print('Saving reliability diagram at: ' + str(filepath))
if confidence.max() <= 1.:
... | [
"\n Takes in confidence values for predictions and correct\n labels for the data, plots a reliability diagram.\n :param confidence: nb_samples x nb_classes (e.g., output of softmax)\n :param labels: vector of nb_samples\n :param filepath: where to save the diagram\n :return:\n "
] |
Please provide a description of the function:def init_lsh(self):
self.query_objects = {
} # contains the object that can be queried to find nearest neighbors at each layer.
# mean of training data representation per layer (that needs to be substracted before LSH).
self.centers = {}
for layer i... | [
"\n Initializes locality-sensitive hashing with FALCONN to find nearest neighbors in training data.\n "
] |
Please provide a description of the function:def find_train_knns(self, data_activations):
knns_ind = {}
knns_labels = {}
for layer in self.layers:
# Pre-process representations of data to normalize and remove training data mean.
data_activations_layer = copy.copy(data_activations[layer])
... | [
"\n Given a data_activation dictionary that contains a np array with activations for each layer,\n find the knns in the training data.\n "
] |
Please provide a description of the function:def nonconformity(self, knns_labels):
nb_data = knns_labels[self.layers[0]].shape[0]
knns_not_in_class = np.zeros((nb_data, self.nb_classes), dtype=np.int32)
for i in range(nb_data):
# Compute number of nearest neighbors per class
knns_in_class =... | [
"\n Given an dictionary of nb_data x nb_classes dimension, compute the nonconformity of\n each candidate label for each data point: i.e. the number of knns whose label is\n different from the candidate label.\n "
] |
Please provide a description of the function:def preds_conf_cred(self, knns_not_in_class):
nb_data = knns_not_in_class.shape[0]
preds_knn = np.zeros(nb_data, dtype=np.int32)
confs = np.zeros((nb_data, self.nb_classes), dtype=np.float32)
creds = np.zeros((nb_data, self.nb_classes), dtype=np.float32)... | [
"\n Given an array of nb_data x nb_classes dimensions, use conformal prediction to compute\n the DkNN's prediction, confidence and credibility.\n "
] |
Please provide a description of the function:def fprop_np(self, data_np):
if not self.calibrated:
raise ValueError(
"DkNN needs to be calibrated by calling DkNNModel.calibrate method once before inferring.")
data_activations = self.get_activations(data_np)
_, knns_labels = self.find_tra... | [
"\n Performs a forward pass through the DkNN on an numpy array of data.\n "
] |
Please provide a description of the function:def fprop(self, x):
logits = tf.py_func(self.fprop_np, [x], tf.float32)
return {self.O_LOGITS: logits} | [
"\n Performs a forward pass through the DkNN on a TF tensor by wrapping\n the fprop_np method.\n "
] |
Please provide a description of the function:def calibrate(self, cali_data, cali_labels):
self.nb_cali = cali_labels.shape[0]
self.cali_activations = self.get_activations(cali_data)
self.cali_labels = cali_labels
print("Starting calibration of DkNN.")
cali_knns_ind, cali_knns_labels = self.fin... | [
"\n Runs the DkNN on holdout data to calibrate the credibility metric.\n :param cali_data: np array of calibration data.\n :param cali_labels: np vector of calibration labels.\n "
] |
Please provide a description of the function:def mnist_tutorial(nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE,
train_end=-1, test_end=-1, learning_rate=LEARNING_RATE):
# Train a pytorch MNIST model
torch_model = PytorchMnistModel()
if torch.cuda.is_available():
torch_model = torch_model.cud... | [
"\n MNIST cleverhans tutorial\n :param nb_epochs: number of epochs to train model\n :param batch_size: size of training batches\n :param learning_rate: learning rate for training\n :return: an AccuracyReport object\n "
] |
Please provide a description of the function:def apply_perturbations(i, j, X, increase, theta, clip_min, clip_max):
warnings.warn(
"This function is dead code and will be removed on or after 2019-07-18")
# perturb our input sample
if increase:
X[0, i] = np.minimum(clip_max, X[0, i] + theta)
X[0,... | [
"\n TensorFlow implementation for apply perturbations to input features based\n on salency maps\n :param i: index of first selected feature\n :param j: index of second selected feature\n :param X: a matrix containing our input features for our sample\n :param increase: boolean; true if we are increasing pixel... |
Please provide a description of the function:def saliency_map(grads_target, grads_other, search_domain, increase):
warnings.warn(
"This function is dead code and will be removed on or after 2019-07-18")
# Compute the size of the input (the number of features)
nf = len(grads_target)
# Remove the alrea... | [
"\n TensorFlow implementation for computing saliency maps\n :param grads_target: a matrix containing forward derivatives for the\n target class\n :param grads_other: a matrix where every element is the sum of forward\n derivatives over all non-target classes at that ind... |
Please provide a description of the function:def jacobian(sess, x, grads, target, X, nb_features, nb_classes, feed=None):
warnings.warn(
"This function is dead code and will be removed on or after 2019-07-18")
# Prepare feeding dictionary for all gradient computations
feed_dict = {x: X}
if feed is not... | [
"\n TensorFlow implementation of the foward derivative / Jacobian\n :param x: the input placeholder\n :param grads: the list of TF gradients returned by jacobian_graph()\n :param target: the target misclassification class\n :param X: numpy array with sample input\n :param nb_features: the number of features i... |
Please provide a description of the function: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):
assert eps_iter <= eps, (ep... | [
"\n This class implements either the Basic Iterative Method\n (Kurakin et al. 2016) when rand_init is set to 0. or the\n Madry et al. (2017) method when rand_minmax is larger than 0.\n Paper link (Kurakin et al. 2016): https://arxiv.org/pdf/1607.02533.pdf\n Paper link (Madry et al. 2017): https://arxiv.org/pdf... |
Please provide a description of the function:def _batch_norm(name, x):
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) | [
"Batch normalization."
] |
Please provide a description of the function:def _residual(x, in_filter, out_filter, stride,
activate_before_residual=False):
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.... | [
"Residual unit with 2 sub layers."
] |
Please provide a description of the function:def _decay():
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) | [
"L2 weight decay loss."
] |
Please provide a description of the function:def _relu(x, leakiness=0.0):
return tf.where(tf.less(x, 0.0), leakiness * x, x, name='leaky_relu') | [
"Relu, with optional leaky support."
] |
Please provide a description of the function:def set_input_shape(self, input_shape):
batch_size, rows, cols, input_channels = input_shape
# assert self.mode == 'train' or self.mode == 'eval'
input_shape = list(input_shape)
input_shape[0] = 1
dummy_batch = tf.zeros(input_shape)
dummy_output ... | [
"Build the core model within the graph."
] |
Please provide a description of the function:def create_projected_dual(self):
# TODO: consider whether we can use shallow copy of the lists without
# using tf.identity
projected_nu = tf.placeholder(tf.float32, shape=[])
min_eig_h = tf.placeholder(tf.float32, shape=[])
projected_lambda_pos = [tf... | [
"Function to create variables for the projected dual object.\n Function that projects the input dual variables onto the feasible set.\n Returns:\n projected_dual: Feasible dual solution corresponding to current dual\n "
] |
Please provide a description of the function: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_produc... | [
"Computes matrices T and V using the Lanczos algorithm.\n\n Args:\n k: number of iterations and dimensionality of the tridiagonal matrix\n Returns:\n eig_vec: eigen vector corresponding to min eigenvalue\n "
] |
Please provide a description of the function: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.... | [
"Function that constructs minimization objective from dual variables."
] |
Please provide a description of the function: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 = []
... | [
"Function that provides matrix product interface with PSD matrix.\n\n Args:\n vector: the vector to be multiplied with matrix H\n\n Returns:\n result_product: Matrix product of H and vector\n "
] |
Please provide a description of the function: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:]
# ... | [
"Function that provides matrix product interface with PSD matrix.\n\n Args:\n vector: the vector to be multiplied with matrix M\n\n Returns:\n result_product: Matrix product of M and vector\n "
] |
Please provide a description of the function: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):... | [
"Function that returns the tf graph corresponding to the entire matrix M.\n\n Returns:\n matrix_h: unrolled version of tf matrix corresponding to H\n matrix_m: unrolled tf matrix corresponding to M\n "
] |
Please provide a description of the function: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... | [
"Run binary search to find a value for nu that makes M PSD\n Args:\n original_nu: starting value of nu to do binary search on\n feed_dictionary: dictionary of updated lambda variables to feed into M\n Returns:\n new_nu: new value of nu\n "
] |
Please provide a description of the function: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_... | [
"Computes the min eigen value and corresponding vector of matrix M or H\n using the Lanczos algorithm.\n Args:\n compute_m: boolean to determine whether we should compute eig val/vec\n for M or for H. True for M; False for H.\n feed_dict: dictionary mapping from TF placeholders to values (opt... |
Please provide a description of the function: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,
... | [
"\n Generate symbolic graph for adversarial examples and return.\n :param x: The model's symbolic inputs.\n :param kwargs: See `parse_params`\n "
] |
Please provide a description of the function: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,
... | [
"\n Take in a dictionary of parameters and applies attack-specific checks\n before saving them as attributes.\n :param n_samples: (optional) The number of transformations sampled to\n construct the attack. Set it to None to run\n full grid attack.\n :param dx_mi... |
Please provide a description of the function: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:
re... | [
"\n Defines the right convolutional layer according to the\n version of Keras that is installed.\n :param filters: (required integer) the dimensionality of the output\n space (i.e. the number output of filters in the\n convolution)\n :param kernel_shape: (required tuple or list... |
Please provide a description of the function: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() ==... | [
"\n Defines a CNN model using Keras sequential model\n :param logits: If set to False, returns a Keras model, otherwise will also\n return logits tensor\n :param input_ph: The TensorFlow tensor for the input\n (needed if returning logits)\n (\"ph\" stands for pl... |
Please provide a description of the function: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") | [
"\n Looks for the name of the softmax layer.\n :return: Softmax layer name\n "
] |
Please provide a description of the function: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 | [
"\n Looks for the name of abstracted layer.\n Usually these layers appears when model is stacked.\n :return: List of abstracted layers\n "
] |
Please provide a description of the function: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
... | [
"\n Looks for the name of the layer producing the logits.\n :return: name of layer producing the logits\n "
] |
Please provide a description of the function: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_lay... | [
"\n :param x: A symbolic representation of the network input.\n :return: A symbolic representation of the logits\n "
] |
Please provide a description of the function:def get_probs(self, x):
name = self._get_softmax_name()
return self.get_layer(x, name) | [
"\n :param x: A symbolic representation of the network input.\n :return: A symbolic representation of the probs\n "
] |
Please provide a description of the function:def get_layer_names(self):
layer_names = [x.name for x in self.model.layers]
return layer_names | [
"\n :return: Names of all the layers kept by Keras\n "
] |
Please provide a description of the function: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_l... | [
"\n Exposes all the layers of the model returned by get_layer_names.\n :param x: A symbolic representation of the network input\n :return: A dictionary mapping layer names to the symbolic\n representation of their output.\n "
] |
Please provide a description of the function: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 | [
"\n Expose the hidden features of a model given a layer name.\n :param x: A symbolic representation of the network input\n :param layer: The name of the hidden layer to return features at.\n :return: A symbolic representation of the hidden features\n :raise: NoSuchLayerError if `layer` is not in the ... |
Please provide a description of the function: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."
] |
Please provide a description of the function: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.\n\n Args:\n command: command to run as a list of tokens\n **kwargs: dirctionary with substitutions\n\n Returns:\n whether command was successful, i.e. returned 0 status code\n\n Example of usage:\n shell_call(['cp', '${A}', '${B}'], A='src_file', B='d... |
Please provide a description of the function: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:
loggi... | [
"Makes directory readable and writable by everybody.\n\n Args:\n dirname: name of the directory\n\n Returns:\n True if operation was successfull\n\n If you run something inside Docker container and it writes files, then\n these files will be written as root user with restricted permissions.\n So to be ab... |
Please provide a description of the function: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 intent... | [
"Cleans up and prepare temporary directory."
] |
Please provide a description of the function: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_... | [
"Extracts submission and moves it into self._extracted_submission_dir."
] |
Please provide a description of the function: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 ... | [
"Verifies size of Docker image.\n\n Args:\n image_name: name of the Docker image.\n\n Returns:\n True if image size is within the limits, False otherwise.\n "
] |
Please provide a description of the function: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(
... | [
"Prepares sample data for the submission.\n\n Args:\n submission_type: type of the submission.\n "
] |
Please provide a description of the function: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.... | [
"Verifies correctness of the submission output.\n\n Args:\n submission_type: type of the submission\n\n Returns:\n True if output looks valid\n "
] |
Please provide a description of the function: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... | [
"Validates submission.\n\n Args:\n filename: submission filename\n\n Returns:\n submission metadata or None if submission is invalid\n "
] |
Please provide a description of the function: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\n "
] |
Please provide a description of the function: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... | [
"Pairwise Euclidean distance between two matrices.\n :param A: a matrix.\n :param B: a matrix.\n\n :returns: A tensor for the pairwise Euclidean between A and B.\n "
] |
Please provide a description of the function: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.\n :param A: a matrix.\n :param B: a matrix.\n\n :returns: A tensor for the pairwise cosine between A and B.\n "
] |
Please provide a description of the function: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\n all those of B.\n :param A: a matrix.\n :param B: a matrix.\n :param temp: Temperature\n :cos_distance: Boolean for using cosine or Euclidean distance.\n\n :returns: A tensor for the exponentiated pairwise distance between\n each ... |
Please provide a description of the function: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\n of x. Conceptualized as the probability of sampling a neighbor point for\n every element of x, proportional to the distance between the points.\n :param x: a matrix\n :param temp: Temperature\n :cos_distance: Boolean for using... |
Please provide a description of the function: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].\n :param y: a list of labels\n :param y2: a list of labels\n\n :returns: A tensor for the masking matrix.\n "
] |
Please provide a description of the function: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\n points which share labels.\n :param x: a matrix\n :param y: a list of labels for each element of x\n :param temp: Temperature\n :cos_distance: Boolean for using cosine or Euclidean distance\n\n :returns: A tensor for the pai... |
Please provide a description of the function: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\n :param x: a matrix.\n :param y: a list of labels for each element of x.\n :param temp: Temperature.\n :cos_distance: Boolean for using cosine or Euclidean distance.\n\n :returns: A tensor for the Soft Nearest Neighbor Loss of the points\n in x with labels y.... |
Please provide a description of the function: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 wh... | [
"The optimized variant of Soft Nearest Neighbor Loss. Every time this\n tensor is evaluated, the temperature is optimized to minimize the loss\n value, this results in more numerically stable calculations of the SNNL.\n :param x: a matrix.\n :param y: a list of labels for each element of x.\n :param ... |
Please provide a description of the function: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]) | [
"\n Display an image.\n :param ndarray: The image as an ndarray\n :param min_val: The minimum pixel value in the image format\n :param max_val: The maximum pixel valie in the image format\n If min_val and max_val are not specified, attempts to\n infer whether the image is in any of the common ranges:\n ... |
Please provide a description of the function:def save(path, ndarray, min_val=None, max_val=None):
as_pil(ndarray, min_val, max_val).save(path) | [
"\n Save an image, represented as an ndarray, to the filesystem\n :param path: string, filepath\n :param ndarray: The image as an ndarray\n :param min_val: The minimum pixel value in the image format\n :param max_val: The maximum pixel valie in the image format\n If min_val and max_val are not specified, at... |
Please provide a description of the function: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 ... | [
"\n Converts an ndarray to a PIL image.\n :param ndarray: The numpy ndarray to convert\n :param min_val: The minimum pixel value in the image format\n :param max_val: The maximum pixel valie in the image format\n If min_val and max_val are not specified, attempts to\n infer whether the image is in any of ... |
Please provide a description of the function: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))... | [
"\n Turns a batch of images into one big image.\n :param image_batch: ndarray, shape (batch_size, rows, cols, channels)\n :returns : a big image containing all `batch_size` images in a grid\n "
] |
Please provide a description of the function: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() | [
"\n Generate adversarial examples and return them as a NumPy array.\n\n :param x_val: A NumPy array with the original inputs.\n :param **kwargs: optional parameters used by child classes.\n :return: A NumPy array holding the adversarial examples.\n "
] |
Please provide a description of the function: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)) | [
"\n Generates the adversarial sample for the given input.\n :param x: The model's inputs.\n :param eps: (optional float) attack step size (input variation)\n :param ord: (optional) Order of the norm (mimics NumPy).\n Possible values: np.inf, 1 or 2.\n :param y: (optional) A tf variable... |
Please provide a description of the function: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.mod... | [
"\n TensorFlow Eager implementation of the Fast Gradient Method.\n :param x: the input variable\n :param targeted: Is the attack targeted or untargeted? Untargeted, the\n default, will try to make the label incorrect.\n Targeted will instead try to move in the direct... |
Please provide a description of the function: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 outpu... | [
"\n Returns random data to be used with `feed_dict`.\n :param rng: A numpy.random.RandomState instance\n :param placeholders: List of tensorflow placeholders\n :return: A dict mapping placeholders to random numpy values\n "
] |
Please provide a description of the function: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... | [
"\n Returns a list of all files in CleverHans with the given suffix.\n\n Parameters\n ----------\n suffix : str\n\n Returns\n -------\n\n file_list : list\n A list of all files in CleverHans whose filepath ends with `suffix`.\n "
] |
Please provide a description of the function: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... | [
"\n Returns a list of all files ending in `suffix` contained within `path`.\n\n Parameters\n ----------\n path : str\n a filepath\n suffix : str\n\n Returns\n -------\n l : list\n A list of all files ending in `suffix` contained within `path`.\n (If `path` is a file rather than a directory, i... |
Please provide a description of the function: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."
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.