desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Reconstruction of input x. Parameters inputs : tuple Tuple (lenght 2) of theano symbolic representing the input minibatch(es) to be encoded. Assumed to be 2-tensors, with the first dimension indexing training examples and the second indexing the two data dimensions (X, Y).'
def reconstructX(self, inputs):
if (self.act_dec is None): act_dec = (lambda x: x) else: act_dec = self.act_dec return act_dec(self.decodeX(inputs))
'Reconstruction of input y. Parameters inputs : tuple Tuple (lenght 2) of theano symbolic representing the input minibatch(es) to be encoded. Assumed to be 2-tensors, with the first dimension indexing training examples and the second indexing the two data dimensions (X, Y).'
def reconstructY(self, inputs):
if (self.act_dec is None): act_dec = (lambda x: x) else: act_dec = self.act_dec return act_dec(self.decodeY(inputs))
'Reconstruction of both datasets. Parameters inputs : tuple Tuple (lenght 2) of theano symbolic representing the input minibatch(es) to be encoded. Assumed to be 2-tensors, with the first dimension indexing training examples and the second indexing the two data dimensions (X, Y). Returns Reconstruction: tuple Tuple (l...
def reconstructXY(self, inputs):
return (self.reconstructX(inputs), self.reconstructY(inputs))
'This just aliases the `_hidden_activation()` function for syntactic sugar/convenience.'
def __call__(self, inputs):
return self._hidden_activation(inputs)
'The filters have to be normalized in each update to increase their stability.'
@wraps(GatedAutoencoder._modify_updates) def _modify_updates(self, updates):
wxf = self.wxf wyf = self.wyf wxf_updated = updates[wxf] wyf_updated = updates[wyf] nwxf = (wxf_updated.std(0) + SMALL)[numpy.newaxis, :] nwyf = (wyf_updated.std(0) + SMALL)[numpy.newaxis, :] meannxf = nwxf.mean() meannyf = nwyf.mean() centered_wxf = (wxf_updated - wxf_updated.mean(0...
'Returns a topological view of the weights, the first half corresponds to wxf and the second half to wyf. Returns weights : ndarray Same as the return value of `get_weights` but formatted as a 4D tensor with the axes being (hidden/factor units, rows, columns, channels).The the number of channels is either 1 or 3 (becau...
def get_weights_topo(self):
if ((not isinstance(self.input_space.components[0], Conv2DSpace)) or (not isinstance(self.input_space.components[1], Conv2DSpace))): raise NotImplementedError() wxf = self.wxf.get_value(borrow=False).T wyf = self.wyf.get_value(borrow=False).T convx = self.input_space.components[0] convy = se...
'Reconstruction of both datasets. Parameters inputs : tuple Tuple (lenght 2) of theano symbolic representing the input minibatch(es) to be encoded. Assumed to be 2-tensors, with the first dimension indexing training examples and the second indexing the two data dimensions (X, Y). Returns Reconstruction: tuple Tuple (l...
def reconstructXY(self, inputs):
corrupted = self.corruptor(inputs) return (self.reconstructX(corrupted), self.reconstructY(corrupted))
'Method that returns the reconstruction without noise Parameters inputs : tuple Tuple (lenght 2) of theano symbolic representing the input minibatch(es) to be encoded. Assumed to be 2-tensors, with the first dimension indexing training examples and the second indexing the two data dimensions (X, Y). Returns Reconstruc...
def reconstructXY_NoiseFree(self, inputs):
return (self.reconstructX(inputs), self.reconstructY(inputs))
'.. todo:: WRITEME'
def redo_everything(self):
self.beta = sharedX((np.ones((self.nvis,)) * self.init_beta), 'beta') self.mu = sharedX((np.ones((self.nvis,)) * self.init_mu), 'mu') self.redo_theano()
'.. todo:: WRITEME'
def free_energy(self, X):
diff = (X - self.mu) sq = T.sqr(diff) return (0.5 * T.dot(sq, self.beta))
'.. todo:: WRITEME'
def log_prob(self, X):
return ((- self.free_energy(X)) - self.log_partition_function())
'.. todo:: WRITEME'
def log_partition_function(self):
return (((float(self.nvis) / 2.0) * np.log((2 * np.pi))) - (0.5 * T.sum(T.log(self.beta))))
'.. todo:: WRITEME'
def redo_theano(self):
init_names = dir(self) self.censored_updates = {} for param in self.get_params(): self.censored_updates[param] = set([]) final_names = dir(self) self.register_names_to_del([name for name in final_names if (name not in init_names)])
'.. todo:: WRITEME'
def _modify_updates(self, updates):
if ((self.beta in updates) and (updates[self.beta] not in self.censored_updates[self.beta])): updates[self.beta] = T.clip(updates[self.beta], self.min_beta, self.max_beta) params = self.get_params() for param in updates: if (param in params): self.censored_updates[param] = self.c...
'.. todo:: WRITEME'
def get_params(self):
return [self.mu, self.beta]
'Returns the log probability of a batch of examples. Parameters X : WRITEME The examples whose log probability should be computed. Returns log_prob : WRITEME The log probability of the examples.'
def log_prob(self, X):
return ((- self.ebm.free_energy(X)) - (self.logZ_driver * self.logZ_lr_scale))
'Returns the free energy of a batch of examples. Parameters X : WRITEME The examples whose free energy should be computed. Returns free_energy : WRITEME The free energy of the examples.'
def free_energy(self, X):
return self.ebm.free_energy(X)
'Returns a SufficientStatistics .. todo:: WRITEME properly Parameters needed_stats : WRITEME a set of string names of the statistics to include V : WRITEME a num_examples x nvis matrix of input examples H_hat : WRITEME a num_examples x nhid matrix of \hat{h} variational parameters S_hat : WRITEME variational parameters...
@classmethod def from_observations(cls, needed_stats, V, H_hat, S_hat, var_s0_hat, var_s1_hat):
m = T.cast(V.shape[0], config.floatX) H_name = make_name(H_hat, 'anon_H_hat') S_name = make_name(S_hat, 'anon_S_hat') assert (H_hat.dtype == config.floatX) mean_h = T.mean(H_hat, axis=0) assert (H_hat.dtype == mean_h.dtype) assert (mean_h.dtype == config.floatX) mean_h.name = (('mean_h('...
'.. todo:: WRITEME'
def reset_rng(self):
self.rng = make_np_rng(self.seed, [1, 2, 3], which_method='uniform')
'.. todo:: WRITEME'
def redo_everything(self):
if (self.init_W is not None): W = self.init_W.copy() else: W = self.rng.uniform((- self.irange), self.irange, (self.nvis, self.nhid)) if (self.constrain_W_norm or self.init_unit_W): norms = numpy_norms(W) W /= norms self.W = sharedX(W, name='W') self.bias_hid = shared...
'.. todo:: WRITEME'
@classmethod def energy_functional_needed_stats(cls):
return S3C.expected_log_prob_vhs_needed_stats()
'.. todo:: WRITEME Returns the energy_functional for a single batch of data stats is assumed to be computed from and only from the same data points that yielded H'
def energy_functional(self, H_hat, S_hat, var_s0_hat, var_s1_hat, stats):
entropy_term = self.entropy_hs(H_hat=H_hat, var_s0_hat=var_s0_hat, var_s1_hat=var_s1_hat).mean() likelihood_term = self.expected_log_prob_vhs(stats, H_hat=H_hat, S_hat=S_hat) energy_functional = (likelihood_term + entropy_term) assert (len(energy_functional.type.broadcastable) == 0) return energy_fu...
'.. todo:: WRITEME Returns the energy_functional for a single batch of data stats is assumed to be computed from and only from the same data points that yielded H'
def energy_functional_batch(self, V, H_hat, S_hat, var_s0_hat, var_s1_hat):
entropy_term = self.entropy_hs(H_hat=H_hat, var_s0_hat=var_s0_hat, var_s1_hat=var_s1_hat) assert (len(entropy_term.type.broadcastable) == 1) likelihood_term = self.expected_log_prob_vhs_batch(V=V, H_hat=H_hat, S_hat=S_hat, var_s0_hat=var_s0_hat, var_s1_hat=var_s1_hat) assert (len(likelihood_term.type.br...
'.. todo:: WRITEME'
def set_monitoring_channel_prefix(self, prefix):
self.monitoring_channel_prefix = prefix
'.. todo:: WRITEME'
def get_monitoring_channels(self, data):
(space, source) = self.get_monitoring_data_specs() space.validate(data) V = data try: self.compile_mode() if (self.m_step != None): rval = self.m_step.get_monitoring_channels(V, self) else: rval = {} if (self.momentum_saturation_example is not None...
'Get the data_specs describing the data for get_monitoring_channel. This implementation returns specification corresponding to unlabeled inputs. WRITEME: Returns section'
def get_monitoring_data_specs(self):
return (self.get_input_space(), self.get_input_source())
'.. todo:: WRITEME This is the symbolic transformation for the Block class'
def __call__(self, V):
if (not hasattr(self, 'w')): self.make_pseudoparams() obs = self.infer(V) return obs['H_hat']
'If any shared variables need to have batch-size dependent sizes, sets them all to the sizes used for interactive debugging during graph construction'
def compile_mode(self):
if self.recycle_q: self.prev_H.set_value(np.cast[self.prev_H.dtype]((np.zeros((self._test_batch_size, self.nhid)) + (1.0 / (1.0 + np.exp((- self.bias_hid.get_value()))))))) self.prev_S.set_value(np.cast[self.prev_S.dtype]((np.zeros((self._test_batch_size, self.nhid)) + self.mu.get_value())))
'If any shared variables need to have batch-size dependent sizes, sets them all to their runtime sizes'
def deploy_mode(self):
if self.recycle_q: self.prev_H.set_value(np.cast[self.prev_H.dtype]((np.zeros((self.recycle_q, self.nhid)) + (1.0 / (1.0 + np.exp((- self.bias_hid.get_value()))))))) self.prev_S.set_value(np.cast[self.prev_S.dtype]((np.zeros((self.recycle_q, self.nhid)) + self.mu.get_value())))
'.. todo:: WRITEME'
def get_params(self):
return [self.W, self.bias_hid, self.alpha, self.mu, self.B_driver]
'.. todo:: WRITEME H MUST be binary'
def energy_vhs(self, V, H, S):
h_term = (- T.dot(H, self.bias_hid)) assert (len(h_term.type.broadcastable) == 1) s_term_1 = (T.dot(T.sqr(S), self.alpha) / 2.0) s_term_2 = (- T.dot(((S * self.mu) * H), self.alpha)) s_term_3 = (T.dot((T.sqr(self.mu) * H), self.alpha) / 2.0) s_term = ((s_term_1 + s_term_2) + s_term_3) assert...
'.. todo:: WRITEME This is not the same as negative expected log prob, which includes the constant term for the log partition function'
def expected_energy_vhs(self, V, H_hat, S_hat, var_s0_hat, var_s1_hat):
var_HS = ((H_hat * var_s1_hat) + ((1.0 - H_hat) * var_s0_hat)) half = as_floatX(0.5) HS = (H_hat * S_hat) sq_HS = (H_hat * (var_s1_hat + T.sqr(S_hat))) sq_S = (sq_HS + ((1.0 - H_hat) * var_s0_hat)) presign = T.dot(H_hat, self.bias_hid) presign.name = 'presign' h_term = (- presign) as...
'.. todo:: WRITEME'
def entropy_h(self, H_hat):
for H_hat_v in get_debug_values(H_hat): assert (H_hat_v.min() >= 0.0) assert (H_hat_v.max() <= 1.0) return entropy_binary_vector(H_hat)
'.. todo:: WRITEME'
def entropy_hs(self, H_hat, var_s0_hat, var_s1_hat):
half = as_floatX(0.5) one = as_floatX(1.0) two = as_floatX(2.0) pi = as_floatX(np.pi) for H_hat_v in get_debug_values(H_hat): assert (H_hat_v.min() >= 0.0) assert (H_hat_v.max() <= 1.0) term1_plus_term2 = self.entropy_h(H_hat) assert (len(term1_plus_term2.type.broadcastable) ...
'.. todo:: WRITEME'
def infer(self, V, return_history=False):
return self.e_step.infer(V, return_history)
'WRITEME Parameters V : tensor_like A symbolic design matrix WRITEME: Returns section'
def make_learn_func(self, V):
hidden_obs = self.infer(V) stats = SufficientStatistics.from_observations(needed_stats=self.m_step.needed_stats(), V=V, **hidden_obs) H_hat = hidden_obs['H_hat'] S_hat = hidden_obs['S_hat'] learning_updates = self.m_step.get_updates(self, stats, H_hat, S_hat) if self.recycle_q: learning_...
'.. todo:: WRITEME'
def _modify_updates(self, updates):
assert (self.bias_hid in self.censored_updates) def should_censor(param): return ((param in updates) and (updates[param] not in self.censored_updates[param])) if should_censor(self.W): if self.disable_W_update: del updates[self.W] elif self.constrain_W_norm: n...
'.. todo:: WRITEME Parameters H_sample: a matrix of values of H, optional if none is provided, samples one from the prior (H_sample is used if you want to see what samples due to specific hidden units look like, or when sampling from a larger model that s3c is part of)'
def random_design_matrix(self, batch_size, theano_rng=None, H_sample=None, S_sample=None, full_sample=True, return_all=False):
if (theano_rng is None): assert (H_sample is not None) assert (S_sample is not None) assert (full_sample == False) if (not hasattr(self, 'p')): self.make_pseudoparams() hid_shape = (batch_size, self.nhid) if (H_sample is None): H_sample = theano_rng.binomial(size=...
'.. todo:: WRITEME'
@classmethod def expected_log_prob_vhs_needed_stats(cls):
h = S3C.expected_log_prob_h_needed_stats() s = S3C.expected_log_prob_s_given_h_needed_stats() v = S3C.expected_log_prob_v_given_hs_needed_stats() union = h.union(s).union(v) return union
'.. todo:: WRITEME'
def expected_log_prob_vhs(self, stats, H_hat, S_hat):
expected_log_prob_v_given_hs = self.expected_log_prob_v_given_hs(stats, H_hat=H_hat, S_hat=S_hat) expected_log_prob_s_given_h = self.expected_log_prob_s_given_h(stats) expected_log_prob_h = self.expected_log_prob_h(stats) rval = ((expected_log_prob_v_given_hs + expected_log_prob_s_given_h) + expected_lo...
'.. todo:: WRITEME'
def log_partition_function(self):
half = as_floatX(0.5) two = as_floatX(2.0) pi = as_floatX(np.pi) N = as_floatX(self.nhid) term1 = ((- half) * T.sum(T.log(self.B))) term2 = ((half * N) * T.log((two * pi))) term3 = ((- half) * T.log(self.alpha).sum()) term4 = ((half * N) * T.log((two * pi))) term5 = T.nnet.softplus(s...
'.. todo:: WRITEME'
def expected_log_prob_vhs_batch(self, V, H_hat, S_hat, var_s0_hat, var_s1_hat):
half = as_floatX(0.5) two = as_floatX(2.0) pi = as_floatX(np.pi) N = as_floatX(self.nhid) negative_log_partition_function = (- self.log_partition_function()) assert (len(negative_log_partition_function.type.broadcastable) == 0) negative_energy = (- self.expected_energy_vhs(V=V, H_hat=H_hat, ...
'V, H, S are SAMPLES (i.e., H must be LITERALLY BINARY) Return value is a vector, of length batch size Parameters V : WRITEME H : WRITEME S : WRITEME Returns WRITEME'
def log_prob_v_given_hs(self, V, H, S):
half = as_floatX(0.5) two = as_floatX(2.0) pi = as_floatX(np.pi) N = as_floatX(self.nhid) term1 = (half * T.sum(T.log(self.B))) term2 = (((- half) * N) * T.log((two * pi))) mean_HS = (H * S) recons = T.dot((H * S), self.W.T) residuals = (V - recons) term3 = ((- half) * T.dot(T.sq...
'.. todo:: WRITEME'
@classmethod def expected_log_prob_v_given_hs_needed_stats(cls):
return set(['mean_sq_v', 'mean_hsv', 'mean_sq_hs', 'mean_sq_mean_hs'])
'Return value is a SCALAR-- expectation taken across batch index too Parameters stats : WRITEME H_hat : WRITEME S_hat : WRITEME Returns WRITEME'
def expected_log_prob_v_given_hs(self, stats, H_hat, S_hat):
'\n E_v,h,s \\sim Q log P( v | h, s)\n = sum_k [ E_v,h,s \\sim Q log sqrt(B/2 pi) exp( - 0.5 B (v- W[v,:] (h*s) )^2) ]\n = sum_k [...
'.. todo:: WRITEME'
@classmethod def expected_log_prob_s_given_h_needed_stats(cls):
return set(['mean_h', 'mean_hs', 'mean_sq_s'])
'.. todo:: WRITEME E_h,s\sim Q log P(s|h) = E_h,s\sim Q log sqrt( alpha / 2pi) exp(- 0.5 alpha (s-mu h)^2) = E_h,s\sim Q log sqrt( alpha / 2pi) - 0.5 alpha (s-mu h)^2 = E_h,s\sim Q 0.5 log alpha - 0.5 log 2 pi - 0.5 alpha s^2 + alpha s mu h + 0.5 alpha mu^2 h^2 = E_h,s\sim Q 0.5 log alpha - 0.5 log 2 pi - 0.5 alpha s^...
def expected_log_prob_s_given_h(self, stats):
mean_h = stats.d['mean_h'] mean_sq_s = stats.d['mean_sq_s'] mean_hs = stats.d['mean_hs'] half = as_floatX(0.5) two = as_floatX(2.0) N = as_floatX(self.nhid) pi = as_floatX(np.pi) term1 = (half * T.log(self.alpha).sum()) term2 = (((- half) * N) * T.log((two * pi))) term3 = ((- hal...
'.. todo:: WRITEME'
@classmethod def expected_log_prob_h_needed_stats(cls):
return set(['mean_h'])
'Returns the expected log probability of the vector h under the model when the data is drawn according to stats: E_h\sim Q log P(h) = E_h\sim Q log exp( bh) / (1+exp(b)) = E_h\sim Q bh - softplus(b) Parameters stats : WRITEME Returns WRITEME'
def expected_log_prob_h(self, stats):
mean_h = stats.d['mean_h'] term1 = T.dot(self.bias_hid, mean_h) term2 = (- T.nnet.softplus(self.bias_hid).sum()) rval = (term1 + term2) assert (len(rval.type.broadcastable) == 0) return rval
'.. todo:: WRITEME'
def make_pseudoparams(self):
if self.tied_B: self.B = (self.B_driver + as_floatX(np.zeros(self.nvis))) self.B.name = 'S3C.tied_B' else: self.B = self.B_driver self.w = T.dot(self.B, T.sqr(self.W)) self.w.name = 'S3C.w' self.p = T.nnet.sigmoid(self.bias_hid) self.p.name = 'S3C.p'
'.. todo:: WRITEME'
def reset_censorship_cache(self):
self.censored_updates = {} self.register_names_to_del(['censored_updates']) for param in self.get_params(): self.censored_updates[param] = set([])
'.. todo:: WRITEME'
def redo_theano(self):
self.reset_censorship_cache() if (not self.autonomous): return try: self.compile_mode() init_names = dir(self) self.make_pseudoparams() self.e_step.register_model(self) self.get_B_value = function([], self.B) X = T.matrix(name='V') X.tag.test_v...
'.. todo:: WRITEME'
def train_batch(self, dataset, batch_size):
if self.set_B_to_marginal_precision: assert (not self.tied_B) var = dataset.X.var(axis=0) self.B_driver.set_value((1.0 / (var + 0.01))) if (self.stop_after_hack is not None): if (self.monitor.examples_seen > self.stop_after_hack): logger.error('stopping due to ...
'.. todo:: WRITEME'
def print_status(self):
b = self.bias_hid.get_value(borrow=True) assert (not contains_nan(b)) p = (1.0 / (1.0 + np.exp((- b)))) logger.info('p: ({0}, {1}, {2})'.format(p.min(), p.mean(), p.max())) B = self.B_driver.get_value(borrow=True) assert (not contains_nan(B)) logger.info('B: ({0}, {1}, {2})...
'.. todo:: WRITEME'
def learn_mini_batch(self, X):
self.learn_func(X) if (self.momentum_saturation_example is not None): alpha = (float(self.monitor.get_examples_seen()) / float(self.momentum_saturation_example)) alpha = min(alpha, 1.0) self.momentum.set_value(np.cast[config.floatX]((((1.0 - alpha) * self.init_momentum) + (alpha * self.f...
'.. todo:: WRITEME'
def get_weights_format(self):
return ['v', 'h']
'.. todo:: WRITEME'
def get_weights(self):
W = self.W.get_value() x = input('multiply weights by mu? (y/n) ') if (x == 'y'): return (W * self.mu.get_value()) elif (x == 'n'): return W assert False
'.. todo:: WRITEME'
def get_monitoring_channels(self, V):
rval = {} if self.autonomous: if (self.monitor_kl or self.monitor_energy_functional or self.monitor_s_mag or self.monitor_ranges): obs_history = self.model.infer(V, return_history=True) assert isinstance(obs_history, list) final_vals = obs_history[(-1)] S_...
'Return value is a scalar Parameters V : WRITEME model : WRITEME obs : WRITEME Returns WRITEME'
def energy_functional(self, V, model, obs):
needed_stats = S3C.expected_log_prob_vhs_needed_stats() stats = SufficientStatistics.from_observations(needed_stats=needed_stats, V=V, **obs) H_hat = obs['H_hat'] S_hat = obs['S_hat'] var_s0_hat = obs['var_s0_hat'] var_s1_hat = obs['var_s1_hat'] entropy_term = model.entropy_hs(H_hat=H_hat, v...
'.. todo:: WRITEME'
def register_model(self, model):
self.model = model
'KL divergence between variation and true posterior, dropping terms that don\'t depend on the variational parameters Parameters V : WRITEME Y : WRITEME obs : WRITEME Returns WRITEME'
def truncated_KL(self, V, Y=None, obs=None):
assert (Y is None) assert (obs is not None) H_hat = obs['H_hat'] var_s0_hat = obs['var_s0_hat'] var_s1_hat = obs['var_s1_hat'] S_hat = obs['S_hat'] model = self.model for H_hat_v in get_debug_values(H_hat): assert (H_hat_v.min() >= 0.0) assert (H_hat_v.max() <= 1.0) e...
'.. todo:: WRITEME'
def init_H_hat(self, V):
if self.model.recycle_q: rval = self.model.prev_H if (config.compute_test_value != 'off'): if (rval.get_value().shape[0] != V.tag.test_value.shape[0]): raise Exception('E step given wrong test batch size', rval.get_value().shape, V.tag.test_value.shape) ...
'.. todo:: WRITEME'
def init_S_hat(self, V):
if self.model.recycle_q: rval = self.model.prev_S_hat else: value = self.model.mu assert (self.model.mu.get_value(borrow=True).shape[0] == self.model.nhid) rval = T.alloc(value, V.shape[0], value.shape[0]) return rval
'.. todo:: WRITEME'
def infer_S_hat(self, V, H_hat, S_hat):
for (Vv, Hv) in get_debug_values(V, H_hat): if (Vv.shape != (self.model._test_batch_size, self.model.nvis)): raise Exception((((('Well this is awkward. We require visible input test tags to be of shape ' + str((self.model._test_batch_size, self.model.nvi...
'.. todo:: WRITEME'
def infer_var_s0_hat(self):
return (1.0 / self.model.alpha)
'Returns the variational parameter for the variance of s given h=1. This is data-independent so its just a vector of size (nhid,) and doesn\'t take any arguments Returns WRITEME'
def infer_var_s1_hat(self):
rval = (1.0 / (self.model.alpha + self.model.w)) rval.name = 'var_s1' return rval
'Computes the value of H_hat prior to the application of the sigmoid function. This is a useful quantity to compute for larger models that influence h with top-down terms. Such models can apply the sigmoid themselves after adding the top-down interactions Parameters V : WRITEME H_hat : WRITEME S_hat : WRITEME Returns W...
def infer_H_hat_presigmoid(self, V, H_hat, S_hat):
half = as_floatX(0.5) alpha = self.model.alpha w = self.model.w mu = self.model.mu W = self.model.W B = self.model.B BW = (B.dimshuffle(0, 'x') * W) HS = (H_hat * S_hat) t1f1t1 = V t1f1t2 = (- T.dot(HS, W.T)) iterm_corrective = ((w * H_hat) * T.sqr(S_hat)) t1f1t3_effect =...
'.. todo:: WRITEME'
def infer_H_hat(self, V, H_hat, S_hat, count=None):
arg_to_sigmoid = self.infer_H_hat_presigmoid(V, H_hat, S_hat) H = T.nnet.sigmoid(arg_to_sigmoid) V_name = make_name(V, anon='anon_V') if (count is not None): H.name = ('H_hat(%s, %d)' % (V_name, count)) return H
'... todo:: WRITEME Parameters V : WRITEME return_history : bool If True, returns a list of dictionaries with showing the history of the variational parameters throughout fixed point updates If False, returns a dictionary containing the final variational parameters Returns WRITEME'
def infer(self, V, return_history=False):
if (not self.autonomous): raise ValueError('Non-autonomous model asked to perform inference on its own') alpha = self.model.alpha var_s0_hat = (1.0 / alpha) var_s1_hat = self.infer_var_s1_hat() H_hat = self.init_H_hat(V) S_hat = self.init_S_hat(V) def check_H(...
'.. todo:: WRITEME'
def __setstate__(self, d):
if ('autonomous' not in d): d['autonomous'] = True self.__dict__.update(d)
'.. todo:: WRITEME'
def get_updates(self, model, stats, H_hat, S_hat):
assert self.autonomous params = model.get_params() obj = (((model.expected_log_prob_vhs(stats, H_hat, S_hat) - (T.mean(model.p) * self.p_penalty)) - (T.mean(model.B) * self.B_penalty)) - (T.mean(model.alpha) * self.alpha_penalty)) constants = set(stats.d.values()).union([H_hat, S_hat]) grads = T.gra...
'.. todo:: WRITEME'
def needed_stats(self):
return S3C.expected_log_prob_vhs_needed_stats()
'.. todo:: WRITEME'
def get_monitoring_channels(self, V, model):
hid_observations = model.infer(V) stats = SufficientStatistics.from_observations(needed_stats=S3C.expected_log_prob_vhs_needed_stats(), V=V, **hid_observations) H_hat = hid_observations['H_hat'] S_hat = hid_observations['S_hat'] obj = model.expected_log_prob_vhs(stats, H_hat, S_hat) return {'exp...
'WRITEME Parameters V : WRITEME return_history : bool If True, returns a list of dictionaries with showing the history of the variational parameters throughout fixed point updates If False, returns a dictionary containing the final variational parameters Returns WRITEME'
def infer(self, V, return_history=False):
if (not self.autonomous): raise ValueError('Non-autonomous model asked to perform inference on its own') alpha = self.model.alpha var_s0_hat = (1.0 / alpha) var_s1_hat = self.infer_var_s1_hat() H_hat = self.init_H_hat(V) S_hat = self.init_S_hat(V) def inner_fu...
'Process kmeans algorithm on the input to localize clusters. Parameters dataset : WRITEME mu : WRITEME Returns rval : bool WRITEME'
def train_all(self, dataset, mu=None):
X = dataset.get_design_matrix() (n, m) = X.shape k = self.k if (milk is not None): (cluster_ids, mu) = milk.kmeans(X, k) else: if (mu is not None): if (not (len(mu) == k)): raise Exception(('You gave %i clusters, but k=%i were expected...
'.. todo:: WRITEME'
def get_params(self):
if (not hasattr(self.mu, 'get_value')): self.mu = sharedX(self.mu) if (not hasattr(self, '_params')): self._params = [self.mu] return [param for param in self._params]
'Compute for each sample its probability to belong to a cluster. Parameters X : numpy.ndarray Matrix of sampless of shape (n, d) Returns WRITEME'
def __call__(self, X):
(n, m) = X.shape k = self.k mu = self.mu dists = numpy.zeros((n, k)) for i in xrange(k): dists[:, i] = numpy.square((X - mu[i, :])).sum(axis=1) return (dists / dists.sum(axis=1).reshape((-1), 1))
'.. todo:: WRITEME'
def get_weights(self):
return self.mu
'.. todo:: WRITEME'
def get_weights_format(self):
return ['h', 'v']
'Don\'t let subclasses use censor_updates.'
def _disallow_censor_updates(self):
if self._overrides_censor_updates(): raise TypeError((str(type(self)) + ' overrides Model.censor_updates, which is no longer in use. Change this to _modify_updates. This check may quit being performed after 2015-05-13.'))
'Makes sure the model has an "extensions" field.'
def _ensure_extensions(self):
if (not hasattr(self, 'extensions')): raise TypeError((('The ' + str(type(self))) + ' Model subclass is required to call the Model superclass constructor but does not.')) self.extensions = []
'An implementation of __setstate__ that patches old pickle files.'
def __setstate__(self, d):
self._disallow_censor_updates() self.__dict__.update(d) if ('extensions' not in d): self.extensions = []
'Returns the default cost to use with this model. Returns default_cost : Cost The default cost to use with this model.'
def get_default_cost(self):
raise NotImplementedError((str(type(self)) + ' does not implement get_default_cost.'))
'If implemented, performs one epoch of training. Parameters dataset : pylearn2.datasets.dataset.Dataset Dataset object to draw training data from Notes This method is useful for models with highly specialized training algorithms for which is does not make much sense to factor the training code into a separate class. It...
def train_all(self, dataset):
raise NotImplementedError((str(type(self)) + ' does not implement train_all.'))
'If train_all is used to train the model, this method is used to determine when the training process has converged. This method is called after the monitor has been run on the latest parameters. Returns rval : bool True if training should continue'
def continue_learning(self):
raise NotImplementedError((str(type(self)) + ' does not implement continue_learning.'))
'If implemented, performs an update on a single minibatch. Parameters dataset: pylearn2.datasets.dataset.Dataset The object to draw training data from. batch_size: int Size of the minibatch to draw from dataset. Returns rval : bool True if the method should be called again for another update. False if convergence has b...
def train_batch(self, dataset, batch_size):
raise NotImplementedError()
'Returns the shape `PatchViewer` should use to display the weights. Returns shape : tuple A tuple containing two ints. These are used as the `grid_shape` argument to `PatchViewer` when displaying the weights of this model. Notes This can be useful when there is some geometric significance to the order of your weight ve...
def get_weights_view_shape(self):
raise NotImplementedError((str(type(self)) + ' does not implement get_weights_view_shape (perhaps by design)'))
'Get monitoring channels for this model. Parameters data : tensor_like, or (possibly nested) tuple of tensor_likes, This is data on which the monitoring quantities will be calculated (e.g., a validation set). See `self.get_monitoring_data_specs()`. Returns channels : OrderedDict A dictionary with strings as keys, mappi...
def get_monitoring_channels(self, data):
(space, source) = self.get_monitoring_data_specs() space.validate(data) return OrderedDict()
'Get the data_specs describing the data for get_monitoring_channels. This implementation returns an empty data_specs, appropriate for when no monitoring channels are defined, or when none of the channels actually need data (for instance, if they only monitor functions of the model\'s parameters). Returns data_specs : T...
def get_monitoring_data_specs(self):
return (NullSpace(), '')
'Sets the batch size used by the model. Parameters batch_size : int If None, allows the model to use any batch size.'
def set_batch_size(self, batch_size):
pass
'Returns the weights (of the first layer if more than one layer is present). Returns weights : ndarray Returns any matrix that is analogous to the weights of the first layer of an MLP, such as the dictionary of a sparse coding model. This implementation raises NotImplementedError. For models where this method is not co...
def get_weights(self):
raise NotImplementedError((str(type(self)) + ' does not implement get_weights (perhaps by design)'))
'Returns a description of how to interpret the return value of `get_weights`. Returns format : tuple Either (\'v\', \'h\') or (\'h\', \'v\'). (\'v\', \'h\') means self.get_weights returns a matrix of shape (num visible units, num hidden units), while (\'h\', \'v\') means it returns the transpose of this.'
def get_weights_format(self):
return ('v', 'h')
'Returns a topological view of the weights. Returns weights : ndarray Same as the return value of `get_weights` but formatted as a 4D tensor with the axes being (hidden units, rows, columns, channels). Only applicable for models where the weights can be viewed as 2D-multichannel, and the number of channels is either 1 ...
def get_weights_topo(self):
raise NotImplementedError((str(type(self)) + ' does not implement get_weights_topo (perhaps by design)'))
'Compute a "score function" for this model, 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 score(self, V):
return T.grad((- self.free_energy(V).sum()), V)
'Specify how to rescale the learning rate on each parameter. Returns lr_scalers : OrderedDict A dictionary mapping the parameters of the model to floats. The learning rate will be multiplied by the float for each parameter. If a parameter does not appear in the dictionary, it will use the global learning rate with no s...
def get_lr_scalers(self):
return OrderedDict()
'Returns true if the model overrides censor_updates. (It shouldn\'t do so because it\'s deprecated, and we have to take special action to handle this case)'
def _overrides_censor_updates(self):
return (type(self).censor_updates != Model.censor_updates)
'Deprecated method. Callers should call modify_updates instead. Subclasses should override _modify_updates instead. This method may be removed on or after 2015-05-25. Parameters updates : dict A dictionary mapping shared variables to symbolic values they will be updated to.'
def censor_updates(self, updates):
raise TypeError('Model.censor_updates has been replaced by Model.modify_updates.')
'Modifies the parameters before a learning update is applied. Behavior is defined by subclass\'s implementation of _modify_updates and any ModelExtension\'s implementation of post_modify_updates. Parameters updates : dict A dictionary mapping shared variables to symbolic values they will be updated to Notes For example...
def modify_updates(self, updates):
self._modify_updates(updates) self._ensure_extensions() for extension in self.extensions: extension.post_modify_updates(updates, self)
'Subclasses may override this method to add functionality to modify_updates. Parameters updates : dict A dictionary mapping shared variables to symbolic values they will be updated to.'
def _modify_updates(self, updates):
self._disallow_censor_updates()
'Returns an instance of pylearn2.space.Space describing the format of the vector space that the model operates on (this is a generalization of get_input_dim)'
def get_input_space(self):
return self.input_space