desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'.. todo:: WRITEME'
def print_status(self):
raise NotImplementedError('TODO fix broken method')
'.. todo:: WRITEME'
def rmul(self, x):
assert (x.ndim == 5) return self._filter_acts(x, self._filters)
'.. todo:: WRITEME'
def rmul_T(self, x):
return self._img_acts(self._filters, x, self._irows, self._icols)
'.. todo:: WRITEME'
def col_shape(self):
ishape = (self.row_shape() + ((-99),)) fshape = self._filters_shape (hshape,) = self._filter_acts.infer_shape(None, (ishape, fshape)) assert (hshape[(-1)] == (-99)) return hshape[:(-1)]
'.. todo:: WRITEME'
def row_shape(self):
fshape = self._filters_shape (fmodulesR, fmodulesC, fcolors, frows, fcols) = fshape[:(-2)] (fgroups, filters_per_group) = fshape[(-2):] return (fgroups, fcolors, self._irows, self._icols)
'.. todo:: WRITEME'
def print_status(self):
raise NotImplementedError('TODO: fix dependence on non-existent ndarray_status function') "print ndarray_status(\n self._filters.get_value(borrow=True),\n msg='%s{%s...
'.. todo:: WRITEME'
def imshow_gray(self):
filters = self._filters.get_value() (modR, modC, colors, rows, cols, grps, fs_per_grp) = filters.shape logger.info(filters.shape) rval = np.zeros((((modR * (rows + 1)) - 1), ((modC * (cols + 1)) - 1))) for (rr, modr) in enumerate(xrange(0, rval.shape[0], (rows + 1))): for (cc, modc) in enume...
'.. todo:: WRITEME'
def _attributes(self):
return (self.module_stride, self.partial_sum)
'.. todo:: WRITEME'
def __eq__(self, other):
return ((type(self) == type(other)) and (self._attributes() == other._attributes()))
'.. todo:: WRITEME'
def __hash__(self):
return hash((type(self), self._attributes()))
'.. todo:: WRITEME'
def __str__(self):
return ('%s{module_stride=%i,partial_sum=%i}' % (self.__class__.__name__, self.module_stride, self.partial_sum))
'.. todo:: WRITEME'
def make_node(self, images, filters):
ibcast = images.broadcastable fbcast = filters.broadcastable (igroups, icolors_per_group, irows, icols, icount) = ibcast (fmodulesR, fmodulesC, fcolors, frows, fcols) = fbcast[:(-2)] (fgroups, filters_per_group) = fbcast[(-2):] hbcast = (fgroups, filters_per_group, fmodulesR, fmodulesC, icount) ...
'.. todo:: WRITEME'
def c_support_code(self):
cufile = open(os.path.join(_this_dir, 'filter_acts.cu')) return cufile.read()
'.. todo:: WRITEME'
def c_code_cache_version(self):
return ()
'.. todo:: WRITEME'
def c_code(self, node, nodename, inputs, outputs, sub):
(images, filters) = inputs (responses,) = outputs fail = sub['fail'] moduleStride = str(self.module_stride) sio = StringIO.StringIO() print('\n\n //XXX: actually the rightmost images dimension can be strided\n ...
'.. todo:: WRITEME'
def make_node(self, images, hidacts, frows, fcols):
if (self.partial_sum != 1): raise NotImplementedError('partial sum') frows = theano.tensor.as_tensor_variable(frows) fcols = theano.tensor.as_tensor_variable(fcols) if (frows.dtype[:3] not in ('int', 'uin')): raise TypeError(frows) if (fcols.dtype[:3] not in ('int', 'uin')): ...
'.. todo:: WRITEME'
def c_support_code(self):
cufile = open(os.path.join(_this_dir, 'weight_acts.cu')) return cufile.read()
'.. todo:: WRITEME'
def c_code_cache_version(self):
return ()
'.. todo:: WRITEME'
def c_code(self, node, nodename, inames, onames, sub):
(images, hidacts, frows, fcols) = inames (dweights,) = onames fail = sub['fail'] moduleStride = str(self.module_stride) sio = StringIO.StringIO() print('\n\n if (!CudaNdarray_is_c_contiguous(%(images)s))\n {\n ...
'.. todo:: WRITEME'
def make_node(self, filters, hidacts, irows, icols):
irows = theano.tensor.as_tensor_variable(irows) icols = theano.tensor.as_tensor_variable(icols) if (irows.dtype[:3] not in ('int', 'uin')): raise TypeError(irows) if (icols.dtype[:3] not in ('int', 'uin')): raise TypeError(irows) if irows.ndim: raise TypeError('irows shoul...
'.. todo:: WRITEME'
def c_support_code(self):
cufile = open(os.path.join(_this_dir, 'raw_img_acts.cu')) return cufile.read()
'.. todo:: WRITEME'
def c_code_cache_version(self):
return ()
'.. todo:: WRITEME'
def c_code(self, node, nodename, inames, onames, sub):
(filters, hidacts, irows, icols) = inames (dimages,) = onames fail = sub['fail'] moduleStride = str(self.module_stride) sio = StringIO.StringIO() print('\n\n if (!CudaNdarray_is_c_contiguous(%(filters)s))\n {\n ...
'.. todo:: WRITEME'
@staticmethod def row_col_channel(row, col, channel, n_rows, n_cols, n_channels):
return ((((row * n_cols) * n_channels) + (col * n_channels)) + channel)
'.. todo:: WRITEME'
@staticmethod def channel_row_col(row, col, channel, n_rows, n_cols, n_channels):
return ((((channel * n_rows) * n_cols) + (row * n_cols)) + col)
'.. todo:: WRITEME'
def make_node(self, x):
return gof.Apply(self, [x], [x.type()])
'.. todo:: WRITEME'
def perform(self, node, xs, zs):
x = xs[0] z = zs[0] if (x.format != 'csc'): raise TypeError('Remove0 only works on csc matrices') (M, N) = x.shape data = x.data indices = x.indices indptr = x.indptr new_data = [] new_indices = [] new_indptr = [0] for j in xrange(0, N): for i_i...
'.. todo:: WRITEME'
def grad(self, x, gz):
return [gz[0]]
'.. todo:: WRITEME'
def make_node(self, x):
return gof.Apply(self, [x], [x.type()])
'.. todo:: WRITEME'
def perform(self, node, xs, zs):
zs[0][0] = xs[0].ensure_sorted_indices(inplace=self.inplace)
'.. todo:: WRITEME'
def grad(self, xs, gz):
return [gz[0]]
'.. todo:: WRITEME'
@staticmethod def sparse_eval(inshp, kshp, nkern, offset=(1, 1), mode='valid'):
return convolution_indices.evaluate(inshp, kshp, offset, nkern, mode=mode, ws=False)
'.. todo:: WRITEME'
@staticmethod def conv_eval(IR, IC, KR, KC, C, subsample=(1, 1), mode='valid'):
raise NotImplementedError('TODO: fix broken method')
'Build a sparse matrix which can be used for performing... * convolution: in this case, the dot product of this matrix with the input images will generate a stack of images patches. Convolution is then a tensordot operation of the filters and the patch stack. * sparse local connections: in this case, the sparse matrix ...
@staticmethod def evaluate(imshp, kshp, offset=(1, 1), nkern=1, mode='valid', ws=True):
N = numpy (dx, dy) = offset if (N.size(imshp) == 2): inshp = ((1,) + imshp) inshp = N.array(imshp) kshp = N.array(kshp) ksize = N.prod(kshp) kern = ((ksize - 1) - N.arange(ksize)) fulloutshp = ((inshp[1:] + kshp) - 1) s = ((-1) if (mode == 'valid') else 1) outshp = N.int6...
'.. todo:: WRITEME'
def perform(self, node, shape, out):
(inshp, kshp) = shape (out_indices, out_indptr, spmat_shape) = out (indices, indptr, spmatshp, outshp) = self.evaluate(inshp, kshp) out_indices[0] = indices out_indptr[0] = indptr spmat_shape[0] = numpy.asarray(spmatshp)
'Computes a nested data_specs for input and all channels Also computes the mapping to flatten it. This function is called from redo_theano.'
def _build_data_specs(self):
(m_space, m_source) = self.model.get_monitoring_data_specs() input_spaces = [m_space] input_sources = [m_source] for channel in self.channels.values(): space = channel.data_specs[0] assert isinstance(space, Space) input_spaces.append(space) input_sources.append(channel.da...
'.. todo:: WRITEME Parameters mode : theano.compile.Mode Theano functions for the monitoring channels will be compiled and run using this mode.'
def set_theano_function_mode(self, mode):
if (self.theano_function_mode != mode): self._dirty = True self.theano_function_mode = mode
'Determines the data used to calculate the values of each channel. Parameters dataset : object A `pylearn2.datasets.Dataset` object. mode : str or object, optional Iteration mode; see the docstring of the `iterator` method on `pylearn2.datasets.Dataset` for details. batch_size : int, optional The size of an individual ...
def add_dataset(self, dataset, mode='sequential', batch_size=None, num_batches=None, seed=None):
if (not isinstance(dataset, list)): dataset = [dataset] if (not isinstance(mode, list)): mode = [mode] if (not isinstance(batch_size, list)): batch_size = [batch_size] if (not isinstance(num_batches, list)): num_batches = [num_batches] if (seed is None): seed ...
'Runs the model on the monitoring dataset in order to add one data point to each of the channels.'
def __call__(self):
if self._dirty: self.redo_theano() datasets = self._datasets self.begin_record_entry() for (d, i, b, n, a, sd, ne) in safe_izip(datasets, self._iteration_mode, self._batch_size, self._num_batches, self.accum, self._rng_seed, self.num_examples): if isinstance(d, six.string_types): ...
'Runs all "prerequistie functions" on a batch of data. Always called right before computing the monitoring channels on that batch. Parameters data : tuple or Variable a member of the Space used as input to the monitoring functions dataset : Dataset the Dataset the data was drawn from'
def run_prereqs(self, data, dataset):
if (dataset not in self.prereqs): return for prereq in self.prereqs[dataset]: prereq(*data)
'Returns the number of batches the model has learned on (assuming that the learning code has been calling Monitor.report_batch correctly).'
def get_batches_seen(self):
return self._num_batches_seen
'.. todo:: WRITEME Returns epochs_seen : int The number of epochs the model has been trained on. One "epoch" is one pass through Dataset.iterator.'
def get_epochs_seen(self):
return self._epochs_seen
'.. todo:: WRITEME Returns examples_seen : int The number of examples the model has learned on (assuming that the learning code has been calling Monitor.report_batch correctly)'
def get_examples_seen(self):
return self._examples_seen
'Call this whenever the model has learned on another batch of examples. Report how many examples were learned on. Parameters num_examples : int The number of examples learned on in this minibatch.'
def report_batch(self, num_examples):
self._examples_seen += num_examples self._num_batches_seen += 1
'Call this whenever the model has completed another "epoch" of learning. We regard one pass through Dataset.iterator as one epoch.'
def report_epoch(self):
self._epochs_seen += 1
'Recompiles Theano functions used by this monitor. This is called any time we need to evaluate the channels and the channel definitions have changed since last we called it, or if the theano functions are unavailable for any other reason (first time they are needed after construction or deserialization, etc.) All chann...
def redo_theano(self):
self._dirty = False self._build_data_specs() init_names = dir(self) self.prereqs = OrderedDict() for channel in self.channels.values(): if (channel.prereqs is not None): dataset = channel.dataset if (dataset not in self.prereqs): self.prereqs[dataset] ...
'Register names of fields that should be deleted before pickling. Parameters names : list A list of attribute names as strings.'
def register_names_to_del(self, names):
for name in names: if (name not in self.names_to_del): self.names_to_del.append(name)
'In order to avoid pickling a copy of the dataset whenever a monitor is saved, the __getstate__ method replaces the dataset field with the dataset\'s yaml source. This is not a perfect solution because it won\'t work with job resuming, which would require saving the state of the dataset\'s random number generator. Like...
def __getstate__(self):
if (not hasattr(self, '_datasets')): self._datasets = [self._dataset] del self._dataset temp = self._datasets if self._datasets: self._datasets = [] for dataset in temp: if isinstance(dataset, six.string_types): self._datasets.append(dataset) ...
'Sets the object to have the state described by `d`. Parameters d : dict A dictionary mapping string names of fields to values for these fields.'
def __setstate__(self, d):
if ('_dataset' in d): d['_datasets'] = [d['_dataset']] del d['_dataset'] self.__dict__.update(d)
'Asks the monitor to start tracking a new value. Can be called even after the monitor is already in use. Parameters name : str The display name in the monitor. ipt : tensor_like The symbolic tensor which should be clamped to the data. (or a list/tuple containing symbolic tensors, following the data_specs) val : tensor...
def add_channel(self, name, ipt, val, dataset=None, prereqs=None, data_specs=None):
if six.PY3: numeric = (float, int) else: numeric = (float, int, long) if isinstance(val, numeric): val = np.cast[theano.config.floatX](val) val = T.as_tensor_variable(val) if (data_specs is None): warnings.warn(("parameter 'data_specs' should be provided ...
'Sometimes we serialize models and then load them somewhere else but still try to use their Monitor, and the Monitor is in a mangled state. I\'ve added some calls to _sanity_check to try to catch when that happens. Not sure what to do for a long term fix. I think it requires making theano graphs serializable first.'
def _sanity_check(self):
for name in self.channels: channel = self.channels[name] assert hasattr(channel, 'prereqs')
'Returns a model\'s monitor. If the model doesn\'t have a monitor yet, installs one and returns that. Parameters model : object An object that implements the `Model` interface specified in `pylearn2.models`.'
@classmethod def get_monitor(cls, model):
if hasattr(model, 'monitor'): rval = model.monitor rval._sanity_check() else: rval = Monitor(model) model.monitor = rval return rval
'.. todo:: WRITEME Returns batch_size : int The size of the batches used for monitoring'
@property def batch_size(self):
return self._batch_size
'.. todo:: WRITEME Returns num_batches : int The number of batches used for monitoring'
@property def num_batches(self):
return self._num_batches
'Sets up the monitor for a cost minimization problem. Adds channels defined by both the model and the cost for the specified dataset(s), as well as a channel called \'objective\' defined by the costs\' __call__ method. Parameters dataset : pylearn2.datasets.Dataset Dataset or dictionary mapping string names to Datasets...
def setup(self, dataset, cost, batch_size, num_batches=None, extra_costs=None, mode='sequential', obj_prereqs=None, cost_monitoring_args=None):
if (dataset is None): return if isinstance(dataset, Dataset): dataset = {'': dataset} else: assert isinstance(dataset, dict) assert all((isinstance(key, str) for key in dataset)) assert all((isinstance(dataset[key], Dataset) for key in dataset)) if (extra_costs is...
'.. todo:: WRITEME Returns s : str A reasonably human-readable string representation of the object.'
def __str__(self):
try: graph_input_str = str(self.graph_input) except Exception: graph_input_str = '<bad graph input>' try: val_str = str(self.val) except Exception: val_str = '<bad val>' try: name_str = str(self.name) except Exception: name_str = '<bad ...
'.. todo:: WRITEME Returns d : dict A dictionary mapping the string names of the fields of the class to values appropriate for pickling.'
def __getstate__(self):
if hasattr(self, 'val'): doc = get_monitor_doc(self.val) elif hasattr(self, 'doc'): doc = self.doc else: doc = None return {'doc': doc, 'example_record': self.example_record, 'batch_record': self.batch_record, 'time_record': self.time_record, 'epoch_record': self.epoch_record, 'v...
'Sets the object to have the state described by `d`. Parameters d : dict A dictionary mapping string names of fields to values for these fields.'
def __setstate__(self, d):
self.__dict__.update(d) if ('batch_record' not in d): self.batch_record = ([None] * len(self.val_record)) if ('epoch_record' not in d): self.epoch_record = range(len(self.val_record)) if ('time_record' not in d): self.time_record = ([None] * len(self.val_record))
'Set the inverse temperature parameters of the AIS procedure. Parameters betas : numpy.ndarray, optional Vector of temperatures specifying interpolating distributions key_betas : numpy.ndarray, optional If specified (not None), specifies specific temperatures at which we want to compute the AIS estimate. AIS.run will t...
def set_betas(self, betas=None, key_betas=None):
self.key_betas = (None if (key_betas is None) else numpy.sort(key_betas)) betas = (numpy.array(betas, dtype=config.floatX) if (betas is not None) else self.dflt_beta) if (key_betas is not None): betas = numpy.hstack((betas, key_betas)) betas.sort() self.betas = betas
'Performs the grunt-work, implementing .. math:: log\:w^{(i)} += \mathcal{F}_{k-1}(v_{k-1}) - \mathcal{F}_{k}(v_{k-1}) recursively for all temperatures. Parameters n_steps : int, optional WRITEME'
def run(self, n_steps=1):
if (not hasattr(self, 'betas')): self.set_betas() self.std_ais_w = [] self.logz_beta = [] self.var_logz_beta = [] state = self.v_sample0 ki = 0 for i in range((len(self.betas) - 1)): (bp, bp1) = (self.betas[i], self.betas[(i + 1)]) self.log_ais_w += (self.free_energy_...
'Once run() method has been called, estimates the mean and variance of log(Zb/Za). Parameters log_ais_w : None or 1D numpy.ndarray optional override for log_ais_w. When None, estimates log(Zb/Za) using the log AIS weights computed by AIS.run() method. Returns f : float Estimated mean of log(Zb/Za), log-ratio of partiti...
def estimate_from_weights(self, log_ais_w=None):
log_ais_w = (self.log_ais_w if (log_ais_w is None) else log_ais_w) dlogz = self.log_mean(log_ais_w) m = numpy.max(log_ais_w) var_dlogz = (((log_ais_w.shape[0] * numpy.sum(numpy.exp((2 * (log_ais_w - m))))) / (numpy.sum(numpy.exp((log_ais_w - m))) ** 2)) - 1.0) return (dlogz, var_dlogz)
'Looks whether the model performs better than earlier. If it\'s the case, records the model\'s parameters. Parameters model : pylearn2.models.model.Model Not used dataset : pylearn2.datasets.dataset.Dataset Not used algorithm : TrainingAlgorithm Not used'
def on_monitor(self, model, dataset, algorithm):
if self.supervised: it = self.dataset.iterator('sequential', batch_size=self.batch_size, targets=True) new_cost = numpy.mean([self.cost_function(minibatch, target) for (minibatch, target) in it]) else: it = self.dataset.iterator('sequential', batch_size=self.batch_size, targets=False) ...
'Returns the best parameters up to now for the model.'
def get_best_params(self):
return self.best_params
'Sets some model tag entries. Parameters model : pylearn2.models.model.Model dataset : pylearn2.datasets.dataset.Dataset Not used algorithm : TrainingAlgorithm Not used'
def setup(self, model, dataset, algorithm):
if (self._tag_key in model.tag): log.warning('Model tag key "%s" already found. This may indicate multiple instances of %s trying to use the same tag entry.', self._tag_key, self.__class__.__name__) log.warning('If this is the case...
'Looks whether the model performs better than earlier. If it\'s the case, saves the model. Parameters model : pylearn2.models.model.Model model.monitor must contain a channel with name given by self.channel_name dataset : pylearn2.datasets.dataset.Dataset Not used algorithm : TrainingAlgorithm Not used'
def on_monitor(self, model, dataset, algorithm):
monitor = model.monitor channels = monitor.channels channel = channels[self.channel_name] val_record = channel.val_record new_cost = val_record[(-1)] if (((self.coeff * new_cost) < (self.coeff * self.best_cost)) and (monitor._epochs_seen >= self.start_epoch)): self.best_cost = new_cost ...
'Update `model.tag` with information about the current best. Parameters model : pylearn2.models.model.Model The model to update.'
def _update_tag(self, model):
model.tag[self._tag_key]['best_cost'] = self.best_cost
'Method that instantiates a response message for a given request message. It is not necessary to implement this function on response messages.'
def get_response(self):
raise NotImplementedError('get_response is not implemented.')
''
def __init__(self, address='127.0.0.1', req_port=5555):
if (not zmq_available): raise ImportError('zeromq needs to be installed to use this module.') self.address = ('tcp://%s' % address) assert (req_port > 0) self.req_port = req_port self.context = zmq.Context() self.req_sock = self.context.socket(zmq.REQ) self.re...
'Returns a list of the channels being monitored.'
def list_channels(self):
self.req_sock.send_pyobj(ChannelListRequest()) return self.req_sock.recv_pyobj()
'Retrieves data for a specified set of channels and combines that data with any previously retrived data. This assumes all the channels have the same number of values. It is unclear as to whether this is a reasonable assumption. If they do not have the same number of values then it may request to much or too little dat...
def update_channels(self, channel_list, start=(-1), end=(-1), step=1):
assert (((start == (-1)) and (end == (-1))) or (end > start)) if (start == (-1)): start = 0 if (len(self.channels.keys()) > 0): channel_name = list(self.channels.keys())[0] start = len(self.channels[channel_name].epoch_record) self.req_sock.send_pyobj(ChannelsRequest(...
'Tracks and plots a specified set of channels in real time. Parameters channel_list : list A list of the channels for which data has been requested.'
def follow_channels(self, channel_list):
if (not pyplot_available): raise ImportError('pyplot needs to be installed for this functionality.') plt.clf() plt.ion() while True: self.update_channels(channel_list) plt.clf() for channel_name in self.channels: plt.plot(self.channels[cha...
'Add WMAPE Numerator channels for monitoring dataset(s) to model.monitor. Parameters model : object The model being trained. dataset : object Training dataset. algorithm : object Training algorithm.'
def setup(self, model, dataset, algorithm):
(m_space, m_source) = model.get_monitoring_data_specs() (state, target) = m_space.make_theano_batch() y = target[:, 0] y_hat = model.fprop(state)[:, 0] wmape_numerator = abs((y - y_hat)).sum() wmape_numerator = T.cast(wmape_numerator, config.floatX) for (dataset_name, dataset) in algorithm.m...
'Add WMAPE Denominator channels for monitoring dataset(s) to model.monitor. Parameters model : object The model being trained. dataset : object Training dataset. algorithm : object Training algorithm.'
def setup(self, model, dataset, algorithm):
(m_space, m_source) = model.get_monitoring_data_specs() (state, target) = m_space.make_theano_batch() y = target[:, 0] wmape_denominator = abs(y).sum() wmape_denominator = T.cast(wmape_denominator, config.floatX) for (dataset_name, dataset) in algorithm.monitoring_dataset.items(): if dat...
'Calculate ROC AUC score. Parameters y_true : tensor_like Target class labels. y_score : tensor_like Predicted class labels or probabilities for positive class.'
def make_node(self, y_true, y_score):
y_true = T.as_tensor_variable(y_true) y_score = T.as_tensor_variable(y_score) output = [T.scalar(name=self.name, dtype=config.floatX)] return gof.Apply(self, [y_true, y_score], output)
'Calculate ROC AUC score. Parameters node : Apply instance Symbolic inputs and outputs. inputs : list Sequence of inputs. output_storage : list List of mutable 1-element lists.'
def perform(self, node, inputs, output_storage):
if (roc_auc_score is None): raise RuntimeError('Could not import from sklearn.') (y_true, y_score) = inputs try: roc_auc = roc_auc_score(y_true, y_score) except ValueError: roc_auc = np.nan output_storage[0][0] = theano._asarray(roc_auc, dtype=config.floatX)
'Add ROC AUC channels for monitoring dataset(s) to model.monitor. Parameters model : object The model being trained. dataset : object Training dataset. algorithm : object Training algorithm.'
def setup(self, model, dataset, algorithm):
(m_space, m_source) = model.get_monitoring_data_specs() (state, target) = m_space.make_theano_batch() y = T.argmax(target, axis=1) y_hat = model.fprop(state)[:, self.positive_class_index] if (self.negative_class_index is None): y = T.eq(y, self.positive_class_index) else: pos = T...
'.. todo:: WRITEME Notes `dataset` argument is ignored'
def setup(self, model, dataset, algorithm):
dataset = None preprocessor = CentralWindow(self._window_shape) for data in self._center: preprocessor.apply(data) randomize_now = (self._randomize + self._randomize_once) self._original = dict(((data, _zero_pad(data.get_topological_view().astype('float32'), self._pad_randomized)) for data i...
'Applies random translations and flips to the selected datasets. Parameters datasets : WRITEME'
def randomize_datasets(self, datasets):
for dataset in datasets: if (tuple(dataset.view_converter.axes) == ('c', 0, 1, 'b')): wf_func = random_window_and_flip_c01b elif (tuple(dataset.view_converter.axes) == ('b', 0, 1, 'c')): wf_func = random_window_and_flip_b01c else: raise ValueError(('Axes ...
'.. todo:: WRITEME Notes All arguments are ignored.'
def on_monitor(self, model, dataset, algorithm):
model = None dataset = None algorithm = None self.randomize_datasets(self._randomize)
'Setup the plotters. Parameters model : pylearn2.models.Model The model trained dataset : pylearn2.datasets.Dataset The dataset on which the model is trained algorithm : pylearn2.training_algorithms.TrainingAlgorithm The algorithm the model is trained with'
def setup(self, model, dataset, algorithm):
raise NotImplementedError((str(type(self)) + ' does not implement setup.'))
'The method that draw and save the desired figure, which depend on the object and its attribute. This method is called by the PlotManager object as frequently as the `freq` attribute defines it.'
def plot(self):
raise NotImplementedError((str(type(self)) + ' does not implement plot.'))
'Make the produced files readable by everyone. Parameters public : bool If public is True, then the associated files are readable by everyone.'
def set_permissions(self, public):
if public: for filename in self.filenames: make_readable(filename)
'.. todo:: WRITEME'
def score(self, X):
assert (X.dtype.find('int') == (-1)) X_name = ('X' if (X.name is None) else X.name) E = self.free_energy(X) assert (len(E.type.broadcastable) == 1) dummy = T.sum(E) rval = T.grad(dummy, X) rval.name = (('score(' + X_name) + ')') return rval
'.. todo:: WRITEME'
def free_energy(self, X):
raise NotImplementedError((str(type(self)) + ' has not implemented free_energy(self,X)'))
'.. todo:: WRITEME'
def energy(self, varlist):
raise NotImplementedError((str(type(self)) + ' has not implemented energy(self,varlist)'))
'.. todo:: WRITEME'
def __call__(self, varlist):
return self.energy(varlist)
'.. todo:: WRITEME'
def supports_vector_sigma(self):
raise NotImplementedError()
'.. todo:: WRITEME'
def log_P_H_given_V(self, H, V):
p_one = self.mean_H_given_V(V) rval = T.log(((H * p_one) + ((1.0 - H) * (1.0 - p_one)))).sum(axis=1) return rval
'.. todo:: WRITEME'
def mean_H_given_V(self, V):
raise NotImplementedError()
'.. todo:: WRITEME'
@classmethod def supports_vector_sigma(cls):
return False
'.. todo:: WRITEME'
def energy(self, varlist):
(V, H) = varlist return ((- (((T.dot(V, self.bias_vis) + (self.transformer.lmul(V) * H).sum(axis=1)) + T.dot(H, self.bias_hid)) - (0.5 * T.sqr(V).sum(axis=1)))) / T.sqr(self.sigma))
'.. todo:: WRITEME'
def mean_H_given_V(self, V):
V_name = 'V' if (hasattr(V, 'name') and (V.name is not None)): V_name = V.name rval = T.nnet.sigmoid(((self.bias_hid + self.transformer.lmul(V)) / T.sqr(self.sigma))) rval.name = ('mean_H_given_V( %s )' % V_name) return rval
'.. todo:: WRITEME'
def reconstruct(self, V):
H = self.mean_H_given_V(V) R = self.mean_V_given_H(H) return R
'.. todo:: WRITEME'
def mean_V_given_H(self, H):
H_name = 'H' if (hasattr(H, 'name') and (H.name is not None)): H_name = H.name transpose = self.transformer.lmul_T(H) transpose.name = 'transpose' rval = (self.bias_vis + transpose) rval.name = ('mean_V_given_H(%s)' % H_name) return rval
'.. todo:: WRITEME'
def free_energy(self, V):
V_name = ('V' if (V.name is None) else V.name) assert (V.ndim == 2) bias_term = T.dot(V, self.bias_vis) bias_term.name = 'bias_term' assert (len(bias_term.type.broadcastable) == 1) sq_term = (0.5 * T.sqr(V).sum(axis=1)) sq_term.name = 'sq_term' assert (len(sq_term.type.broadcastable) == ...
'.. todo:: WRITEME'
def score(self, V):
rval = ((- (V - self.reconstruct(V))) / T.sqr(self.sigma)) rval.name = 'score' return rval
'Returns True if training should continue for this model, False otherwise Parameters model : a Model instance Returns bool True or False as described above'
def continue_learning(self, model):
raise NotImplementedError(((str(type(self)) + ' does not implement ') + 'continue_learning.'))
'The optimization should stop if the model has run for N epochs without sufficient 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 if training should continue'
def continue_learning(self, model):
monitor = model.monitor if (self._channel_name is None): v = monitor.channels['objective'].val_record else: v = monitor.channels[self._channel_name].val_record if (v[(-1)] < ((1.0 - self.prop_decrease) * self.best_value)): self.countdown = self.N else: self.countdown ...
'Calls setup on all extensions.'
def setup_extensions(self):
for ext in self.extensions: ext.setup(self.model, self.dataset, self.algorithm)
'.. todo:: WRITEME'
def exceeded_time_budget(self, t0, time_budget):
dt = total_seconds((datetime.now() - t0)) if ((time_budget is not None) and (dt >= time_budget)): log.warning('Time budget exceeded (%.3f/%d seconds).', dt, time_budget) self.model.monitor.time_budget_exceeded = True return True else: return False