Search is not available for this dataset
text
stringlengths
75
104k
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...
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()...
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_...
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...
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)...
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...
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]: ...
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...
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...
def report(self): """ Report elapsed time. """ if not self.end_time: self.end() print ("Time: {} mins".format((self.end_time - self.start_time )/ 60))
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 ...
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)
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...
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...
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 = {} ...
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...
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...
def iftrain(self, then_branch, else_branch): """ Execute `then_branch` when training. """ return ifelse(self._training_flag, then_branch, else_branch, name="iftrain")
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...
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...
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
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...
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: ...
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) ...
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 ...
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),...
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...
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()) ...
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...
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...
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))
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]
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)
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): ...
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 ""))
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
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)
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...
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...
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...
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...
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_...
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...
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
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") ...
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()
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)
def stack_encoders(self, *layers): """ Stack encoding layers, this must be done before stacking decoding layers. """ self.stack(*layers) self.encoding_layes.extend(layers)
def stack_decoders(self, *layers): """ Stack decoding layers. """ self.stack(*layers) self.decoding_layers.extend(layers)
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: ...
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...
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 """ # ...
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 ...
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...
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...
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()))
def all_parameters(self): """ Return all parameters. """ params = [] params.extend(self.parameters) params.extend(self.free_parameters) return params
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') ...
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
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...
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 =...
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...
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...
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...
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...
def register_parameters(self, *parameters): """ Register parameters. """ for param in parameters: self.parameter_count += np.prod(param.get_value().shape) self.parameters.extend(parameters)
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)
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...
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...
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] ...
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...
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...
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...
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)
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...
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....
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...
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...
def convert_to_theano_var(obj): """ Convert neural vars to theano vars. :param obj: NeuralVariable or list or dict or tuple :return: theano var, test var, tensor found, neural var found """ from deepy.core.neural_var import NeuralVariable if type(obj) == tuple: return tuple(convert_t...
def convert_to_neural_var(obj): """ Convert object and a test object into neural var. :param obj: tensor or list or dict or tuple :param test_obj: NeuralVar or list or dict or tuple :return: """ from theano.tensor.var import TensorVariable from deepy.core.neural_var import NeuralVariable...
def neural_computation(original_func, prefer_tensor=False): """ An annotation to enable theano-based fucntions to be called with NeuralVar. :param original_func: :param prefer_tensor: a switch to return tensors when no inputs :return: """ def wrapper(*args, **kwargs): normal_args, t...
def onehot_tensor(i_matrix, vocab_size): """ # batch x time """ dim0, dim1 = i_matrix.shape i_vector = i_matrix.reshape((-1,)) hot_matrix = T.extra_ops.to_one_hot(i_vector, vocab_size).reshape((dim0, dim1, vocab_size)) return hot_matrix
def create_request_elements( cls, request_type, credentials, url, method='GET', params=None, headers=None, body='', secret=None, redirect_uri='', scope='', csrf='', user_state='' ): """ Creates |oauth2| request elements. """ headers = headers or {...
def decode_state(cls, state, param='user_state'): """ Decode state and return param. :param str state: state parameter passed through by provider :param str param: key to query from decoded state variable. Options include 'csrf' and 'user_state'. ...
def refresh_credentials(self, credentials): """ Refreshes :class:`.Credentials` if it gives sense. :param credentials: :class:`.Credentials` to be refreshed. :returns: :class:`.Response`. """ if not self._x_refresh_credentials_if(credentials): ...
def _x_credentials_parser(credentials, data): """ We need to override this method to fix Facebooks naming deviation. """ # Facebook returns "expires" instead of "expires_in". credentials.expire_in = data.get('expires') if data.get('token_type') == 'bearer': ...
def _x_request_elements_filter(cls, request_type, request_elements, credentials): """ Google doesn't accept client ID and secret to be at the same time in request parameters and in the basic authorization header in the access token request. """ ...
def login(provider_name): """ Login handler, must accept both GET and POST to be able to use OpenID. """ # We need response object for the WerkzeugAdapter. response = make_response() # Log the user in, pass it the adapter and the provider name. result = authomatic.login( WerkzeugAd...
def normalize_dict(dict_): """ Replaces all values that are single-item iterables with the value of its index 0. :param dict dict_: Dictionary to normalize. :returns: Normalized dictionary. """ return dict([(k, v[0] if not isinstance(v, str) and len(v) == 1 else v) ...
def items_to_dict(items): """ Converts list of tuples to dictionary with duplicate keys converted to lists. :param list items: List of tuples. :returns: :class:`dict` """ res = collections.defaultdict(list) for k, v in items: res[k].append(v) return norm...
def json_qs_parser(body): """ Parses response body from JSON, XML or query string. :param body: string :returns: :class:`dict`, :class:`list` if input is JSON or query string, :class:`xml.etree.ElementTree.Element` if XML. """ try: # Try JSON first. ret...
def resolve_provider_class(class_): """ Returns a provider class. :param class_name: :class:`string` or :class:`authomatic.providers.BaseProvider` subclass. """ if isinstance(class_, str): # prepare path for authomatic.providers package path = '.'.join([__package__, 'providers...
def id_to_name(config, short_name): """ Returns the provider :doc:`config` key based on it's ``id`` value. :param dict config: :doc:`config`. :param id: Value of the id parameter in the :ref:`config` to search for. """ for k, v in list(config.items()): if v.get('id') =...
def create_cookie(self, delete=None): """ Creates the value for ``Set-Cookie`` HTTP header. :param bool delete: If ``True`` the cookie value will be ``deleted`` and the Expires value will be ``Thu, 01-Jan-1970 00:00:01 GMT``. """ value = 'deleted' if del...
def save(self): """ Adds the session cookie to headers. """ if self.data: cookie = self.create_cookie() cookie_len = len(cookie) if cookie_len > 4093: raise SessionError('Cookie too long! The cookie size {0} ' ...
def _get_data(self): """ Extracts the session data from cookie. """ cookie = self.adapter.cookies.get(self.name) return self._deserialize(cookie) if cookie else {}
def data(self): """ Gets session data lazily. """ if not self._data: self._data = self._get_data() # Always return a dict, even if deserialization returned nothing if self._data is None: self._data = {} return self._data
def _signature(self, *parts): """ Creates signature for the session. """ signature = hmac.new(six.b(self.secret), digestmod=hashlib.sha1) signature.update(six.b('|'.join(parts))) return signature.hexdigest()
def _serialize(self, value): """ Converts the value to a signed string with timestamp. :param value: Object to be serialized. :returns: Serialized value. """ # data = copy.deepcopy(value) data = value # 1. Serialize ser...
def _deserialize(self, value): """ Deserializes and verifies the value created by :meth:`._serialize`. :param str value: The serialized value. :returns: Deserialized object. """ # 3. Split encoded, timestamp, signature = value.split('|'...