INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
General optimization function for Theano. Parameters: params - parameters gradients - gradients config - training config Returns: Theano updates: type config: deepy. TrainerConfig or dict | def optimize_updates(params, gradients, config=None, shapes=None):
"""
General optimization function for Theano.
Parameters:
params - parameters
gradients - gradients
config - training config
Returns:
Theano updates
:type config: deepy.TrainerConfig or dict
"""
... |
Create a optimizing function receives gradients. Parameters: params - parameters config - training configuration Returns: updating function receives gradients | def optimize_function(params, config=None):
"""
Create a optimizing function receives gradients.
Parameters:
params - parameters
config - training configuration
Returns:
updating function receives gradients
"""
gs = [dim_to_var(p.ndim) for p in params]
updates, _ = op... |
Return updates in the training. | def _learning_updates(self):
"""
Return updates in the training.
"""
params = self.training_params()
gradients = self.get_gradients(params)
return self.optimization_updates(params, gradients) |
Get parameters to be optimized. | def training_params(self):
"""
Get parameters to be optimized.
"""
params = self.network.parameters
# Freeze parameters
if self.config.fixed_parameters:
logging.info("fixed parameters: %s" % ", ".join(map(str, self.config.fixed_parameters)))
params... |
Return updates from optimization. | def optimization_updates(self, params, gradients):
"""
Return updates from optimization.
"""
updates, free_parameters = optimize_updates(params, gradients, self.config)
self.network.free_parameters.extend(free_parameters)
logging.info("Added %d free parameters for optimiz... |
Get the learning function.: param func:: return: | def learning_function(self):
"""
Get the learning function.
:param func:
:return:
"""
network_updates = list(self.network.updates) + list(self.network.training_updates)
learning_updates = list(self._learning_updates())
update_list = network_updates + learn... |
Parameters: x_t - 28x28 image l_p - 2x1 focus vector Returns: 4x12 matrix | def _glimpse_sensor(self, x_t, l_p):
"""
Parameters:
x_t - 28x28 image
l_p - 2x1 focus vector
Returns:
4x12 matrix
"""
# Turn l_p to the left-top point of rectangle
l_p = l_p * 14 + 14 - 2
l_p = T.cast(T.round(l_p), "int32")
... |
Parameters: x_t - 28x28 image l_p - 2x1 focus vector Returns: 7 * 14 matrix | def _refined_glimpse_sensor(self, x_t, l_p):
"""
Parameters:
x_t - 28x28 image
l_p - 2x1 focus vector
Returns:
7*14 matrix
"""
# Turn l_p to the left-top point of rectangle
l_p = l_p * 14 + 14 - 4
l_p = T.cast(T.round(l_p), "int... |
Parameters: x_t - 28x28 image l_p - 2x1 focus vector Returns: 4x12 matrix | def _glimpse_network(self, x_t, l_p):
"""
Parameters:
x_t - 28x28 image
l_p - 2x1 focus vector
Returns:
4x12 matrix
"""
sensor_output = self._refined_glimpse_sensor(x_t, l_p)
sensor_output = T.flatten(sensor_output)
h_g = self._... |
Parameters: h_t - 256x1 vector Returns: 10x1 vector | def _action_network(self, h_t):
"""
Parameters:
h_t - 256x1 vector
Returns:
10x1 vector
"""
z = self._relu(T.dot(h_t, self.W_a) + self.B_a)
return self._softmax(z) |
Get baseline model. Parameters: model - model path Returns: network | def get_network(model=None, std=0.005, disable_reinforce=False, random_glimpse=False):
"""
Get baseline model.
Parameters:
model - model path
Returns:
network
"""
network = NeuralClassifier(input_dim=28 * 28)
network.stack_layer(FirstGlimpseLayer(std=std, disable_reinforce=di... |
Compute first glimpse position using down - sampled image. | def _first_glimpse_sensor(self, x_t):
"""
Compute first glimpse position using down-sampled image.
"""
downsampled_img = theano.tensor.signal.downsample.max_pool_2d(x_t, (4,4))
downsampled_img = downsampled_img.flatten()
first_l = T.dot(downsampled_img, self.W_f)
... |
Parameters: x_t - 28x28 image l_p - 2x1 focus vector h_p - 256x1 vector Returns: h_t 256x1 vector | def _core_network(self, l_p, h_p, x_t):
"""
Parameters:
x_t - 28x28 image
l_p - 2x1 focus vector
h_p - 256x1 vector
Returns:
h_t, 256x1 vector
"""
g_t = self._glimpse_network(x_t, l_p)
h_t = self._tanh(T.dot(g_t, self.W_h_g)... |
All codes that create parameters should be put into setup function. | def prepare(self):
"""
All codes that create parameters should be put into 'setup' function.
"""
self.output_dim = 10
self.encoder = Chain(self.input_dim).stack(Dense(self.internal_layer_size, 'tanh'))
self.decoder = Chain(self.internal_layer_size).stack(Dense(self.input_... |
Build the computation graph here. | def compute_tensor(self, x):
"""
Build the computation graph here.
"""
internal_variable = self.encoder.compute_tensor(x)
decoding_output = self.decoder.compute_tensor(internal_variable)
classification_output = self.classifier.compute_tensor(internal_variable)
... |
Process all data with given function. The scheme of function should be x y - > x y. | def map(self, func):
"""
Process all data with given function.
The scheme of function should be x,y -> x,y.
"""
if self._train_set:
self._train_set = map(func, self._train_set)
if self._valid_set:
self._valid_set = map(func, self._valid_set)
... |
Make targets be one - hot vectors. | def vectorize_target(self, size):
"""
Make targets be one-hot vectors.
"""
if self._train_set:
self._train_set = self._vectorize_set(self._train_set, size)
if self._valid_set:
self._valid_set = self._vectorize_set(self._valid_set, size)
if self._te... |
Print dataset statistics. | def report(self):
"""
Print dataset statistics.
"""
logging.info("%s train=%d valid=%d test=%d" % (self.__class__.__name__,
len(list(self._train_set)) if self._train_set else 0,
... |
We train over mini - batches and evaluate periodically. | def train(self, train_set, valid_set=None, test_set=None, train_size=None):
'''We train over mini-batches and evaluate periodically.'''
iteration = 0
while True:
if not iteration % self.config.test_frequency and test_set:
try:
self.test(iteration, ... |
Sample outputs from LM. | def sample(self, input, steps):
"""
Sample outputs from LM.
"""
inputs = [[onehot(self.input_dim, x) for x in input]]
for _ in range(steps):
target = self.compute(inputs)[0,-1].argmax()
input.append(target)
inputs[0].append(onehot(self.input_di... |
: param x: ( batch time vec ) | def compute_tensor(self, x):
"""
:param x: (batch, time, vec)
"""
# Target class
class_matrix = self.target_tensor // self.output_size
class_vector = class_matrix.reshape((-1,))
# Target index
target_matrix = self.target_tensor % self.output_size
t... |
Compute the alignment weights based on the previous state. | def compute_alignments(self, prev_state, precomputed_values, mask=None):
"""
Compute the alignment weights based on the previous state.
"""
WaSp = T.dot(prev_state, self.Wa)
UaH = precomputed_values
# For test time the UaH will be (time, output_dim)
if UaH.ndim =... |
Compute the context vector with soft attention. | def compute_context_vector(self, prev_state, inputs, precomputed_values=None, mask=None):
"""
Compute the context vector with soft attention.
"""
precomputed_values = precomputed_values if precomputed_values else self.precompute(inputs)
align_weights = self.compute_alignments(pre... |
Train the model in multi - GPU environment. | def train(self, train_set, valid_set=None, test_set=None, train_size=None):
"""
Train the model in multi-GPU environment.
"""
from platoon.channel import Worker
from platoon.param_sync import EASGD, ASGD
server_port = self._port
param_map = self.create_param_map()... |
A utility function of concatenate. | def concatenate(vars, axis=-1):
"""
A utility function of concatenate.
"""
from deepy.core.neural_var import NeuralVariable
if isinstance(vars[0], NeuralVariable):
concat_var = Concatenate(axis=axis).compute(*vars)
if axis == -1 or axis == vars[0].tensor.ndim - 1:
concat_... |
Wrap a Theano tensor into the variable for defining neural network.: param last_dim: last dimension of tensor 0 indicates that the last dimension is flexible: rtype: deepy. core. neural_var. NeuralVariable | def var(tensor_type, last_dim=0, test_shape=None):
"""
Wrap a Theano tensor into the variable for defining neural network.
:param last_dim: last dimension of tensor, 0 indicates that the last dimension is flexible
:rtype: deepy.core.neural_var.NeuralVariable
"""
# Create tensor
from deepy.co... |
Pad sequences to given length in the left or right side. | def _pad(self, side, length):
"""
Pad sequences to given length in the left or right side.
"""
if self._train_set:
self._train_set = pad_dataset(self._train_set, side, length)
if self._valid_set:
self._valid_set = pad_dataset(self._valid_set, side, length)... |
RMSPROP optimization core. | def rmsprop_core(params, gradients, momentum=0.9, learning_rate=0.01):
"""
RMSPROP optimization core.
"""
for param, grad in zip(params, gradients):
rms_ = theano.shared(np.zeros_like(param.get_value()), name=param.name + '_rms')
rms = momentum * rms_ + (1 - momentum) * grad * gr... |
Pad data set to specified length. Parameters: length - max length a just to the max length in the batch if length is - 1 | def pad_dataset(subset, side="right", length=-1):
"""
Pad data set to specified length.
Parameters:
length - max length, a just to the max length in the batch if length is -1
"""
assert length == -1 or length > 0
if type(subset[0][0][0]) in [float, int, np.int64, np.int32, np.float32]:
... |
Prepare for one epoch. Returns: bool: False if to stop the training. | def prepare_epoch(self):
"""
Prepare for one epoch.
Returns:
bool: False if to stop the training.
"""
self.epoch += 1
if self.epoch >= self.epoch_start_halving and ((self.epoch - self.epoch_start_halving) % self._halving_freq == 0):
self._lr *= 0.5... |
Handles a control_request received from a worker. Returns: string or dict: response | def handle_control(self, req, worker_id, req_info):
"""
Handles a control_request received from a worker.
Returns:
string or dict: response
'stop' - the worker should quit
'wait' - wait for 1 second
'eval' - evaluate on valid and test set to start... |
Report elapsed time. | def report(self):
"""
Report elapsed time.
"""
if not self.end_time:
self.end()
print ("Time: {} mins".format((self.end_time - self.start_time )/ 60)) |
Compare to previous records and return whether the given cost is a new best.: return: True if the given cost is a new best | def compare(self, cost_map):
"""
Compare to previous records and return whether the given cost is a new best.
:return: True if the given cost is a new best
"""
cri_val = cost_map[self._criteria]
if self._best_criteria is None:
self._best_criteria = cri_val
... |
Run the model with validation data and return costs. | def run(self, data_x):
"""
Run the model with validation data and return costs.
"""
output_vars = self.compute(*data_x)
return self._extract_costs(output_vars) |
This function will be called after each iteration. | def invoke(self):
"""
This function will be called after each iteration.
"""
self._counter += 1
if self._counter % self._freq == 0:
cnt = 0.
sum_map = defaultdict(float)
for x in self._trainer.get_data(self._data_split):
val_map... |
Create inner loop variables. | def _build_loop_vars(self):
"""
Create inner loop variables.
"""
from theano.tensor.var import TensorVariable
from deepy.core.neural_var import NeuralVariable
if not self._loop_vars:
self._ordered_out_keys = self._outputs.keys()
seq_keys = self._se... |
Internal scan with dummy input variables. | def _scan_step(self, vars):
"""
Internal scan with dummy input variables.
"""
from neural_var import NeuralVariable
if not self._loop_vars:
raise Exception("The loop is not initialized. To initialize the loop, use `with loop as vars`")
replace_map = {}
... |
Get the outputs of the loop. Return specific variables by passing the keys to the arguments.: rtype: MapDict | def get_outputs(self, *args):
"""
Get the outputs of the loop.
Return specific variables by passing the keys to the arguments.
:rtype: MapDict
"""
if args:
output_vars = map(self._scan_outputs.get, args)
if len(output_vars) == 1:
re... |
Momentum SGD optimization core. | def momentum_core(params, gradients, momentum=0.9, learning_rate=0.01):
"""
Momentum SGD optimization core.
"""
free_parameters = []
updates = []
for param, grad in zip(params, gradients):
delta = learning_rate * grad
velocity = theano.shared(np.zeros_like(param.get_value... |
Execute then_branch when training. | def iftrain(self, then_branch, else_branch):
"""
Execute `then_branch` when training.
"""
return ifelse(self._training_flag, then_branch, else_branch, name="iftrain") |
Switch training mode.: param flag: switch on training mode when flag is True. | def switch_training(self, flag):
"""
Switch training mode.
:param flag: switch on training mode when flag is True.
"""
if self._is_training == flag: return
self._is_training = flag
if flag:
self._training_flag.set_value(1)
else:
sel... |
Nesterov s Accelerated Gradient ( NAG ). See http:// www. cs. toronto. edu/ ~fritz/ absps/ momentum. pdf. Still unfinished | def nag_core(params, J, momentum=0.9, learning_rate=0.01):
"""
Nesterov's Accelerated Gradient (NAG).
See http://www.cs.toronto.edu/~fritz/absps/momentum.pdf .
Still unfinished
"""
# TODO: this requires some refractorings.
for param in params:
step = theano.shared(np.zeros_like(param... |
Skip N batches in the training. | def skip(self, n_batches, n_epochs=0):
"""
Skip N batches in the training.
"""
logging.info("skip %d epochs and %d batches" % (n_epochs, n_batches))
self._skip_batches = n_batches
self._skip_epochs = n_epochs |
Load parameters for the training. This method can load free parameters and resume the training progress. | def load_params(self, path, exclude_free_params=False):
"""
Load parameters for the training.
This method can load free parameters and resume the training progress.
"""
self.network.load_params(path, exclude_free_params=exclude_free_params)
self.best_params = self.copy_pa... |
Add iteration callbacks function ( receives an argument of the trainer ).: param controllers: can be a TrainingController or a function.: type funcs: list of TrainingContoller | def add_iter_controllers(self, *controllers):
"""
Add iteration callbacks function (receives an argument of the trainer).
:param controllers: can be a `TrainingController` or a function.
:type funcs: list of TrainingContoller
"""
for controller in controllers:
... |
Add epoch callbacks function.: param controllers: can be a TrainingController or a function. | def add_epoch_controllers(self, *controllers):
"""
Add epoch callbacks function.
:param controllers: can be a `TrainingController` or a function.
"""
for controller in controllers:
if isinstance(controller, TrainingController):
controller.bind(self)
... |
Train the model and return costs. | def train(self, train_set, valid_set=None, test_set=None, train_size=None):
"""
Train the model and return costs.
"""
self._epoch = 0
while True:
if self._skip_epochs > 0:
logging.info("skipping one epoch ...")
self._skip_epochs -= 1
... |
Run one training iteration. | def _run_train(self, epoch, train_set, train_size=None):
"""
Run one training iteration.
"""
self.network.train_logger.record_epoch(epoch + 1)
costs = self.train_step(train_set, train_size)
if not epoch % self.config.monitor_frequency:
self.report(dict(costs),... |
Run one valid iteration return true if to continue training. | def _run_valid(self, epoch, valid_set, dry_run=False, save_path=None):
"""
Run one valid iteration, return true if to continue training.
"""
costs = self.valid_step(valid_set)
# this is the same as: (J_i - J_f) / J_i > min improvement
_, J = costs[0]
new_best = Fa... |
Report the scores and record them in the log. | def report(self, score_map, type="valid", epoch=-1, new_best=False):
"""
Report the scores and record them in the log.
"""
type_str = type
if len(type_str) < 5:
type_str += " " * (5 - len(type_str))
info = " ".join("%s=%.2f" % el for el in score_map.items())
... |
Get specified split of data. | def get_data(self, data_split="train"):
"""
Get specified split of data.
"""
if data_split == 'train':
return self._current_train_set
elif data_split == 'valid':
return self._current_valid_set
elif data_split == 'test':
return self._cur... |
Run until the end.: param epoch_controllers: deprecated | def run(self, train_set, valid_set=None, test_set=None, train_size=None, epoch_controllers=None):
"""
Run until the end.
:param epoch_controllers: deprecated
"""
epoch_controllers = epoch_controllers if epoch_controllers else []
epoch_controllers += self._epoch_controller... |
: type bunch_stack: list of list of int | def _cut_to_pieces(self, bunch_stack):
"""
:type bunch_stack: list of list of int
"""
stack_len = len(bunch_stack[0])
for i in xrange(0, stack_len, self.fragment_length):
yield np.array(map(lambda stack: stack[i: i + self.fragment_length], bunch_stack)) |
: type bunch_stack: list of list | def _pad_zeros(self, bunch_stack):
"""
:type bunch_stack: list of list
"""
min_len = min(map(len, bunch_stack))
for i in range(len(bunch_stack)):
bunch_stack[i] = bunch_stack[i][:min_len] |
Apply a function to tensors. | def apply(self, func, dim=None):
"""
Apply a function to tensors.
"""
output_dim = dim if dim else self.output_dim
return NeuralVariable(func(self.tensor), output_dim) |
Rprop optimizer. See http:// sci2s. ugr. es/ keel/ pdf/ algorithm/ articulo/ 2003 - Neuro - Igel - IRprop +. pdf. | def rprop_core(params, gradients, rprop_increase=1.01, rprop_decrease=0.99, rprop_min_step=0, rprop_max_step=100,
learning_rate=0.01):
"""
Rprop optimizer.
See http://sci2s.ugr.es/keel/pdf/algorithm/articulo/2003-Neuro-Igel-IRprop+.pdf.
"""
for param, grad in zip(params, gradients):
... |
Report usage of training parameters. | def report(self):
"""
Report usage of training parameters.
"""
if self.logger:
self.logger.info("accessed parameters:")
for key in self.used_parameters:
self.logger.info(" - %s %s" % (key, "(undefined)" if key in self.undefined_parameters else "")) |
Create a parameters block.: param layers: register some layers in the block: param name: specify the name of this block | def new_block(self, *layers, **kwargs):
"""
Create a parameters block.
:param layers: register some layers in the block
:param name: specify the name of this block
"""
from deepy.layers.block import Block
block = Block(*layers, **kwargs)
return block |
An alias of deepy. tensor. var. | def var(self, tensor_type, last_dim=0, test_shape=None):
"""
An alias of deepy.tensor.var.
"""
from deepy.tensor import var
return var(tensor_type, last_dim=last_dim, test_shape=test_shape) |
Create vars given a dataset and set test values. Useful when dataset is already defined. | def create_vars_from_data(self, dataset, split="train"):
"""
Create vars given a dataset and set test values.
Useful when dataset is already defined.
"""
from deepy.core.neural_var import NeuralVariable
vars = []
if split == "valid":
data_split = datas... |
A loop function the usage is identical with the theano one.: type block: deepy. layers. Block | def scan(self, func, sequences=None, outputs=None, non_sequences=None, block=None, **kwargs):
"""
A loop function, the usage is identical with the theano one.
:type block: deepy.layers.Block
"""
results, updates = Scanner(func, sequences, outputs, non_sequences, neural_computatio... |
Start a loop. Usage: with deepy. graph. loop ( sequences = { x: x } outputs = { o: None } ) as vars: vars. o = vars. x + 1 loop_outputs = deepy. graph. loop_outputs () result = loop_outputs. o | def loop(self, sequences=None, outputs=None, non_sequences=None, block=None, **kwargs):
"""
Start a loop.
Usage:
```
with deepy.graph.loop(sequences={"x": x}, outputs={"o": None}) as vars:
vars.o = vars.x + 1
loop_outputs = deepy.graph.loop_outputs()
r... |
Get a trainer to optimize given model.: rtype: deepy. trainers. GeneralNeuralTrainer | def get_trainer(self, model, method='sgd', config=None, annealer=None, validator=None):
"""
Get a trainer to optimize given model.
:rtype: deepy.trainers.GeneralNeuralTrainer
"""
from deepy.trainers import GeneralNeuralTrainer
return GeneralNeuralTrainer(model, method=me... |
Create a shared theano scalar value. | def shared(self, value, name=None):
"""
Create a shared theano scalar value.
"""
if type(value) == int:
final_value = np.array(value, dtype="int32")
elif type(value) == float:
final_value = np.array(value, dtype=env.FLOATX)
else:
final_... |
Load parameters from file to fill all blocks sequentially.: type blocks: list of deepy. layers. Block | def fill_parameters(self, path, blocks, exclude_free_params=False, check_parameters=False):
"""
Load parameters from file to fill all blocks sequentially.
:type blocks: list of deepy.layers.Block
"""
if not os.path.exists(path):
raise Exception("model {} does not exis... |
Return size of training data. ( optional ): rtype: number | def train_size(self):
"""
Return size of training data. (optional)
:rtype: number
"""
train_set = self.train_set()
if isinstance(train_set, collections.Iterable):
return len(list(train_set))
else:
return None |
Run it return whether to end training. | def invoke(self):
"""
Run it, return whether to end training.
"""
self._iter += 1
if self._iter - max(self._trainer.best_iter, self._annealed_iter) >= self._patience:
if self._annealed_times >= self._anneal_times:
logging.info("ending")
... |
Run it return whether to end training. | def invoke(self):
"""
Run it, return whether to end training.
"""
self._iter += 1
logging.info("{} epochs left to run".format(self._patience - self._iter))
if self._iter >= self._patience:
self._trainer.exit() |
Perform reparameterization trick for latent variables.: param layer_size: the size of latent variable | def stack_reparameterization_layer(self, layer_size):
"""
Perform reparameterization trick for latent variables.
:param layer_size: the size of latent variable
"""
self.rep_layer = ReparameterizationLayer(layer_size, sample=self.sample)
self.stack_encoders(self.rep_layer) |
Stack encoding layers this must be done before stacking decoding layers. | def stack_encoders(self, *layers):
"""
Stack encoding layers, this must be done before stacking decoding layers.
"""
self.stack(*layers)
self.encoding_layes.extend(layers) |
Stack decoding layers. | def stack_decoders(self, *layers):
"""
Stack decoding layers.
"""
self.stack(*layers)
self.decoding_layers.extend(layers) |
Encode given input. | def encode(self, x):
"""
Encode given input.
"""
if not self.encoding_network:
self.encoding_network = NeuralNetwork(self.input_dim, self.input_tensor)
self.encoding_network.input_variables = self.input_variables
for layer in self.encoding_layes:
... |
Decode given representation. | def decode(self, x):
"""
Decode given representation.
"""
if not self.rep_dim:
raise Exception("rep_dim must be set to decode.")
if not self.decoding_network:
self.decoding_network = NeuralNetwork(self.rep_dim)
for layer in self.decoding_layers... |
This function creates a 2d gaussian kernel with the standard deviation denoted by sigma | def create_2d_gaussian(dim, sigma):
"""
This function creates a 2d gaussian kernel with the standard deviation
denoted by sigma
:param dim: integer denoting a side (1-d) of gaussian kernel
:param sigma: floating point indicating the standard deviation
:returns: a numpy 2d array
"""
# ... |
This method performs elastic transformations on an image by convolving with a gaussian kernel.: param image: a numpy nd array: kernel_dim: dimension ( 1 - D ) of the gaussian kernel: param sigma: standard deviation of the kernel: param alpha: a multiplicative factor for image after convolution: param negated: a flag in... | def elastic_distortion(image, kernel_dim=21, sigma=6, alpha=30, negated=True):
"""
This method performs elastic transformations on an image by convolving
with a gaussian kernel.
:param image: a numpy nd array
:kernel_dim: dimension(1-D) of the gaussian kernel
:param sigma: standard deviation of ... |
Stack a neural layer.: type layer: NeuralLayer: param no_setup: whether the layer is already initialized | def stack_layer(self, layer, no_setup=False):
"""
Stack a neural layer.
:type layer: NeuralLayer
:param no_setup: whether the layer is already initialized
"""
if layer.name:
layer.name += "%d" % (len(self.layers) + 1)
if not self.layers:
la... |
Register the layer so that it s param will be trained. But the output of the layer will not be stacked. | def register_layer(self, layer):
"""
Register the layer so that it's param will be trained.
But the output of the layer will not be stacked.
"""
if type(layer) == Block:
layer.fix()
self.parameter_count += layer.parameter_count
self.parameters.extend(l... |
Monitoring the outputs of each layer. Useful for troubleshooting convergence problems. | def monitor_layer_outputs(self):
"""
Monitoring the outputs of each layer.
Useful for troubleshooting convergence problems.
"""
for layer, hidden in zip(self.layers, self._hidden_outputs):
self.training_monitors.append(('mean(%s)' % (layer.name), abs(hidden).mean())) |
Return all parameters. | def all_parameters(self):
"""
Return all parameters.
"""
params = []
params.extend(self.parameters)
params.extend(self.free_parameters)
return params |
Set up variables. | def setup_variables(self):
"""
Set up variables.
"""
if self.input_tensor:
if type(self.input_tensor) == int:
x = dim_to_var(self.input_tensor, name="x")
else:
x = self.input_tensor
else:
x = T.matrix('x')
... |
Return network output. | def compute(self, *x):
"""
Return network output.
"""
self._compile()
outs = self._compute(*x)
if self._output_keys:
return MapDict(dict(zip(self._output_keys, outs)))
else:
return outs |
Save parameters to file. | def save_params(self, path, new_thread=False):
"""
Save parameters to file.
"""
save_logger.info(path)
param_variables = self.all_parameters
params = [p.get_value().copy() for p in param_variables]
if new_thread:
thread = Thread(target=save_network_par... |
Load parameters from file. | def load_params(self, path, exclude_free_params=False):
"""
Load parameters from file.
"""
if not os.path.exists(path): return;
logging.info("loading parameters from %s" % path)
# Decide which parameters to load
if exclude_free_params:
params_to_load =... |
Print network statistics. | def report(self):
"""
Print network statistics.
"""
logging.info("network inputs: %s", " ".join(map(str, self.input_variables)))
logging.info("network targets: %s", " ".join(map(str, self.target_variables)))
logging.info("network parameters: %s", " ".join(map(str, self.al... |
Initialize the layer.: param no_prepare: avoid calling preparation function | def init(self, input_dim=0, input_dims=None, no_prepare=False):
"""
Initialize the layer.
:param no_prepare: avoid calling preparation function
"""
if self.initialized:
return
# configure input dimensions
if input_dims:
self.input_dims = in... |
Compute based on NeuralVariable.: type inputs: list of NeuralVariable: return: NeuralVariable | def compute(self, *inputs, **kwargs):
"""
Compute based on NeuralVariable.
:type inputs: list of NeuralVariable
:return: NeuralVariable
"""
from deepy.core.neural_var import NeuralVariable
from deepy.core.graph import graph
if type(inputs[0]) != NeuralVar... |
Let the given block or network manage the parameters of this layer.: param block: Block or NeuralNetwork: return: NeuralLayer | def belongs_to(self, block):
"""
Let the given block or network manage the parameters of this layer.
:param block: Block or NeuralNetwork
:return: NeuralLayer
"""
if self._linked_block:
raise SystemError("The layer {} has already blonged to {}".format(self.nam... |
Register parameters. | def register_parameters(self, *parameters):
"""
Register parameters.
"""
for param in parameters:
self.parameter_count += np.prod(param.get_value().shape)
self.parameters.extend(parameters) |
Register updates that will be executed in each iteration. | def register_updates(self, *updates):
"""
Register updates that will be executed in each iteration.
"""
for key, node in updates:
if key not in self._registered_updates:
self.updates.append((key, node))
self._registered_updates.add(key) |
Register updates that will only be executed in training phase. | def register_training_updates(self, *updates):
"""
Register updates that will only be executed in training phase.
"""
for key, node in updates:
if key not in self._registered_training_updates:
self.training_updates.append((key, node))
self._reg... |
Register monitors they should be tuple of name and Theano variable. | def register_monitors(self, *monitors):
"""
Register monitors they should be tuple of name and Theano variable.
"""
for key, node in monitors:
if key not in self._registered_monitors:
node *= 1.0 # Avoid CudaNdarray
self.training_monitors.appen... |
Get the L2 norm of multiple tensors. This function is taken from blocks. | def multiple_l2_norm(tensors):
"""
Get the L2 norm of multiple tensors.
This function is taken from blocks.
"""
# Another way for doing this, I don't know which one is fast
# return T.sqrt(sum(T.sum(t ** 2) for t in tensors))
flattened = [T.as_tensor_variable(t).flatten() for t in tensors]
... |
dumps one element to file_obj a file opened in write mode | def dump_one(elt_to_pickle, file_obj):
"""
dumps one element to file_obj, a file opened in write mode
"""
pickled_elt_str = dumps(elt_to_pickle)
file_obj.write(pickled_elt_str)
# record separator is a blank line
# (since pickled_elt_str might contain its own newli... |
load contents from file_obj returning a generator that yields one element at a time | def load(file_obj):
"""
load contents from file_obj, returning a generator that yields one
element at a time
"""
cur_elt = []
for line in file_obj:
cur_elt.append(line)
if line == '\n':
pickled_elt_str = ''.join(cur_elt)
cur_el... |
Fix the block register all the parameters of sub layers.: return: | def fix(self):
"""
Fix the block, register all the parameters of sub layers.
:return:
"""
if not self.fixed:
for layer in self.layers:
if not layer.initialized:
raise Exception("All sub layers in a block must be initialized when fix... |
Register one connected layer.: type layer: NeuralLayer | def register_layer(self, layer):
"""
Register one connected layer.
:type layer: NeuralLayer
"""
if self.fixed:
raise Exception("After a block is fixed, no more layers can be registered.")
self.layers.append(layer) |
Load parameters to the block. | def load_params(self, path, exclude_free_params=False):
from deepy.core import graph
"""
Load parameters to the block.
"""
from deepy.core.comp_graph import ComputationalGraph
model = graph.compile(blocks=[self])
model.load_params(path, exclude_free_params=exclude... |
Compute one step in the RNN.: return: one variable for RNN and GRU multiple variables for LSTM | def compute_step(self, state, lstm_cell=None, input=None, additional_inputs=None):
"""
Compute one step in the RNN.
:return: one variable for RNN and GRU, multiple variables for LSTM
"""
if not self.initialized:
input_dim = None
if input and hasattr(input.... |
: type input_var: T. var: rtype: dict | def get_initial_states(self, input_var, init_state=None):
"""
:type input_var: T.var
:rtype: dict
"""
initial_states = {}
for state in self.state_names:
if state != "state" or not init_state:
if self._input_type == 'sequence' and input_var.ndim... |
: type input_var: T. var: rtype: dict | def get_step_inputs(self, input_var, states=None, mask=None, additional_inputs=None):
"""
:type input_var: T.var
:rtype: dict
"""
step_inputs = {}
if self._input_type == "sequence":
if not additional_inputs:
additional_inputs = []
i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.