desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Creates the mask for a given set of data. Parameters data : numpy sequence of ndarrays A sequence of ndarrays representing sequential data'
def _create_mask(self, data):
sequence_lengths = [len(sample) for sample in data] max_sequence_length = max(sequence_lengths) mask = np.zeros((max_sequence_length, len(data)), dtype=config.floatX) for (i, sequence_length) in enumerate(sequence_lengths): mask[:sequence_length, i] = 1 return mask
'Initializes a projection layer.'
def __init__(self, dim, layer_name, irange=None, istdev=None):
super(ProjectionLayer, self).__init__() self.dim = dim self.layer_name = layer_name if ((irange is None) and (istdev is None)): raise ValueError('ProjectionLayer needs either irange oristdev in order to intitalize the projections.') elif ((irange is not None) an...
'Returns the vocabulary (a dictionary from word to word indices)'
@property def vocabulary(self):
if hasattr(self, '_vocabulary'): if (not getattr(self, '_vocabulary_case_checked', False)): for word in self._vocabulary: if (word != word.lower()): raise ValueError(('The vocabulary contains cased words (%s) but the dataset is su...
'The index referring to the unknown word.'
@property def unknown_index(self):
if ((not hasattr(self, '_unknown_index')) and (0 in self.inverse_vocabulary)): raise NotImplementedError('This dataset does not define an index for unknown words, but the default `0` is already taken') return getattr(self, '_unknown_index', 0)
'The string to use for the unknown words. If not defined, return `UNK`.'
@property def unknown_word(self):
if ((not hasattr(self, '_unknown_word')) and ('UNK' in self.vocabulary)): raise NotImplementedError('This dataset does not define a string for unknown words, but the default `UNK` is already taken') return getattr(self, '_unknown_word', 'UNK')
'The inverse vocabulary, a dictionary from integers to strings. If it does not exist, it is created from the vocabulary if possible.'
@property def inverse_vocabulary(self):
if hasattr(self, '_inverse_vocabulary'): return self._inverse_vocabulary elif hasattr(self, '_vocabulary'): self._inverse_vocabulary = dict(((index, word) for (word, index) in six.iteritems(self._vocabulary))) return self._inverse_vocabulary else: raise NotImplementedError
'Converts the elements of a (nested) list of strings to word indices Parameters words : (nested) list of strings Assumes each element is a word'
def words_to_indices(self, words):
assert isinstance(words, list) if all((isinstance(word, list) for word in words)): return [self.words_to_indices(word) for word in words] assert all((isinstance(word, six.string_types) for word in words)) if self.is_case_sensitive: return [self.vocabulary.get(word, self.unknown_index) fo...
'Converts word indices back to words and returns a list of strings Parameters indices : list of ints A list of word indices'
def indices_to_words(self, indices):
return [self.inverse_vocabulary.get(index, self.unknown_word) for index in indices]
'Takes a sequence of integers and projects (embeds) these labels into a continuous space by concatenating the correspending rows in the projection matrix W i.e. [2, 5] -> [W[2] ... W[5]] Parameters x : theano.tensor, int dtype A vector of labels (or a matrix where each row is a sample in a batch) which will be projecte...
def project(self, x):
assert ('int' in str(x.dtype)) if (x.ndim == 2): shape = (x.shape[0], (x.shape[1] * self._W.shape[1])) return self._W[x.flatten()].reshape(shape) elif (x.ndim == 1): return self._W[x].flatten() else: assert ValueError('project needs 1- or 2-dimensional inpu...
'Deterministic, compile-time tuple indexing.'
def __getitem__(self, index):
if isinstance(index, slice): if any((((elem is not None) or (not isinstance(elem, int))) for elem in [index.start, index.step, index.stop])): raise TypeError('slice elements must be int or None--symbolic indexing not supported yet') return tuple_variable(sel...
'Returns a theano function that takes an action and returns a reward.'
def get_action_func(self):
action = T.iscalar() reward_mean = self.means[action] reward_std = self.stds[action] reward = self.theano_rng.normal(avg=reward_mean, std=reward_std, dtype=config.floatX, size=reward_mean.shape) rval = function([action], reward) return rval
'Returns a theano function that takes a minibatch (num_examples, num_features) of contexts and returns a minibatch (num_examples, num_classes) of one-hot codes for actions.'
def get_decide_func(self):
X = T.matrix() y_hat = self.mlp.fprop(X) theano_rng = make_theano_rng(None, ((2013 + 11) + 20), which_method='multinomial') if self.stochastic: a = theano_rng.multinomial(pvals=y_hat, dtype='float32') else: mx = T.max(y_hat, axis=1).dimshuffle(0, 'x') a = T.eq(y_hat, mx) ...
'Returns a theano function that does a learning update when passed a context, the action that the agent chose, and the reward it got. This agent expects the action to be a matrix of one-hot class selections and the reward to be a vector of 0 / 1 rewards per example.'
def get_learn_func(self):
contexts = T.matrix() actions = T.matrix() rewards = T.vector() assert (sum([self.neg_target, self.ignore_wrong]) <= 1) if self.neg_target: signed_rewards = ((2.0 * rewards) - 1.0) fake_targets = (actions * signed_rewards.dimshuffle(0, 'x')) elif self.ignore_wrong: fake_t...
'Returns a callable that takes no arguments and returns a minibatch of contexts. Minibatch should be in VectorSpace(n).'
def get_context_func(self):
def rval(): (X, y) = self.dataset.get_batch_design(self.batch_size, include_labels=True) self.y_cache = y return X return rval
'Returns a callable that takes no arguments and returns a minibatch of rewards. Assumes that this function has been called after a call to context_func that gave the contexts used to choose the actions.'
def get_action_func(self):
def rval(a): return (a * self.y_cache).sum(axis=1) return rval
'Returns a callable that takes a minibatch of contexts, a minibatch of actions, and a minibatch of rewards, and updates the model according to them.'
def get_learn_func(self):
raise NotImplementedError()
'Returns a theano function that decides what action to take. Since this is a bandit playing agent, there is no input.'
def get_decide_func(self):
return function([], T.cast(T.argmax(self.estimated_rewards), 'int32'))
'Returns a theano function that takes an action and a reward, and updates the agent based on this experience.'
def get_learn_func(self):
a = T.iscalar() r = T.scalar() old_estimated_reward = self.estimated_rewards[a] old_observation_count = self.observation_counts[a] observation_count = (old_observation_count + 1.0) delta = (r - old_estimated_reward) new_estimated_reward = (old_estimated_reward + (delta / observation_count)) ...
'Parameters data : str String with lines separated by \''
def __init__(self, data):
if isinstance(data, list): self._str = data else: self._str = data.split('\n') self.reset()
'func_name : Descriptive text continued text another_func_name : Descriptive text func_name1, func_name2, func_name3'
def _parse_see_also(self, content):
functions = [] current_func = None rest = [] for line in content: if (not line.strip()): continue if (':' in line): if current_func: functions.append((current_func, rest)) r = line.split(':', 1) current_func = r[0].strip() ...
'.. index: default :refguide: something, else, and more'
def _parse_index(self, section, content):
def strip_each_in(lst): return [s.strip() for s in lst] out = {} section = section.split('::') if (len(section) > 1): out['default'] = strip_each_in(section[1].split(','))[0] for line in content: line = line.split(':') if (len(line) > 2): out[line[1]] = st...
'Grab signature (if given) and summary'
def _parse_summary(self):
summary = self._doc.read_to_next_empty_line() summary_str = '\n'.join([s.strip() for s in summary]) if re.compile('^([\\w. ]+=)?[\\w\\.]+\\(.*\\)$').match(summary_str): self['Signature'] = summary_str if (not self._is_at_section()): self['Summary'] = self._doc.read_to_next_emp...
'Get the next line from the input buffer.'
def readline(self):
self.line_number += 1 if (self.line_number > len(self.lines)): return '' line = self.lines[(self.line_number - 1)] if ((self.indent_char is None) and (line[:1] in WHITESPACE)): self.indent_char = line[0] return line
'Run a check plugin.'
def run_check(self, check, argument_names):
arguments = [] for name in argument_names: arguments.append(getattr(self, name)) return check(*arguments)
'Run all physical checks on a raw input line.'
def check_physical(self, line):
self.physical_line = line for (name, check, argument_names) in self._physical_checks: result = self.run_check(check, argument_names) if (result is not None): (offset, text) = result self.report_error(self.line_number, offset, text, check) if (text[:4] == 'E101...
'Build a logical line from tokens.'
def build_tokens_line(self):
self.mapping = [] logical = [] comments = [] length = 0 previous = None for token in self.tokens: (token_type, text) = token[0:2] if (token_type == tokenize.COMMENT): comments.append(text) continue if (token_type in SKIP_TOKENS): contin...
'Build a line from tokens and run all logical checks on it.'
def check_logical(self):
self.build_tokens_line() self.report.increment_logical_line() token0 = (self.mapping[0][1] if self.mapping else self.tokens[0]) first_line = self.lines[(token0[2][0] - 1)] indent = first_line[:token0[2][1]] self.indent_level = expand_indent(indent) if (self.verbose >= 2): print self....
'If appropriate (based on token), check current physical line(s).'
def maybe_check_physical(self, token):
if (token[0] in (tokenize.NEWLINE, tokenize.NL)): self.check_physical(token[4]) elif ((token[0] == tokenize.STRING) and ('\n' in token[1])): if noqa(token[4]): return self.multiline = True self.line_number = token[2][0] for line in token[1].split('\n')[:(-1)]:...
'Run all checks on the input file.'
def check_all(self, expected=None, line_offset=0):
self.report.init_file(self.filename, self.lines, expected, line_offset) if self._ast_checks: self.check_ast() self.line_number = 0 self.indent_char = None self.indent_level = 0 self.previous_indent_level = 0 self.previous_logical = '' self.tokens = [] self.blank_lines = blank...
'Start the timer.'
def start(self):
self._start_time = time.time()
'Stop the timer.'
def stop(self):
self.elapsed = (time.time() - self._start_time)
'Signal a new file.'
def init_file(self, filename, lines, expected, line_offset):
self.filename = filename self.lines = lines self.expected = (expected or ()) self.line_offset = line_offset self.file_errors = 0 self.counters['files'] += 1 self.counters['physical lines'] += len(lines)
'Signal a new logical line.'
def increment_logical_line(self):
self.counters['logical lines'] += 1
'Report an error, according to options.'
def error(self, line_number, offset, text, check):
code = text[:4] if self._ignore_code(code): return if (code in self.counters): self.counters[code] += 1 else: self.counters[code] = 1 self.messages[code] = text[5:] if (code in self.expected): return if (self.print_filename and (not self.file_errors)): ...
'Return the count of errors and warnings for this file.'
def get_file_results(self):
return self.file_errors
'Return the total count of errors and warnings.'
def get_count(self, prefix=''):
return sum([self.counters[key] for key in self.messages if key.startswith(prefix)])
'Get statistics for message codes that start with the prefix. prefix=\'\' matches all errors and warnings prefix=\'E\' matches all errors prefix=\'W\' matches all warnings prefix=\'E4\' matches all errors that have to do with imports'
def get_statistics(self, prefix=''):
return [('%-7s %s %s' % (self.counters[key], key, self.messages[key])) for key in sorted(self.messages) if key.startswith(prefix)]
'Print overall statistics (number of errors and warnings).'
def print_statistics(self, prefix=''):
for line in self.get_statistics(prefix): print line
'Print benchmark numbers.'
def print_benchmark(self):
print ('%-7.2f %s' % (self.elapsed, 'seconds elapsed')) if self.elapsed: for key in self._benchmark_keys: print ('%-7d %s per second (%d total)' % ((self.counters[key] / self.elapsed), key, self.counters[key]))
'Signal a new file.'
def init_file(self, filename, lines, expected, line_offset):
self._deferred_print = [] return super(StandardReport, self).init_file(filename, lines, expected, line_offset)
'Report an error, according to options.'
def error(self, line_number, offset, text, check):
code = super(StandardReport, self).error(line_number, offset, text, check) if (code and ((self.counters[code] == 1) or self._repeat)): self._deferred_print.append((line_number, offset, code, text[5:], check.__doc__)) return code
'Print the result and return the overall count for this file.'
def get_file_results(self):
self._deferred_print.sort() for (line_number, offset, code, text, doc) in self._deferred_print: print (self._fmt % {'path': self.filename, 'row': (self.line_offset + line_number), 'col': (offset + 1), 'code': code, 'text': text}) if self._show_source: if (line_number > len(self.lines...
'Initialize the report instance.'
def init_report(self, reporter=None):
self.options.report = (reporter or self.options.reporter)(self.options) return self.options.report
'Run all checks on the paths.'
def check_files(self, paths=None):
if (paths is None): paths = self.paths report = self.options.report runner = self.runner report.start() try: for path in paths: if os.path.isdir(path): self.input_dir(path) elif (not self.excluded(path)): runner(path) except...
'Run all checks on a Python source file.'
def input_file(self, filename, lines=None, expected=None, line_offset=0):
if self.options.verbose: print ('checking %s' % filename) fchecker = self.checker_class(filename, lines=lines, options=self.options) return fchecker.check_all(expected=expected, line_offset=line_offset)
'Check all files in this directory and all subdirectories.'
def input_dir(self, dirname):
dirname = dirname.rstrip('/') if self.excluded(dirname): return 0 counters = self.options.report.counters verbose = self.options.verbose filepatterns = self.options.filename runner = self.runner for (root, dirs, files) in os.walk(dirname): if verbose: print ('dire...
'Check if options.exclude contains a pattern that matches filename.'
def excluded(self, filename, parent=None):
if (not self.options.exclude): return False basename = os.path.basename(filename) if filename_match(basename, self.options.exclude): return True if parent: filename = os.path.join(parent, filename) filename = os.path.abspath(filename) return filename_match(filename, self....
'Check if the error code should be ignored. If \'options.select\' contains a prefix of the error code, return False. Else, if \'options.ignore\' contains a prefix of the error code, return True.'
def ignore_code(self, code):
if ((len(code) < 4) and any((s.startswith(code) for s in self.options.select))): return False return (code.startswith(self.options.ignore) and (not code.startswith(self.options.select)))
'Find all globally visible functions where the first argument name starts with argument_name and which contain selected tests.'
def get_checks(self, argument_name):
checks = [] for (check, attrs) in _checks[argument_name].items(): (codes, args) = attrs if any(((not (code and self.ignore_code(code))) for code in codes)): checks.append((check.__name__, check, args)) return sorted(checks)
'Method called by the training algorithm, which allows LearningRules to add monitoring channels. Parameters monitor : pylearn2.monitor.Monitor Monitor object, to which the rule should register additional monitoring channels. monitoring_dataset : pylearn2.datasets.dataset.Dataset or dict Dataset instance or dictionary w...
def add_channels_to_monitor(self, monitor, monitoring_dataset):
pass
'Provides the symbolic (theano) description of the updates needed to perform this learning rule. Parameters learning_rate : float Learning rate coefficient. grads : dict A dictionary mapping from the model\'s parameters to their gradients. lr_scalers : dict A dictionary mapping from the model\'s parameters to a learnin...
def get_updates(self, learning_rate, grads, lr_scalers=None):
raise NotImplementedError((str(type(self)) + ' does not implement get_updates.'))
'Activates monitoring of the momentum. Parameters monitor : pylearn2.monitor.Monitor Monitor object, to which the rule should register additional monitoring channels. monitoring_dataset : pylearn2.datasets.dataset.Dataset or dict Dataset instance or dictionary whose values are Dataset objects.'
def add_channels_to_monitor(self, monitor, monitoring_dataset):
monitor.add_channel(name='momentum', ipt=None, val=self.momentum, data_specs=(NullSpace(), ''), dataset=monitoring_dataset)
'Provides the updates for learning with gradient descent + momentum. Parameters learning_rate : float Learning rate coefficient. grads : dict A dictionary mapping from the model\'s parameters to their gradients. lr_scalers : dict A dictionary mapping from the model\'s parameters to a learning rate multiplier.'
def get_updates(self, learning_rate, grads, lr_scalers=None):
updates = OrderedDict() for (param, grad) in six.iteritems(grads): vel = sharedX((param.get_value() * 0.0)) assert (param.dtype == vel.dtype) assert (grad.dtype == param.dtype) if (param.name is not None): vel.name = ('vel_' + param.name) scaled_lr = (learning...
'Initializes the momentum schedule based on epochs_seen. Parameters model : pylearn2.models.Model The model to which the training algorithm is applied. dataset : pylearn2.datasets.Dataset The dataset to which the model is applied. algorithm : pylearn2.training_algorithms.TrainingAlgorithm Describes how gradients should...
def setup(self, model, dataset, algorithm):
monitor = Monitor.get_monitor(model) self._count = monitor.get_epochs_seen() self._apply_momentum(algorithm)
'Updates the momentum according to the linear schedule. Parameters model : pylearn2.models.Model The model to which the training algorithm is applied. dataset : pylearn2.datasets.Dataset The dataset to which the model is applied. algorithm : pylearn2.training_algorithms.TrainingAlgorithm Describes how gradients should ...
def on_monitor(self, model, dataset, algorithm):
self._count += 1 self._apply_momentum(algorithm)
'Updates the momentum on algorithm based on the epochs elapsed.'
def _apply_momentum(self, algorithm):
if (not hasattr(algorithm, 'learning_rule')): raise ValueError('For MomentumAdjustor to work, you need to use a TrainingAlgorithm that supports learning rules (for instance, SGD), and specify a learning_rule (for instance, Momentum) for...
'Returns the momentum currently desired by the schedule.'
def current_momentum(self):
w = (self.saturate - self.start) if (w == 0): if (self._count >= self.start): return self.final_momentum return self._init_momentum alpha = (float((self._count - self.start)) / float(w)) if (alpha < 0.0): alpha = 0.0 if (alpha > 1.0): alpha = 1.0 retur...
'Compute the AdaDelta updates Parameters learning_rate : float Learning rate coefficient. grads : dict A dictionary mapping from the model\'s parameters to their gradients. lr_scalers : dict A dictionary mapping from the model\'s parameters to a learning rate multiplier.'
def get_updates(self, learning_rate, grads, lr_scalers=None):
updates = OrderedDict() for param in grads.keys(): mean_square_grad = sharedX((param.get_value() * 0.0)) mean_square_dx = sharedX((param.get_value() * 0.0)) if (param.name is not None): mean_square_grad.name = ('mean_square_grad_' + param.name) mean_square_dx.name...
'Compute the AdaGrad updates Parameters learning_rate : float Learning rate coefficient. grads : dict A dictionary mapping from the model\'s parameters to their gradients. lr_scalers : dict A dictionary mapping from the model\'s parameters to a learning rate multiplier.'
def get_updates(self, learning_rate, grads, lr_scalers=None):
updates = OrderedDict() for param in grads.keys(): sum_square_grad = sharedX((param.get_value() * 0.0)) if (param.name is not None): sum_square_grad.name = ('sum_square_grad_' + param.name) new_sum_squared_grad = (sum_square_grad + T.sqr(grads[param])) epsilon = (lr_s...
'The channels added are the min, mean, and max of the mean_square_grad of each parameter.'
@wraps(LearningRule.add_channels_to_monitor) def add_channels_to_monitor(self, monitor, monitoring_dataset):
channel_mapping = {'_min': T.min, '_max': T.max, '_mean': T.mean} for mean_square_grad in self.mean_square_grads.values(): for (suffix, op) in channel_mapping.items(): monitor.add_channel(name=(mean_square_grad.name + suffix), ipt=None, val=op(mean_square_grad), data_specs=(NullSpace(), ''),...
'Provides the symbolic (theano) description of the updates needed to perform this learning rule. See Notes for side-effects. Parameters learning_rate : float Learning rate coefficient. grads : dict A dictionary mapping from the model\'s parameters to their gradients. lr_scalers : dict A dictionary mapping from the mode...
def get_updates(self, learning_rate, grads, lr_scalers=None):
updates = OrderedDict() for param in grads: mean_square_grad = sharedX((param.get_value() * 0.0)) if (param.name is None): raise ValueError('Model parameters must be named.') mean_square_grad.name = ('mean_square_grad_' + param.name) if (param.name in self...
'Allows the training algorithm to do some preliminary configuration *before* we actually start training the model. The dataset is provided in case other derived training algorithms need to modify model based on the dataset. Parameters model : object A Python object representing the model to train. Loosely implementing ...
def setup(self, model, dataset):
self.model = model if (self.cost is None): self.cost = model.get_default_cost() try: if self.cost.is_stochastic(): raise TypeError('BGD is not compatible with stochastic costs.') except NotImplementedError: warnings.warn('BGD is not compatib...
'.. todo:: WRITEME'
def train(self, dataset):
assert self.bSetup model = self.model rng = self.rng train_iteration_mode = 'shuffled_sequential' if (not is_stochastic(train_iteration_mode)): rng = None data_specs = self.cost.get_data_specs(self.model) mapping = DataSpecsMapping(data_specs) space_tuple = mapping.flatten(data_s...
'.. todo:: WRITEME'
def continue_learning(self, model):
if (self.termination_criterion is None): return True else: rval = self.termination_criterion.continue_learning(self.model) assert (rval in [True, False, 0, 1]) return rval
'.. todo:: WRITEME'
def before_step(self, model):
if (self.scale_step != 1.0): self.params = list(model.get_params()) self.value = [param.get_value() for param in self.params]
'.. todo:: WRITEME'
def after_step(self, model):
if (self.scale_step != 1): for (param, value) in safe_zip(self.params, self.value): value = (((1.0 - self.scale_step) * value) + (self.scale_step * param.get_value())) param.set_value(value)
'.. todo:: WRITEME'
def on_monitor(self, model, dataset, algorithm):
monitor = model.monitor if self.first: self.first = False self.monitor_channel = sharedX(algorithm.scale_step) hack = monitor.channels.values()[0] monitor.add_channel('scale_step', hack.graph_input, self.monitor_channel, dataset=hack.dataset, data_specs=hack.data_specs) chann...
'.. todo:: WRITEME'
def __call__(self, model):
return self.continue_learning
'.. todo:: WRITEME'
def on_monitor(self, model, dataset, algorithm):
if self.first: monitor = model.monitor self.first = False self.monitor_channel = sharedX(algorithm.scale_step) hack = monitor.channels.values()[0] monitor.add_channel('scale_step', hack.graph_input, self.monitor_channel, dataset=hack.dataset) cur = algorithm.scale_step ...
'.. todo:: WRITEME'
def on_monitor(self, model, dataset, algorithm):
monitor = model.monitor if self.first: self.first = False self.monitor_channel = sharedX(algorithm.scale_step) hack = monitor.channels.values()[0] monitor.add_channel('scale_step', hack.graph_input, self.monitor_channel, dataset=hack.dataset) channel = monitor.channels[self.c...
'.. todo:: WRITEME'
def __call__(self, model):
return self.continue_learning
'Set up monitor to model the objective value, learning rate, momentum (if applicable), and extra channels defined by the cost. This method must be called after `learning_rule.get_updates`, since it may have an effect on `learning_rule.add_channels_to_monitor` (that is currently the case for `learning_rule.RMSProp`).'
def _setup_monitor(self):
if bool(self.monitoring_dataset): if ((self.monitoring_batch_size is None) and (self.monitoring_batches is None)): self.monitoring_batch_size = self.batch_size self.monitoring_batches = self.batches_per_iter self.monitor.setup(dataset=self.monitoring_dataset, cost=self.cost, ...
'Compiles the theano functions needed for the train method. Parameters model : a Model instance dataset : Dataset'
def setup(self, model, dataset):
if (self.cost is None): self.cost = model.get_default_cost() inf_params = [param for param in model.get_params() if contains_inf(param.get_value())] if (len(inf_params) > 0): raise ValueError(('These params are Inf: ' + str(inf_params))) if any([contains_nan(param.get_value()...
'Runs one epoch of SGD training on the specified dataset. Parameters dataset : Dataset'
def train(self, dataset):
if (not hasattr(self, 'sgd_update')): raise Exception('train called without first calling setup') for param in self.params: value = param.get_value(borrow=True) if (not isfinite(value)): raise RuntimeError(('NaN in ' + param.name)) self.first = False ...
'Returns True if the algorithm should continue running, or False if it has reached convergence / started overfitting and should stop. Parameters model : a Model instance'
def continue_learning(self, model):
if (self.termination_criterion is None): return True else: return self.termination_criterion.continue_learning(self.model)
'Adjusts the learning rate based on the contents of model.monitor Parameters model : a Model instance dataset : Dataset algorithm : WRITEME'
def on_monitor(self, model, dataset, algorithm):
model = algorithm.model lr = algorithm.learning_rate current_learning_rate = lr.get_value() assert hasattr(model, 'monitor'), ('no monitor associated with ' + str(model)) monitor = model.monitor monitor_channel_specified = True if (self.channel_name is None): monitor_chan...
'Returns True or False depending on whether the optimization should stop or not. The optimization should stop if it has run for a number of epochs superior to the patience without any improvement. Parameters model : Model The model used in the experiment and from which the monitor used in the termination criterion will...
def __call__(self, model):
monitor = model.monitor if (self._channel_name is None): if (len(monitor.channels) != 1): raise ValueError('Only single-channel monitors are supported for channel_name == None') v = monitor.channels.values()[0].val_record else: v = monitor.channels...
'Updates the learning rate according to the annealing schedule. Parameters algorithm : WRITEME'
def __call__(self, algorithm):
if (not self._initialized): self._base = algorithm.learning_rate.get_value() self._initialized = True self._count += 1 algorithm.learning_rate.set_value(np.cast[config.floatX](self.current_learning_rate()))
'Returns the current desired learning rate according to the annealing schedule.'
def current_learning_rate(self):
return (self._base * min(1, (self._anneal_start / self._count)))
'Updates the learning rate according to the exponential decay schedule. Parameters algorithm : SGD The SGD instance whose `learning_rate` field should be modified.'
def __call__(self, algorithm):
if (self._count == 0): self._base_lr = algorithm.learning_rate.get_value() self._count += 1 if (not self._min_reached): new_lr = (self._base_lr / (self.decay_factor ** self._count)) if (new_lr <= self.min_lr): self._min_reached = True new_lr = self.min_lr ...
'Adjusts the learning rate according to the linear decay schedule Parameters algorithm : WRITEME'
def __call__(self, algorithm):
if (self._count == 0): self._base_lr = algorithm.learning_rate.get_value() self._step = ((self._base_lr - (self._base_lr * self.decay_factor)) / ((self.saturate - self.start) + 1)) self._count += 1 if (self._count >= self.start): if (self._count < self.saturate): new_lr =...
'Adjusts the learning rate according to the decay schedule. Parameters model : a Model instance dataset : Dataset algorithm : WRITEME'
def on_monitor(self, model, dataset, algorithm):
if (not self._initialized): self._init_lr = algorithm.learning_rate.get_value() if (self._init_lr < self.min_lr): raise ValueError(('The initial learning rate is smaller than ' + 'the minimum allowed learning rate.')) self._initialized = True ...
'Returns the learning rate currently desired by the decay schedule.'
def current_lr(self):
if (self._count < self.start): scale = 1 else: scale = (float(self.half_life) / float(((self._count - self.start) + self.half_life))) lr = (self._init_lr * scale) clipped = max(self.min_lr, lr) return clipped
'Initializes the decay schedule based on epochs_seen. Parameters model : pylearn2.models.Model The model to which the training algorithm is applied. dataset : pylearn2.datasets.Dataset The dataset to which the model is applied. algorithm : pylearn2.training_algorithms.TrainingAlgorithm Describes how gradients should be...
def setup(self, model, dataset, algorithm):
monitor = Monitor.get_monitor(model) self._count = monitor.get_epochs_seen() self._apply_learning_rate(algorithm)
'Updates the learning rate based on the linear decay schedule. Parameters model : a Model instance dataset : Dataset algorithm : WRITEME'
def on_monitor(self, model, dataset, algorithm):
self._count += 1 self._apply_learning_rate(algorithm)
'Updates the learning rate on algorithm based on the epochs elapsed.'
def _apply_learning_rate(self, algorithm):
if (not self._initialized): self._init_lr = algorithm.learning_rate.get_value() self._step = ((self._init_lr - (self._init_lr * self.decay_factor)) / ((self.saturate - self.start) + 1)) self._initialized = True algorithm.learning_rate.set_value(np.cast[config.floatX](self.current_lr()))
'Returns the learning rate currently desired by the decay schedule.'
def current_lr(self):
if (self._count >= self.start): if (self._count < self.saturate): new_lr = (self._init_lr - (self._step * ((self._count - self.start) + 1))) else: new_lr = (self._init_lr * self.decay_factor) else: new_lr = self._init_lr assert (new_lr > 0) return new_lr
'To be called after each SGD step. Updates the Polyak averaged-parameters for this model Parameters algorithm : WRITEME'
def __call__(self, algorithm):
self.avg()
'Make sure Polyak-averaged model gets monitored. Save the model if necessary. Parameters model : a Model instance dataset : Dataset algorithm : WRITEME'
def on_monitor(self, model, dataset, algorithm):
if (self._count == self.start): self._worker = _PolyakWorker(model) algorithm.update_callbacks.append(self._worker) try: model.add_polyak_channels(self._worker.param_to_mean, algorithm.monitoring_dataset) except AttributeError: pass elif ((self.save_path i...
'.. todo:: WRITEME'
def _register_update_callbacks(self, update_callbacks):
if (update_callbacks is None): update_callbacks = [] try: iter(update_callbacks) self.update_callbacks = update_callbacks except TypeError: self.update_callbacks = [update_callbacks]
'Initialize the given training algorithm. Parameters model : object Object that implements the Model interface defined in `pylearn2.models`. dataset : object Object that implements the Dataset interface defined in `pylearn2.datasets`. Notes Called by the training script prior to any calls involving data. This is a good...
def setup(self, model, dataset):
self.model = model
'Performs some amount of training, generally one "epoch" of online learning Parameters dataset : object Object implementing the dataset interface defined in `pylearn2.datasets.dataset.Dataset`. Returns None'
def train(self, dataset):
raise NotImplementedError()
'.. todo:: WRITEME Parameters monitoring_dataset : None or Dataset or dict None for no monitoring, or Dataset, to monitor on one dataset, or dict mapping string names to Datasets'
def _set_monitoring_dataset(self, monitoring_dataset):
if isinstance(monitoring_dataset, Dataset): self.monitoring_dataset = {'': monitoring_dataset} else: if (monitoring_dataset is not None): assert isinstance(monitoring_dataset, dict) for key in monitoring_dataset: assert isinstance(key, str) ...
'Return True to continue learning. Called after the Monitor has been run on the latest parameters so the monitor may be used to determine convergence. Parameters model : WRITEME'
def continue_learning(self, model):
raise NotImplementedError(((str(type(self)) + ' does not implement ') + 'continue_learning.'))
'Adapts `self.batch_size` to be consistent with `model` Parameters model : Model The model to synchronize the batch size with'
def _synchronize_batch_size(self, model):
batch_size = self.batch_size if hasattr(model, 'force_batch_size'): if (model.force_batch_size and (model.force_batch_size > 0)): if (batch_size is not None): if (batch_size != model.force_batch_size): if self.set_batch_size: model....
'Allows the training algorithm to do some preliminary configuration *before* we actually start training the model. The dataset is provided in case other derived training algorithms need to modify model based on the dataset. Parameters model : object Python object representing the model to train loosely implementing the...
def setup(self, model, dataset):
self._synchronize_batch_size(model) self.model = model self.monitor = Monitor.get_monitor(model) if (self.monitoring_dataset is not None): (space, source) = model.get_monitoring_data_specs() mapping = DataSpecsMapping((space, source)) space_tuple = mapping.flatten(space, return_t...
'.. todo:: WRITEME'
def continue_learning(self, model):
if self.learn_more: if (self.termination_criterion is not None): return self.termination_criterion.continue_learning(model) return True return False
'Returns true iff space.format_as(batch, self) and space.format_as(batch, other) return the same formatted batch.'
def __eq__(self, other):
raise NotImplementedError(('__eq__ not implemented in class %s.' % type(self)))
'Returns the batch axis of the output space. Returns batch_axis : int the axis of the batch in the output space.'
def get_batch_axis(self):
return 0
'.. todo:: WRITEME'
def __ne__(self, other):
return (not (self == other))