Search is not available for this dataset
text
stringlengths
75
104k
def download(self): """Method which downloads submission to local directory.""" # Structure of the download directory: # submission_dir=LOCAL_SUBMISSIONS_DIR/submission_id # submission_dir/s.ext <-- archived submission # submission_dir/extracted <-- extracted submission # Check whether s...
def temp_copy_extracted_submission(self): """Creates a temporary copy of extracted submission. When executed, submission is allowed to modify it's own directory. So to ensure that submission does not pass any data between runs, new copy of the submission is made before each run. After a run temporary c...
def run_without_time_limit(self, cmd): """Runs docker command without time limit. Args: cmd: list with the command line arguments which are passed to docker binary Returns: how long it took to run submission in seconds Raises: WorkerError: if error occurred during execution ...
def run_with_time_limit(self, cmd, time_limit=SUBMISSION_TIME_LIMIT): """Runs docker command and enforces time limit. Args: cmd: list with the command line arguments which are passed to docker binary after run time_limit: time limit, in seconds. Negative value means no limit. Returns: ...
def run(self, input_dir, output_dir, epsilon): """Runs attack inside Docker. Args: input_dir: directory with input (dataset). output_dir: directory where output (adversarial images) should be written. epsilon: maximum allowed size of adversarial perturbation, should be in range [0, 25...
def run(self, input_dir, output_file_path): """Runs defense inside Docker. Args: input_dir: directory with input (adversarial images). output_file_path: path of the output file. Returns: how long it took to run submission in seconds """ logging.info('Running defense %s', self.sub...
def read_dataset_metadata(self): """Read `dataset_meta` field from bucket""" if self.dataset_meta: return shell_call(['gsutil', 'cp', 'gs://' + self.storage_client.bucket_name + '/' + 'dataset/' + self.dataset_name + '_dataset.csv', LOCAL_DATASET_METADAT...
def fetch_attacks_data(self): """Initializes data necessary to execute attacks. This method could be called multiple times, only first call does initialization, subsequent calls are noop. """ if self.attacks_data_initialized: return # init data from datastore self.submissions.init_fro...
def run_attack_work(self, work_id): """Runs one attack work. Args: work_id: ID of the piece of work to run Returns: elapsed_time_sec, submission_id - elapsed time and id of the submission Raises: WorkerError: if error occurred during execution. """ adv_batch_id = ( s...
def run_attacks(self): """Method which evaluates all attack work. In a loop this method queries not completed attack work, picks one attack work and runs it. """ logging.info('******** Start evaluation of attacks ********') prev_submission_id = None while True: # wait until work is av...
def fetch_defense_data(self): """Lazy initialization of data necessary to execute defenses.""" if self.defenses_data_initialized: return logging.info('Fetching defense data from datastore') # init data from datastore self.submissions.init_from_datastore() self.dataset_batches.init_from_dat...
def run_defense_work(self, work_id): """Runs one defense work. Args: work_id: ID of the piece of work to run Returns: elapsed_time_sec, submission_id - elapsed time and id of the submission Raises: WorkerError: if error occurred during execution. """ class_batch_id = ( ...
def run_defenses(self): """Method which evaluates all defense work. In a loop this method queries not completed defense work, picks one defense work and runs it. """ logging.info('******** Start evaluation of defenses ********') prev_submission_id = None need_reload_work = True while Tr...
def run_work(self): """Run attacks and defenses""" if os.path.exists(LOCAL_EVAL_ROOT_DIR): sudo_remove_dirtree(LOCAL_EVAL_ROOT_DIR) self.run_attacks() self.run_defenses()
def arg_type(arg_names, kwargs): """ Returns a hashable summary of the types of arg_names within kwargs. :param arg_names: tuple containing names of relevant arguments :param kwargs: dict mapping string argument names to values. These must be values for which we can create a tf placeholder. Currently su...
def construct_graph(self, fixed, feedable, x_val, hash_key): """ Construct the graph required to run the attack through generate_np. :param fixed: Structural elements that require defining a new graph. :param feedable: Arguments that can be fed to the same graph when they take diff...
def generate_np(self, x_val, **kwargs): """ Generate adversarial examples and return them as a NumPy array. Sub-classes *should not* implement this method unless they must perform special handling of arguments. :param x_val: A NumPy array with the original inputs. :param **kwargs: optional para...
def construct_variables(self, kwargs): """ Construct the inputs to the attack graph to be used by generate_np. :param kwargs: Keyword arguments to generate_np. :return: Structural arguments Feedable arguments Output of `arg_type` describing feedable arguments A unique key ""...
def get_or_guess_labels(self, 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 no...
def dueling_model(img_in, num_actions, scope, noisy=False, reuse=False, concat_softmax=False): """As described in https://arxiv.org/abs/1511.06581""" with tf.variable_scope(scope, reuse=reuse): out = img_in with tf.variable_scope("convnet"): # original architecture out = layers...
def mnist_tutorial_jsma(train_start=0, train_end=60000, test_start=0, test_end=10000, viz_enabled=VIZ_ENABLED, nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE, source_samples=SOURCE_SAMPLES, learning_rate=LEARNING_RATE): """ ...
def generate(self, x, **kwargs): """ Generate symbolic graph for adversarial examples and return. :param x: The model's symbolic inputs. :param kwargs: Keyword arguments. See `parse_params` for documentation. """ # Parse and save attack-specific parameters assert self.parse_params(**kwargs)...
def parse_params(self, eps=0.3, eps_iter=0.06, nb_iter=10, y=None, ord=np.inf, decay_factor=1.0, clip_min=None, clip_max=None, y_target=None, ...
def train(sess, loss, x_train, y_train, init_all=False, evaluate=None, feed=None, args=None, rng=None, var_list=None, fprop_args=None, optimizer=None, devices=None, x_batch_preprocessor=None, use_ema=False, ema_decay=.998, run_canary=None, loss_threshold=1e5, dataset_tr...
def avg_grads(tower_grads): """Calculate the average gradient for each shared variable across all towers. Note that this function provides a synchronization point across all towers. Args: tower_grads: List of lists of (gradient, variable) tuples. The outer list is over individual gradients. The inner ...
def create_adv_by_name(model, x, attack_type, sess, dataset, y=None, **kwargs): """ Creates the symbolic graph of an adversarial example given the name of an attack. Simplifies creating the symbolic graph of an attack by defining dataset-specific parameters. Dataset-specific default parameters are used unless...
def log_value(self, tag, val, desc=''): """ Log values to standard output and Tensorflow summary. :param tag: summary tag. :param val: (required float or numpy array) value to be logged. :param desc: (optional) additional description to be printed. """ logging.info('%s (%s): %.4f' % (desc, ...
def eval_advs(self, x, y, preds_adv, X_test, Y_test, att_type): """ Evaluate the accuracy of the model on adversarial examples :param x: symbolic input to model. :param y: symbolic variable for the label. :param preds_adv: symbolic variable for the prediction on an adversarial...
def eval_multi(self, inc_epoch=True): """ Run the evaluation on multiple attacks. """ sess = self.sess preds = self.preds x = self.x_pre y = self.y X_train = self.X_train Y_train = self.Y_train X_test = self.X_test Y_test = self.Y_test writer = self.writer self.summa...
def run_canary(): """ Runs some code that will crash if the GPUs / GPU driver are suffering from a common bug. This helps to prevent contaminating results in the rest of the library with incorrect calculations. """ # Note: please do not edit this function unless you have access to a machine # with GPUs s...
def _wrap(f): """ Wraps a callable `f` in a function that warns that the function is deprecated. """ def wrapper(*args, **kwargs): """ Issues a deprecation warning and passes through the arguments. """ warnings.warn(str(f) + " is deprecated. Switch to calling the equivalent function in tensorflo...
def reduce_function(op_func, input_tensor, axis=None, keepdims=None, name=None, reduction_indices=None): """ This function used to be needed to support tf 1.4 and early, but support for tf 1.4 and earlier is now dropped. :param op_func: expects the function to handle eg: tf.reduce_sum. :para...
def softmax_cross_entropy_with_logits(sentinel=None, labels=None, logits=None, dim=-1): """ Wrapper around tf.nn.softmax_cross_entropy_with_logits_v2 to handle deprecated warning """ # Make sure t...
def enforce_epsilon_and_compute_hash(dataset_batch_dir, adv_dir, output_dir, epsilon): """Enforces size of perturbation on images, and compute hashes for all images. Args: dataset_batch_dir: directory with the images of specific dataset batch adv_dir: directory with gen...
def download_dataset(storage_client, image_batches, target_dir, local_dataset_copy=None): """Downloads dataset, organize it by batches and rename images. Args: storage_client: instance of the CompetitionStorageClient image_batches: subclass of ImageBatchesBase with data about images ...
def save_target_classes_for_batch(self, filename, image_batches, batch_id): """Saves file with target class for given dataset batch. Args: filename: output filename image_batches: instance of...
def tf_min_eig_vec(self): """Function for min eigen vector using tf's full eigen decomposition.""" # Full eigen decomposition requires the explicit psd matrix M _, matrix_m = self.dual_object.get_full_psd_matrix() [eig_vals, eig_vectors] = tf.self_adjoint_eig(matrix_m) index = tf.argmin(eig_vals) ...
def tf_smooth_eig_vec(self): """Function that returns smoothed version of min eigen vector.""" _, matrix_m = self.dual_object.get_full_psd_matrix() # Easier to think in terms of max so negating the matrix [eig_vals, eig_vectors] = tf.self_adjoint_eig(-matrix_m) exp_eig_vals = tf.exp(tf.divide(eig_va...
def get_min_eig_vec_proxy(self, use_tf_eig=False): """Computes the min eigen value and corresponding vector of matrix M. Args: use_tf_eig: Whether to use tf's default full eigen decomposition Returns: eig_vec: Minimum absolute eigen value eig_val: Corresponding eigen vector """ if...
def get_scipy_eig_vec(self): """Computes scipy estimate of min eigenvalue for matrix M. Returns: eig_vec: Minimum absolute eigen value eig_val: Corresponding eigen vector """ if not self.params['has_conv']: matrix_m = self.sess.run(self.dual_object.matrix_m) min_eig_vec_val, est...
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....
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...
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...
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}
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 ...
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 ...
def deepfool_batch(sess, x, pred, logits, grads, X, nb_candidate, overshoot, max_iter, clip_min, clip_max, nb_c...
def deepfool_attack(sess, x, predictions, logits, grads, sample, nb_candidate, overshoot, max_iter, clip_min, clip_max, ...
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...
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., ...
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...
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...
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....
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 ...
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...
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...
def attack(self, imgs, targets): """ Perform the EAD attack on the given instance for the given targets. If self.targeted is true, then the targets represents the target labels If self.targeted is false, then targets are the original class labels """ batch_size = self.batch_size r = [] ...
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('')
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...
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...
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...
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, ...
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...
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...
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...
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...
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...
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...
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 ) :...
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...
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 ...
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)))
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...
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)
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...
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: ...
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)
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: ...
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(): ...
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,...
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(...
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...
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...
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...
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] ...
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(...
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_...
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}
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...
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...
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...
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 ...
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...
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...
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)
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...
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)
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')
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 =...
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...