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) and (istdev is not None)): raise ValueError('ProjectionLayer was passed both irange and istdev but needs only one') else: self._irange = irange self._istdev = istdev
'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 supposed to be case-insensitive' % word)) self._vocabulary_case_checked = True return self._vocabulary else: raise NotImplementedError('No vocabulary given')
'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) for word in words] else: return [self.vocabulary.get(word.lower(), self.unknown_index) for word in words]
'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 projected'
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 input')
'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(self.component_variables[index]) if (not isinstance(index, int)): raise TypeError('index must be int or slice--symbolic indexing not supported yet') return self.component_variables[index]
'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) if (self.epsilon is not None): a = theano_rng.multinomial(pvals=(((1.0 - self.epsilon) * a) + ((self.epsilon * T.ones_like(y_hat)) / y_hat.shape[1])), dtype='float32') if (self.epsilon_stochastic is not None): a = theano_rng.multinomial(pvals=(((1.0 - self.epsilon_stochastic) * a) + (self.epsilon_stochastic * y_hat)), dtype='float32') logger.info('Compiling classifier agent learning function') t1 = time.time() f = function([X], a) t2 = time.time() logger.info('...done, took {0}'.format((t2 - t1))) return f
'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_targets = (actions * rewards.dimshuffle(0, 'x')) else: correct_actions = (actions * rewards.dimshuffle(0, 'x')) roads_not_taken = ((T.ones_like(actions) - actions) / (T.cast(actions.shape[1], 'float32') - 1.0)) fake_targets = (correct_actions + (roads_not_taken * (1 - rewards).dimshuffle(0, 'x'))) lr_scalers = self.mlp.get_lr_scalers() (grads, updates) = self.cost.get_gradients(self.mlp, (contexts, fake_targets)) updates.update(self.learning_rule.get_updates(self.learning_rate, grads, lr_scalers)) self.mlp.modify_updates(updates) learn_func = function([contexts, actions, rewards], updates=updates) def rval(contexts, actions, rewards): learn_func(contexts, actions, rewards) for callback in self.update_callbacks: callback(self) return rval
'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)) new_estimated_rewards = T.set_subtensor(self.estimated_rewards[a], new_estimated_reward) new_observation_counts = T.set_subtensor(self.observation_counts[a], observation_count) updates = OrderedDict([(self.estimated_rewards, new_estimated_rewards), (self.observation_counts, new_observation_counts)]) rval = function([a, r], updates=updates) return rval
'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() r[1] = r[1].strip() if r[1]: rest = [r[1]] else: rest = [] elif (not line.startswith(' ')): if current_func: functions.append((current_func, rest)) current_func = None rest = [] if (',' in line): for func in line.split(','): func = func.strip() if func: functions.append((func, [])) elif line.strip(): current_func = line.strip() elif (current_func is not None): rest.append(line.strip()) if current_func: functions.append((current_func, rest)) return functions
'.. 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]] = strip_each_in(line[2].split(',')) return out
'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_empty_line() elif re.compile('^[\\w]+\n[-]+').match(summary_str): self['Summary'] = '' self._doc.reset() else: self['Summary'] = summary if (not self._is_at_section()): self['Extended Summary'] = self._read_to_next_section()
'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'): self.indent_char = line[0]
'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): continue if (token_type == tokenize.STRING): text = mute_string(text) if previous: (end_row, end) = previous[3] (start_row, start) = token[2] if (end_row != start_row): prev_text = self.lines[(end_row - 1)][(end - 1)] if ((prev_text == ',') or ((prev_text not in '{[(') and (text not in '}])'))): logical.append(' ') length += 1 elif (end != start): fill = self.lines[(end_row - 1)][end:start] logical.append(fill) length += len(fill) self.mapping.append((length, token)) logical.append(text) length += len(text) previous = token self.logical_line = ''.join(logical) self.noqa = (comments and noqa(''.join(comments)))
'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.logical_line[:80].rstrip() for (name, check, argument_names) in self._logical_checks: if (self.verbose >= 4): print (' ' + name) for result in (self.run_check(check, argument_names) or ()): (offset, text) = result if isinstance(offset, tuple): (orig_number, orig_offset) = offset else: orig_number = token0[2][0] orig_offset = (token0[2][1] + offset) for (token_offset, token) in self.mapping: if (offset >= token_offset): orig_number = token[2][0] orig_offset = ((token[2][1] + offset) - token_offset) self.report_error(orig_number, orig_offset, text, check) if self.logical_line: self.previous_indent_level = self.indent_level self.previous_logical = self.logical_line self.tokens = []
'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)]: self.check_physical((line + '\n')) self.line_number += 1 self.multiline = False
'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_lines_before_comment = 0 parens = 0 for token in self.generate_tokens(): self.tokens.append(token) (token_type, text) = token[0:2] if (self.verbose >= 3): if (token[2][0] == token[3][0]): pos = ('[%s:%s]' % ((token[2][1] or ''), token[3][1])) else: pos = ('l.%s' % token[3][0]) print ('l.%s DCTB %s DCTB %s DCTB %r' % (token[2][0], pos, tokenize.tok_name[token[0]], text)) if (token_type == tokenize.OP): if (text in '([{'): parens += 1 elif (text in '}])'): parens -= 1 elif (not parens): if (token_type == tokenize.NEWLINE): if (self.blank_lines < blank_lines_before_comment): self.blank_lines = blank_lines_before_comment self.check_logical() self.blank_lines = blank_lines_before_comment = 0 elif (token_type == tokenize.NL): if (len(self.tokens) == 1): self.blank_lines += 1 del self.tokens[0] else: self.check_logical() elif ((token_type == tokenize.COMMENT) and (len(self.tokens) == 1)): if (blank_lines_before_comment < self.blank_lines): blank_lines_before_comment = self.blank_lines self.blank_lines = 0 if COMMENT_WITH_NL: text = text.rstrip('\r\n') self.tokens = [((token_type, text) + token[2:])] self.check_logical() return self.report.get_file_results()
'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)): print self.filename self.file_errors += 1 self.total_errors += 1 return code
'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)): line = '' else: line = self.lines[(line_number - 1)] print line.rstrip() print ((' ' * offset) + '^') if (self._show_pep8 and doc): print doc.lstrip('\n').rstrip() return self.file_errors
'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 KeyboardInterrupt: print '... stopped' report.stop() return report
'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 ('directory ' + root) counters['directories'] += 1 for subdir in sorted(dirs): if self.excluded(subdir, root): dirs.remove(subdir) for filename in sorted(files): if (filename_match(filename, filepatterns) and (not self.excluded(filename, root))): runner(os.path.join(root, filename))
'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.options.exclude)
'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 whose values are Dataset objects.'
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 learning rate multiplier. Returns updates : OrderdDict A dictionary mapping from the old model parameters, to their new values after a single iteration of the learning rule. Notes e.g. for standard SGD, one would return `sgd_rule_updates` defined below. Note that such a `LearningRule` object is not implemented, as these updates are implemented by default when the `learning_rule` parameter of sgd.SGD.__init__ is None. .. code-block:: python sgd_rule_updates = OrderedDict() for (param, grad) in grads.iteritems(): sgd_rule_updates[k] = (param - learning_rate * lr_scalers.get(param, 1.) * grad)'
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_rate * lr_scalers.get(param, 1.0)) updates[vel] = ((self.momentum * vel) - (scaled_lr * grad)) inc = updates[vel] if self.nesterov_momentum: inc = ((self.momentum * inc) - (scaled_lr * grad)) assert (inc.dtype == vel.dtype) updates[param] = (param + inc) return updates
'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 be updated.'
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 be updated.'
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 that training algorithm.') momentum = algorithm.learning_rule.momentum if (not self._initialized): self._init_momentum = momentum.get_value() self._initialized = True momentum.set_value(np.cast[config.floatX](self.current_momentum()))
'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 return ((self._init_momentum * (1 - alpha)) + (alpha * self.final_momentum))
'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 = ('mean_square_dx_' + param.name) new_mean_squared_grad = ((self.decay * mean_square_grad) + ((1 - self.decay) * T.sqr(grads[param]))) epsilon = (lr_scalers.get(param, 1.0) * learning_rate) rms_dx_tm1 = T.sqrt((mean_square_dx + epsilon)) rms_grad_t = T.sqrt((new_mean_squared_grad + epsilon)) delta_x_t = (((- rms_dx_tm1) / rms_grad_t) * grads[param]) new_mean_square_dx = ((self.decay * mean_square_dx) + ((1 - self.decay) * T.sqr(delta_x_t))) updates[mean_square_grad] = new_mean_squared_grad updates[mean_square_dx] = new_mean_square_dx updates[param] = (param + delta_x_t) return updates
'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_scalers.get(param, 1.0) * learning_rate) scale = T.maximum(self.eps, T.sqrt(new_sum_squared_grad)) delta_x_t = (((- epsilon) / scale) * grads[param]) updates[sum_square_grad] = new_sum_squared_grad updates[param] = (param + delta_x_t) return updates
'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(), ''), dataset=monitoring_dataset) return
'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 model\'s parameters to a learning rate multiplier. Returns updates : OrderdDict A dictionary mapping from the old model parameters, to their new values after a single iteration of the learning rule. Notes This method has the side effect of storing the moving average of the square gradient in `self.mean_square_grads`. This is necessary in order for the monitoring channels to be able to track the value of these moving averages. Therefore, this method should only get called once for each instance of RMSProp.'
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.mean_square_grads): warnings.warn(('Calling get_updates more than once on the gradients of `%s` may make monitored values incorrect.' % param.name)) self.mean_square_grads[param.name] = mean_square_grad new_mean_squared_grad = ((self.decay * mean_square_grad) + ((1 - self.decay) * T.sqr(grads[param]))) scaled_lr = (lr_scalers.get(param, 1.0) * learning_rate) rms_grad_t = T.sqrt(new_mean_squared_grad) rms_grad_t = T.maximum(rms_grad_t, self.epsilon) delta_x_t = (((- scaled_lr) * grads[param]) / rms_grad_t) updates[mean_square_grad] = new_mean_squared_grad updates[param] = (param + delta_x_t) return updates
'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 the interface of models.model.Model. dataset : pylearn2.datasets.dataset.Dataset Dataset object used to draw training data'
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 compatible with stochastic costs and cannot determine whether the current cost is stochastic.') if (self.batch_size is None): self.batch_size = model.force_batch_size else: batch_size = self.batch_size if self.set_batch_size: model.set_batch_size(batch_size) elif hasattr(model, 'force_batch_size'): if (not ((model.force_batch_size is None) or (model.force_batch_size <= 0) or (batch_size == model.force_batch_size))): raise ValueError(('batch_size is %d but ' + ('model.force_batch_size is %d' % (batch_size, model.force_batch_size)))) self.monitor = Monitor.get_monitor(model) self.monitor.set_theano_function_mode(self.theano_function_mode) data_specs = self.cost.get_data_specs(model) mapping = DataSpecsMapping(data_specs) space_tuple = mapping.flatten(data_specs[0], return_tuple=True) source_tuple = mapping.flatten(data_specs[1], return_tuple=True) theano_args = [] for (space, source) in safe_zip(space_tuple, source_tuple): name = ('BGD_[%s]' % source) arg = space.make_theano_batch(name=name) theano_args.append(arg) theano_args = tuple(theano_args) nested_args = mapping.nest(theano_args) fixed_var_descr = self.cost.get_fixed_var_descr(model, nested_args) self.on_load_batch = fixed_var_descr.on_load_batch cost_value = self.cost.expr(model, nested_args, **fixed_var_descr.fixed_vars) (grads, grad_updates) = self.cost.get_gradients(model, nested_args, **fixed_var_descr.fixed_vars) assert isinstance(grads, OrderedDict) assert isinstance(grad_updates, OrderedDict) if (cost_value is None): raise ValueError(((('BGD is incompatible with ' + str(self.cost)) + ' because it is intractable, but BGD uses the ') + 'cost function value to do line searches.')) def capture(f, mapping=mapping): new_f = (lambda *args: f(mapping.flatten(args, return_tuple=True))) return new_f obj_prereqs = [capture(f) for f in fixed_var_descr.on_load_batch] if (self.monitoring_dataset is not None): 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, batch_size=self.monitoring_batch_size, num_batches=self.monitoring_batches, obj_prereqs=obj_prereqs, cost_monitoring_args=fixed_var_descr.fixed_vars) params = model.get_params() self.optimizer = BatchGradientDescent(objective=cost_value, gradients=grads, gradient_updates=grad_updates, params=params, param_constrainers=[model.modify_updates], lr_scalers=model.get_lr_scalers(), inputs=theano_args, verbose=self.verbose_optimization, max_iter=self.updates_per_batch, reset_alpha=self.reset_alpha, conjugate=self.conjugate, reset_conjugate=self.reset_conjugate, min_init_alpha=self.min_init_alpha, line_search_mode=self.line_search_mode, theano_function_mode=self.theano_function_mode, init_alpha=self.init_alpha) if (self.monitoring_dataset is not None): self.monitor.add_channel(name='ave_step_size', ipt=None, val=self.optimizer.ave_step_size, data_specs=(NullSpace(), ''), dataset=first_value(self.monitoring_dataset)) self.monitor.add_channel(name='ave_grad_size', ipt=None, val=self.optimizer.ave_grad_size, data_specs=(NullSpace(), ''), dataset=first_value(self.monitoring_dataset)) self.monitor.add_channel(name='ave_grad_mult', ipt=None, val=self.optimizer.ave_grad_mult, data_specs=(NullSpace(), ''), dataset=first_value(self.monitoring_dataset)) self.first = True self.bSetup = True
'.. 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_specs[0], return_tuple=True) source_tuple = mapping.flatten(data_specs[1], return_tuple=True) if (len(space_tuple) == 0): raise NotImplementedError(('Unable to train with BGD, because the cost does not actually use data from the data set. data_specs: %s' % str(data_specs))) flat_data_specs = (CompositeSpace(space_tuple), source_tuple) iterator = dataset.iterator(mode=train_iteration_mode, batch_size=self.batch_size, num_batches=self.batches_per_iter, data_specs=flat_data_specs, return_tuple=True, rng=rng) mode = self.theano_function_mode for data in iterator: if (('targets' in source_tuple) and (mode is not None) and hasattr(mode, 'record')): Y = data[source_tuple.index('targets')] stry = str(Y).replace('\n', ' ') mode.record.handle_line((('data Y ' + stry) + '\n')) for on_load_batch in self.on_load_batch: on_load_batch(mapping.nest(data)) self.before_step(model) self.optimizer.minimize(*data) self.after_step(model) actual_batch_size = flat_data_specs[0].np_batch_size(data) model.monitor.report_batch(actual_batch_size)
'.. 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) channel = monitor.channels[self.channel] v = channel.val_record if (len(v) == 1): return latest = v[(-1)] logger.info('Latest {0}: {1}'.format(self.channel, latest)) logger.info('Previous is {0}'.format(self.prev)) cur = algorithm.scale_step if (latest >= self.prev): logger.info("Looks like using {0} isn't working out so great for us.".format(cur)) cur *= self.scale if (cur < self.giveup_after): logger.info('Guess we just have to give up.') self.continue_learning = False cur = self.giveup_after logger.info("Let's see how {0} does.".format(cur)) elif ((latest <= self.prev) and (self.scale_up != 1.0)): logger.info("Looks like we're making progress on the validation set, let's try speeding up") cur *= self.scale_up if (cur > self.max_scale): cur = self.max_scale logger.info('New scale is {0}'.format(cur)) algorithm.scale_step = cur self.monitor_channel.set_value(np.cast[config.floatX](cur)) self.prev = latest
'.. 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 cur *= self.scale cur = max(cur, self.min_value) algorithm.scale_step = cur self.monitor_channel.set_value(np.cast[config.floatX](cur))
'.. 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.channel] v = channel.val_record if (len(v) == 1): return latest = v[(-1)] logger.info('Latest {0}: {1}'.format(self.channel, latest)) logger.info('Previous is {0}'.format(self.prev)) cur = algorithm.scale_step if (latest >= self.prev): logger.info("Looks like using {0} isn't working out so great for us.".format(cur)) cur *= self.scale if (cur < self.giveup_after): logger.info('Guess we just have to give up.') self.continue_learning = False cur = self.giveup_after logger.info("Let's see how {0} does.".format(cur)) logger.info('Reloading saved params from last call') for (p, v) in safe_zip(model.get_params(), self.stored_values): p.set_value(v) latest = self.prev elif ((latest <= self.prev) and (self.scale_up != 1.0)): logger.info("Looks like we're making progress on the validation set, let's try speeding up") cur *= self.scale_up if (cur > self.max_scale): cur = self.max_scale logger.info('New scale is {0}'.format(cur)) algorithm.scale_step = cur self.monitor_channel.set_value(np.cast[config.floatX](cur)) self.prev = latest self.stored_values = [param.get_value() for param in model.get_params()]
'.. 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, batch_size=self.monitoring_batch_size, num_batches=self.monitoring_batches, extra_costs=self.monitoring_costs, mode=self.monitor_iteration_mode) dataset_name = first_key(self.monitoring_dataset) monitoring_dataset = self.monitoring_dataset[dataset_name] self.monitor.add_channel(name='learning_rate', ipt=None, val=self.learning_rate, data_specs=(NullSpace(), ''), dataset=monitoring_dataset) if self.learning_rule: self.learning_rule.add_channels_to_monitor(self.monitor, monitoring_dataset)
'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()) for param in model.get_params()]): nan_params = [param for param in model.get_params() if contains_nan(param.get_value())] raise ValueError(('These params are NaN: ' + str(nan_params))) self.model = model self._synchronize_batch_size(model) model._test_batch_size = self.batch_size self.monitor = Monitor.get_monitor(model) self.monitor._sanity_check() has_force_batch_size = getattr(model, 'force_batch_size', False) train_dataset_is_uneven = ((dataset.get_num_examples() % self.batch_size) != 0) has_monitoring_datasets = bool(self.monitoring_dataset) if has_monitoring_datasets: monitoring_datasets_are_uneven = any((((d.get_num_examples() % self.batch_size) != 0) for d in self.monitoring_dataset.values())) else: monitoring_datasets_are_uneven = False if (has_force_batch_size and train_dataset_is_uneven and (not has_uniform_batch_size(self.train_iteration_mode))): raise ValueError('Dataset size is not a multiple of batch size.You should set train_iteration_mode (and maybe monitor_iteration_mode) to even_sequential, even_shuffled_sequential or even_batchwise_shuffled_sequential') if (has_force_batch_size and has_monitoring_datasets and monitoring_datasets_are_uneven and (not has_uniform_batch_size(self.monitor_iteration_mode))): raise ValueError('Dataset size is not a multiple of batch size.You should set monitor_iteration_mode to even_sequential, even_shuffled_sequential or even_batchwise_shuffled_sequential') data_specs = self.cost.get_data_specs(self.model) mapping = DataSpecsMapping(data_specs) space_tuple = mapping.flatten(data_specs[0], return_tuple=True) source_tuple = mapping.flatten(data_specs[1], return_tuple=True) theano_args = [] for (space, source) in safe_zip(space_tuple, source_tuple): name = ('%s[%s]' % (self.__class__.__name__, source)) arg = space.make_theano_batch(name=name, batch_size=self.batch_size) theano_args.append(arg) theano_args = tuple(theano_args) nested_args = mapping.nest(theano_args) fixed_var_descr = self.cost.get_fixed_var_descr(model, nested_args) self.on_load_batch = fixed_var_descr.on_load_batch cost_value = self.cost.expr(model, nested_args, **fixed_var_descr.fixed_vars) if ((cost_value is not None) and (cost_value.name is None)): cost_value.name = 'objective' learning_rate = self.learning_rate params = list(model.get_params()) assert (len(params) > 0) for (i, param) in enumerate(params): if (param.name is None): param.name = ('sgd_params[%d]' % i) (grads, updates) = self.cost.get_gradients(model, nested_args, **fixed_var_descr.fixed_vars) if (not isinstance(grads, OrderedDict)): raise TypeError((((((str(type(self.cost)) + '.get_gradients returned ') + 'something with') + str(type(grads))) + 'as its ') + 'first member. Expected OrderedDict.')) for param in grads: assert (param in params) for param in params: assert (param in grads) for param in grads: if ((grads[param].name is None) and (cost_value is not None)): grads[param].name = ('grad(%(costname)s, %(paramname)s)' % {'costname': cost_value.name, 'paramname': param.name}) assert (grads[param].dtype == param.dtype) lr_scalers = model.get_lr_scalers() for key in lr_scalers: if (key not in params): raise ValueError((('Tried to scale the learning rate on ' + str(key)) + ' which is not an optimization parameter.')) log.info('Parameter and initial learning rate summary:') for param in params: param_name = param.name if (param_name is None): param_name = 'anon_param' lr = (learning_rate.get_value() * lr_scalers.get(param, 1.0)) log.info((((' DCTB ' + param_name) + ': ') + str(lr))) if self.learning_rule: updates.update(self.learning_rule.get_updates(learning_rate, grads, lr_scalers)) else: updates.update(dict(safe_zip(params, [(param - ((learning_rate * lr_scalers.get(param, 1.0)) * grads[param])) for param in params]))) for param in params: if (updates[param].name is None): updates[param].name = (('sgd_update(' + param.name) + ')') model.modify_updates(updates) for param in params: update = updates[param] if (update.name is None): update.name = (('censor(sgd_update(' + param.name) + '))') for update_val in get_debug_values(update): if contains_inf(update_val): raise ValueError(('debug value of %s contains infs' % update.name)) if contains_nan(update_val): raise ValueError(('debug value of %s contains nans' % update.name)) self._setup_monitor() with log_timing(log, 'Compiling sgd_update'): self.sgd_update = function(theano_args, updates=updates, name='sgd_update', on_unused_input='ignore', mode=self.theano_function_mode) self.params = params
'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 rng = self.rng if (not is_stochastic(self.train_iteration_mode)): rng = None data_specs = self.cost.get_data_specs(self.model) mapping = DataSpecsMapping(data_specs) space_tuple = mapping.flatten(data_specs[0], return_tuple=True) source_tuple = mapping.flatten(data_specs[1], return_tuple=True) if (len(space_tuple) == 0): raise NotImplementedError(('Unable to train with SGD, because the cost does not actually use data from the data set. data_specs: %s' % str(data_specs))) flat_data_specs = (CompositeSpace(space_tuple), source_tuple) iterator = dataset.iterator(mode=self.train_iteration_mode, batch_size=self.batch_size, data_specs=flat_data_specs, return_tuple=True, rng=rng, num_batches=self.batches_per_iter) on_load_batch = self.on_load_batch for batch in iterator: for callback in on_load_batch: callback(*batch) self.sgd_update(*batch) actual_batch_size = flat_data_specs[0].np_batch_size(batch) self.monitor.report_batch(actual_batch_size) for callback in self.update_callbacks: callback(self) for param in self.params: value = param.get_value(borrow=True) if (not isfinite(value)): raise RuntimeError(('NaN in ' + param.name))
'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_channel_specified = False channels = [elem for elem in monitor.channels if elem.endswith('objective')] if (len(channels) < 1): raise ValueError('There are no monitoring channels that end with "objective". Please specify either channel_name or dataset_name.') elif (len(channels) > 1): datasets = algorithm.monitoring_dataset.keys() raise ValueError((('There are multiple monitoring channels thatend with "_objective". The list of available datasets are: ' + str(datasets)) + ' . Please specify either channel_name or dataset_name in the MonitorBasedLRAdjuster constructor to disambiguate.')) else: self.channel_name = channels[0] warnings.warn((('The channel that has been chosen for monitoring is: ' + str(self.channel_name)) + '.')) try: v = monitor.channels[self.channel_name].val_record except KeyError: err_input = '' if monitor_channel_specified: if self.dataset_name: err_input = (("The dataset_name '" + str(self.dataset_name)) + "' is not valid.") else: err_input = (("The channel_name '" + str(self.channel_name)) + "' is not valid.") err_message = (((((("There is no monitoring channel named '" + str(self.channel_name)) + "'. You probably need to ") + 'specify a valid monitoring channel by using either ') + 'dataset_name or channel_name in the ') + 'MonitorBasedLRAdjuster constructor. ') + err_input) reraise_as(ValueError(err_message)) if (len(v) < 1): if (monitor.dataset is None): assert (len(v) == 0) raise ValueError("You're trying to use a monitor-based learning rate adjustor but the monitor has no entries because you didn't specify a monitoring dataset.") raise ValueError('For some reason there are no monitor entriesyet the MonitorBasedLRAdjuster has been called. This should never happen. The Train object should call the monitor once on initialization, then call the callbacks. It seems you are either calling the callback manually rather than as part of a training algorithm, or there is a problem with the Train object.') if (len(v) == 1): return rval = current_learning_rate log.info('monitoring channel is {0}'.format(self.channel_name)) if (v[(-1)] > (self.high_trigger * v[(-2)])): rval *= self.shrink_amt log.info(('shrinking learning rate to %f' % rval)) elif (v[(-1)] > (self.low_trigger * v[(-2)])): rval *= self.grow_amt log.info(('growing learning rate to %f' % rval)) rval = max(self.min_lr, rval) rval = min(self.max_lr, rval) lr.set_value(np.cast[lr.dtype](rval))
'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 be extracted. Returns bool True or False, indicating if the optimization should stop or not.'
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[self._channel_name].val_record if (v[(-1)] < (self.best_value * (1.0 - self.prop_decrease))): self.patience = max(self.patience, (len(v) * self.patience_increase)) self.best_value = v[(-1)] return (len(v) < self.patience)
'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 else: new_lr = self.min_lr new_lr = np.cast[config.floatX](new_lr) algorithm.learning_rate.set_value(new_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 = (self._base_lr - (self._step * ((self._count - self.start) + 1))) else: new_lr = (self._base_lr * self.decay_factor) else: new_lr = self._base_lr assert (new_lr > 0) new_lr = np.cast[config.floatX](new_lr) algorithm.learning_rate.set_value(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 self._count += 1 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): 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 updated.'
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 is not None) and (self._count > self.start) and ((self._count % self.save_freq) == 0)): saved_params = OrderedDict() for param in model.get_params(): saved_params[param] = param.get_value() param.set_value(self._worker.param_to_mean[param].get_value()) serial.save(self.save_path, model) for param in model.get_params(): param.set_value(saved_params[param]) self._count += 1
'.. 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 place to compile theano functions for doing learning.'
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) value = monitoring_dataset[key] if (not isinstance(value, Dataset)): raise TypeError(((('Monitoring dataset with name ' + key) + ' is not a dataset, it is a ') + str(type(value)))) self.monitoring_dataset = monitoring_dataset
'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.set_batch_size(batch_size) else: raise ValueError(((('batch_size argument to ' + str(type(self))) + "conflicts with model's ") + 'force_batch_size attribute')) else: self.batch_size = model.force_batch_size if (self.batch_size is None): raise NoBatchSizeError()
'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 interface of models.model.Model. dataset : pylearn2.datasets.dataset.Dataset Dataset object used to draw training data'
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_tuple=True) source_tuple = mapping.flatten(source, return_tuple=True) ipt = tuple((sp.make_theano_batch(name=('monitor_%s' % src)) for (sp, src) in safe_zip(space_tuple, source_tuple))) nested_ipt = mapping.nest(ipt) channels = model.get_monitoring_channels(nested_ipt) if (not isinstance(channels, dict)): raise TypeError(('model.get_monitoring_channels must return a dictionary, but it returned ' + str(channels))) for dataset_name in self.monitoring_dataset: if (dataset_name == ''): prefix = '' else: prefix = (dataset_name + '_') monitoring_dataset = self.monitoring_dataset[dataset_name] if ((self.monitoring_batch_size is None) and (self.monitoring_batches == (-1))): self.monitoring_batch_size = self.batch_size self.monitoring_batches = self.batches_per_iter self.monitor.add_dataset(dataset=monitoring_dataset, mode='sequential', batch_size=self.monitoring_batch_size, num_batches=self.monitoring_batches) for name in channels: J = channels[name] if isinstance(J, tuple): assert (len(J) == 2) (J, prereqs) = J else: prereqs = None self.monitor.add_channel(name=(prefix + name), ipt=nested_ipt, val=J, dataset=monitoring_dataset, prereqs=prereqs, data_specs=(space, source)) self.first = True self.bSetup = True
'.. 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))