desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'.. todo::
WRITEME'
| def _get_positive_phase(self, model, X, Y=None):
| return (self._get_variational_pos(model, X, Y), OrderedDict())
|
'.. todo::
WRITEME
d/d theta log Z = (d/d theta Z) / Z
= (d/d theta sum_h sum_v exp(-E(v,h)) ) / Z
= (sum_h sum_v - exp(-E(v,h)) d/d theta E(v,h) ) / Z
= - sum_h sum_v P(v,h) d/d theta E(v,h)'
| def _get_negative_phase(self, model, X, Y=None):
| layer_to_chains = model.make_layer_to_state(self.num_chains)
def recurse_check(l):
if isinstance(l, (list, tuple)):
for elem in l:
recurse_check(elem)
else:
assert (l.get_value().shape[0] == self.num_chains)
recurse_check(layer_to_chains.values())
... |
''
| def __init__(self, num_chains, num_gibbs_steps, supervised=False):
| self.__dict__.update(locals())
del self.self
self.theano_rng = MRG_RandomStreams(((2012 + 10) + 14))
assert (supervised in [True, False])
|
'The partition function makes this intractable.
Parameters
model : Model
data : Batch in get_data_specs format
Returns
None : (always returns None because it\'s intractable)'
| def expr(self, model, data):
| if self.supervised:
(X, Y) = data
assert (Y is not None)
return None
|
'PCD approximation to the gradient of the bound.
Keep in mind this is a cost, so we are upper bounding
the negative log likelihood.
Parameters
model : DBM
data : Batch in get_data_specs_format
Returns
grads : OrderedDict
Dictionary mapping from parameters to (approximate) gradients
updates : OrderedDict
Dictionary cont... | def get_gradients(self, model, data):
| if self.supervised:
(X, Y) = data
assert (Y is not None)
assert isinstance(model.hidden_layers[(-1)], dbm.Softmax)
else:
X = data
Y = None
q = model.mf(X, Y)
'\n Use the non-negativity of the KL divergence to ... |
'.. todo::
WRITEME'
| def _get_positive_phase(self, model, X, Y=None):
| return (self._get_variational_pos(model, X, Y), OrderedDict())
|
'.. todo::
WRITEME
d/d theta log Z = (d/d theta Z) / Z
= (d/d theta sum_h sum_v exp(-E(v,h)) ) / Z
= (sum_h sum_v - exp(-E(v,h)) d/d theta E(v,h) ) / Z
= - sum_h sum_v P(v,h) d/d theta E(v,h)'
| def _get_negative_phase(self, model, X, Y=None):
| layer_to_clamp = OrderedDict([(model.visible_layer, True)])
layer_to_chains = model.make_layer_to_symbolic_state(self.num_chains, self.theano_rng)
layer_to_chains[model.visible_layer] = X
if self.supervised:
assert (Y is not None)
assert isinstance(model.hidden_layers[(-1)], Softmax)
... |
'Returns the expression for the Cost.
Parameters
model : Model
data : Batch in get_data_specs format
return_locals : bool
If returns locals is True, returns (objective, locals())
Note that this means adding / removing / changing the value of
local variables is an interface change.
In particular, TorontoSparsity depends... | def expr(self, model, data, return_locals=False, **kwargs):
| self.get_data_specs(model)[0].validate(data)
if self.supervised:
(X, Y) = data
else:
X = data
Y = None
H_hat = model.mf(X, Y=Y)
terms = []
hidden_layers = model.hidden_layers
for (layer, mf_state, targets, coeffs) in safe_zip(hidden_layers, H_hat, self.targets, self.c... |
'Returns the FixedVarDescr object responsible for making sure the
masks that determine which units are inputs and outputs are generated
each time a minibatch is loaded.
Parameters
model : DBM
data : Batch in get_data_specs format'
| def get_fixed_var_descr(self, model, data):
| (X, Y) = data
assert (Y is not None)
batch_size = model.batch_size
drop_mask_X = sharedX(model.get_input_space().get_origin_batch(batch_size))
drop_mask_X.name = 'drop_mask'
X_space = model.get_input_space()
updates = OrderedDict()
rval = FixedVarDescr()
inputs = [X, Y]
if (not s... |
'Returns the generalized pseudolikelihood giving raw data, a mask,
and the output of inference.
Parameters
dbm : DBM
X : a batch of inputs
V_hat_unmasked : A batch of reconstructions of X
drop_mask : A batch of mask values
state : Hidden states of the DBM
Y : a batch of labels
drop_mask_Y : A batch of Y mask values'
| def get_inpaint_cost(self, dbm, X, V_hat_unmasked, drop_mask, state, Y, drop_mask_Y):
| rval = dbm.visible_layer.recons_cost(X, V_hat_unmasked, drop_mask, use_sum=self.use_sum)
if self.supervised:
scale = None
if self.use_sum:
scale = 1.0
else:
scale = (1.0 / float(dbm.get_input_space().get_total_dimension()))
Y_hat_unmasked = state['Y_hat_un... |
'Returns the total cost, given the states produced by inference.
This includes activity regularization costs, not just generalized
pseudolikelihood costs.
Parameters
state : The state of the model after inference.
new_state : OrderedDict
The state of the model after inference with a different mask.
dbm : DBM.
X : A bat... | def cost_from_states(self, state, new_state, dbm, X, Y, drop_mask, drop_mask_Y, new_drop_mask, new_drop_mask_Y, return_locals=False):
| if (not self.supervised):
assert (drop_mask_Y is None)
assert (new_drop_mask_Y is None)
if self.supervised:
assert (drop_mask_Y is not None)
if self.both_directions:
assert (new_drop_mask_Y is not None)
assert (Y is not None)
V_hat_unmasked = state['V_hat_... |
'Provides the mask for multi-prediction training. A 1 in the mask
corresponds to a variable that should be used as an input to the
inference process. A 0 corresponds to a variable that should be
used as a prediction target of the multi-prediction training
criterion.
Parameters
X : Variable
A batch of input features to ... | def __call__(self, X, Y=None, X_space=None):
| assert (X_space is not None)
self.called = True
assert (X.dtype == config.floatX)
theano_rng = make_theano_rng(getattr(self, 'seed', None), default_seed, which_method='binomial')
if ((X.ndim == 2) and self.sync_channels):
raise NotImplementedError()
p = self.drop_prob
if ((not hasatt... |
'Returns a theano expression for the cost function.
Returns a symbolic expression for a cost function applied to the
minibatch of data.
Optionally, may return None. This represents that the cost function
is intractable but may be optimized via the get_gradients method.
Parameters
model : a pylearn2 Model instance
data ... | def expr(self, model, data, **kwargs):
| try:
per_example = self.cost_per_example(self, model, data, **kwargs)
except NotImplementedError:
raise NotImplementedError((str(type(self)) + ' does not implement expr.'))
if (per_example is None):
return None
assert (per_example.ndim == 1)
return per_example.mea... |
'Returns a theano expression for the cost per example.
This method is optional. Most training algorithms will work without
it.
Parameters
model : Model
data : a batch in cosst.get_data_specs() form
kwargs : dict
Optional extra arguments to be used by 3rd party
TrainingAlgorithm classes and/or FixedVarDescr.
Returns
cos... | def cost_per_example(self, model, data, **kwargs):
| raise NotImplementedError((str(type(self)) + 'does not implement cost_per_example.'))
|
'Provides the gradients of the cost function with respect to the model
parameters.
These are not necessarily those obtained by theano.tensor.grad
--you may wish to use approximate or even intentionally incorrect
gradients in some cases.
Parameters
model : a pylearn2 Model instance
data : a batch in cost.get_data_specs(... | def get_gradients(self, model, data, **kwargs):
| try:
cost = self.expr(model=model, data=data, **kwargs)
except TypeError:
message = (('Error while calling ' + str(type(self))) + '.expr')
reraise_as(TypeError(message))
if (cost is None):
raise NotImplementedError((str(type(self)) + ' represents an intracta... |
'.. todo::
WRITEME
.. todo::
how do you do prereqs in this setup? (I think PL changed
it, not sure if there still is a way in this context)
Returns a dictionary mapping channel names to expressions for
channel values.
Parameters
model : Model
the model to use to compute the monitoring channels
data : batch
(a member of... | def get_monitoring_channels(self, model, data, **kwargs):
| self.get_data_specs(model)[0].validate(data)
return OrderedDict()
|
'Subclasses should override this if they need variables held
constant across multiple updates to a minibatch.
TrainingAlgorithms that do multiple updates to a minibatch should
respect this. See the FixedVarDescr class for details.
Parameters
model : Model
data : theano.gof.Variable or tuple
A valid member of the Space ... | def get_fixed_var_descr(self, model, data):
| self.get_data_specs(model)[0].validate(data)
fixed_var_descr = FixedVarDescr()
return fixed_var_descr
|
'Returns a specification of the Space the data should lie in and
its source (what part of the dataset it should come from).
Parameters
model : Model
The model to train with this cost
Returns
data_specs : tuple
The tuple should be of length two.
The first element of the tuple should be a Space (possibly a
CompositeSpace... | def get_data_specs(self, model):
| raise NotImplementedError(((str(type(self)) + ' does not implement ') + 'get_data_specs.'))
|
'Returns True if the cost is stochastic.
Stochastic costs are incompatible with some optimization algorithms
that make multiple updates per minibatch, such as algorithms that
use line searches. These optimizations should raise a TypeError if
given a stochastic Cost, or issue a warning if given a Cost whose
`is_stochast... | def is_stochastic(self):
| raise NotImplementedError((str(type(self)) + ' needs to implement is_stochastic.'))
|
'Initialize the SumOfCosts object and make sure that the list of costs
contains only Cost instances.
Parameters
costs : list
List of Cost objects or (coeff, Cost) pairs'
| def __init__(self, costs):
| assert isinstance(costs, list)
assert (len(costs) > 0)
self.costs = []
self.coeffs = []
for cost in costs:
if isinstance(cost, (list, tuple)):
(coeff, cost) = cost
else:
coeff = 1.0
self.coeffs.append(coeff)
self.costs.append(cost)
if (... |
'Returns the sum of the costs the SumOfCosts instance was given at
initialization.
Parameters
model : pylearn2.models.model.Model
the model for which we want to calculate the sum of costs
data : flat tuple of tensor_like variables.
data has to follow the format defined by self.get_data_specs(),
but this format will alw... | def expr(self, model, data, **kwargs):
| self.get_data_specs(model)[0].validate(data)
(composite_specs, mapping) = self.get_composite_specs_and_mapping(model)
nested_data = mapping.nest(data)
costs = []
for (cost, cost_data) in safe_zip(self.costs, nested_data):
costs.append(cost.expr(model, cost_data, **kwargs))
assert (len(co... |
'Build and return a composite data_specs of all costs.
The returned space is a CompositeSpace, where the components are
the spaces of each of self.costs, in the same order. The returned
source is a tuple of the corresponding sources.
Parameters
model : pylearn2.models.Model'
| def get_composite_data_specs(self, model):
| spaces = []
sources = []
for cost in self.costs:
(space, source) = cost.get_data_specs(model)
spaces.append(space)
sources.append(source)
composite_space = CompositeSpace(spaces)
sources = tuple(sources)
return (composite_space, sources)
|
'Build the composite data_specs and a mapping to flatten it, return both
Build the composite data_specs described in `get_composite_specs`, and
build a DataSpecsMapping that can convert between it and a flat
equivalent version. In particular, it helps building a flat data_specs
to request data, and nesting this data ba... | def get_composite_specs_and_mapping(self, model):
| (composite_space, sources) = self.get_composite_data_specs(model)
mapping = DataSpecsMapping((composite_space, sources))
return ((composite_space, sources), mapping)
|
'Get a flat data_specs containing all information for all sub-costs.
Parameters
model : pylearn2.models.Model
TODO WRITEME
Notes
This data_specs should be non-redundant. It is built by flattening
the composite data_specs returned by `get_composite_specs`.
This is the format that SumOfCosts will request its data in. The... | def get_data_specs(self, model):
| (composite_specs, mapping) = self.get_composite_specs_and_mapping(model)
(composite_space, sources) = composite_specs
flat_composite_space = mapping.flatten(composite_space)
flat_sources = mapping.flatten(sources)
data_specs = (flat_composite_space, flat_sources)
return data_specs
|
'.. todo::
WRITEME
Parameters
model : Model
data : theano.gof.Variable or tuple
A valid member of the Space defined by
self.get_data_specs(model)[0]'
| def get_fixed_var_descr(self, model, data):
| data_specs = self.get_data_specs(model)
data_specs[0].validate(data)
(composite_specs, mapping) = self.get_composite_specs_and_mapping(model)
nested_data = mapping.nest(data)
descrs = [cost.get_fixed_var_descr(model, cost_data) for (cost, cost_data) in safe_zip(self.costs, nested_data)]
return r... |
'Provides an implementation of `Cost.expr`.
Returns data specifications corresponding to not using any
data at all.
Parameters
model : pylearn2.models.Model'
| def get_data_specs(self, model):
| return (NullSpace(), '')
|
'Provides a default data specification.
The cost requests input features from the model\'s input space and
input source. `self` must contain a bool field called `supervised`.
If this field is True, the cost requests targets as well.
Parameters
model : pylearn2.models.Model
TODO WRITEME'
| def get_data_specs(self, model):
| if self.supervised:
space = CompositeSpace([model.get_input_space(), model.get_target_space()])
sources = (model.get_input_source(), model.get_target_source())
return (space, sources)
else:
return (model.get_input_space(), model.get_input_source())
|
'Parameters
variables : list
list of tensor variables to be regularized
p : int
p in "L-p penalty"'
| def __init__(self, variables, p):
| self.variables = variables
self.p = p
|
'Return the L-p penalty term. The optional parameters are never used;
they\'re only there to provide an interface that\'s consistent with
the Cost superclass.
Parameters
model : a pylearn2 Model instance
data : a batch in cost.get_data_specs() form
kwargs : dict
Optional extra arguments. Not used by the base class.'
| def expr(self, model, data, **kwargs):
| self.get_data_specs(model)[0].validate(data)
penalty = 0
for var in self.variables:
penalty = (penalty + abs((var ** self.p)).sum())
return penalty
|
'.. todo::
WRITEME
Parameters
method : a string specifying the name of the method of the model
that should be called to generate the objective function.
data_specs : a string specifying the name of a method/property of
the model that describe the data specs required by
method'
| def __init__(self, method, data_specs=None):
| self.method = method
self.data_specs = data_specs
|
'Patches calls through to a user-specified method of the model
Parameters
model : pylearn2.models.model.Model
the model for which we want to calculate the sum of costs
data : flat tuple of tensor_like variables.
data has to follow the format defined by self.get_data_specs(),
but this format will always be a flat tuple.... | def expr(self, model, data, *args, **kwargs):
| self.get_data_specs(model)[0].validate(data)
fn = getattr(model, self.method)
return fn(data, *args, **kwargs)
|
'The cost of returning `output` when the truth was `target`
Parameters
target : Theano tensor
The ground truth
output : Theano tensor
The model\'s output'
| @staticmethod
def cost(target, output):
| raise NotImplementedError()
|
'The cost of reconstructing `data` using `model`.
Parameters
model : a GSN
data : a batch of inputs to reconstruct.
args : evidently ignored?
kwargs : optional keyword arguments
For use with third party TrainingAlgorithms or FixedVarDescr'
| def expr(self, model, data, *args, **kwargs):
| self.get_data_specs(model)[0].validate(data)
X = data
return self.cost(X, model.reconstruct(X))
|
'Symmetric reconstruction cost.
Parameters
x : tensor_like
Theano symbolic representing the first input minibatch.
Assumed to be 2-tensors, with the first dimension
indexing training examples and the second indexing
data dimensions.
y : tensor_like
Theano symbolic representing the seconde input minibatch.
Assumed to be... | @staticmethod
def cost(x, y, rx, ry):
| raise NotImplementedError
|
'Returns a theano expression for the cost function.
Returns a symbolic expression for a cost function applied to the
minibatch of data.
Optionally, may return None. This represents that the cost function
is intractable but may be optimized via the get_gradients method.
Parameters
model : a pylearn2 Model instance
data ... | def expr(self, model, data, *args, **kwargs):
| self.get_data_specs(model)[0].validate(data)
(x, y) = data
input_space = model.get_input_space()
if (not isinstance(input_space.components[0], VectorSpace)):
conv = input_space.components[0]
vec = VectorSpace(conv.get_total_dimension())
x = conv.format_as(x, vec)
if (not isin... |
'Summary (Definition of the cost).
Mean squared reconstruction error.
Parameters
x : tensor_like
Theano symbolic representing the first input minibatch.
Assumed to be 2-tensors, with the first dimension
indexing training examples and the second indexing
data dimensions.
y : tensor_like
Theano symbolic representing the ... | @staticmethod
def cost(x, y, rx, ry):
| return ((0.5 * ((x - rx) ** 2)) + (0.5 * ((y - ry) ** 2))).sum(axis=1).mean()
|
'Summary (Definition of the cost).
Normalized Mean squared reconstruction error. Values
between 0 and 1.
Parameters
x : tensor_like
Theano symbolic representing the first input minibatch.
Assumed to be 2-tensors, with the first dimension
indexing training examples and the second indexing
data dimensions.
y : tensor_lik... | @staticmethod
def cost(x, y, rx, ry):
| num = ((0.5 * ((x - rx) ** 2)) + (0.5 * ((y - ry) ** 2))).sum(axis=1).mean()
den = ((0.5 * (x.norm(2, 1) ** 2)) + (0.5 * (y.norm(2, 1) ** 2))).mean()
return (num / den)
|
'Computes the total cost contribution from one layer given the full
output of the GSN.
Parameters
idx : int
init_data and model_output both contain a subset of the layer activations at each time step. This is the index of the layer we want to evaluate the cost on WITHIN this subset. This is ... | @staticmethod
def _get_total_for_cost(idx, costf, init_data, model_output):
| total = 0.0
for step in model_output:
total += costf(init_data[idx], step[idx])
return (total / len(model_output))
|
'.. todo::
WRITEME properly
Handles the different GSNCost modes.'
| def _get_samples_from_model(self, model, data):
| layer_idxs = [idx for (idx, _, _) in self.costs]
zipped = safe_zip(layer_idxs, data)
if (self.mode == 'joint'):
use = zipped
elif (self.mode == 'supervised'):
use = zipped[:1]
elif (self.mode == 'anti_supervised'):
use = zipped[1:]
else:
raise ValueError(('Unknown... |
'Theano expression for the cost.
Parameters
model : GSN object
WRITEME
data : list of tensor_likes
Data must be a list or tuple of the same length as self.costs.
All elements in data must be a tensor_like (cannot be None).
Returns
y : tensor_like
The actual cost that is backpropagated on.'
| def expr(self, model, data):
| self.get_data_specs(model)[0].validate(data)
output = self._get_samples_from_model(model, data)
total = 0.0
for (cost_idx, (_, coeff, costf)) in enumerate(self.costs):
total += (coeff * self._get_total_for_cost(cost_idx, costf, data, output))
coeff_sum = sum((coeff for (_, coeff, _) in self.... |
'Returns a theano expression for the cost function.
Parameters
model : MLP
data : tuple
Should be a valid occupant of
CompositeSpace(model.get_input_space(),
model.get_output_space())
Returns
rval : theano.gof.Variable
The cost obtained by calling model.cost_from_X(data)'
| def expr(self, model, data, **kwargs):
| (space, sources) = self.get_data_specs(model)
space.validate(data)
return model.cost_from_X(data)
|
'Returns a theano expression for the cost function.
Parameters
model : MLP
data : tuple
Should be a valid occupant of
CompositeSpace(model.get_input_space(),
model.get_output_space())
Returns
total_cost : theano.gof.Variable
coeff * sum(sqr(weights))
added up for each set of weights.'
| def expr(self, model, data, **kwargs):
| self.get_data_specs(model)[0].validate(data)
assert (T.scalar() != 0.0)
def wrapped_layer_cost(layer, coeff):
try:
return layer.get_weight_decay(coeff)
except NotImplementedError:
if (coeff == 0.0):
return 0.0
else:
reraise_... |
'Returns a theano expression for the cost function.
Parameters
model : MLP
data : tuple
Should be a valid occupant of
CompositeSpace(model.get_input_space(),
model.get_output_space())
Returns
total_cost : theano.gof.Variable
coeff * sum(abs(weights))
added up for each set of weights.'
| def expr(self, model, data, **kwargs):
| assert (T.scalar() != 0.0)
self.get_data_specs(model)[0].validate(data)
if isinstance(self.coeffs, list):
warnings.warn('Coefficients should be given as a dictionary with layer names as key. The support of coefficients as list would be depr... |
'Computes `h` from the NCE paper.
Parameters
X : Theano matrix
Batch of input data
model : Model
Any model with a `log_prob` method.
Returns
h : A theano symbol for the `h` function from the paper.'
| def h(self, X, model):
| return (- T.nnet.sigmoid(self.G(X, model)))
|
'Computes `G` from the NCE paper.
Parameters
X : Theano matrix
Batch of input data
model : Model
Any model with a `log_prob` method.
Returns
G : A theano symbol for the `G` function from the paper.'
| def G(self, X, model):
| return (model.log_prob(X) - self.noise.log_prob(X))
|
'Computes the NCE objective.
Parameters
model : Model
Any Model that implements a `log_probs` method.
data : Theano matrix
noisy_data : Theano matrix, optional
The noise samples used for noise-contrastive
estimation. Will be generated internally if not
provided. The keyword argument allows FixedVarDescr
to provide the ... | def expr(self, model, data, noisy_data=None):
| (space, source) = self.get_data_specs(model)
space.validate(data)
X = data
if (X.name is None):
X_name = 'X'
else:
X_name = X.name
m_data = X.shape[0]
m_noise = (m_data * self.noise_per_clean)
if (noisy_data is not None):
space.validate(noisy_data)
Y = noi... |
'A fake cost that we differentiate symbolically to derive the SML
update rule.
Parameters
model : Model
data : Batch in get_data_specs format
Returns
cost : 0-d Theano tensor
The fake cost'
| def _cost(self, model, data):
| if (not hasattr(self, 'sampler')):
self.sampler = BlockGibbsSampler(rbm=model, particles=(0.5 + np.zeros((self.nchains, model.get_input_dim()))), rng=model.rng, steps=self.nsteps)
sampler_updates = self.sampler.updates()
pos_v = data
neg_v = self.sampler.particles
ml_cost = (model.free_energ... |
'.. todo::
WRITEME'
| def set_params(self, params):
| self._params = list(params)
|
'.. todo::
WRITEME'
| def params(self):
| return list(self._params)
|
'.. todo::
WRITEME'
| def __str__(self):
| return (self.__class__.__name__ + '{}')
|
'.. todo::
WRITEME'
| def __add__(self, other):
| return Sum([self, other])
|
'.. todo::
WRITEME'
| def __radd__(self, other):
| return Sum([other, self])
|
'.. todo::
WRITEME'
| def lmul(self, x):
| try:
AT_xT = self.rmul_T(self.transpose_left(x, False))
rval = self.transpose_right(AT_xT, True)
return rval
except RuntimeError as e:
if ('ecursion' in str(e)):
raise TypeError('either lmul or rmul_T must be implemented')
raise
except Ty... |
'.. todo::
WRITEME'
| def lmul_T(self, x):
| A_xT = self.rmul(self.transpose_right(x, True))
rval = self.transpose_left(A_xT, True)
return rval
|
'.. todo::
WRITEME'
| def rmul(self, x):
| try:
xT_AT = self.lmul_T(self.transpose_right(x, False))
rval = self.transpose_left(xT_AT, False)
return rval
except RuntimeError as e:
if ('ecursion' in str(e)):
raise TypeError('either rmul or lmul_T must be implemented')
raise
except T... |
'.. todo::
WRITEME'
| def rmul_T(self, x):
| xT_A = self.lmul(self.transpose_left(x, True))
rval = self.transpose_right(xT_A, True)
return rval
|
'.. todo::
WRITEME'
| def transpose_left(self, x, T):
| cshp = self.col_shape()
if T:
ss = len(cshp)
else:
ss = (x.ndim - len(cshp))
pattern = (list(range(ss, x.ndim)) + list(range(ss)))
return x.transpose(pattern)
|
'.. todo::
WRITEME'
| def transpose_right(self, x, T):
| rshp = self.row_shape()
if T:
ss = len(rshp)
else:
ss = (x.ndim - len(rshp))
pattern = (list(range(ss, x.ndim)) + list(range(ss)))
return x.transpose(pattern)
|
'.. todo::
WRITEME'
| def split_left_shape(self, xshp, T):
| if (type(xshp) != tuple):
raise TypeError('need tuple', xshp)
cshp = self.col_shape()
assert (type(cshp) == tuple)
if T:
ss = len(cshp)
(RR, CC) = (xshp[ss:], xshp[:ss])
else:
ss = (len(xshp) - len(cshp))
(RR, CC) = (xshp[:ss], xshp[ss:])
if ((len(CC) !... |
'.. todo::
WRITEME'
| def split_right_shape(self, xshp, T):
| if (type(xshp) != tuple):
raise TypeError('need tuple', xshp)
rshp = self.row_shape()
assert (type(rshp) == tuple)
if T:
ss = (len(xshp) - len(rshp))
(RR, CC) = (xshp[ss:], xshp[:ss])
else:
ss = len(rshp)
(RR, CC) = (xshp[:ss], xshp[ss:])
if ((len(RR) !... |
'.. todo::
WRITEME'
| def transpose_left_shape(self, xshp, T):
| (RR, CC) = self.split_left_shape(xshp, T)
return (CC + RR)
|
'.. todo::
WRITEME'
| def transpose_right_shape(self, xshp, T):
| (RR, CC) = self.split_right_shape(xshp, T)
return (CC + RR)
|
'.. todo::
WRITEME'
| def is_valid_left_shape(self, xshp, T):
| try:
self.split_left_shape(xshp, T)
return True
except ValueError:
return False
|
'.. todo::
WRITEME'
| def is_valid_right_shape(self, xshp, T):
| try:
self.split_right_shape(xshp, T)
return True
except ValueError:
return False
|
'.. todo::
WRITEME'
| def row_shape(self):
| raise NotImplementedError('override me')
|
'.. todo::
WRITEME'
| def col_shape(self):
| raise NotImplementedError('override me')
|
'.. todo::
WRITEME'
| def transpose(self):
| return TransposeTransform(self)
|
'.. todo::
WRITEME'
| def transpose(self):
| return self.base
|
'.. todo::
WRITEME'
| def params(self):
| return self.base.params()
|
'.. todo::
WRITEME'
| def lmul(self, x):
| return self.base.lmul_T(x)
|
'.. todo::
WRITEME'
| def lmul_T(self, x):
| return self.base.lmul(x)
|
'.. todo::
WRITEME'
| def rmul(self, x):
| return self.base.rmul_T(x)
|
'.. todo::
WRITEME'
| def rmul_T(self, x):
| return self.base.rmul(x)
|
'.. todo::
WRITEME'
| def transpose_left(self, x, T):
| return self.base.transpose_right(x, (not T))
|
'.. todo::
WRITEME'
| def transpose_right(self, x, T):
| return self.base.transpose_left(x, (not T))
|
'.. todo::
WRITEME'
| def transpose_left_shape(self, x, T):
| return self.base.transpose_right_shape(x, (not T))
|
'.. todo::
WRITEME'
| def transpose_right_shape(self, x, T):
| return self.base.transpose_left_shape(x, (not T))
|
'.. todo::
WRITEME'
| def split_left_shape(self, x, T):
| return self.base.split_right_shape(x, (not T))
|
'.. todo::
WRITEME'
| def split_right_shape(self, x, T):
| return self.base.split_left_shape(x, (not T))
|
'.. todo::
WRITEME'
| def is_valid_left_shape(self, x, T):
| return self.base.is_valid_right_shape(x, (not T))
|
'.. todo::
WRITEME'
| def is_valid_right_shape(self, x, T):
| return self.base.is_valid_left_shape(x, (not T))
|
'.. todo::
WRITEME'
| def row_shape(self):
| return self.base.col_shape()
|
'.. todo::
WRITEME'
| def col_shape(self):
| return self.base.row_shape()
|
'.. todo::
WRITEME'
| def print_status(self):
| return self.base.print_status()
|
'.. todo::
WRITEME'
| def tile_columns(self):
| return self.base.tile_columns()
|
'.. todo::
WRITEME'
| def props(self):
| return (self.n_levels,)
|
'.. todo::
WRITEME'
| def __hash__(self):
| return hash((type(self), self.props()))
|
'.. todo::
WRITEME'
| def __eq__(self, other):
| return ((type(self) == type(other)) and (self.props() == other.props()))
|
'.. todo::
WRITEME'
| def __repr__(self):
| return ('%s{n_levels=%s}' % (self.__class__.__name__, self.n_levels))
|
'.. todo::
WRITEME'
| def infer_shape(self, node, input_shapes):
| (xshp,) = input_shapes
out_shapes = [xshp]
while (len(out_shapes) < self.n_levels):
s = out_shapes[(-1)]
out_shapes.append((s[0], (s[1] // 2), (s[2] // 2), s[3]))
return out_shapes
|
'.. todo::
WRITEME'
| def make_node(self, x):
| if (self.n_levels < 1):
raise ValueError('It does not make sense for GaussianPyramid to generate %i levels', self.n_levels)
x = as_tensor_variable(x)
return Apply(self, [x], [x.type() for i in range(self.n_levels)])
|
'.. todo::
WRITEME'
| def perform(self, node, ins, outs):
| (x,) = ins
outs[0][0] = z = x.copy()
(B, M, N, K) = x.shape
for level in range(1, self.n_levels):
z0 = z[0]
if ((z0.shape[0] <= 2) or (z0.shape[1] <= 2)):
raise ValueError('Cannot downsample an image smaller than 3x3', z0.shape)
logger.info('{0} {... |
'This function returns (zlike) transpose(W(y))
Parameters
zlike : WRITEME
*inputs_1_to_n : WRITEME
Returns
WRITEME'
| def transpose(zlike, *inputs_1_to_n):
| raise NotImplementedError('override-me')
|
'.. todo::
WRITEME'
| def grads_1_to_n(inputs, gzlist):
| raise NotImplementedError('override-me')
|
'.. todo::
WRITEME'
| def grad(self, inputs, gzlist):
| if (len(gzlist) > 1):
raise NotImplementedError()
g_input0 = self.transpose(gzlist[0], *inputs[1:])
return ([g_input0] + self.grads_1_to_n(inputs, gzlist))
|
'.. todo::
WRITEME'
| def lmul(self, x):
| return conv2d(x, self._filters, image_shape=self._img_shape, filter_shape=self._filters_shape, subsample=self._subsample, border_mode=self._border_mode)
|
'.. todo::
WRITEME'
| def lmul_T(self, x):
| dummy_v = tensor.tensor4()
z_hs = conv2d(dummy_v, self._filters, image_shape=self._img_shape, filter_shape=self._filters_shape, subsample=self._subsample, border_mode=self._border_mode)
(xfilters, xdummy) = z_hs.owner.op.grad((dummy_v, self._filters), (x,))
return xfilters
|
'.. todo::
WRITEME'
| def row_shape(self):
| return self._img_shape[1:]
|
'.. todo::
WRITEME'
| def col_shape(self):
| rows_cols = ConvOp.getOutputShape(self._img_shape[2:], self._filters_shape[2:], self._subsample, self._border_mode)
rval = ((self._filters_shape[0],) + tuple(rows_cols))
return rval
|
'.. todo::
WRITEME'
| def tile_columns(self, scale_each=True, **kwargs):
| return tile_slices_to_image(self._filters.get_value()[:, :, ::(-1), ::(-1)].transpose(0, 2, 3, 1), scale_each=scale_each, **kwargs)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.