desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'.. todo:: WRITEME'
def downward_message(self, downward_state):
rval = self.transformer.lmul_T(downward_state) if self.requires_reformat: rval = self.desired_space.format_as(rval, self.input_space) return (rval * self.copies)
'.. todo:: WRITEME'
def init_mf_state(self):
z = ((T.alloc(0.0, self.dbm.batch_size, self.detector_layer_dim).astype(self.b.dtype) + self.b.dimshuffle('x', 0)) + self.beta_bias()) rval = max_pool_channels(z=z, pool_size=self.pool_size) return rval
'.. todo:: WRITEME properly Returns a shared variable containing an actual state (not a mean field state) for this variable.'
def make_state(self, num_examples, numpy_rng):
raise NotImplementedError('need to account for beta') if (not hasattr(self, 'copies')): self.copies = 1 if (self.copies != 1): raise NotImplementedError() empty_input = self.h_space.get_origin_batch(num_examples) empty_output = self.output_space.get_origin_batch(num_examp...
'.. todo:: WRITEME'
def expected_energy_term(self, state, average, state_below, average_below):
raise NotImplementedError('need to account for beta, and maybe some oether stuff') self.input_space.validate(state_below) if self.requires_reformat: if (not isinstance(state_below, tuple)): for sb in get_debug_values(state_below): if (sb.shape[0...
'.. todo:: WRITEME properly Used to implement TorontoSparsity. Unclear exactly what properties of it are important or how to implement it for other layers. Properties it must have: output is same kind of data structure (ie, tuple of theano 2-tensors) as mf_update Properties it probably should have for other layer types...
def linear_feed_forward_approximation(self, state_below):
raise NotImplementedError('need to account for beta') z = (self.transformer.lmul(state_below) + self.b) if (self.pool_size != 1): raise NotImplementedError() return (z, z)
'.. todo:: WRITEME'
def beta_bias(self):
(W,) = self.transformer.get_params() beta = self.input_layer.beta assert (beta.ndim == 1) return ((-0.5) * T.dot(beta, T.sqr(W)))
'.. todo:: WRITEME'
def mf_update(self, state_below, state_above, layer_above=None, double_weights=False, iter_name=None):
self.input_space.validate(state_below) if self.requires_reformat: if (not isinstance(state_below, tuple)): for sb in get_debug_values(state_below): if (sb.shape[0] != self.dbm.batch_size): raise ValueError(('self.dbm.batch_size is %d but got ...
'.. todo:: WRITEME'
def set_input_space(self, space):
self.input_space = space if (not isinstance(space, CompositeSpace)): assert (self.inputs_to_components is None) self.routing_needed = False elif (self.inputs_to_components is None): self.routing_needed = False else: self.routing_needed = True assert (max(self.inpu...
'.. todo:: WRITEME'
def make_state(self, num_examples, numpy_rng):
return tuple((component.make_state(num_examples, numpy_rng) for component in self.components))
'.. todo:: WRITEME'
def get_total_state_space(self):
return CompositeSpace([component.get_total_state_space() for component in self.components])
'.. todo:: WRITEME'
def set_batch_size(self, batch_size):
for component in self.components: component.set_batch_size(batch_size)
'.. todo:: WRITEME'
def set_dbm(self, dbm):
for component in self.components: component.set_dbm(dbm)
'.. todo:: WRITEME'
def mf_update(self, state_below, state_above, layer_above=None, double_weights=False, iter_name=None):
rval = [] for (i, component) in enumerate(self.components): if (self.routing_needed and (i in self.components_to_inputs)): cur_state_below = self.input_space.restrict_batch(state_below, self.components_to_inputs[i]) else: cur_state_below = state_below class Routin...
'.. todo:: WRITEME'
def init_mf_state(self):
return tuple([component.init_mf_state() for component in self.components])
'.. todo:: WRITEME'
def get_weight_decay(self, coeffs):
return sum([component.get_weight_decay(coeff) for (component, coeff) in safe_zip(self.components, coeffs)])
'.. todo:: WRITEME'
def upward_state(self, total_state):
return tuple([component.upward_state(elem) for (component, elem) in safe_zip(self.components, total_state)])
'.. todo:: WRITEME'
def downward_state(self, total_state):
return tuple([component.downward_state(elem) for (component, elem) in safe_zip(self.components, total_state)])
'.. todo:: WRITEME'
def downward_message(self, downward_state):
if isinstance(self.input_space, CompositeSpace): num_input_components = self.input_space.num_components else: num_input_components = 1 rval = ([None] * num_input_components) def add(x, y): if (x is None): return y if (y is None): return x r...
'.. todo:: WRITEME'
def get_l1_act_cost(self, state, target, coeff, eps):
return sum([comp.get_l1_act_cost(s, t, c, e) for (comp, s, t, c, e) in safe_zip(self.components, state, target, coeff, eps)])
'.. todo:: WRITEME'
def get_range_rewards(self, state, coeffs):
return sum([comp.get_range_rewards(s, c) for (comp, s, c) in safe_zip(self.components, state, coeffs)])
'.. todo:: WRITEME'
def get_params(self):
return reduce((lambda x, y: safe_union(x, y)), [component.get_params() for component in self.components])
'.. todo:: WRITEME'
def get_weights_topo(self):
logger.info('Get topological weights for which layer?') for (i, component) in enumerate(self.components): logger.info('{0} {1}'.format(i, component.layer_name)) x = input() return self.components[int(x)].get_weights_topo()
'.. todo:: WRITEME'
def get_monitoring_channels_from_state(self, state):
rval = OrderedDict() for (layer, s) in safe_zip(self.components, state): d = layer.get_monitoring_channels_from_state(s) for key in d: rval[((layer.layer_name + '_') + key)] = d[key] return rval
'.. todo:: WRITEME'
def sample(self, state_below=None, state_above=None, layer_above=None, theano_rng=None):
rval = [] for (i, component) in enumerate(self.components): if (self.routing_needed and (i in self.components_to_inputs)): cur_state_below = self.input_space.restrict_batch(state_below, self.components_to_inputs[i]) else: cur_state_below = state_below class Routin...
'Associates the SamplingProcedure with a specific DBM. Parameters dbm : pylearn2.models.dbm.DBM instance The model to perform sampling from.'
def set_dbm(self, dbm):
self.dbm = dbm
'Samples from self.dbm using `layer_to_state` as starting values. Parameters layer_to_state : dict Maps the DBM\'s Layer instances to theano variables representing batches of samples of them. theano_rng : theano.sandbox.rng_mrg.MRG_RandomStreams Random number generator layer_to_clamp : dict, optional Maps Layers to boo...
def sample(self, layer_to_state, theano_rng, layer_to_clamp=None, num_steps=1):
raise NotImplementedError(((str(type(self)) + ' does not implement ') + 'sample.'))
'.. todo:: WRITEME'
def sample(self, layer_to_state, theano_rng, layer_to_clamp=None, num_steps=1):
assert isinstance(num_steps, py_integer_types) assert (num_steps > 0) if (num_steps != 1): for i in xrange(num_steps): layer_to_state = self.sample(layer_to_state, theano_rng, layer_to_clamp, num_steps=1) return layer_to_state assert (len(self.dbm.hidden_layers) > 0) if (...
'.. todo:: WRITEME'
def get_output_dim(self):
return self.nhid
'.. todo:: WRITEME'
def get_output_channels(self):
return self.nhid
'.. todo:: WRITEME'
def normalize_W(self):
W = self.W.get_value(borrow=True) norms = N.sqrt(N.square(W).sum(axis=0)) self.W.set_value((W / norms), borrow=True)
'.. todo:: WRITEME'
def redo_everything(self):
self.W = shared(N.cast[floatX](self.rng.randn(self.nvis, self.nhid)), name='W') self.pred_W = shared(self.W.get_value(borrow=False), name='pred_W') self.pred_b = shared(N.zeros(self.nhid, dtype=floatX), name='pred_b') self.pred_g = shared(N.ones(self.nhid, dtype=floatX), name='pred_g') self.normaliz...
'.. todo:: WRITEME'
def recons_error(self, v, h):
recons = T.dot(self.W, h) diffs = (recons - v) rval = (T.dot(diffs, diffs) / N.cast[floatX](self.nvis)) return rval
'.. todo:: WRITEME'
def recons_error_batch(self, V, H):
recons = T.dot(H, self.W.T) diffs = (recons - V) rval = T.mean(T.sqr(diffs)) return rval
'.. todo:: WRITEME'
def sparsity_penalty(self, v, h):
sparsity_measure = ((((h * T.log(h)) - (h * T.log(self.p))) - h) + self.p) rval = (T.dot(self.lamda, sparsity_measure) / N.cast[floatX](self.nhid)) return rval
'.. todo:: WRITEME'
def sparsity_penalty_batch(self, V, H):
sparsity_measure = ((((H * T.log(H)) - (H * T.log(self.p))) - H) + self.p) sparsity_measure_exp = T.mean(sparsity_measure, axis=0) rval = (T.dot(self.lamda, sparsity_measure_exp) / N.cast[floatX](self.nhid)) return rval
'.. todo:: WRITEME'
def coding_obj(self, v, h):
return (self.recons_error(v, h) + self.sparsity_penalty(v, h))
'.. todo:: WRITEME'
def coding_obj_batch(self, V, H):
return (self.recons_error_batch(V, H) + self.sparsity_penalty_batch(V, H))
'.. todo:: WRITEME'
def predict(self, V):
rval = (T.nnet.sigmoid((T.dot(V, self.pred_W) + self.pred_b)) * self.pred_g) assert (rval.type.dtype == V.type.dtype) return rval
'.. todo:: WRITEME'
def redo_theano(self):
self.h = shared(N.zeros(self.nhid, dtype=floatX), name='h') self.v = shared(N.zeros(self.nvis, dtype=floatX), name='v') input_v = T.vector() assert (input_v.type.dtype == floatX) self.init_h_v = function([input_v], updates={self.h: self.predict(input_v), self.v: input_v}) coding_obj = self.codin...
'.. todo:: WRITEME'
def weights_format(self):
return ['v', 'h']
'.. todo:: WRITEME'
def error_func(self, x):
batch_size = x.shape[0] H = N.zeros((batch_size, self.nhid), dtype=floatX) for i in xrange(batch_size): assert (self.alpha > 9e-08) H[i, :] = self.optimize_h(x[i, :]) assert (self.alpha > 9e-08) return self.code_learning_obj(x, H)
'.. todo:: WRITEME'
def record_monitoring_error(self, dataset, batch_size, batches):
logger.info('running on monitoring set') assert (self.error_record_mode == self.ERROR_RECORD_MODE_MONITORING) w = self.W.get_value(borrow=True) logger.info('weights summary: ({0}, {1}, {2})'.format(w.min(), w.mean(), w.max())) errors = [] if self.instrumented: self.c...
'.. todo:: WRITEME'
def infer_h(self, v):
return self.optimize_h(v)
'.. todo:: WRITEME'
def optimize_h(self, v):
assert (self.alpha > 9e-08) self.init_h_v(v) first = True while True: (obj, grad) = self.coding_obj_grad() if first: first = False assert (not N.any(N.isnan(obj))) assert (not N.any(N.isnan(grad))) if (N.abs(grad).max() < self.tol): break ...
'.. todo:: WRITEME'
def train_batch(self, dataset, batch_size):
self.learn_mini_batch(dataset.get_batch_design(batch_size)) return True
'.. todo:: WRITEME'
def learn_mini_batch(self, x):
assert (self.alpha > 9e-08) batch_size = x.shape[0] H = N.zeros((batch_size, self.nhid), dtype=floatX) for i in xrange(batch_size): assert (self.alpha > 9e-08) H[i, :] = self.optimize_h(x[i, :]) assert (self.alpha > 9e-08) self.code_learning_step(x, H, self.learning_rate) ...
'Returns the MLP that this layer belongs to. Returns mlp : MLP The MLP that this layer belongs to, or None if it has not been assigned to an MLP yet.'
def get_mlp(self):
if hasattr(self, 'mlp'): return self.mlp return None
'Assigns this layer to an MLP. This layer will then use the MLP\'s random number generator, batch size, etc. This layer\'s name must be unique within the MLP. Parameters mlp : MLP'
def set_mlp(self, mlp):
assert (self.get_mlp() is None) self.mlp = mlp
'Returns monitoring channels. Parameters state_below : member of self.input_space A minibatch of states that this Layer took as input. Most of the time providing state_blow is unnecessary when state is given. state : member of self.output_space A minibatch of states that this Layer took on during fprop. Provided extern...
def get_layer_monitoring_channels(self, state_below=None, state=None, targets=None):
return OrderedDict()
'Does the forward prop transformation for this layer. Parameters state_below : member of self.input_space A minibatch of states of the layer below. Returns state : member of self.output_space A minibatch of states of this layer.'
def fprop(self, state_below):
raise NotImplementedError((str(type(self)) + ' does not implement fprop.'))
'The cost of outputting Y_hat when the true output is Y. Parameters Y : theano.gof.Variable The targets Y_hat : theano.gof.Variable The predictions. Assumed to be the output of the layer\'s `fprop` method. The implmentation is permitted to do things like look at the ancestors of `Y_hat` in the theano graph. This is use...
def cost(self, Y, Y_hat):
raise NotImplementedError((str(type(self)) + ' does not implement mlp.Layer.cost.'))
'The cost final scalar cost computed from the cost matrix Parameters cost_matrix : WRITEME Examples >>> # C = model.cost_matrix(Y, Y_hat) >>> # Do something with C like setting some values to 0 >>> # cost = model.cost_from_cost_matrix(C)'
def cost_from_cost_matrix(self, cost_matrix):
raise NotImplementedError((str(type(self)) + ' does not implement mlp.Layer.cost_from_cost_matrix.'))
'The element wise cost of outputting Y_hat when the true output is Y. Parameters Y : WRITEME Y_hat : WRITEME Returns WRITEME'
def cost_matrix(self, Y, Y_hat):
raise NotImplementedError((str(type(self)) + ' does not implement mlp.Layer.cost_matrix'))
'Sets the weights of the layer. Parameters weights : ndarray A numpy ndarray containing the desired weights of the layer. This docstring is provided by the Layer base class. Layer subclasses should add their own docstring explaining the subclass-specific format of the ndarray.'
def set_weights(self, weights):
raise NotImplementedError((str(type(self)) + ' does not implement set_weights.'))
'Returns the value of the biases of the layer. Returns biases : ndarray A numpy ndarray containing the biases of the layer. This docstring is provided by the Layer base class. Layer subclasses should add their own docstring explaining the subclass-specific format of the ndarray.'
def get_biases(self):
raise NotImplementedError((str(type(self)) + ' does not implement get_biases (perhaps because the class has no biases).'))
'Sets the biases of the layer. Parameters biases : ndarray A numpy ndarray containing the desired biases of the layer. This docstring is provided by the Layer base class. Layer subclasses should add their own docstring explaining the subclass-specific format of the ndarray.'
def set_biases(self, biases):
raise NotImplementedError((str(type(self)) + ' does not implement set_biases (perhaps because the class has no biases).'))
'Returns a description of how to interpret the weights of the layer. Returns format: tuple Either (\'v\', \'h\') or (\'h\', \'v\'). (\'v\', \'h\') means a weight matrix of shape (num visible units, num hidden units), while (\'h\', \'v\') means the transpose of it.'
def get_weights_format(self):
raise NotImplementedError
'Provides an expression for a squared L2 penalty on the weights. Parameters coeff : float or tuple The coefficient on the weight decay penalty for this layer. This docstring is provided by the Layer base class. Individual Layer subclasses should add their own docstring explaining the format of `coeff` for that particul...
def get_weight_decay(self, coeff):
raise NotImplementedError((str(type(self)) + ' does not implement get_weight_decay.'))
'Provides an expression for an L1 penalty on the weights. Parameters coeff : float or tuple The coefficient on the L1 weight decay penalty for this layer. This docstring is provided by the Layer base class. Individual Layer subclasses should add their own docstring explaining the format of `coeff` for that particular l...
def get_l1_weight_decay(self, coeff):
raise NotImplementedError((str(type(self)) + ' does not implement get_l1_weight_decay.'))
'Tells the layer to prepare for input formatted according to the given space. Parameters space : Space The Space the input to this layer will lie in. Notes This usually resets parameters.'
def set_input_space(self, space):
raise NotImplementedError((str(type(self)) + ' does not implement set_input_space.'))
'.. todo:: WRITEME'
def setup_rng(self):
assert (not self._nested), "Nested MLPs should use their parent's RNG" if (self.seed is None): self.seed = [2013, 1, 4] self.rng = np.random.RandomState(self.seed)
'Tells each layer what its input space should be. Notes This usually resets the layer\'s parameters!'
def _update_layer_input_spaces(self):
layers = self.layers try: layers[0].set_input_space(self.get_input_space()) except BadInputSpaceError as e: raise TypeError((((((((((('Layer 0 (' + str(layers[0])) + ' of type ') + str(type(layers[0]))) + ") does not support the MLP's ") + 'specified input...
'Add new layers on top of the existing hidden layers Parameters layers : WRITEME'
def add_layers(self, layers):
existing_layers = self.layers assert (len(existing_layers) > 0) for layer in layers: assert (layer.get_mlp() is None) layer.set_mlp(self) if ((not self._nested) or hasattr(self, 'input_space')): layer.set_input_space(existing_layers[(-1)].get_output_space()) exist...
'Freezes some of the parameters (new theano functions that implement learning will not use them; existing theano functions will continue to modify them). Parameters parameter_set : set Set of parameters to freeze.'
def freeze(self, parameter_set):
self.freeze_set = self.freeze_set.union(parameter_set)
'Returns data specs requiring both inputs and targets. Returns data_specs: TODO The data specifications for both inputs and targets.'
def get_monitoring_data_specs(self):
if (not self.monitor_targets): return (self.get_input_space(), self.get_input_source()) space = CompositeSpace((self.get_input_space(), self.get_target_space())) source = (self.get_input_source(), self.get_target_source()) return (space, source)
'Returns the output of the MLP, when applying dropout to the input and intermediate layers. Parameters state_below : WRITEME The input to the MLP default_input_include_prob : WRITEME input_include_probs : WRITEME default_input_scale : WRITEME input_scales : WRITEME per_example : bool, optional Sample a different mask v...
def dropout_fprop(self, state_below, default_input_include_prob=0.5, input_include_probs=None, default_input_scale=2.0, input_scales=None, per_example=True):
if (input_include_probs is None): input_include_probs = {} if (input_scales is None): input_scales = {} self._validate_layer_names(list(input_include_probs.keys())) self._validate_layer_names(list(input_scales.keys())) theano_rng = MRG_RandomStreams(max(self.rng.randint((2 ** 15)), 1...
'Forward propagate through the network with a dropout mask determined by an integer (the binary representation of which is used to generate the mask). Parameters state_below : tensor_like The (symbolic) output state of the layer below. mask : int An integer indexing possible binary masks. It should be < 2 ** get_total_...
def masked_fprop(self, state_below, mask, masked_input_layers=None, default_input_scale=2.0, input_scales=None):
if (input_scales is not None): self._validate_layer_names(input_scales) else: input_scales = {} if any(((n not in masked_input_layers) for n in input_scales)): layers = [n for n in input_scales if (n not in masked_input_layers)] raise ValueError(('input scales provided ...
'.. todo:: WRITEME'
def _validate_layer_names(self, layers):
if any(((layer not in self.layer_names) for layer in layers)): unknown_names = [layer for layer in layers if (layer not in self.layer_names)] raise ValueError(('MLP has no layer(s) named %s' % ', '.join(unknown_names)))
'Get the total number of inputs to the layers whose names are listed in `layers`. Used for computing the total number of dropout masks. Parameters layers : WRITEME Returns WRITEME'
def get_total_input_dimension(self, layers):
self._validate_layer_names(layers) total = 0 for layer in self.layers: if (layer.layer_name in layers): total += layer.get_input_space().get_total_dimension() return total
'.. todo:: WRITEME Parameters state: WRITEME include_prob : WRITEME scale : WRITEME theano_rng : WRITEME input_space : WRITEME mask_value : WRITEME per_example : bool, optional Sample a different mask value for every example in a batch. Defaults to `True`. If `False`, sample one mask per mini-batch.'
def apply_dropout(self, state, include_prob, scale, theano_rng, input_space, mask_value=0, per_example=True):
if (include_prob in [None, 1.0, 1]): return state assert (scale is not None) if isinstance(state, tuple): return tuple((self.apply_dropout(substate, include_prob, scale, theano_rng, mask_value) for substate in state)) if per_example: mask = theano_rng.binomial(p=include_prob, siz...
'Computes self.cost, but takes data=(X, Y) rather than Y_hat as an argument. This is just a wrapper around self.cost that computes Y_hat by calling Y_hat = self.fprop(X) Parameters data : WRITEME'
def cost_from_X(self, data):
self.cost_from_X_data_specs()[0].validate(data) (X, Y) = data Y_hat = self.fprop(X) return self.cost(Y, Y_hat)
'Returns the data specs needed by cost_from_X. This is useful if cost_from_X is used in a MethodCost.'
def cost_from_X_data_specs(self):
space = CompositeSpace((self.get_input_space(), self.get_target_space())) source = (self.get_input_source(), self.get_target_source()) return (space, source)
'Summarizes the MLP by printing the size and format of the input to all layers. Feel free to add reasonably concise info as needed.'
def __str__(self):
rval = [] for layer in self.layers: rval.append(layer.layer_name) input_space = layer.get_input_space() rval.append((' DCTB Input space: ' + str(input_space))) rval.append((' DCTB Total input dimension: ' + str(input_space.get_total_dimension()))) rval = '\n'.j...
'.. todo:: WRITEME'
@wraps(Layer.set_biases) def set_biases(self, biases):
self.b.set_value(biases)
'.. todo:: WRITEME'
@wraps(Layer.get_biases) def get_biases(self):
return self.b.get_value()
'Parameters state_below : member of input_space Returns output : theano matrix Affine transformation of state_below'
def _linear_part(self, state_below):
self.input_space.validate(state_below) if self.requires_reformat: state_below = self.input_space.format_as(state_below, self.desired_space) z = self.transformer.lmul(state_below) if self.use_bias: z += self.b if (self.layer_name is not None): z.name = (self.layer_name + '_z')...
'Returns a batch (vector) of mean across units of KL divergence for each example. Parameters Y : theano.gof.Variable Targets Y_hat : theano.gof.Variable Output of `fprop` mean across units, mean across batch of KL divergence Notes Uses KL(P || Q) where P is defined by Y and Q is defined by Y_hat Currently Y must be pur...
@wraps(Layer.cost) def cost(self, Y, Y_hat):
total = self.kl(Y=Y, Y_hat=Y_hat) ave = total.mean() return ave
'Computes the KL divergence. Parameters Y : Variable targets for the sigmoid outputs. Currently Y must be purely binary. If it\'s not, you\'ll still get the right gradient, but the value in the monitoring channel will be wrong. Y_hat : Variable predictions made by the sigmoid layer. Y_hat must be generated by fprop, i....
def kl(self, Y, Y_hat):
batch_axis = self.output_space.get_batch_axis() div = kl(Y=Y, Y_hat=Y_hat, batch_axis=batch_axis) return div
'Returns monitoring channels when using the layer to do detection of binary events. Parameters state : theano.gof.Variable Output of `fprop` target : theano.gof.Variable The targets from the dataset Returns channels : OrderedDict Dictionary mapping channel names to Theano channel values.'
def get_detection_channels_from_state(self, state, target):
rval = OrderedDict() y_hat = (state > 0.5) y = (target > 0.5) wrong_bit = T.cast(T.neq(y, y_hat), state.dtype) rval['01_loss'] = wrong_bit.mean() rval['kl'] = self.cost(Y_hat=state, Y=target) y = T.cast(y, state.dtype) y_hat = T.cast(y_hat, state.dtype) tp = (y * y_hat).sum() fp ...
'Applies the nonlinearity over the convolutional layer. Parameters linear_response: Variable linear response of the layer. Returns p: Variable the response of the layer after the activation function is applied over.'
def apply(self, linear_response):
p = linear_response return p
'Computes the monitoring channels which does not require targets. Parameters state : member of self.output_space A minibatch of states that this Layer took on during fprop. Provided externally so that we don\'t need to make a second expression for it. This helps keep the Theano graph smaller so that function compilatio...
def _get_monitoring_channels_for_activations(self, state):
rval = OrderedDict({}) mx = state.max(axis=0) mean = state.mean(axis=0) mn = state.min(axis=0) rg = (mx - mn) rval['range_x_max_u'] = rg.max() rval['range_x_mean_u'] = rg.mean() rval['range_x_min_u'] = rg.min() rval['max_x_max_u'] = mx.max() rval['max_x_mean_u'] = mx.mean() r...
'Override the default get_monitoring_channels_from_state function. Parameters state : member of self.output_space A minibatch of states that this Layer took on during fprop. Provided externally so that we don\'t need to make a second expression for it. This helps keep the Theano graph smaller so that function compilati...
def get_monitoring_channels_from_state(self, state, target, cost_fn=None):
rval = self._get_monitoring_channels_for_activations(state) return rval
'The cost of outputting Y_hat when the true output is Y. Parameters Y : theano.gof.Variable Output of `fprop` Y_hat : theano.gof.Variable Targets batch_axis : integer axis representing batch dimension Returns cost : theano.gof.Variable 0-D tensor describing the cost'
def cost(self, Y, Y_hat, batch_axis):
raise NotImplementedError((str(type(self)) + ' does not implement cost function.'))
'Notes Mean squared error across examples in a batch'
@wraps(ConvNonlinearity.cost, append=True) def cost(self, Y, Y_hat, batch_axis):
return T.sum(T.mean(T.sqr((Y - Y_hat)), axis=batch_axis))
'Parameters left_slope : float, optional left slope for the linear response of the rectifier function. default is 0.0.'
def __init__(self, left_slope=0.0):
self.non_lin_name = 'rectifier' self.left_slope = left_slope
'Applies the rectifier nonlinearity over the convolutional layer.'
@wraps(ConvNonlinearity.apply) def apply(self, linear_response):
p = ((linear_response * (linear_response > 0.0)) + ((self.left_slope * linear_response) * (linear_response < 0.0))) return p
'Applies the sigmoid nonlinearity over the convolutional layer.'
@wraps(ConvNonlinearity.apply) def apply(self, linear_response):
p = T.nnet.sigmoid(linear_response) return p
'Notes Cost mean across units, mean across batch of KL divergence KL(P || Q) where P is defined by Y and Q is defined by Y_hat KL(P || Q) = p log p - p log q + (1-p) log (1-p) - (1-p) log (1-q)'
@wraps(ConvNonlinearity.cost, append=True) def cost(self, Y, Y_hat, batch_axis):
ave_total = kl(Y=Y, Y_hat=Y_hat, batch_axis=batch_axis) ave = ave_total.mean() return ave
'Applies the tanh nonlinearity over the convolutional layer.'
@wraps(ConvNonlinearity.apply) def apply(self, linear_response):
p = T.tanh(linear_response) return p
'This function initializes the transformer of the class. Re-running this function will reset the transformer. Parameters rng : object random number generator object.'
def initialize_transformer(self, rng):
if (self.irange is not None): assert (self.sparse_init is None) self.transformer = conv2d.make_random_conv2D(irange=self.irange, input_space=self.input_space, output_space=self.detector_space, kernel_shape=self.kernel_shape, subsample=self.kernel_stride, border_mode=self.border_mode, rng=rng) el...
'Initializes the output space of the ConvElemwise layer by taking pooling operator and the hyperparameters of the convolutional layer into consideration as well.'
def initialize_output_space(self):
dummy_batch_size = self.mlp.batch_size if (dummy_batch_size is None): dummy_batch_size = 2 dummy_detector = sharedX(self.detector_space.get_origin_batch(dummy_batch_size)) if (self.pool_type is not None): assert (self.pool_type in ['max', 'mean']) if (self.pool_type == 'max'): ...
'Note: this function will reset the parameters!'
@wraps(Layer.set_input_space) def set_input_space(self, space):
self.input_space = space if (not isinstance(space, Conv2DSpace)): raise BadInputSpaceError(((((self.__class__.__name__ + '.set_input_space expected a Conv2DSpace, got ') + str(space)) + ' of type ') + str(type(space)))) rng = self.mlp.rng if (self.border_mode == 'valid'):...
'Notes The cost method calls `self.nonlin.cost`'
@wraps(Layer.cost, append=True) def cost(self, Y, Y_hat):
batch_axis = self.output_space.get_batch_axis() return self.nonlin.cost(Y=Y, Y_hat=Y_hat, batch_axis=batch_axis)
'Provides an expression for a squared L2 penalty on the weights, which is the weighted sum of the squared L2 penalties of the layer components. Parameters coeff : float or tuple/list The coefficient on the squared L2 weight decay penalty for this layer. If a single value is provided, this coefficient is used for each c...
def get_weight_decay(self, coeff):
return self._weight_decay_aggregate('get_weight_decay', coeff)
'Provides an expression for a squared L1 penalty on the weights, which is the weighted sum of the squared L1 penalties of the layer components. Parameters coeff : float or tuple/list The coefficient on the L1 weight decay penalty for this layer. If a single value is provided, this coefficient is used for each component...
def get_l1_weight_decay(self, coeff):
return self._weight_decay_aggregate('get_l1_weight_decay', coeff)
'Compute the PCA transformation matrix. Given a rectangular matrix :math:`X = USV` such that :math:`S` is a diagonal matrix with :math:`X`\'s singular values along its diagonal, returns :math:`W = V^{-1}`. If mean is provided, :math:`X` will not be centered first. Parameters X : numpy.ndarray Matrix of shape (n, d) on ...
def train(self, X, mean=None):
if (self.num_components is None): self.num_components = X.shape[1] if (mean is None): mean = X.mean(axis=0) X = (X - mean) (v, W) = self._cov_eigen(X) self.W = sharedX(W, name='W') self.v = sharedX(v, name='v') self.mean = sharedX(mean, name='mean') self._update_cutof...
'Compute and return the PCA transformation of the current data. Parameters inputs : numpy.ndarray Matrix of shape (n, d) on which to compute PCA Returns WRITEME'
def __call__(self, inputs):
self._update_cutoff() normalized_mean = (inputs - self.mean) normalized_mean.name = 'normalized_mean' W = self.W[:, :self.component_cutoff] if self.whiten: W = (W / tensor.sqrt(self.v[:self.component_cutoff])) Y = tensor.dot(normalized_mean, W) return Y
'Compute and return the matrix one should multiply with to get the PCA/whitened data Returns WRITEME'
def get_weights(self):
self._update_cutoff() component_cutoff = self.component_cutoff.get_value() W = self.W.get_value(borrow=False) W = W[:, :component_cutoff] if self.whiten: W /= N.sqrt(self.v.get_value(borrow=False)[:component_cutoff]) return W
'Given a PCA transformation of the current data, compute and return the reconstruction of the original input Parameters inputs : WRITEME add_mean : bool, optional WRITEME Returns WRITEME'
def reconstruct(self, inputs, add_mean=True):
self._update_cutoff() if self.whiten: inputs *= tensor.sqrt(self.v[:self.component_cutoff]) X = tensor.dot(inputs, self.W[:, :self.component_cutoff].T) if add_mean: X = (X + self.mean) return X
'Update component cutoff shared var, based on current parameters.'
def _update_cutoff(self):
assert ((self.num_components is not None) and (self.num_components > 0)), 'Number of components requested must be >= 1' v = self.v.get_value(borrow=True) var_mask = ((v / v.sum()) > self.min_variance) assert numpy.any(var_mask), 'No components exceed the given min. ...