INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Return the counts for only those examples that are below the threshold
def filter(self, run_counts, criteria): """ Return the counts for only those examples that are below the threshold """ wrong_confidence = criteria['wrong_confidence'] below_t = wrong_confidence <= self.t filtered_counts = deep_copy(run_counts) for key in filtered_counts: filtered_count...
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...
Clip an image, or an image batch, with upper and lower threshold.
def clip_image(image, clip_min, clip_max): """ Clip an image, or an image batch, with upper and lower threshold. """ return np.minimum(np.maximum(clip_min, image), clip_max)
Compute the distance between two images.
def compute_distance(x_ori, x_pert, constraint='l2'): """ Compute the distance between two images. """ if constraint == 'l2': dist = np.linalg.norm(x_ori - x_pert) elif constraint == 'linf': dist = np.max(abs(x_ori - x_pert)) return dist
Gradient direction estimation
def approximate_gradient(decision_function, sample, num_evals, delta, constraint, shape, clip_min, clip_max): """ Gradient direction estimation """ # Generate random vectors. noise_shape = [num_evals] + list(shape) if constraint == 'l2': rv = np.random.randn(*noise_shape) elif con...
Projection onto given l2 / linf balls in a batch.
def project(original_image, perturbed_images, alphas, shape, constraint): """ Projection onto given l2 / linf balls in a batch. """ alphas_shape = [len(alphas)] + [1] * len(shape) alphas = alphas.reshape(alphas_shape) if constraint == 'l2': projected = (1-alphas) * original_image + alphas * perturbed_images...
Binary search to approach the boundary.
def binary_search_batch(original_image, perturbed_images, decision_function, shape, constraint, theta): """ Binary search to approach the boundary. """ # Compute distance between each of perturbed image and original image. dists_post_update = np.array([ compute_distance( o...
Efficient Implementation of BlendedUniformNoiseAttack in Foolbox.
def initialize(decision_function, sample, shape, clip_min, clip_max): """ Efficient Implementation of BlendedUniformNoiseAttack in Foolbox. """ success = 0 num_evals = 0 # Find a misclassified random noise. while True: random_noise = np.random.uniform(clip_min, clip_max, size=shape) success = dec...
Geometric progression to search for stepsize. Keep decreasing stepsize by half until reaching the desired side of the boundary.
def geometric_progression_for_stepsize(x, update, dist, decision_function, current_iteration): """ Geometric progression to search for stepsize. Keep decreasing stepsize by half until reaching the desired side of the boundary. """ epsilon = dist / np.sqrt(current...
Choose the delta at the scale of distance between x and perturbed sample.
def select_delta(dist_post_update, current_iteration, clip_max, clip_min, d, theta, constraint): """ Choose the delta at the scale of distance between x and perturbed sample. """ if current_iteration == 1: delta = 0.1 * (clip_max - clip_min) else: if constraint == 'l2': delta...
Return a tensor that constructs adversarial examples for the given input. Generate uses tf.py_func in order to operate over tensors. :param x: A tensor with the inputs. :param kwargs: See `parse_params`
def generate(self, x, **kwargs): """ Return a tensor that constructs adversarial examples for the given input. Generate uses tf.py_func in order to operate over tensors. :param x: A tensor with the inputs. :param kwargs: See `parse_params` """ self.parse_params(**kwargs) shape = [int(i) ...
Generate adversarial images in a for loop. :param y: An array of shape (n, nb_classes) for true labels. :param y_target: An array of shape (n, nb_classes) for target labels. Required for targeted attack. :param image_target: An array of shape (n, **image shape) for initial target images. Required f...
def generate_np(self, x, **kwargs): """ Generate adversarial images in a for loop. :param y: An array of shape (n, nb_classes) for true labels. :param y_target: An array of shape (n, nb_classes) for target labels. Required for targeted attack. :param image_target: An array of shape (n, **image ...
:param y: A tensor of shape (1, nb_classes) for true labels. :param y_target: A tensor of shape (1, nb_classes) for target labels. Required for targeted attack. :param image_target: A tensor of shape (1, **image shape) for initial target images. Required for targeted attack. :param initial_num_eval...
def parse_params(self, y_target=None, image_target=None, initial_num_evals=100, max_num_evals=10000, stepsize_search='grid_search', num_iterations=64, gamma=0.01, const...
Main algorithm for Boundary Attack ++. Return a tensor that constructs adversarial examples for the given input. Generate uses tf.py_func in order to operate over tensors. :param sample: input image. Without the batchsize dimension. :param target_label: integer for targeted attack, None for nont...
def _bapp(self, sample, target_label, target_image): """ Main algorithm for Boundary Attack ++. Return a tensor that constructs adversarial examples for the given input. Generate uses tf.py_func in order to operate over tensors. :param sample: input image. Without the batchsize dimension. :par...
Take in a dictionary of parameters and applies attack-specific checks before saving them as attributes. Attack-specific parameters: :param layer: (required str) name of the layer to target. :param eps: (optional float) maximum distortion of adversarial example compared to original inpu...
def parse_params(self, layer=None, eps=0.3, eps_iter=0.05, nb_iter=10, ord=np.inf, clip_min=None, clip_max=None, **kwargs): """ Take in a dictionary of paramete...
TensorFlow implementation of the Fast Feature Gradient. This is a single step attack similar to Fast Gradient Method that attacks an internal representation. :param x: the input placeholder :param eta: A tensor the same shape as x that holds the perturbation. :param g_feat: model's internal tensor ...
def attack_single_step(self, x, eta, g_feat): """ TensorFlow implementation of the Fast Feature Gradient. This is a single step attack similar to Fast Gradient Method that attacks an internal representation. :param x: the input placeholder :param eta: A tensor the same shape as x that holds the...
Generate symbolic graph for adversarial examples and return. :param x: The model's symbolic inputs. :param g: The target value of the symbolic representation :param kwargs: See `parse_params`
def generate(self, x, g, **kwargs): """ Generate symbolic graph for adversarial examples and return. :param x: The model's symbolic inputs. :param g: The target value of the symbolic representation :param kwargs: See `parse_params` """ # Parse and save attack-specific parameters assert...
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) print(filepath) make_confidence_report_bundled(filepath=filepath, test_start=FLAGS.test_start, ...
Builds the 35x35 resnet block.
def block35(net, scale=1.0, activation_fn=tf.nn.relu, scope=None, reuse=None): """Builds the 35x35 resnet block.""" with tf.variable_scope(scope, 'Block35', [net], reuse=reuse): with tf.variable_scope('Branch_0'): tower_conv = slim.conv2d(net, 32, 1, scope='Conv2d_1x1') with tf.variable_scope('Branch_...
Builds the 17x17 resnet block.
def block17(net, scale=1.0, activation_fn=tf.nn.relu, scope=None, reuse=None): """Builds the 17x17 resnet block.""" with tf.variable_scope(scope, 'Block17', [net], reuse=reuse): with tf.variable_scope('Branch_0'): tower_conv = slim.conv2d(net, 192, 1, scope='Conv2d_1x1') with tf.variable_scope('Branch...
Inception model from http://arxiv.org/abs/1602.07261. Constructs an Inception Resnet v2 network from inputs to the given final endpoint. This method can construct the network up to the final inception block Conv2d_7b_1x1. Args: inputs: a tensor of size [batch_size, height, width, channels]. final_end...
def inception_resnet_v2_base(inputs, final_endpoint='Conv2d_7b_1x1', output_stride=16, align_feature_maps=False, scope=None): """Inception model from http://arxiv.org/abs/1602.07261. Constructs an I...
Creates the Inception Resnet V2 model. Args: inputs: a 4-D tensor of size [batch_size, height, width, 3]. nb_classes: number of predicted classes. is_training: whether is training or not. dropout_keep_prob: float, the fraction to keep before final layer. reuse: whether or not the network and its ...
def inception_resnet_v2(inputs, nb_classes=1001, is_training=True, dropout_keep_prob=0.8, reuse=None, scope='InceptionResnetV2', create_aux_logits=True, num_classes=None): """Creates the Inception R...
Returns the scope with the default parameters for inception_resnet_v2. Args: weight_decay: the weight decay for weights variables. batch_norm_decay: decay for the moving average of batch_norm momentums. batch_norm_epsilon: small float added to variance to avoid dividing by zero. Returns: a arg_sco...
def inception_resnet_v2_arg_scope(weight_decay=0.00004, batch_norm_decay=0.9997, batch_norm_epsilon=0.001): """Returns the scope with the default parameters for inception_resnet_v2. Args: weight_decay: the weight decay for weights variables. ...
Load training and test data.
def ld_mnist(): """Load training and test data.""" def convert_types(image, label): image = tf.cast(image, tf.float32) image /= 255 return image, label dataset, info = tfds.load('mnist', data_dir='gs://tfds-data/datasets', with_info=True, as_supervised=True) mnist_train...
MNIST CleverHans tutorial :param train_start: index of first training set example :param train_end: index of last training set example :param test_start: index of first test set example :param test_end: index of last test set example :param nb_epochs: number of epochs to train model :param batch_size: size ...
def mnist_tutorial(train_start=0, train_end=60000, test_start=0, test_end=10000, nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE, learning_rate=LEARNING_RATE, testing=False, label_smoothing=0.1): """ MNIST CleverHans tutorial :param train_start: index of first t...
Validate all submissions and copy them into place
def main(args): """Validate all submissions and copy them into place""" random.seed() temp_dir = tempfile.mkdtemp() logging.info('Created temporary directory: %s', temp_dir) validator = SubmissionValidator( source_dir=args.source_dir, target_dir=args.target_dir, temp_dir=temp_dir, do_c...
Common method to update submission statistics.
def _update_stat(self, submission_type, increase_success, increase_fail): """Common method to update submission statistics.""" stat = self.stats.get(submission_type, (0, 0)) stat = (stat[0] + increase_success, stat[1] + increase_fail) self.stats[submission_type] = stat
Print statistics into log.
def log_stats(self): """Print statistics into log.""" logging.info('Validation statistics: ') for k, v in iteritems(self.stats): logging.info('%s - %d valid out of %d total submissions', k, v[0], v[0] + v[1])
Copies submission from Google Cloud Storage to local directory. Args: cloud_path: path of the submission in Google Cloud Storage Returns: name of the local file where submission is copied to
def copy_submission_locally(self, cloud_path): """Copies submission from Google Cloud Storage to local directory. Args: cloud_path: path of the submission in Google Cloud Storage Returns: name of the local file where submission is copied to """ local_path = os.path.join(self.download_d...
Copies submission to target directory. Args: src_filename: source filename of the submission dst_subdir: subdirectory of the target directory where submission should be copied to submission_id: ID of the submission, will be used as a new submission filename (before extension)
def copy_submission_to_destination(self, src_filename, dst_subdir, submission_id): """Copies submission to target directory. Args: src_filename: source filename of the submission dst_subdir: subdirectory of the target directory where submission should be...
Validates one submission and copies it to target directory. Args: submission_path: path in Google Cloud Storage of the submission file
def validate_and_copy_one_submission(self, submission_path): """Validates one submission and copies it to target directory. Args: submission_path: path in Google Cloud Storage of the submission file """ if os.path.exists(self.download_dir): shutil.rmtree(self.download_dir) os.makedirs(s...
Saves mapping from submission IDs to original filenames. This mapping is saved as CSV file into target directory.
def save_id_to_path_mapping(self): """Saves mapping from submission IDs to original filenames. This mapping is saved as CSV file into target directory. """ if not self.id_to_path_mapping: return with open(self.local_id_to_path_mapping_file, 'w') as f: writer = csv.writer(f) writer...
Runs validation of all submissions.
def run(self): """Runs validation of all submissions.""" cmd = ['gsutil', 'ls', os.path.join(self.source_dir, '**')] try: files_list = subprocess.check_output(cmd).split('\n') except subprocess.CalledProcessError: logging.error('Can''t read source directory') all_submissions = [ ...
Takes the path to a directory with reports and renders success fail plots.
def main(argv=None): """Takes the path to a directory with reports and renders success fail plots.""" report_paths = argv[1:] fail_names = FLAGS.fail_names.split(',') for report_path in report_paths: plot_report_from_path(report_path, label=report_path, fail_names=fail_names) pyplot.legend() pyplot.x...
Returns True if work piece is unclaimed.
def is_unclaimed(work): """Returns True if work piece is unclaimed.""" if work['is_completed']: return False cutoff_time = time.time() - MAX_PROCESSING_TIME if (work['claimed_worker_id'] and work['claimed_worker_start_time'] is not None and work['claimed_worker_start_time'] >= cutoff_time): ...
Writes all work pieces into datastore. Each work piece is identified by ID. This method writes/updates only those work pieces which IDs are stored in this class. For examples, if this class has only work pieces with IDs '1' ... '100' and datastore already contains work pieces with IDs '50' ... '200' t...
def write_all_to_datastore(self): """Writes all work pieces into datastore. Each work piece is identified by ID. This method writes/updates only those work pieces which IDs are stored in this class. For examples, if this class has only work pieces with IDs '1' ... '100' and datastore already contains ...
Reads all work pieces from the datastore.
def read_all_from_datastore(self): """Reads all work pieces from the datastore.""" self._work = {} client = self._datastore_client parent_key = client.key(KIND_WORK_TYPE, self._work_type_entity_id) for entity in client.query_fetch(kind=KIND_WORK, ancestor=parent_key): work_id = entity.key.flat...
Reads undone worke pieces which are assigned to shard with given id.
def _read_undone_shard_from_datastore(self, shard_id=None): """Reads undone worke pieces which are assigned to shard with given id.""" self._work = {} client = self._datastore_client parent_key = client.key(KIND_WORK_TYPE, self._work_type_entity_id) filters = [('is_completed', '=', False)] if sh...
Reads undone work from the datastore. If shard_id and num_shards are specified then this method will attempt to read undone work for shard with id shard_id. If no undone work was found then it will try to read shard (shard_id+1) and so on until either found shard with undone work or all shards are read...
def read_undone_from_datastore(self, shard_id=None, num_shards=None): """Reads undone work from the datastore. If shard_id and num_shards are specified then this method will attempt to read undone work for shard with id shard_id. If no undone work was found then it will try to read shard (shard_id+1) a...
Tries pick next unclaimed piece of work to do. Attempt to claim work piece is done using Cloud Datastore transaction, so only one worker can claim any work piece at a time. Args: worker_id: ID of current worker submission_id: if not None then this method will try to pick piece of work ...
def try_pick_piece_of_work(self, worker_id, submission_id=None): """Tries pick next unclaimed piece of work to do. Attempt to claim work piece is done using Cloud Datastore transaction, so only one worker can claim any work piece at a time. Args: worker_id: ID of current worker submission_...
Updates work piece in datastore as completed. Args: worker_id: ID of the worker which did the work work_id: ID of the work which was done other_values: dictionary with additonal values which should be saved with the work piece error: if not None then error occurred during computatio...
def update_work_as_completed(self, worker_id, work_id, other_values=None, error=None): """Updates work piece in datastore as completed. Args: worker_id: ID of the worker which did the work work_id: ID of the work which was done other_values: dictionary with addi...
Computes statistics from all work pieces stored in this class.
def compute_work_statistics(self): """Computes statistics from all work pieces stored in this class.""" result = {} for v in itervalues(self.work): submission_id = v['submission_id'] if submission_id not in result: result[submission_id] = { 'completed': 0, 'num_er...
Initializes work pieces from adversarial batches. Args: adv_batches: dict with adversarial batches, could be obtained as AversarialBatches.data
def init_from_adversarial_batches(self, adv_batches): """Initializes work pieces from adversarial batches. Args: adv_batches: dict with adversarial batches, could be obtained as AversarialBatches.data """ for idx, (adv_batch_id, adv_batch_val) in enumerate(iteritems(adv_batches)): w...
Initializes work pieces from classification batches. Args: class_batches: dict with classification batches, could be obtained as ClassificationBatches.data num_shards: number of shards to split data into, if None then no sharding is done.
def init_from_class_batches(self, class_batches, num_shards=None): """Initializes work pieces from classification batches. Args: class_batches: dict with classification batches, could be obtained as ClassificationBatches.data num_shards: number of shards to split data into, if None ...
Make a confidence report and save it to disk.
def main(argv=None): """ Make a confidence report and save it to disk. """ assert len(argv) >= 3 _name_of_script = argv[0] model_filepath = argv[1] adv_x_filepaths = argv[2:] sess = tf.Session() with sess.as_default(): model = serial.load(model_filepath) factory = model.dataset_factory facto...
TensorFlow implementation of the Fast Gradient Method. :param x: the input placeholder :param logits: output of model.get_logits :param y: (optional) A placeholder for the true labels. If targeted is true, then provide the target label. Otherwise, only provide this parameter if you'd like ...
def fgm(x, logits, y=None, eps=0.3, ord=np.inf, clip_min=None, clip_max=None, targeted=False, sanity_checks=True): """ TensorFlow implementation of the Fast Gradient Method. :param x: the input placeholder :param logits: output of model.get_logits ...
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: tf tensor containing a batch of gradients :param eps: float scalar specifying size of constraint region :param ord: int specifying order of norm :re...
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: tf tensor containing a batch of gradients :param eps: float scalar specifying size of constraint reg...
Returns the graph for Fast Gradient Method adversarial examples. :param x: The model's symbolic inputs. :param kwargs: See `parse_params`
def generate(self, x, **kwargs): """ Returns the graph for Fast Gradient Method adversarial examples. :param x: The model's symbolic inputs. :param kwargs: See `parse_params` """ # Parse and save attack-specific parameters assert self.parse_params(**kwargs) labels, _nb_classes = self.g...
Function to read the weights from checkpoint based on json description. Args: checkpoint: tensorflow checkpoint with trained model to verify model_json: path of json file with model description of the network list of dictionary items for each layer containing 'type', 'weight_var...
def load_network_from_checkpoint(checkpoint, model_json, input_shape=None): """Function to read the weights from checkpoint based on json description. Args: checkpoint: tensorflow checkpoint with trained model to verify model_json: path of json file with model description of the netwo...
Performs forward pass through the layer weights at layer_index. Args: vector: vector that has to be passed through in forward pass layer_index: index of the layer is_transpose: whether the weights of the layer have to be transposed is_abs: whether to take the absolute value of the weights ...
def forward_pass(self, vector, layer_index, is_transpose=False, is_abs=False): """Performs forward pass through the layer weights at layer_index. Args: vector: vector that has to be passed through in forward pass layer_index: index of the layer is_transpose: whether the weights of the layer h...
Returns a hexdigest of all the python files in the module.
def dev_version(): """ Returns a hexdigest of all the python files in the module. """ md5_hash = hashlib.md5() py_files = sorted(list_files(suffix=".py")) if not py_files: return '' for filename in py_files: with open(filename, 'rb') as fobj: content = fobj.read() md5_hash.update(conten...
The current implementation of report printing. :param report: ConfidenceReport
def current(report): """ The current implementation of report printing. :param report: ConfidenceReport """ if hasattr(report, "completed"): if report.completed: print("Report completed") else: print("REPORT NOT COMPLETED") else: warnings.warn("This report does not indicate whether i...
The deprecated implementation of report printing. :param report: dict
def deprecated(report): """ The deprecated implementation of report printing. :param report: dict """ warnings.warn("Printing dict-based reports is deprecated. This function " "is included only to support a private development branch " "and may be removed without warning.") ...
A simple model trained to minimize Cross Entropy and Maximize Soft Nearest Neighbor Loss at each internal layer. This outputs a TSNE of the sign of the adversarial gradients of a trained model. A model with a negative SNNL_factor will show little or no class clusters, while a model with a 0 SNNL_factor will hav...
def SNNL_example(train_start=0, train_end=60000, test_start=0, test_end=10000, nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE, learning_rate=LEARNING_RATE, nb_filters=NB_FILTERS, SNNL_factor=SNNL_FACTOR, output_dir=OUTPUT_DIR): """ A s...
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) asserts = [] # If a data ra...
Take in a dictionary of parameters and applies attack-specific checks before saving them as attributes. Attack-specific parameters: :param eps: (optional float) maximum distortion of adversarial example compared to original input :param eps_iter: (optional float) step size for each att...
def parse_params(self, eps=0.3, eps_iter=0.05, nb_iter=10, y=None, ord=np.inf, clip_min=None, clip_max=None, y_target=None, rand_init=None, ...
Train a TF Eager model :param model: cleverhans.model.Model :param X_train: numpy array with training inputs :param Y_train: numpy array with training outputs :param save: boolean controlling the save operation :param predictions_adv: if set with the adversarial example tensor, will ...
def train(model, X_train=None, Y_train=None, save=False, predictions_adv=None, evaluate=None, args=None, rng=None, var_list=None, attack=None, attack_args=None): """ Train a TF Eager model :param model: cleverhans.model.Model :param X_train: numpy array with training inputs :para...
Compute the accuracy of a TF Eager model on some data :param model: instance of cleverhans.model.Model_Eager with pretrained weights for evaluation. :param X_test: numpy array with training inputs :param Y_test: numpy array with training outputs :param args: dict or argparse `Namespace` object...
def model_eval(model, X_test=None, Y_test=None, args=None, attack=None, attack_args=None): """ Compute the accuracy of a TF Eager model on some data :param model: instance of cleverhans.model.Model_Eager with pretrained weights for evaluation. :param X_test: numpy array with tra...
Helper function that computes the current class prediction :param samples: numpy array with input samples (dims must match x) :return: the argmax output of predictions, i.e. the current predicted class
def model_argmax(model, samples): """ Helper function that computes the current class prediction :param samples: numpy array with input samples (dims must match x) :return: the argmax output of predictions, i.e. the current predicted class """ tfe = tf.contrib.eager tf_samples = tfe.Variable(samples) pr...
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) if self.ord != np.inf: rai...
Function to initialize the dual variables of the class. Args: neural_net_params_object: Object with the neural net weights, biases and types init_dual_file: Path to file containing dual variables, if the path is empty, perform random initialization Expects numpy dictionary with lambda...
def initialize_dual(neural_net_params_object, init_dual_file=None, random_init_variance=0.01, init_nu=200.0): """Function to initialize the dual variables of the class. Args: neural_net_params_object: Object with the neural net weights, biases and types init_dual_file: Path to fil...
Function that performs one step of gd (variant) for min eigen value. Args: current_vector: current estimate of the eigen vector with minimum eigen value. learning_rate: learning rate. vector_prod_fn: function which returns product H*x, where H is a matrix for which we computing eigenvector. ...
def eig_one_step(current_vector, learning_rate, vector_prod_fn): """Function that performs one step of gd (variant) for min eigen value. Args: current_vector: current estimate of the eigen vector with minimum eigen value. learning_rate: learning rate. vector_prod_fn: function which returns produc...
Computes eigenvector which corresponds to minimum eigenvalue. Args: x: initial value of eigenvector. num_steps: number of optimization steps. learning_rate: learning rate. vector_prod_fn: function which takes x and returns product H*x. Returns: approximate value of eigenvector. This functio...
def minimum_eigen_vector(x, num_steps, learning_rate, vector_prod_fn): """Computes eigenvector which corresponds to minimum eigenvalue. Args: x: initial value of eigenvector. num_steps: number of optimization steps. learning_rate: learning rate. vector_prod_fn: function which takes x and returns pr...
Provides access to the model's Variables. This may include Variables that are not parameters, such as batch norm running moments. :return: A list of all Variables defining the model.
def get_vars(self): """ Provides access to the model's Variables. This may include Variables that are not parameters, such as batch norm running moments. :return: A list of all Variables defining the model. """ # Catch eager execution and assert function overload. try: if tf.execu...
Forward propagation as either no-op or dropping random units. :param x: The input to the layer :param dropout: bool specifying whether to drop units :param dropout_dict: dict This dictionary is usually not needed. In rare cases, generally for research purposes, this dictionary makes ...
def fprop(self, x, dropout=False, dropout_dict=None, **kwargs): """ Forward propagation as either no-op or dropping random units. :param x: The input to the layer :param dropout: bool specifying whether to drop units :param dropout_dict: dict This dictionary is usually not needed. In...
Return a tensor that constructs adversarial examples for the given input. Generate uses tf.py_func in order to operate over tensors. :param x: A tensor with the inputs. :param kwargs: See `parse_params`
def generate(self, x, **kwargs): """ Return a tensor that constructs adversarial examples for the given input. Generate uses tf.py_func in order to operate over tensors. :param x: A tensor with the inputs. :param kwargs: See `parse_params` """ assert self.sess is not None, \ 'Cannot...
: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 confidence: Confide...
def parse_params(self, y=None, y_target=None, batch_size=1, confidence=0, learning_rate=5e-3, binary_search_steps=5, max_iterations=1000, abort_early=True, ...
Perform the L_2 attack on the given instance for the given targets. If self.targeted is true, then the targets represents the target labels If self.targeted is false, then targets are the original class labels
def attack(self, imgs, targets): """ Perform the L_2 attack on the given instance for the given targets. If self.targeted is true, then the targets represents the target labels If self.targeted is false, then targets are the original class labels """ r = [] for i in range(0, len(imgs), sel...
Run the attack on a batch of instance and labels.
def attack_batch(self, imgs, labs): """ Run the attack on a batch of instance and labels. """ def compare(x, y): if not isinstance(x, (float, int, np.int64)): x = np.copy(x) if self.TARGETED: x[y] -= self.CONFIDENCE else: x[y] += self.CONFIDENCE ...
Load model if present at the specified path.
def maybe_load_model(savedir, container): """Load model if present at the specified path.""" if savedir is None: return state_path = os.path.join(os.path.join(savedir, 'training_state.pkl.zip')) if container is not None: logger.log("Attempting to download model from Azure") found_model = container....
Warn user if running cleverhans from a different directory than tutorial.
def check_installation(cur_file): """Warn user if running cleverhans from a different directory than tutorial.""" cur_dir = os.path.split(os.path.dirname(os.path.abspath(cur_file)))[0] ch_dir = os.path.split(cleverhans.__path__[0])[0] if cur_dir != ch_dir: warnings.warn("It appears that you have at least tw...
Parses command line arguments.
def parse_args(): """Parses command line arguments.""" parser = argparse.ArgumentParser( description='Tool to download dataset images.') parser.add_argument('--input_file', required=True, help='Location of dataset.csv') parser.add_argument('--output_dir', required=True, ...
Downloads the image that corresponds to the given row. Prints a notification if the download fails.
def get_image(row, output_dir): """Downloads the image that corresponds to the given row. Prints a notification if the download fails.""" if not download_image(image_id=row[0], url=row[1], x1=float(row[2]), y1=float(row[3]), ...
Downloads one image, crops it, resizes it and saves it locally.
def download_image(image_id, url, x1, y1, x2, y2, output_dir): """Downloads one image, crops it, resizes it and saves it locally.""" output_filename = os.path.join(output_dir, image_id + '.png') if os.path.exists(output_filename): # Don't download image if it's already there return True try: # Downl...
Custom py_func with gradient support
def py_func_grad(func, inp, Tout, stateful=True, name=None, grad=None): """Custom py_func with gradient support """ # Need to generate a unique name to avoid duplicates: rnd_name = 'PyFuncGrad' + str(np.random.randint(0, 1E+8)) tf.RegisterGradient(rnd_name)(grad) g = tf.get_default_graph() with g.gradie...
Forward propagation throught the network :return: dictionary with layer names mapping to activation values.
def fprop(self, x): """ Forward propagation throught the network :return: dictionary with layer names mapping to activation values. """ # Feed forward through the network layers for layer_name in self.layer_names: if layer_name == 'input': prev_layer_act = x continue ...
Provides access to the parameters of the given layer. Works arounds the non-availability of graph collections in eager mode. :layer_name: name of the layer for which parameters are required, must be one of the string in the list layer_names :return: list of pa...
def get_layer_params(self, layer_name): """ Provides access to the parameters of the given layer. Works arounds the non-availability of graph collections in eager mode. :layer_name: name of the layer for which parameters are required, must be one of the string in the ...
Provides access to the model's parameters. Works arounds the non-availability of graph collections in eager mode. :return: A list of all Variables defining the model parameters.
def get_params(self): """ Provides access to the model's parameters. Works arounds the non-availability of graph collections in eager mode. :return: A list of all Variables defining the model parameters. """ assert tf.executing_eagerly() out = [] # Collecting params ...
This function displays two images: the original and the adversarial sample :param original: the original input :param adversarial: the input after perturbations have been applied :param figure: if we've already displayed images, use the same plot :return: the matplot figure to reuse for future samples
def pair_visual(original, adversarial, figure=None): """ This function displays two images: the original and the adversarial sample :param original: the original input :param adversarial: the input after perturbations have been applied :param figure: if we've already displayed images, use the same plot :ret...
This function displays a grid of images to show full misclassification :param data: grid data of the form; [nb_classes : nb_classes : img_rows : img_cols : nb_channels] :return: if necessary, the matplot figure to reuse
def grid_visual(data): """ This function displays a grid of images to show full misclassification :param data: grid data of the form; [nb_classes : nb_classes : img_rows : img_cols : nb_channels] :return: if necessary, the matplot figure to reuse """ import matplotlib.pyplot as plt # Ensure interac...
Get logits when the input is perturbed in an interval in adv direction. Args: sess: Tf session model: Model for which we wish to get logits. x_data: Numpy array corresponding to single data. point of shape [height, width, channels]. fgsm_params: Parameters for generating adversa...
def get_logits_over_interval(sess, model, x_data, fgsm_params, min_epsilon=-10., max_epsilon=10., num_points=21): """Get logits when the input is perturbed in an interval in adv direction. Args: sess: Tf session model: Model for which we wish to...
Generate linear extrapolation plot. Args: log_prob_adv_array: Numpy array containing log probabilities y: Tf placeholder for the labels file_name: Plot filename min_epsilon: Minimum value of epsilon over the interval max_epsilon: Maximum value of epsilon over the interval num_poin...
def linear_extrapolation_plot(log_prob_adv_array, y, file_name, min_epsilon=-10, max_epsilon=10, num_points=21): """Generate linear extrapolation plot. Args: log_prob_adv_array: Numpy array containing log probabilities y: Tf placeholder for th...
Encode IQFeed API messages.
def _send_cmd(self, cmd: str): """Encode IQFeed API messages.""" self._sock.sendall(cmd.encode(encoding='latin-1', errors='strict'))
Send data query to IQFeed API.
def iq_query(self, message: str): """Send data query to IQFeed API.""" end_msg = '!ENDMSG!' recv_buffer = 4096 # Send the historical data request message and buffer the data self._send_cmd(message) chunk = "" data = "" while True: chunk = sel...
Request historical 5 minute data from DTN.
def get_historical_minute_data(self, ticker: str): """Request historical 5 minute data from DTN.""" start = self._start stop = self._stop if len(stop) > 4: stop = stop[:4] if len(start) > 4: start = start[:4] for year in range(int(start), int(st...
Build Pandas Dataframe in memory
def add_data_to_df(self, data: np.array): """Build Pandas Dataframe in memory""" col_names = ['high_p', 'low_p', 'open_p', 'close_p', 'volume', 'oi'] data = np.array(data).reshape(-1, len(col_names) + 1) df = pd.DataFrame(data=data[:, 1:], index=data[:, 0], co...
Load ticker list from txt file
def get_tickers_from_file(self, filename): """Load ticker list from txt file""" if not os.path.exists(filename): log.error("Ticker List file does not exist: %s", filename) tickers = [] with io.open(filename, 'r') as fd: for ticker in fd: tickers.a...
Write Pandas Dataframe to InfluxDB database
def write_dataframe_to_idb(self, ticker): """Write Pandas Dataframe to InfluxDB database""" cachepath = self._cache cachefile = ('%s/%s-1M.csv.gz' % (cachepath, ticker)) if not os.path.exists(cachefile): log.warn('Import file does not exist: %s' % (cache...
connect events
def connect(self): """connect events""" self._cidmotion = self.canvas.mpl_connect('motion_notify_event', self.onmove) self._ciddraw = self.canvas.mpl_connect('draw_event', self.clear)
disconnect events
def disconnect(self): """disconnect events""" self.canvas.mpl_disconnect(self._cidmotion) self.canvas.mpl_disconnect(self._ciddraw)
Connect to window and set it foreground Args: **kwargs: optional arguments Returns: None
def connect(self, **kwargs): """ Connect to window and set it foreground Args: **kwargs: optional arguments Returns: None """ self.app = self._app.connect(**kwargs) try: self._top_window = self.app.top_window().wrapper_object...
Get rectangle of app or desktop resolution Returns: RECT(left, top, right, bottom)
def get_rect(self): """ Get rectangle of app or desktop resolution Returns: RECT(left, top, right, bottom) """ if self.handle: left, top, right, bottom = win32gui.GetWindowRect(self.handle) return RECT(left, top, right, bottom) else: ...
Take a screenshot and save it to `tmp.png` filename by default Args: filename: name of file where to store the screenshot Returns: display the screenshot
def snapshot(self, filename="tmp.png"): """ Take a screenshot and save it to `tmp.png` filename by default Args: filename: name of file where to store the screenshot Returns: display the screenshot """ if not filename: filename = "tm...
从数据中获取到绘图相关的有用信息.
def extract_data(self): """从数据中获取到绘图相关的有用信息.""" self.time_axis = [] self.cpu_axis = [] self.mem_axis = [] self.timestamp_list = [] plot_data = self.data.get("plot_data", []) # 按照时间分割线,划分成几段数据,取其中的最值 for i in plot_data: timestamp = i["timestamp"...
获取每个方法中的cpu和内存耗费最值点.
def get_each_method_maximun_cpu_mem(self): """获取每个方法中的cpu和内存耗费最值点.""" # 本函数用于丰富self.method_exec_info的信息:存入cpu、mem最值点 self.method_exec_info = deepcopy(self.data.get("method_exec_info", [])) method_exec_info = deepcopy(self.method_exec_info) # 用来辅助循环 method_index, cpu_max, cpu_max...
获取图像的title.
def _get_graph_title(self): """获取图像的title.""" start_time = datetime.fromtimestamp(int(self.timestamp_list[0])) end_time = datetime.fromtimestamp(int(self.timestamp_list[-1])) end_time = end_time.strftime('%H:%M:%S') title = "Timespan: %s —— %s" % (start_time, end_time) r...
绘制CPU/Mem/特征点数量.
def plot_cpu_mem_keypoints(self): """绘制CPU/Mem/特征点数量.""" plt.figure(1) # 开始绘制子图: plt.subplot(311) title = self._get_graph_title() plt.title(title, loc="center") # 设置绘图的标题 mem_ins = plt.plot(self.time_axis, self.mem_axis, "-", label="Mem(MB)", color='deepskyblue',...
初始化方法对象.
def refresh_method_objects(self): """初始化方法对象.""" self.method_object_dict = {} for key, method in self.MATCHING_METHODS.items(): method_object = method(self.im_search, self.im_source, self.threshold, self.rgb) self.method_object_dict.update({key: method_object})
获取特征点.
def _get_result(self, method_name="kaze"): """获取特征点.""" method_object = self.method_object_dict.get(method_name) # 提取结果和特征点: try: result = method_object.find_best_result() except Exception: import traceback traceback.print_exc() ret...
获取并且绘制出特征点匹配结果.
def get_and_plot_keypoints(self, method_name, plot=False): """获取并且绘制出特征点匹配结果.""" if method_name not in self.method_object_dict.keys(): print("'%s' is not in MATCHING_METHODS" % method_name) return None kp_sch, kp_src, good, result = self._get_result(method_name) ...