desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Returns an instance of pylearn2.space.Space describing the format of the vector space that the model outputs (this is a generalization of get_output_dim)'
def get_output_space(self):
return self.output_space
'Returns an instance of pylearn2.space.Space describing the format of that the targets should be in, which may be different from the output space. Calls get_output_space() unless _target_space exists.'
def get_target_space(self):
if hasattr(self, '_target_space'): return self._target_space else: return self.get_output_space()
'Returns a string, stating the source for the input. By default the model expects only one input source, which is called \'features\'.'
def get_input_source(self):
if hasattr(self, 'input_source'): return self.input_source else: return 'features'
'Returns a string, stating the source for the output. By default the model expects only one output source, which is called \'targets\'.'
def get_target_source(self):
if hasattr(self, 'target_source'): return self.target_source else: return 'targets'
'Compute the free energy of data examples, if this model has probabilistic semantics. Parameters V : tensor_like, 2-dimensional A batch of i.i.d. examples with examples indexed along the first axis and features along the second. This is data on which the monitoring quantities will be calculated (e.g., a validation set)...
def free_energy(self, V):
raise NotImplementedError()
'Returns the parameters that define the model. Returns params : list A list of (Theano shared variable) parameters of the model. Notes By default, this returns a copy of the _params attribute, which individual models can simply fill with the list of model parameters. Alternatively, models may override `get_params`, so ...
def get_params(self):
return list(self._params)
'Returns numerical values for the parameters that define the model. Parameters borrow : bool, optional Flag to be passed to the `.get_value()` method of the shared variable. If `False`, a copy will always be returned. Returns params : list A list of `numpy.ndarray` objects containing the current parameters of the model...
def get_param_values(self, borrow=False):
assert (not isinstance(self.get_params(), set)) return [param.get_value(borrow=borrow) for param in self.get_params()]
'Sets the values of the parameters that define the model Parameters values : list list of ndarrays borrow : bool The `borrow` flag to use with `set_value`.'
def set_param_values(self, values, borrow=False):
for (param, value) in zip(self.get_params(), values): param.set_value(value, borrow=borrow)
'Returns all parameters flattened into a single vector. Returns params : ndarray 1-D array of all parameter values.'
def get_param_vector(self):
values = self.get_param_values() values = [value.reshape(value.size) for value in values] return np.concatenate(values, axis=0)
'Sets all parameters from a single flat vector. Format is consistent with `get_param_vector`. Parameters vector : ndarray 1-D array of all parameter values.'
def set_param_vector(self, vector):
params = self.get_params() cur_values = self.get_param_values() pos = 0 for (param, value) in safe_zip(params, cur_values): size = value.size new_value = vector[pos:(pos + size)] param.set_value(new_value.reshape(*value.shape)) pos += size assert (pos == vector.size)
'Re-compiles all Theano functions used internally by the model. Notes This function is often called after a model is unpickled from disk, since Theano functions are not pickled. However, it is not always called. This allows scripts like show_weights.py to rapidly unpickle a model and inspect its weights without needing...
def redo_theano(self):
pass
'Returns the number of visible units of the model. Deprecated; this assumes the model operates on a vector. Use get_input_space instead. This method may be removed on or after 2015-05-25.'
def get_input_dim(self):
raise NotImplementedError()
'Returns the number of visible units of the model. Deprecated; this assumes the model operates on a vector. Use get_input_space instead. This method may be removed on or after 2015-05-25.'
def get_output_dim(self):
raise NotImplementedError()
'This is the method that pickle/cPickle uses to determine what portion of the model to serialize. We remove all fields listed in `self.fields_to_del`. In particular, this should include all Theano functions, since they do not play nice with pickling.'
def __getstate__(self):
self._disallow_censor_updates() d = OrderedDict() names_to_del = getattr(self, 'names_to_del', set()) names_to_keep = set(self.__dict__.keys()).difference(names_to_del) for name in names_to_keep: d[name] = self.__dict__[name] return d
'Specifies the batch size to use with compute.test_value Returns test_batch_size : int Number of examples to use in batches with compute.test_value Notes The model specifies the number of examples in case it needs a fixed batch size or to keep the memory usage of testing under control.'
def get_test_batch_size(self):
return self._test_batch_size
'Print version of the various Python packages and basic information about the experiment setup (e.g. cpu, os) Parameters print_theano_config : bool TODO WRITEME Notes Example output: .. code-block:: none numpy:1.6.1 | pylearn:a6e634b83d | pylearn2:57a156beb0 CPU: x86_64 OS: Linux-2.6.35.14-106.fc14.x86_64-x86_64-with-...
def print_versions(self, print_theano_config=False):
self.libv.print_versions() self.libv.print_exp_env_info(print_theano_config)
'Register names of fields that should not be pickled. Parameters names : iterable A collection of strings indicating names of fields on ts object that should not be pickled. Notes All names registered will be deleted from the dictionary returned by the model\'s `__getstate__` method (unless a particular model overrides...
def register_names_to_del(self, names):
if isinstance(names, six.string_types): names = [names] try: assert all((isinstance(n, six.string_types) for n in iter(names))) except (TypeError, AssertionError): reraise_as(ValueError('Invalid names argument')) if (not hasattr(self, 'names_to_del')): self.names_to...
'Enforces all constraints encoded by self.modify_updates.'
def enforce_constraints(self):
params = self.get_params() updates = OrderedDict(izip_no_length_check(params, params)) self.modify_updates(updates) f = function([], updates=updates) f()
'A "scratch-space" for storing model metadata. Returns tag : defaultdict A defaultdict with "dict" as the default constructor. This lets you do things like `model.tag[ext_name][quantity_name]` without the annoyance of first initializing the dict `model.tag[ext_name]`. Notes Nothing critical to the implementation of a p...
@property def tag(self):
if (not hasattr(self, '_tag')): self._tag = defaultdict(dict) return self._tag
'Creates the Autoencoder objects needed by the GSN. Parameters layer_sizes : WRITEME activation_funcs : WRITEME tied : WRITEME'
@staticmethod def _make_aes(layer_sizes, activation_funcs, tied=True):
aes = [] assert (len(activation_funcs) == len(layer_sizes)) for i in xrange((len(layer_sizes) - 1)): act_enc = activation_funcs[(i + 1)] act_dec = (act_enc if (i != 0) else activation_funcs[0]) aes.append(Autoencoder(layer_sizes[i], layer_sizes[(i + 1)], act_enc, act_dec, tied_weight...
'An easy (and recommended) way to initialize a GSN. Parameters layer_sizes : list A list of integers. The i_th element in the list is the size of the i_th layer of the network, and the network will have len(layer_sizes) layers. activation_funcs : list activation_funcs must be a list of the same length as layer_sizes wh...
@classmethod def new(cls, layer_sizes, activation_funcs, pre_corruptors, post_corruptors, layer_samplers, tied=True):
args = [layer_sizes, pre_corruptors, post_corruptors, layer_samplers] if (not all((isinstance(arg, list) for arg in args))): raise TypeError('All arguments except for tied must be lists') if (not all(((len(arg) == len(args[0])) for arg in args))): lengths = map(len, args...
'.. todo:: WRITEME'
@functools.wraps(Model.get_params) def get_params(self):
params = set() for ae in self.aes: params.update(ae.get_params()) return list(params)
'Returns how many layers the GSN has.'
@property def nlayers(self):
return (len(self.aes) + 1)
'This runs the GSN on input \'minibatch\' and returns all of the activations at every time step. Parameters minibatch : see parameter description in _set_activations walkback : int How many walkback steps to perform. clamped : list of theano tensors or None. clamped must be None or a list of len(minibatch) where each e...
def _run(self, minibatch, walkback=0, clamped=None):
set_idxs = safe_zip(*minibatch)[0] if ((self.nlayers == 2) and (len(set_idxs) == 2)): if (clamped is None): raise ValueError((('Setting both layers of 2 layer GSN without ' + 'clamping causes one layer to overwrite the ') + 'other. The value...
'Compiles, wraps, and caches Theano functions for non-symbolic calls to get_samples. Parameters indices : WRITEME clamped : WRITEME'
def _make_or_get_compiled(self, indices, clamped=False):
def compile_f_init(): mb = T.matrices(len(indices)) zipped = safe_zip(indices, mb) f_init = theano.function(mb, self._set_activations(zipped, corrupt=True), allow_input_downcast=True) def wrap_f_init(*args): data = f_init(*args) length = (len(data) / 2) ...
'Runs minibatch through GSN and returns reconstructed data. Parameters minibatch : see parameter description in _set_activations In addition to the description in get_samples, the tensor_likes in the list should be replaced by numpy matrices if symbolic=False. walkback : int How many walkback steps to perform. This is ...
def get_samples(self, minibatch, walkback=0, indices=None, symbolic=True, include_first=False, clamped=None):
if ((walkback > 8) and symbolic): warnings.warn((((('Running GSN in symbolic mode (needed for training) ' + 'with a lot of walkback. Theano may take a very long ') + 'time to compile this computational graph. If ') + 'compiling ...
'.. todo:: WRITEME'
@functools.wraps(Autoencoder.reconstruct) def reconstruct(self, minibatch):
assert (len(minibatch) == 1) idx = minibatch[0][0] return self.get_samples(minibatch, walkback=0, indices=[idx])
'As specified by StackedBlocks, this returns the output representation of all layers. This occurs at the final time step. Parameters minibatch : WRITEME Returns WRITEME'
def __call__(self, minibatch):
return self._run(minibatch)[(-1)]
'Initializes the GSN as specified by minibatch. Parameters minibatch : list of (int, tensor_like) The minibatch parameter must be a list of tuples of form (int, tensor_like), where the int component represents the index of the layer (so 0 for visible, -1 for top/last layer) and the tensor_like represents the activation...
def _set_activations(self, minibatch, set_val=True, corrupt=False):
activations = ([None] * self.nlayers) mb_size = minibatch[0][1].shape[0] first_layer_size = self.aes[0].weights.shape[0] activations[0] = T.alloc(0, mb_size, first_layer_size) for i in xrange(1, len(activations)): activations[i] = T.zeros_like(T.dot(activations[(i - 1)], self.aes[(i - 1)].we...
'Updates just the odd layers of the network. Parameters activations : list List of symbolic tensors representing the current activations. skip_idxs : list List of integers representing which odd indices should not be updated. This parameter exists so that _set_activations can solve the tricky problem of initializing th...
def _update_odds(self, activations, skip_idxs=frozenset(), corrupt=True, clamped=None):
odds = filter((lambda i: (i not in skip_idxs)), range(1, len(activations), 2)) self._update_activations(activations, odds) if (clamped is not None): self._apply_clamping(activations, clamped) odds_copy = [(i, activations[i]) for i in xrange(1, len(activations), 2)] if corrupt: self.a...
'Updates just the even layers of the network. Parameters See all of the descriptions for _update_evens.'
def _update_evens(self, activations, clamped=None):
evens = xrange(0, len(activations), 2) self._update_activations(activations, evens) if (clamped is not None): self._apply_clamping(activations, clamped) evens_copy = [(i, activations[i]) for i in evens] self.apply_postact_corruption(activations, evens) return evens_copy
'See Figure 1 in "Deep Generative Stochastic Networks as Generative Models" by Bengio, Thibodeau-Laufer. This and _update_activations implement exactly that, which is essentially forward propogating the neural network in both directions. Parameters activations : list of tensors List of activations at time step t - 1. c...
def _update(self, activations, clamped=None, return_activations=False):
evens_copy = self._update_evens(activations, clamped=clamped) odds_copy = self._update_odds(activations, clamped=clamped) precor = ([None] * len(self.activations)) for (idx, val) in (evens_copy + odds_copy): assert (precor[idx] is None) precor[idx] = val assert (None not in precor) ...
'Resets the value of some layers within the network. Parameters activations : list List of symbolic tensors representing the current activations. clamped : list of (int, matrix, matrix or None) tuples The first component of each tuple is an int representing the index of the layer to clamp. The second component is a mat...
@staticmethod def _apply_clamping(activations, clamped, symbolic=True):
for (idx, initial, clamp) in clamped: if (clamp is None): continue clamped_val = (clamp * initial) if symbolic: activations[idx] = T.switch(clamp, initial, activations[idx]) else: activations[idx] = np.switch(clamp, initial, activations[idx]) r...
'Applies a list of corruptor functions to all layers. Parameters activations : list of tensor_likes Generally gsn.activations corruptors : list of callables Generally gsn.postact_cors or gsn.preact_cors idx_iter : iterable An iterable of indices into self.activations. The indexes indicate which layers the post activati...
@staticmethod def _apply_corruption(activations, corruptors, idx_iter):
assert (len(corruptors) == len(activations)) for i in idx_iter: activations[i] = corruptors[i](activations[i]) return activations
'.. todo:: WRITEME'
def apply_sampling(self, activations, idx_iter):
if self._sample_switch: self._apply_corruption(activations, self._layer_samplers, idx_iter) return activations
'.. todo:: WRITEME'
def apply_postact_corruption(self, activations, idx_iter, sample=True):
if sample: self.apply_sampling(activations, idx_iter) if self._corrupt_switch: self._apply_corruption(activations, self._postact_cors, idx_iter) return activations
'.. todo:: WRITEME'
def apply_preact_corruption(self, activations, idx_iter):
if self._corrupt_switch: self._apply_corruption(activations, self._preact_cors, idx_iter) return activations
'Actually computes the activations for all indices in idx_iters. This method computes the values for a layer by computing a linear combination of the neighboring layers (dictated by the weight matrices), applying the pre-activation corruption, and then applying the layer\'s activation function. Parameters activations :...
def _update_activations(self, activations, idx_iter):
from_above = (lambda i: ((self.aes[i].visbias if self._bias_switch else 0) + T.dot(activations[(i + 1)], self.aes[i].w_prime))) from_below = (lambda i: ((self.aes[(i - 1)].hidbias if self._bias_switch else 0) + T.dot(activations[(i - 1)], self.aes[(i - 1)].weights))) for i in idx_iter: if (i == 0): ...
'\'convert\' essentially serves as the constructor for JointGSN. Parameters gsn : GSN input_idx : int The index of the layer which serves as the "input" to the network. During classification, this layer will be given. Defaults to 0. label_idx : int The index of the layer which serves as the "output" of the network. Thi...
@classmethod def convert(cls, gsn, input_idx=0, label_idx=None):
gsn = copy.copy(gsn) gsn.__class__ = cls gsn.input_idx = input_idx gsn.label_idx = (label_idx or (gsn.nlayers - 1)) return gsn
'Utility method that calculates how much walkback is needed to get at at least \'trials\' samples. Parameters trials : WRITEME'
def calc_walkback(self, trials):
wb = (trials - len(self.aes)) if (wb <= 0): return 0 else: return wb
'See classify method. Returns the prediction vector aggregated over all time steps where axis 0 is the minibatch item and axis 1 is the output for the label.'
def _get_aggregate_classification(self, minibatch, trials=10, skip=0):
clamped = np.ones(minibatch.shape, dtype=np.float32) data = self.get_samples([(self.input_idx, minibatch)], walkback=self.calc_walkback((trials + skip)), indices=[self.label_idx], clamped=[clamped], symbolic=False) data = np.asarray(data[skip:(skip + trials)])[:, 0, :, :] return data.mean(axis=0)
'Classifies a minibatch. This method clamps minibatch at self.input_idx and then runs the GSN. The first \'skip\' predictions are skipped and the next \'trials\' predictions are averaged and then arg-maxed to make a final prediction. The prediction vectors are the activations at self.label_idx. Parameters minibatch : n...
def classify(self, minibatch, trials=10, skip=0):
mean = self._get_aggregate_classification(minibatch, trials=trials, skip=skip) am = np.argmax(mean, axis=1) labels = np.zeros_like(mean) labels[(np.arange(labels.shape[0]), am)] = 1.0 return labels
'Clamps labels and generates samples. Parameters labels : WRITEME trials : WRITEME'
def get_samples_from_labels(self, labels, trials=5):
clamped = np.ones(labels.shape, dtype=np.float32) data = self.get_samples([(self.label_idx, labels)], walkback=self.calc_walkback(trials), indices=[self.input_idx], clamped=[clamped], symbolic=False) return np.array(data)[:, 0, :, :]
'Get all layers in this model. Returns layers : list'
def get_all_layers(self):
return ([self.visible_layer] + self.hidden_layers)
'Compute the energy of current model with visible and hidden samples. Parameters V : tensor_like Theano batch of visible unit observations (must be SAMPLES, not mean field parameters) hidden : list List, one element per hidden layer, of batches of samples (must be SAMPLES, not mean field parameters) Returns rval : tens...
def energy(self, V, hidden):
terms = [] terms.append(self.visible_layer.expected_energy_term(state=V, average=False)) assert (len(self.hidden_layers) > 0) terms.append(self.hidden_layers[0].expected_energy_term(state_below=self.visible_layer.upward_state(V), state=hidden[0], average_below=False, average=False)) for i in xrange(...
'Perform mean field inference, using the model\'s inference procedure.'
def mf(self, *args, **kwargs):
self.setup_inference_procedure() return self.inference_procedure.mf(*args, **kwargs)
'Compute the energy of current model with the visible samples and variational parameters. Parameters V : tensor_like Theano batch of visible unit observations (must be SAMPLES, not mean field parameters: the random variables in the expectation are the hiddens only) mf_hidden : list List, one element per hidden layer, o...
def expected_energy(self, V, mf_hidden):
self.visible_layer.space.validate(V) assert isinstance(mf_hidden, (list, tuple)) assert (len(mf_hidden) == len(self.hidden_layers)) terms = [] terms.append(self.visible_layer.expected_energy_term(state=V, average=False)) assert (len(self.hidden_layers) > 0) terms.append(self.hidden_layers[0]...
'Set the random number generator for the model.'
def setup_rng(self):
self.rng = make_np_rng(None, [2012, 10, 17], which_method='uniform')
'Set the inference procedure for the model. Default using `WeightDoubling`'
def setup_inference_procedure(self):
if ((not hasattr(self, 'inference_procedure')) or (self.inference_procedure is None)): self.inference_procedure = WeightDoubling() self.inference_procedure.set_dbm(self)
'Set the sampling procedure for the model. Default using `GibbsEvenOdd`'
def setup_sampling_procedure(self):
if ((not hasattr(self, 'sampling_procedure')) or (self.sampling_procedure is None)): self.sampling_procedure = GibbsEvenOdd() self.sampling_procedure.set_dbm(self)
'.. todo:: WRITEME'
def get_output_space(self):
return self.hidden_layers[(-1)].get_output_space()
'Tells each layer what its input space should be. Notes This usually resets the layer\'s parameters!'
def _update_layer_input_spaces(self):
visible_layer = self.visible_layer hidden_layers = self.hidden_layers self.hidden_layers[0].set_input_space(visible_layer.space) for i in xrange(1, len(hidden_layers)): hidden_layers[i].set_input_space(hidden_layers[(i - 1)].get_output_space()) for layer in self.get_all_layers(): lay...
'Add new layers on top of the existing hidden layers Parameters layers : list layers to be added'
def add_layers(self, layers):
if (not hasattr(self, 'rng')): self.setup_rng() hidden_layers = self.hidden_layers assert (len(hidden_layers) > 0) for layer in layers: assert (layer.get_dbm() is None) layer.set_dbm(self) layer.set_input_space(hidden_layers[(-1)].get_output_space()) hidden_layers...
'.. todo:: WRITEME'
def freeze(self, parameter_set):
if (not hasattr(self, 'freeze_set')): self.freeze_set = set([]) self.freeze_set = self.freeze_set.union(parameter_set)
'.. todo:: WRITEME'
def get_params(self):
rval = [] for param in self.visible_layer.get_params(): assert (param.name is not None) rval = self.visible_layer.get_params() for layer in self.hidden_layers: for param in layer.get_params(): if (param.name is None): raise ValueError((('All of your p...
'.. todo:: WRITEME'
def set_batch_size(self, batch_size):
self.batch_size = batch_size self.force_batch_size = batch_size for layer in self.hidden_layers: layer.set_batch_size(batch_size) if (not hasattr(self, 'inference_procedure')): self.setup_inference_procedure() self.inference_procedure.set_batch_size(batch_size)
'.. todo:: WRITEME'
def get_input_space(self):
return self.visible_layer.space
'.. todo:: WRITEME'
def get_lr_scalers(self):
rval = OrderedDict() params = self.get_params() for layer in (self.hidden_layers + [self.visible_layer]): contrib = layer.get_lr_scalers() assert (not any([(key in rval) for key in contrib])) assert all([(key in params) for key in contrib]) rval.update(contrib) assert all...
'.. todo:: WRITEME'
def get_weights(self):
return self.hidden_layers[0].get_weights()
'.. todo:: WRITEME'
def get_weights_view_shape(self):
return self.hidden_layers[0].get_weights_view_shape()
'.. todo:: WRITEME'
def get_weights_format(self):
return self.hidden_layers[0].get_weights_format()
'.. todo:: WRITEME'
def get_weights_topo(self):
return self.hidden_layers[0].get_weights_topo()
'Makes and returns a dictionary mapping layers to states. By states, we mean here a real assignment, not a mean field state. For example, for a layer containing binary random variables, the state will be a shared variable containing values in {0,1}, not [0,1]. The visible layer will be included. Uses a dictionary so it...
def make_layer_to_state(self, num_examples, rng=None):
layers = ([self.visible_layer] + self.hidden_layers) if (rng is None): rng = self.rng states = [layer.make_state(num_examples, rng) for layer in layers] def recurse_check(layer, state): if isinstance(state, (list, tuple)): for elem in state: recurse_check(laye...
'Makes and returns a dictionary mapping layers to states. By states, we mean here a real assignment, not a mean field state. For example, for a layer containing binary random variables, the state will be a shared variable containing values in {0,1}, not [0,1]. The visible layer will be included. Uses a dictionary so it...
def make_layer_to_symbolic_state(self, num_examples, rng=None):
layers = ([self.visible_layer] + self.hidden_layers) assert (rng is not None) states = [layer.make_symbolic_state(num_examples, rng) for layer in layers] zipped = safe_zip(layers, states) rval = OrderedDict(zipped) return rval
'This method is for getting an updates dictionary for a theano function. It thus implies that the samples are represented as shared variables. If you want an expression for a sampling step applied to arbitrary theano variables, use the `DBM.sampling_procedure.sample` method. This is a wrapper around that method. Parame...
def get_sampling_updates(self, layer_to_state, theano_rng, layer_to_clamp=None, num_steps=1, return_layer_to_updated=False):
updated = self.sampling_procedure.sample(layer_to_state, theano_rng, layer_to_clamp, num_steps) rval = OrderedDict() def add_updates(old, new): if isinstance(old, (list, tuple)): for (old_elem, new_elem) in safe_izip(old, new): add_updates(old_elem, new_elem) else...
'.. todo:: WRITEME'
def get_monitoring_channels(self, data):
(space, source) = self.get_monitoring_data_specs() space.validate(data) X = data history = self.mf(X, return_history=True) q = history[(-1)] rval = OrderedDict() ch = self.visible_layer.get_monitoring_channels() for key in ch: rval[('vis_' + key)] = ch[key] for (state, layer)...
'Get the data_specs describing the data for get_monitoring_channel. This implementation returns specification corresponding to unlabeled inputs.'
def get_monitoring_data_specs(self):
return (self.get_input_space(), self.get_input_source())
'.. todo:: WRITEME'
def get_test_batch_size(self):
return self.batch_size
'Reconstruct the visible variables. Returns recons : tensor_like Unmasked reconstructed visible variables.'
def reconstruct(self, V):
H = self.mf(V)[0] downward_state = self.hidden_layers[0].downward_state(H) recons = self.visible_layer.inpaint_update(layer_above=self.hidden_layers[0], state_above=downward_state, drop_mask=None, V=None) return recons
'Does the inference required for multi-prediction training, using the model\'s inference procedure.'
def do_inpainting(self, *args, **kwargs):
self.setup_inference_procedure() return self.inference_procedure.do_inpainting(*args, **kwargs)
'Associates the InferenceProcedure with a specific DBM. Parameters dbm : pylearn2.models.dbm.DBM instance The model to perform inference in.'
def set_dbm(self, dbm):
self.dbm = dbm
'Perform mean field inference. Subclasses must implement. Parameters V : Input space batch The values of the input features modeled by the DBM. Y : (Optional) Target space batch The values of the labels modeled by the DBM. Must be omitted if the DBM does not model labels. If the DBM does model labels, they may be inclu...
def mf(self, V, Y=None, return_history=False, niter=None, block_grad=None):
raise NotImplementedError((str(type(self)) + ' does not implement mf.'))
'Inference using "the multi-inference trick." See "Multi-prediction deep Boltzmann machines", Goodfellow et al 2013. Subclasses may implement this method, however it is not needed for any training algorithm, and only expected to work at evaluation time if the model was trained with multi-prediction training. Parameters...
def multi_infer(self, V, return_history=False, niter=None, block_grad=None):
raise NotImplementedError((str(type(self)) + ' does not implement multi_infer.'))
'Does the inference required for multi-prediction training. If you use this method in your research work, please cite: Multi-prediction deep Boltzmann machines. Ian J. Goodfellow, Mehdi Mirza, Aaron Courville, and Yoshua Bengio. NIPS 2013. Gives the mean field expression for units masked out by drop_mask. Uses self.nit...
def do_inpainting(self, V, Y=None, drop_mask=None, drop_mask_Y=None, return_history=False, noise=False, niter=None, block_grad=None):
raise NotImplementedError((str(type(self)) + ' does not implement do_inpainting.'))
'.. todo:: WRITEME properly Gives the mean field expression for units masked out by drop_mask. Uses self.niter mean field updates. If you use this method in your research work, please cite: Multi-prediction deep Boltzmann machines. Ian J. Goodfellow, Mehdi Mirza, Aaron Courville, and Yoshua Bengio. NIPS 2013. Comes in ...
def do_inpainting(self, V, Y=None, drop_mask=None, drop_mask_Y=None, return_history=False, noise=False, niter=None, block_grad=None):
dbm = self.dbm 'TODO: Should add unit test that calling this with a batch of\n different inputs should yield the same output for each\n ...
'Gives the mean field expression for units masked out by drop_mask. Uses self.niter mean field updates. Comes in two variants, unsupervised and supervised: * unsupervised: Y and drop_mask_Y are not passed to the method. The method produces V_hat, an inpainted version of V. * supervised: Y and drop_mask_Y are passed to ...
def do_inpainting(self, V, Y=None, drop_mask=None, drop_mask_Y=None, return_history=False, noise=False, niter=None, block_grad=None):
dbm = self.dbm 'TODO: Should add unit test that calling this with a batch of\n different inputs should yield the same output for each\n ...
'.. todo:: WRITEME'
@functools.wraps(InferenceProcedure.mf) def mf(self, V, Y=None, return_history=False, niter=None, block_grad=None):
dbm = self.dbm assert (Y not in [True, False, 0, 1]) assert (return_history in [True, False, 0, 1]) if (Y is not None): dbm.hidden_layers[(-1)].get_output_space().validate(Y) if (niter is None): niter = dbm.niter H_hat = ([None] + [layer.init_mf_state() for layer in dbm.hidden_la...
'.. todo:: WRITEME properly Gives the mean field expression for units masked out by drop_mask. Uses self.niter mean field updates. Comes in two variants, unsupervised and supervised: * unsupervised: Y and drop_mask_Y are not passed to the method. The method produces V_hat, an inpainted version of V. * supervised: Y and...
def do_inpainting(self, V, Y=None, drop_mask=None, drop_mask_Y=None, return_history=False, noise=False, niter=None, block_grad=None):
if (Y is not None): assert isinstance(self.hidden_layers[(-1)], Softmax) model = self.dbm 'TODO: Should add unit test that calling this with a batch of\n different inputs should yield the ...
'.. todo:: WRITEME'
def __call__(self, inputs):
space = self.dbm.get_input_space() num_examples = space.batch_size(inputs) last_layer = self.dbm.get_all_layers()[(-1)] layer_to_chains = self.dbm.make_layer_to_symbolic_state(num_examples, self.theano_rng) layer_to_chains[self.dbm.visible_layer] = inputs layer_to_clamp = OrderedDict([(self.dbm....
'.. todo:: WRITEME'
def get_input_space(self):
return self.dbm.get_input_space()
'.. todo:: WRITEME'
def get_output_space(self):
return self.dbm.get_output_space()
'.. todo:: WRITEME'
def get_biases(self):
return self.bias.get_value()
'.. todo:: WRITEME'
def set_biases(self, biases, recenter=False):
self.bias.set_value(biases) if recenter: assert self.center self.offset.set_value(sigmoid_numpy(self.bias.get_value()))
'.. todo:: WRITEME'
def upward_state(self, total_state):
return total_state
'.. todo:: WRITEME'
def get_params(self):
rval = [self.bias] if self.learn_beta: rval.append(self.beta) return rval
'.. todo:: WRITEME'
def mf_update(self, state_above, layer_above):
msg = layer_above.downward_message(state_above) bias = self.bias z = (msg + bias) rval = T.tanh((self.beta * z)) return rval
'.. todo:: WRITEME'
def sample(self, state_below=None, state_above=None, layer_above=None, theano_rng=None):
assert (state_below is None) msg = layer_above.downward_message(state_above) bias = self.bias z = (msg + bias) phi = T.nnet.sigmoid(((2.0 * self.beta) * z)) rval = theano_rng.binomial(size=phi.shape, p=phi, dtype=phi.dtype, n=1) return ((rval * 2.0) - 1.0)
'.. todo:: WRITEME'
def make_state(self, num_examples, numpy_rng):
driver = numpy_rng.uniform(0.0, 1.0, (num_examples, self.nvis)) on_prob = sigmoid_numpy(((2.0 * self.beta.get_value()) * self.bias.get_value())) sample = ((2.0 * (driver < on_prob)) - 1.0) rval = sharedX(sample, name='v_sample_shared') return rval
'.. todo:: WRITEME'
def make_symbolic_state(self, num_examples, theano_rng):
mean = T.nnet.sigmoid(((2.0 * self.beta) * self.b)) rval = theano_rng.binomial(size=(num_examples, self.nvis), p=mean) rval = ((2.0 * rval) - 1.0) return rval
'.. todo:: WRITEME'
def expected_energy_term(self, state, average, state_below=None, average_below=None):
assert (state_below is None) assert (average_below is None) assert (average in [True, False]) self.space.validate(state) rval = (- (self.beta * T.dot(state, self.bias))) assert (rval.ndim == 1) return rval
'.. todo:: WRITEME'
def get_lr_scalers(self):
if (not hasattr(self, 'W_lr_scale')): self.W_lr_scale = None if (not hasattr(self, 'b_lr_scale')): self.b_lr_scale = None rval = OrderedDict() if (self.W_lr_scale is not None): (W,) = self.transformer.get_params() rval[W] = self.W_lr_scale if (self.b_lr_scale is not N...
'.. todo:: WRITEME properly Notes Note: this resets parameters!'
def set_input_space(self, space):
self.input_space = space if isinstance(space, VectorSpace): self.requires_reformat = False self.input_dim = space.dim else: self.requires_reformat = True self.input_dim = space.get_total_dimension() self.desired_space = VectorSpace(self.input_dim) self.output_spac...
'.. todo:: WRITEME'
def get_total_state_space(self):
return VectorSpace(self.dim)
'.. todo:: WRITEME'
def get_params(self):
assert (self.b.name is not None) (W,) = self.transformer.get_params() assert (W.name is not None) rval = self.transformer.get_params() assert (not isinstance(rval, set)) rval = list(rval) assert (self.b not in rval) rval.append(self.b) if self.learn_beta: rval.append(self.bet...
'.. todo:: WRITEME'
def get_weight_decay(self, coeff):
if isinstance(coeff, str): coeff = float(coeff) assert (isinstance(coeff, float) or hasattr(coeff, 'dtype')) (W,) = self.transformer.get_params() return (coeff * T.sqr(W).sum())
'.. todo:: WRITEME'
def get_weights(self):
if self.requires_reformat: raise NotImplementedError() (W,) = self.transformer.get_params() return W.get_value()
'.. todo:: WRITEME'
def set_weights(self, weights):
(W,) = self.transformer.get_params() W.set_value(weights)
'.. todo:: WRITEME'
def set_biases(self, biases, recenter=False):
self.b.set_value(biases) if recenter: assert self.center if (self.pool_size != 1): raise NotImplementedError() self.offset.set_value(sigmoid_numpy(self.b.get_value()))
'.. todo:: WRITEME'
def get_biases(self):
return self.b.get_value()
'.. todo:: WRITEME'
def get_weights_format(self):
return ('v', 'h')