code
stringlengths
17
6.64M
def pad(x, width, val=0, batch_ndim=1): '\n Pad a tensor with a constant value.\n\n Parameters\n ----------\n x : tensor\n\n width : int, iterable of int, or iterable of tuple\n Padding width. If an int, pads each axis symmetrically with the same\n amount in the beginning and end. If ...
def get_or_compute_grads(loss_or_grads, params): 'Helper function returning a list of gradients\n\n Parameters\n ----------\n loss_or_grads : symbolic expression or list of expressions\n A scalar loss expression, or a list of gradient expressions\n params : list of shared variables\n The...
def sgd(loss_or_grads, params, learning_rate): 'Stochastic Gradient Descent (SGD) updates\n\n Generates update expressions of the form:\n\n * ``param := param - learning_rate * gradient``\n\n Parameters\n ----------\n loss_or_grads : symbolic expression or list of expressions\n A scalar loss...
def apply_momentum(updates, params=None, momentum=0.9): 'Returns a modified update dictionary including momentum\n\n Generates update expressions of the form:\n\n * ``velocity := momentum * velocity + updates[param] - param``\n * ``param := param + velocity``\n\n Parameters\n ----------\n update...
def momentum(loss_or_grads, params, learning_rate, momentum=0.9): "Stochastic Gradient Descent (SGD) updates with momentum\n\n Generates update expressions of the form:\n\n * ``velocity := momentum * velocity - learning_rate * gradient``\n * ``param := param + velocity``\n\n Parameters\n ----------...
def apply_nesterov_momentum(updates, params=None, momentum=0.9): 'Returns a modified update dictionary including Nesterov momentum\n\n Generates update expressions of the form:\n\n * ``velocity := momentum * velocity + updates[param] - param``\n * ``param := param + momentum * velocity + updates[param] -...
def nesterov_momentum(loss_or_grads, params, learning_rate, momentum=0.9): 'Stochastic Gradient Descent (SGD) updates with Nesterov momentum\n\n Generates update expressions of the form:\n\n * ``velocity := momentum * velocity - learning_rate * gradient``\n * ``param := param + momentum * velocity - lear...
def adagrad(loss_or_grads, params, learning_rate=1.0, epsilon=1e-06): 'Adagrad updates\n\n Scale learning rates by dividing with the square root of accumulated\n squared gradients. See [1]_ for further description.\n\n Parameters\n ----------\n loss_or_grads : symbolic expression or list of express...
def rmsprop(loss_or_grads, params, learning_rate=1.0, rho=0.9, epsilon=1e-06): 'RMSProp updates\n\n Scale learning rates by dividing with the moving average of the root mean\n squared (RMS) gradients. See [1]_ for further description.\n\n Parameters\n ----------\n loss_or_grads : symbolic expressio...
def adadelta(loss_or_grads, params, learning_rate=1.0, rho=0.95, epsilon=1e-06): ' Adadelta updates\n\n Scale learning rates by a the ratio of accumulated gradients to accumulated\n step sizes, see [1]_ and notes for further description.\n\n Parameters\n ----------\n loss_or_grads : symbolic expres...
def adam(loss_or_grads, params, learning_rate=0.001, beta1=0.9, beta2=0.999, epsilon=1e-08): 'Adam updates\n\n Adam updates implemented as in [1]_.\n\n Parameters\n ----------\n loss_or_grads : symbolic expression or list of expressions\n A scalar loss expression, or a list of gradient expressi...
def adamax(loss_or_grads, params, learning_rate=0.002, beta1=0.9, beta2=0.999, epsilon=1e-08): 'Adamax updates\n\n Adamax updates implemented as in [1]_. This is a variant of of the Adam\n algorithm based on the infinity norm.\n\n Parameters\n ----------\n loss_or_grads : symbolic expression or lis...
def norm_constraint(tensor_var, max_norm, norm_axes=None, epsilon=1e-07): 'Max weight norm constraints and gradient clipping\n\n This takes a TensorVariable and rescales it so that incoming weight\n norms are below a specified constraint value. Vectors violating the\n constraint are rescaled so that they...
def total_norm_constraint(tensor_vars, max_norm, epsilon=1e-07, return_norm=False): 'Rescales a list of tensors based on their combined norm\n\n If the combined norm of the input tensors exceeds the threshold then all\n tensors are rescaled such that the combined norm is equal to the threshold.\n\n Scali...
def floatX(arr): 'Converts data to a numpy array of dtype ``theano.config.floatX``.\n\n Parameters\n ----------\n arr : array_like\n The data to be converted.\n\n Returns\n -------\n numpy ndarray\n The input array in the ``floatX`` dtype configured for Theano.\n If `arr` is...
def shared_empty(dim=2, dtype=None): 'Creates empty Theano shared variable.\n\n Shortcut to create an empty Theano shared variable with\n the specified number of dimensions.\n\n Parameters\n ----------\n dim : int, optional\n The number of dimensions for the empty variable, defaults to 2.\n ...
def as_theano_expression(input): 'Wrap as Theano expression.\n\n Wraps the given input as a Theano constant if it is not\n a valid Theano expression already. Useful to transparently\n handle numpy arrays and Python scalars, for example.\n\n Parameters\n ----------\n input : number, numpy array o...
def collect_shared_vars(expressions): 'Returns all shared variables the given expression(s) depend on.\n\n Parameters\n ----------\n expressions : Theano expression or iterable of Theano expressions\n The expressions to collect shared variables from.\n\n Returns\n -------\n list of Theano...
def one_hot(x, m=None): 'One-hot representation of integer vector.\n\n Given a vector of integers from 0 to m-1, returns a matrix\n with a one-hot representation, where each row corresponds\n to an element of x.\n\n Parameters\n ----------\n x : integer vector\n The integer vector to conv...
def unique(l): 'Filters duplicates of iterable.\n\n Create a new list from l with duplicate entries removed,\n while preserving the original order.\n\n Parameters\n ----------\n l : iterable\n Input iterable to filter of duplicates.\n\n Returns\n -------\n list\n A list of el...
def as_tuple(x, N, t=None): '\n Coerce a value to a tuple of given length (and possibly given type).\n\n Parameters\n ----------\n x : value or iterable\n N : integer\n length of the desired tuple\n t : type, optional\n required type for all elements\n\n Returns\n -------\n ...
def compute_norms(array, norm_axes=None): ' Compute incoming weight vector norms.\n\n Parameters\n ----------\n array : ndarray\n Weight array.\n norm_axes : sequence (list or tuple)\n The axes over which to compute the norm. This overrides the\n default norm axes defined for the...
def create_param(spec, shape, name=None): '\n Helper method to create Theano shared variables for layer parameters\n and to initialize them.\n\n Parameters\n ----------\n spec : numpy array, Theano expression, or callable\n Either of the following:\n\n * a numpy array with the initial...
def unroll_scan(fn, sequences, outputs_info, non_sequences, n_steps, go_backwards=False): '\n Helper function to unroll for loops. Can be used to unroll theano.scan.\n The parameter names are identical to theano.scan, please refer to here\n for more information.\n\n Note that this func...
class CustomInstall(install): def run(self): install.run(self) os.system('pip3 install -r requirements.txt --ignore-installed') os.system('pip3 uninstall transformers -y') os.system('pip install git+https://github.com/jordiclive/transformers.git@controlprefixes --ignore-installed'...
def count_trainable_parameters(model): model_parameters = filter((lambda p: p.requires_grad), model.parameters()) params = sum([np.prod(p.size()) for p in model_parameters]) return params
class Seq2SeqLoggingCallback(pl.Callback): def on_batch_end(self, trainer, pl_module): lrs = {f'lr_group_{i}': param['lr'] for (i, param) in enumerate(pl_module.trainer.optimizers[0].param_groups)} pl_module.logger.log_metrics(lrs) @rank_zero_only def _write_logs(self, trainer: pl.Traine...
def bespoke_scheduler(optimizer, num_warmup_steps, num_training_steps, last_epoch=(- 1)): '\n Create a schedule with a learning rate that decreases linearly from the initial lr set in the optimizer to 0, after\n a warmup period during which it increases linearly from 0 to the initial lr set in the optimizer...
class PrefixModule(PrefixTransformer): mode = 'datatotext' loss_names = ['loss'] metric_names = ['sacrebleu'] default_val_metric = 'bleu' def __init__(self, hparams, **kwargs): if (hparams.sortish_sampler and (hparams.gpus > 1)): hparams.replace_sampler_ddp = False eli...
def eval(args, model=None): if (model is None): if ('datatotext' in args.task_mode): if (args.tuning_mode == 'prefixtune'): model = PrefixModule(args) rank_zero_info('the length penalty is {}'.format(args.length_penalty)) with torch.no_grad(): model.eval() ...
def main(args, model=None): Path(args.output_dir).mkdir(exist_ok=True) if (model is None): if ('datatotext' in args.task_mode): if (args.tuning_mode == 'prefixtune'): model = PrefixModule(args) pickle_save(model.hparams, (model.output_dir / 'hparams.pkl')) if ((args...
class PrefixTransformer(pl.LightningModule): def __init__(self, hparams: argparse.Namespace, num_labels=None, config=None, tokenizer=None, seq2seq_model=None, **config_kwargs): 'Initialize a model, tokenizer and config.' super().__init__() self.save_hyperparameters(hparams) self.s...
def add_generic_args(parser, root_dir) -> None: parser.add_argument('--output_dir', default=None, type=str, required=True, help='The output directory where the model predictions and checkpoints will be written.') parser.add_argument('--n_tpu_cores', dest='tpu_cores', type=int) parser.add_argument('--max_g...
def generic_train(model, args: argparse.Namespace, early_stopping_callback=False, logger=True, extra_callbacks=[], checkpoint_callback=None, logging_callback=None, **extra_train_kwargs): pl.seed_everything(args.seed) odir = Path(model.hparams.output_dir) odir.mkdir(exist_ok=True) checkpoint_callback =...
class PartiallyFixedEmbedding(torch.nn.Module): def __init__(self, fixed_weights, num_to_learn, padding_idx=1): super().__init__() self.num_fixed = fixed_weights.size(0) self.num_to_learn = num_to_learn weight = torch.empty((self.num_fixed + num_to_learn), fixed_weights.size(1)) ...
def make_new_embeddings_learnable(model, tokenizer_len, num_to_learn): print('fixed_embeds', (tokenizer_len - num_to_learn)) fixed_weights = model.shared.weight[:32100] new_embed_layer = PartiallyFixedEmbedding(fixed_weights, num_to_learn) model.decoder.embed_tokens = new_embed_layer model.encoder...
def run_experiment(yaml_file): with open(yaml_file, 'r') as stream: parsed_yaml = yaml.safe_load(stream) args = '' for (arg, value) in parsed_yaml.items(): args += f'--{arg} {value} ' os.system(f'python finetune.py {args}--adafactor')
def label_smoothed_nll_loss(lprobs, target, epsilon, ignore_index=(- 100)): 'From fairseq' if (target.dim() == (lprobs.dim() - 1)): target = target.unsqueeze((- 1)) nll_loss = (- lprobs.gather(dim=(- 1), index=target)) smooth_loss = (- lprobs.sum(dim=(- 1), keepdim=True)) if (ignore_index ...
def lmap(f: Callable, x: Iterable) -> List: 'list(map(f, x))' return list(map(f, x))
def calculate_bleu(output_lns, refs_lns) -> dict: "Uses sacrebleu's corpus_bleu implementation." return {'sacrebleu': round(corpus_bleu(output_lns, [refs_lns]).score, 4)}
class AbstractSeq2SeqDataset(Dataset): def __init__(self, tokenizer, data_dir, max_source_length, max_target_length, type_path='train', n_obs=None, prefix='', **dataset_kwargs): super().__init__() self.src_file = Path(data_dir).joinpath((type_path + '.source')) self.tgt_file = Path(data_d...
class Seq2SeqDataset(AbstractSeq2SeqDataset): 'A dataset that calls prepare_seq2seq_batch.' def __getitem__(self, index) -> Dict[(str, str)]: index = (index + 1) source_line = (self.prefix + linecache.getline(str(self.src_file), index).rstrip('\n')) tgt_line = linecache.getline(str(se...
class SortishSampler(Sampler): 'Go through the text data by order of src length with a bit of randomness. From fastai repo.' def __init__(self, data, batch_size, shuffle=True): (self.data, self.bs, self.shuffle) = (data, batch_size, shuffle) def __len__(self) -> int: return len(self.data...
def sortish_sampler_indices(data: List, bs: int, shuffle=True) -> np.array: 'Go through the text data by order of src length with a bit of randomness. From fastai repo.' if (not shuffle): return np.argsort((np.array(data) * (- 1))) def key_fn(i): return data[i] idxs = np.random.permut...
class DistributedSortishSampler(Sampler): 'Copied from torch DistributedSampler' def __init__(self, dataset, batch_size, num_replicas=None, rank=None, add_extra_examples=True, shuffle=True): if (num_replicas is None): if (not dist.is_available()): raise RuntimeError('Requi...
def use_task_specific_params(model, task): 'Update config with GEC specific params.' task_specific_params = model.config.task_specific_params if (task_specific_params is not None): pars = task_specific_params.get(task, {}) logger.info(f'using task specific params for {task}: {pars}') ...
def pickle_load(path): 'pickle.load(path)' with open(path, 'rb') as f: return pickle.load(f)
def pickle_save(obj, path): 'pickle.dump(obj, path)' with open(path, 'wb') as f: return pickle.dump(obj, f)
def flatten_list(summary_ids: List[List]): return [x for x in itertools.chain.from_iterable(summary_ids)]
def freeze_params(model: nn.Module): 'Set requires_grad=False for each of model.parameters()' for par in model.parameters(): par.requires_grad = False
def freeze_embeds(model): 'Freeze token embeddings and positional embeddings for bart, just token embeddings for t5.' model_type = model.config.model_type if (model_type == 't5'): freeze_params(model.shared) for d in [model.encoder, model.decoder]: freeze_params(d.embed_tokens)...
def assert_all_frozen(model): model_grads: List[bool] = list(grad_status(model)) n_require_grad = sum(lmap(int, model_grads)) npars = len(model_grads) assert (not any(model_grads)), f'{(n_require_grad / npars):.1%} of {npars} weights require grad'
def grad_status(model: nn.Module) -> Iterable: return (par.requires_grad for par in model.parameters())
def convert_text(text): text = text.lower() text = ' '.join(re.split('(\\W)', text)) text = ' '.join(text.split()) return text
def eval_meteor_test_webnlg(folder_data, pred_file, dataset): dir_path = os.path.dirname(os.path.realpath(__file__)) folder_data_before = (dir_path + '/utils') cmd_string = ((((((((('java -jar ' + folder_data_before) + '/meteor-1.5.jar ') + pred_file) + ' ') + folder_data) + '/') + dataset) + '.target_eva...
def eval_chrf_test_webnlg(folder_data, pred_file, dataset): dir_path = os.path.dirname(os.path.realpath(__file__)) folder_data_before = (dir_path + '/utils') cmd_string = ((((((((('python ' + folder_data_before) + '/chrf++.py -H ') + pred_file) + ' -R ') + folder_data) + '/') + dataset) + '.target_eval_cr...
def eval_bleu(folder_data, pred_file, dataset): dir_path = os.path.dirname(os.path.realpath(__file__)) cmd_string = ((((((((((((((((('perl ' + dir_path) + '/multi-bleu.perl -lc ') + folder_data) + '/') + dataset) + '.target_eval ') + folder_data) + '/') + dataset) + '.target2_eval ') + folder_data) + '/') + d...
def eval_bleu_sents_tok(pred_file, folder_data, dataset): dir_path = os.path.dirname(os.path.realpath(__file__)) folder_data_before = (dir_path + '/utils') cmd_string = (((((('perl ' + folder_data_before) + '/tokenizer.perl -threads 4 -no-escape < ') + pred_file) + ' > ') + pred_file) + '_tok') os.sys...
def eval_meteor(ref_file, pred_file): dir_path = os.path.dirname(os.path.realpath(__file__)) folder_data_before = (dir_path + '/utils') cmd_string = ((((((('java -jar ' + folder_data_before) + '/meteor-1.5.jar ') + pred_file) + ' ') + ref_file) + ' > ') + pred_file.replace('txt', 'meteor')) os.system(...
def eval_chrf(ref_file, pred_file): dir_path = os.path.dirname(os.path.realpath(__file__)) folder_data_before = (dir_path + '/utils') cmd_string = ((((((('python ' + folder_data_before) + '/chrf++.py -H ') + pred_file) + ' -R ') + ref_file) + ' > ') + pred_file.replace('txt', 'chrf')) os.system(cmd_st...
def save_json(content, path, indent=4, **json_dump_kwargs): with open(path, 'w') as f: json.dump(content, f, indent=indent, **json_dump_kwargs)
def freeze_prefix(model): params = [p for (n, p) in model.named_parameters() if (not any(((nd in n) for nd in ['CEFR_matrices'])))] for par in params: par.requires_grad = False
class AbstractSeq2SeqDatasetSingle(Dataset): def __init__(self, tokenizer, data_dir, max_source_length, max_target_length, type_path='train', n_obs=None, prefix='', **dataset_kwargs): super().__init__() self.src_file = Path(data_dir).joinpath((type_path + '.source')) self.tgt_file = Path(...
class Seq2SeqDatasetSingle(AbstractSeq2SeqDatasetSingle): 'A dataset that calls prepare_seq2seq_batch.' def __getitem__(self, index) -> Dict[(str, str)]: index = (index + 1) source_line = (self.prefix + linecache.getline(str(self.src_file), index).rstrip('\n')) tgt_line = linecache.ge...
def count_trainable_parameters(model): model_parameters = filter((lambda p: p.requires_grad), model.parameters()) params = sum([np.prod(p.size()) for p in model_parameters]) return params
class Seq2SeqLoggingCallback(pl.Callback): def on_batch_end(self, trainer, pl_module): lrs = {f'lr_group_{i}': param['lr'] for (i, param) in enumerate(pl_module.trainer.optimizers[0].param_groups)} pl_module.logger.log_metrics(lrs) @rank_zero_only def _write_logs(self, trainer: pl.Traine...
def bespoke_scheduler(optimizer, num_warmup_steps, num_training_steps, last_epoch=(- 1)): '\n Create a schedule with a learning rate that decreases linearly from the initial lr set in the optimizer to 0, after\n a warmup period during which it increases linearly from 0 to the initial lr set in the optimizer...
class PrefixSummarizationModule(PrefixTransformer): mode = 'summarization' loss_names = ['loss'] metric_names = ROUGE_KEYS default_val_metric = 'rouge2' def __init__(self, hparams, **kwargs): if (hparams.sortish_sampler and (hparams.gpus > 1)): hparams.replace_sampler_ddp = Fa...
def eval(args, model=None): if (model is None): if ('summarization' in args.task_mode): if (args.tuning_mode == 'prefixtune'): model = PrefixSummarizationModule(args) print('the length penalty is {}'.format(args.length_penalty)) with torch.no_grad(): model.eval(...
def main(args, model=None): Path(args.output_dir).mkdir(exist_ok=True) if (model is None): if ('summarization' in args.task_mode): if (args.tuning_mode == 'prefixtune'): model = PrefixSummarizationModule(args) pickle_save(args, os.path.join(args.output_dir, 'args.pkl'))...
class PrefixTransformer(pl.LightningModule): def __init__(self, hparams: argparse.Namespace, num_labels=None, mode='base', config=None, tokenizer=None, seq2seq_model=None, **config_kwargs): 'Initialize a model, tokenizer and config.' super().__init__() self.save_hyperparameters(hparams) ...
def add_generic_args(parser, root_dir) -> None: parser.add_argument('--output_dir', default=None, type=str, required=True, help='The output directory where the model predictions and checkpoints will be written.') parser.add_argument('--n_tpu_cores', dest='tpu_cores', type=int) parser.add_argument('--max_g...
def generic_train(model, args: argparse.Namespace, early_stopping_callback=False, logger=True, extra_callbacks=[], checkpoint_callback=None, logging_callback=None, **extra_train_kwargs): pl.seed_everything(args.seed) odir = Path(model.hparams.output_dir) odir.mkdir(exist_ok=True) checkpoint_callback =...
def run_experiment(yaml_file): with open(yaml_file, 'r') as stream: parsed_yaml = yaml.safe_load(stream) args = '' for (arg, value) in parsed_yaml.items(): args += f'--{arg} {value} ' os.system(f'python finetune.py {args}')
def count_trainable_parameters(model): model_parameters = filter((lambda p: p.requires_grad), model.parameters()) params = sum([np.prod(p.size()) for p in model_parameters]) return params
class Seq2SeqLoggingCallback(pl.Callback): def on_batch_end(self, trainer, pl_module): lrs = {f'lr_group_{i}': param['lr'] for (i, param) in enumerate(pl_module.trainer.optimizers[0].param_groups)} pl_module.logger.log_metrics(lrs) @rank_zero_only def _write_logs(self, trainer: pl.Traine...
def bespoke_scheduler(optimizer, num_warmup_steps, num_training_steps, last_epoch=(- 1)): '\n Create a schedule with a learning rate that decreases linearly from the initial lr set in the optimizer to 0, after\n a warmup period during which it increases linearly from 0 to the initial lr set in the optimizer...
class PrefixSummarizationModule(PrefixTransformer): mode = 'summarization' loss_names = ['loss'] metric_names = ROUGE_KEYS default_val_metric = 'rouge2' def __init__(self, hparams, **kwargs): if (hparams.sortish_sampler and (hparams.gpus > 1)): hparams.replace_sampler_ddp = Fa...
def eval(args, model=None): if (model is None): if ('summarization' in args.task_mode): if (args.tuning_mode == 'prefixtune'): model = PrefixSummarizationModule(args) print('the length penalty is {}'.format(args.length_penalty)) with torch.no_grad(): model.eval(...
def main(args, model=None): Path(args.output_dir).mkdir(exist_ok=True) if (model is None): if ('summarization' in args.task_mode): if (args.tuning_mode == 'prefixtune'): model = PrefixSummarizationModule(args) pickle_save(args, os.path.join(args.output_dir, 'args.pkl'))...
class PrefixTransformer(pl.LightningModule): def __init__(self, hparams: argparse.Namespace, num_labels=None, config=None, tokenizer=None, seq2seq_model=None, **config_kwargs): 'Initialize a model, tokenizer and config.' super().__init__() self.save_hyperparameters(hparams) self.s...
def add_generic_args(parser, root_dir) -> None: parser.add_argument('--output_dir', default=None, type=str, required=True, help='The output directory where the model predictions and checkpoints will be written.') parser.add_argument('--n_tpu_cores', dest='tpu_cores', type=int) parser.add_argument('--max_g...
def generic_train(model, args: argparse.Namespace, early_stopping_callback=False, logger=True, extra_callbacks=[], checkpoint_callback=None, logging_callback=None, **extra_train_kwargs): pl.seed_everything(args.seed) odir = Path(model.hparams.output_dir) odir.mkdir(exist_ok=True) checkpoint_callback =...
def run_experiment(yaml_file): with open(yaml_file, 'r') as stream: parsed_yaml = yaml.safe_load(stream) args = '' for (arg, value) in parsed_yaml.items(): args += f'--{arg} {value} ' os.system(f'python finetune.py {args}')
class LiviaSoftmax(LiviaNet3DConvLayer): ' Final Classification layer with Softmax ' def __init__(self, rng, layerID, inputSample_Train, inputSample_Test, inputToLayerShapeTrain, inputToLayerShapeTest, filterShape, applyBatchNorm, applyBatchNormNumberEpochs, maxPoolingParameters, weights_initialization, weig...
def computeDice(autoSeg, groundTruth): ' Returns\n -------\n DiceArray : floats array\n \n Dice coefficient as a float on range [0,1].\n Maximum similarity = 1\n No similarity = 0 ' n_classes = int((np.max(groundTruth) + 1)) DiceArray = [] for c_i in xrange(1,...
def dice(im1, im2): '\n Computes the Dice coefficient\n ----------\n im1 : boolean array\n im2 : boolean array\n \n If they are not boolean, they will be converted.\n \n -------\n It returns the Dice coefficient as a float on the range [0,1].\n 1: Perfect overlapping \n 0:...
def applyActivationFunction_Sigmoid(inputData): ' inputData is a tensor5D with shape:\n (batchSize,\n Number of feature Maps,\n convolvedImageShape[0],\n convolvedImageShape[1],\n convolvedImageShape[2]) ' outputData = T.nnet.sigmoid(inputData) return outputData
def applyActivationFunction_Tanh(inputData): 'inputData is a tensor5D with shape:\n # (batchSize,\n # Number of feature Maps,\n # convolvedImageShape[0],\n # convolvedImageShape[1],\n # convolvedImageShape[2])' outputData = T.tanh(inputData) return outputData
def applyActivationFunction_ReLU_v1(inputData): ' inputData is a tensor5D with shape:\n # (batchSize,\n # Number of feature Maps,\n # convolvedImageShape[0],\n # convolvedImageShape[1],\n # convolvedImageShape[2]) ' return T.maximum(inputData, 0)
def applyActivationFunction_ReLU_v2(inputData): return T.switch((inputData < 0.0), 0.0, inputData)
def applyActivationFunction_ReLU_v3(inputData): return ((inputData + abs(inputData)) / 2.0)
def applyActivationFunction_ReLU_v4(inputData): return (((T.sgn(inputData) + 1) * inputData) * 0.5)
def applyActivationFunction_LeakyReLU(inputData, leakiness): 'leakiness : float\n Slope for negative input, usually between 0 and 1.\n A leakiness of 0 will lead to the standard rectifier,\n a leakiness of 1 will lead to a linear activation function,\n and any value in between will giv...
def applyActivationFunction_PReLU(inputData, PreluActivations): 'Parametric Rectified Linear Unit.\n It follows:\n `f(x) = alpha * x for x < 0`,\n `f(x) = x for x >= 0`,\n where `alpha` is a learned array with the same shape as x.\n \n - The input is a tensor of shape (batchSize, FeatMaps, xDim,...
def applyActivationFunction_PReLU_v2(inputData, PreluActivations): ' inputData is a tensor5D with shape:\n (batchSize,\n Number of feature Maps,\n convolvedImageShape[0],\n convolvedImageShape[1],\n convolvedImageShape[2]) ' preluActivationsAsRow = PreluActivations.dimshuffle('x', 0, 'x', ...
def applyActivationFunction_PReLU_v3(inputData, PreluActivations): ' inputData is a tensor5D with shape:\n (batchSize,\n Number of feature Maps,\n convolvedImageShape[0],\n convolvedImageShape[1],\n convolvedImageShape[2]) ' preluActivationsAsRow = PreluActivations.dimshuffle('x', 0, 'x', ...
def apply_Dropout(rng, dropoutRate, inputShape, inputData, task): ' Task:\n # 0: Training\n # 1: Validation\n # 2: Testing ' outputData = inputData if (dropoutRate > 0.001): activationRate = (1 - dropoutRate) srng = T.shared_randomstreams.RandomStreams(rng.randint(999999)...
def convolveWithKernel(W, filter_shape, inputSample, inputSampleShape): wReshapedForConv = W.dimshuffle(0, 4, 1, 2, 3) wReshapedForConvShape = (filter_shape[0], filter_shape[4], filter_shape[1], filter_shape[2], filter_shape[3]) inputSampleReshaped = inputSample.dimshuffle(0, 4, 1, 2, 3) inputSampleRe...
def applyBn(numberEpochApplyRolling, inputTrain, inputTest, inputShapeTrain): numberOfChannels = inputShapeTrain[1] gBn_values = np.ones(numberOfChannels, dtype='float32') gBn = theano.shared(value=gBn_values, borrow=True) bBn_values = np.zeros(numberOfChannels, dtype='float32') bBn = theano.share...