INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Returns a pre - defined model by name.
def get_model(name, dataset_name='wikitext-2', **kwargs): """Returns a pre-defined model by name. Parameters ---------- name : str Name of the model. dataset_name : str or None, default 'wikitext-2'. If None, then vocab is required, for specifying embedding weight size, and is direc...
Static BERT BASE model.
def bert_12_768_12(dataset_name=None, vocab=None, pretrained=True, ctx=mx.cpu(), root=os.path.join(get_home_dir(), 'models'), use_pooler=True, use_decoder=True, use_classifier=True, input_size=None, seq_length=None, **kwargs): """Static BERT BASE model. ...
Generate the representation given the inputs.
def hybrid_forward(self, F, inputs, token_types, valid_length=None, masked_positions=None): # pylint: disable=arguments-differ # pylint: disable=unused-argument """Generate the representation given the inputs. This is used in training or fine-tuning a static (hybridized) BERT model. ...
Load parameters from file.
def load_parameters(self, filename, ctx=mx.cpu()): # pylint: disable=arguments-differ """Load parameters from file. filename : str Path to parameter file. ctx : Context or list of Context, default cpu() Context(s) initialize loaded parameters on. """ self...
Defines the forward computation for cache cell. Arguments can be either: py: class: NDArray or: py: class: Symbol.
def forward(self, inputs, target, next_word_history, cache_history, begin_state=None): # pylint: disable=arguments-differ """Defines the forward computation for cache cell. Arguments can be either :py:class:`NDArray` or :py:class:`Symbol`. Parameters ---------- inputs: NDArray ...
Assign input x to an available worker and invoke parallizable. forward_backward with x.
def put(self, x): """Assign input `x` to an available worker and invoke `parallizable.forward_backward` with x. """ if self._num_serial > 0 or len(self._threads) == 0: self._num_serial -= 1 out = self._parallizable.forward_backward(x) self._out_queue.put(out) ...
Deserialize BERTVocab object from json string.
def from_json(cls, json_str): """Deserialize BERTVocab object from json string. Parameters ---------- json_str : str Serialized json string of a BERTVocab object. Returns ------- BERTVocab """ vocab_dict = json.loads(json_str) ...
Defines the forward computation. Arguments can be either: py: class: NDArray or: py: class: Symbol.
def forward(self, inputs, begin_state=None): # pylint: disable=arguments-differ """Defines the forward computation. Arguments can be either :py:class:`NDArray` or :py:class:`Symbol`. Parameters ----------- inputs : NDArray input tensor with shape `(sequence_length, b...
Defines the forward computation.
def forward(self, inputs, label, begin_state, sampled_values): # pylint: disable=arguments-differ """Defines the forward computation. Parameters ----------- inputs : NDArray input tensor with shape `(sequence_length, batch_size)` when `layout` is "TNC". b...
SkipGram forward pass.
def hybrid_forward(self, F, center, context, center_words): """SkipGram forward pass. Parameters ---------- center : mxnet.nd.NDArray or mxnet.sym.Symbol Sparse CSR array of word / subword indices of shape (batch_size, len(token_to_idx) + num_subwords). Embedding...
Evaluate network on the specified dataset
def evaluate(dataloader): """Evaluate network on the specified dataset""" total_L = 0.0 total_sample_num = 0 total_correct_num = 0 start_log_interval_time = time.time() print('Begin Testing...') for i, ((data, valid_length), label) in enumerate(dataloader): data = mx.nd.transpose(dat...
Training process
def train(): """Training process""" start_pipeline_time = time.time() # Training/Testing best_valid_acc = 0 stop_early = 0 for epoch in range(args.epochs): # Epoch training stats start_epoch_time = time.time() epoch_L = 0.0 epoch_sent_num = 0 epoch_wc = 0...
Forward logic
def hybrid_forward(self, F, data, valid_length): # pylint: disable=arguments-differ """Forward logic""" # Data will have shape (T, N, C) if self._use_mean_pool: masked_encoded = F.SequenceMask(data, sequence_length=valid_length, ...
r Hybrid forward computation for Long - Short Term Memory Projected network cell with cell clip and projection clip.
def hybrid_forward(self, F, inputs, states, i2h_weight, h2h_weight, h2r_weight, i2h_bias, h2h_bias): r"""Hybrid forward computation for Long-Short Term Memory Projected network cell with cell clip and projection clip. Parameters ---------- inputs : input t...
Rescales gradients of parameters so that the sum of their 2 - norm is smaller than max_norm. If gradients exist for more than one context for a parameter user needs to explicitly call trainer. allreduce_grads so that the gradients are summed first before calculating the 2 - norm.
def clip_grad_global_norm(parameters, max_norm, check_isfinite=True): """Rescales gradients of parameters so that the sum of their 2-norm is smaller than `max_norm`. If gradients exist for more than one context for a parameter, user needs to explicitly call ``trainer.allreduce_grads`` so that the gradients ...
Training function.
def train(data_train, model, nsp_loss, mlm_loss, vocab_size, ctx, store): """Training function.""" mlm_metric = nlp.metric.MaskedAccuracy() nsp_metric = nlp.metric.MaskedAccuracy() mlm_metric.reset() nsp_metric.reset() lr = args.lr optim_params = {'learning_rate': lr, 'epsilon': 1e-6, 'wd':...
forward backward implementation
def forward_backward(self, x): """forward backward implementation""" with mx.autograd.record(): (ls, next_sentence_label, classified, masked_id, decoded, \ masked_weight, ls1, ls2, valid_length) = forward(x, self._model, self._mlm_loss, ...
Print statistical information via the provided logger
def log_info(self, logger): """Print statistical information via the provided logger Parameters ---------- logger : logging.Logger logger created using logging.getLogger() """ logger.info('#words in training set: %d' % self._words_in_train_data) logge...
Read pre - trained embedding file for extending vocabulary
def _add_pret_words(self, pret_embeddings): """Read pre-trained embedding file for extending vocabulary Parameters ---------- pret_embeddings : tuple (embedding_name, source), used for gluonnlp.embedding.create(embedding_name, source) """ words_in_train_data ...
Read pre - trained embedding file
def get_pret_embs(self, word_dims=None): """Read pre-trained embedding file Parameters ---------- word_dims : int or None vector size. Use `None` for auto-infer Returns ------- numpy.ndarray T x C numpy NDArray """ assert (...
Get randomly initialized embeddings when pre - trained embeddings are used otherwise zero vectors
def get_word_embs(self, word_dims): """Get randomly initialized embeddings when pre-trained embeddings are used, otherwise zero vectors Parameters ---------- word_dims : int word vector size Returns ------- numpy.ndarray T x C numpy NDArra...
Randomly initialize embeddings for tag
def get_tag_embs(self, tag_dims): """Randomly initialize embeddings for tag Parameters ---------- tag_dims : int tag vector size Returns ------- numpy.ndarray random embeddings """ return np.random.randn(self.tag_size, tag...
Map word ( s ) to its id ( s )
def word2id(self, xs): """Map word(s) to its id(s) Parameters ---------- xs : str or list word or a list of words Returns ------- int or list id or a list of ids """ if isinstance(xs, list): return [self._word2...
Map id ( s ) to word ( s )
def id2word(self, xs): """Map id(s) to word(s) Parameters ---------- xs : int id or a list of ids Returns ------- str or list word or a list of words """ if isinstance(xs, list): return [self._id2word[x] for x ...
Map relation ( s ) to id ( s )
def rel2id(self, xs): """Map relation(s) to id(s) Parameters ---------- xs : str or list relation Returns ------- int or list id(s) of relation """ if isinstance(xs, list): return [self._rel2id[x] for x in xs] ...
Map id ( s ) to relation ( s )
def id2rel(self, xs): """Map id(s) to relation(s) Parameters ---------- xs : int id or a list of ids Returns ------- str or list relation or a list of relations """ if isinstance(xs, list): return [self._id2rel...
Map tag ( s ) to id ( s )
def tag2id(self, xs): """Map tag(s) to id(s) Parameters ---------- xs : str or list tag or tags Returns ------- int or list id(s) of tag(s) """ if isinstance(xs, list): return [self._tag2id.get(x, self.UNK) for...
Indices of sentences when enumerating data set from batches. Useful when retrieving the correct order of sentences
def idx_sequence(self): """Indices of sentences when enumerating data set from batches. Useful when retrieving the correct order of sentences Returns ------- list List of ids ranging from 0 to #sent -1 """ return [x[1] for x in sorted(zip(self._record...
Get batch iterator
def get_batches(self, batch_size, shuffle=True): """Get batch iterator Parameters ---------- batch_size : int size of one batch shuffle : bool whether to shuffle batches. Don't set to True when evaluating on dev or test set. Returns ------...
Extract a set of n - grams from a list of integers. >>> create_ngram_set ( [ 1 4 9 4 1 4 ] ngram_value = 2 ) { ( 4 9 ) ( 4 1 ) ( 1 4 ) ( 9 4 ) } >>> create_ngram_set ( [ 1 4 9 4 1 4 ] ngram_value = 3 ) [ ( 1 4 9 ) ( 4 9 4 ) ( 9 4 1 ) ( 4 1 4 ) ]
def create_ngram_set(input_list, ngram_value=2): """ Extract a set of n-grams from a list of integers. >>> create_ngram_set([1, 4, 9, 4, 1, 4], ngram_value=2) {(4, 9), (4, 1), (1, 4), (9, 4)} >>> create_ngram_set([1, 4, 9, 4, 1, 4], ngram_value=3) [(1, 4, 9), (4, 9, 4), (9, 4, 1), (4, 1, 4)] ...
Augment the input list of list ( sequences ) by appending n - grams values. Example: adding bi - gram >>> sequences = [[ 1 3 4 5 ] [ 1 3 7 9 2 ]] >>> token_indice = { ( 1 3 ): 1337 ( 9 2 ): 42 ( 4 5 ): 2017 } >>> add_ngram ( sequences token_indice ngram_range = 2 ) [[ 1 3 4 5 1337 2017 ] [ 1 3 7 9 2 1337 42 ]] Example:...
def add_ngram(sequences, token_indice, ngram_range=2): """ Augment the input list of list (sequences) by appending n-grams values. Example: adding bi-gram >>> sequences = [[1, 3, 4, 5], [1, 3, 7, 9, 2]] >>> token_indice = {(1, 3): 1337, (9, 2): 42, (4, 5): 2017} >>> add_ngram(sequences, token_in...
This function is used for evaluating accuracy of a given data iterator. ( Either Train/ Test data ) It takes in the loss function used too!
def evaluate_accuracy(data_iterator, net, ctx, loss_fun, num_classes): """ This function is used for evaluating accuracy of a given data iterator. (Either Train/Test data) It takes in the loss function used too! """ acc = mx.metric.Accuracy() loss_avg = 0. for i, ((data, length), label) ...
Helper function to get training data
def read_input_data(filename): """Helper function to get training data""" logging.info('Opening file %s for reading input', filename) input_file = open(filename, 'r') data = [] labels = [] for line in input_file: tokens = line.split(',', 1) labels.append(tokens[0].strip()) ...
Parse command line arguments.
def parse_args(): """Parse command line arguments.""" parser = argparse.ArgumentParser( description='Text Classification with FastText', formatter_class=argparse.ArgumentDefaultsHelpFormatter) # Computation options group = parser.add_argument_group('Computation arguments') group.add...
Create the mapping from label to numeric label
def get_label_mapping(train_labels): """ Create the mapping from label to numeric label """ sorted_labels = np.sort(np.unique(train_labels)) label_mapping = {} for i, label in enumerate(sorted_labels): label_mapping[label] = i logging.info('Label mapping:%s', format(label_mapping)) ...
This function takes a dataset and converts it into sequences via multiprocessing
def convert_to_sequences(dataset, vocab): """This function takes a dataset and converts it into sequences via multiprocessing """ start = time.time() dataset_vocab = map(lambda x: (x, vocab), dataset) with mp.Pool() as pool: # Each sample is processed in an asynchronous manner. o...
Preprocess and prepare a dataset
def preprocess_dataset(dataset, labels): """ Preprocess and prepare a dataset""" start = time.time() with mp.Pool() as pool: # Each sample is processed in an asynchronous manner. dataset = gluon.data.SimpleDataset(list(zip(dataset, labels))) lengths = gluon.data.SimpleDataset(pool.ma...
Construct the DataLoader. Pad data stack label and lengths
def get_dataloader(train_dataset, train_data_lengths, test_dataset, batch_size): """ Construct the DataLoader. Pad data, stack label and lengths""" bucket_num, bucket_ratio = 20, 0.2 batchify_fn = gluonnlp.data.batchify.Tuple( gluonnlp.data.batchify.Pad(axis=0, ret_length=True), ...
Training function that orchestrates the Classification!
def train(args): """Training function that orchestrates the Classification! """ train_file = args.input test_file = args.validation ngram_range = args.ngrams logging.info('Ngrams range for the training run : %s', ngram_range) logging.info('Loading Training data') train_labels, train_data = r...
Generate the unnormalized score for the given the input sequences.
def hybrid_forward(self, F, inputs, token_types, valid_length=None): # pylint: disable=arguments-differ # pylint: disable=unused-argument """Generate the unnormalized score for the given the input sequences. Parameters ---------- inputs : NDArray, shape (batch_size, seq_...
Parameters ---------- pred: NDArray shape ( batch_size seq_length 2 ) BERTSquad forward output. label: list length is 2 each shape is ( batch_size 1 ) label [ 0 ] is the starting position of the answer label [ 1 ] is the ending position of the answer.
def hybrid_forward(self, F, pred, label): # pylint: disable=arguments-differ """ Parameters ---------- pred : NDArray, shape (batch_size, seq_length, 2) BERTSquad forward output. label : list, length is 2, each shape is (batch_size,1) label[0] is the star...
Encode the input sequence.
def encode(self, inputs, states=None, valid_length=None): """Encode the input sequence. Parameters ---------- inputs : NDArray states : list of NDArrays or None, default None valid_length : NDArray or None, default None Returns ------- outputs : ...
Decode given the input sequence.
def decode_seq(self, inputs, states, valid_length=None): """Decode given the input sequence. Parameters ---------- inputs : NDArray states : list of NDArrays valid_length : NDArray or None, default None Returns ------- output : NDArray ...
One step decoding of the translation model.
def decode_step(self, step_input, states): """One step decoding of the translation model. Parameters ---------- step_input : NDArray Shape (batch_size,) states : list of NDArrays Returns ------- step_output : NDArray Shape (batch_...
Generate the prediction given the src_seq and tgt_seq.
def forward(self, src_seq, tgt_seq, src_valid_length=None, tgt_valid_length=None): #pylint: disable=arguments-differ """Generate the prediction given the src_seq and tgt_seq. This is used in training an NMT model. Parameters ---------- src_seq : NDArray tgt_seq : NDArr...
Creates an instance of a subword function.
def create_subword_function(subword_function_name, **kwargs): """Creates an instance of a subword function.""" create_ = registry.get_create_func(SubwordFunction, 'token embedding') return create_(subword_function_name, **kwargs)
Indexes unknown and reserved tokens.
def _index_special_tokens(self, unknown_token, special_tokens): """Indexes unknown and reserved tokens.""" self._idx_to_token = [unknown_token] if unknown_token else [] if not special_tokens: self._reserved_tokens = None else: self._reserved_tokens = special_toke...
Indexes keys of counter.
def _index_counter_keys(self, counter, unknown_token, special_tokens, max_size, min_freq): """Indexes keys of `counter`. Indexes keys of `counter` according to frequency thresholds such as `max_size` and `min_freq`. """ unknown_and_special_tokens = ...
Attaches one or more embeddings to the indexed text tokens.
def set_embedding(self, *embeddings): """Attaches one or more embeddings to the indexed text tokens. Parameters ---------- embeddings : None or tuple of :class:`gluonnlp.embedding.TokenEmbedding` instances The embedding to be attached to the indexed tokens. If a tuple of mu...
Converts token indices to tokens according to the vocabulary.
def to_tokens(self, indices): """Converts token indices to tokens according to the vocabulary. Parameters ---------- indices : int or list of ints A source token index or token indices to be converted. Returns ------- str or list of strs ...
Serialize Vocab object to json string.
def to_json(self): """Serialize Vocab object to json string. This method does not serialize the underlying embedding. """ if self._embedding: warnings.warn('Serialization of attached embedding ' 'to json is not supported. ' ...
Deserialize Vocab object from json string.
def from_json(cls, json_str): """Deserialize Vocab object from json string. Parameters ---------- json_str : str Serialized json string of a Vocab object. Returns ------- Vocab """ vocab_dict = json.loads(json_str) unknown_t...
Training function.
def train(data_train, model, nsp_loss, mlm_loss, vocab_size, ctx): """Training function.""" hvd.broadcast_parameters(model.collect_params(), root_rank=0) mlm_metric = nlp.metric.MaskedAccuracy() nsp_metric = nlp.metric.MaskedAccuracy() mlm_metric.reset() nsp_metric.reset() logging.debug('C...
Training function.
def train(): """Training function.""" log.info('Loader Train data...') if version_2: train_data = SQuAD('train', version='2.0') else: train_data = SQuAD('train', version='1.1') log.info('Number of records in Train data:{}'.format(len(train_data))) train_data_transform, _ = prepr...
Evaluate the model on validation dataset.
def evaluate(): """Evaluate the model on validation dataset. """ log.info('Loader dev data...') if version_2: dev_data = SQuAD('dev', version='2.0') else: dev_data = SQuAD('dev', version='1.1') log.info('Number of records in Train data:{}'.format(len(dev_data))) dev_dataset ...
Inner Implementation of the Pad batchify
def _pad_arrs_to_max_length(arrs, pad_axis, pad_val, use_shared_mem, dtype): """Inner Implementation of the Pad batchify Parameters ---------- arrs : list pad_axis : int pad_val : number use_shared_mem : bool, default False Returns ------- ret : NDArray original_length : ND...
Train a deep biaffine dependency parser
def train(self, train_file, dev_file, test_file, save_dir, pretrained_embeddings=None, min_occur_count=2, lstm_layers=3, word_dims=100, tag_dims=100, dropout_emb=0.33, lstm_hiddens=400, dropout_lstm_input=0.33, dropout_lstm_hidden=0.33, mlp_arc_size=500, mlp_rel_size=100, dropo...
Load from disk
def load(self, path): """Load from disk Parameters ---------- path : str path to the directory which typically contains a config.pkl file and a model.bin file Returns ------- DepParser parser itself """ config = _Config.lo...
Run evaluation on test set
def evaluate(self, test_file, save_dir=None, logger=None, num_buckets_test=10, test_batch_size=5000): """Run evaluation on test set Parameters ---------- test_file : str path to test set save_dir : str where to store intermediate results and log l...
Parse raw sentence into ConllSentence
def parse(self, sentence): """Parse raw sentence into ConllSentence Parameters ---------- sentence : list a list of (word, tag) tuples Returns ------- ConllSentence ConllSentence object """ words = np.zeros((len(sentence) ...
Apply weight drop to the parameter of a block.
def apply_weight_drop(block, local_param_regex, rate, axes=(), weight_dropout_mode='training'): """Apply weight drop to the parameter of a block. Parameters ---------- block : Block or HybridBlock The block whose parameter is to be applied weight-drop. local_param_rege...
create rnn cell given specs
def _get_rnn_cell(mode, num_layers, input_size, hidden_size, dropout, weight_dropout, var_drop_in, var_drop_state, var_drop_out, skip_connection, proj_size=None, cell_clip=None, proj_clip=None): """create rnn cell given specs Parameters ---------- m...
create rnn layer given specs
def _get_rnn_layer(mode, num_layers, input_size, hidden_size, dropout, weight_dropout): """create rnn layer given specs""" if mode == 'rnn_relu': rnn_block = functools.partial(rnn.RNN, activation='relu') elif mode == 'rnn_tanh': rnn_block = functools.partial(rnn.RNN, activation='tanh') e...
Forward computation.
def hybrid_forward(self, F, x, sampled_values, label, w_all, b_all): """Forward computation.""" sampled_candidates, expected_count_sampled, expected_count_true = sampled_values # (num_sampled, in_unit) w_sampled = w_all.slice(begin=(0, 0), end=(self._num_sampled, None)) w_true = ...
Forward computation.
def hybrid_forward(self, F, x, sampled_values, label, weight, bias): """Forward computation.""" sampled_candidates, _, _ = sampled_values # (batch_size,) label = F.reshape(label, shape=(-1,)) # (num_sampled+batch_size,) ids = F.concat(sampled_candidates, label, dim=0) ...
Forward computation.
def forward(self, x, sampled_values, label): """Forward computation.""" sampled_candidates, _, _ = sampled_values # (batch_size,) label = label.reshape(shape=(-1,)) # (num_sampled+batch_size,) ids = nd.concat(sampled_candidates, label, dim=0) # lookup weights and ...
Flatten the structure of a nested container to a list.
def _extract_and_flatten_nested_structure(data, flattened=None): """Flatten the structure of a nested container to a list. Parameters ---------- data : A single NDArray/Symbol or nested container with NDArrays/Symbol. The nested container to be flattened. flattened : list or None Th...
Reconstruct the flattened list back to ( possibly ) nested structure.
def _reconstruct_flattened_structure(structure, flattened): """Reconstruct the flattened list back to (possibly) nested structure. Parameters ---------- structure : An integer or a nested container with integers. The extracted structure of the container of `data`. flattened : list or None ...
Tile all the states to have batch_size * beam_size on the batch axis.
def _expand_to_beam_size(data, beam_size, batch_size, state_info=None): """Tile all the states to have batch_size * beam_size on the batch axis. Parameters ---------- data : A single NDArray/Symbol or nested container with NDArrays/Symbol Each NDArray/Symbol should have shape (N, ...) when stat...
Parameters ---------- F samples: NDArray or Symbol The current samples generated by beam search. Shape ( batch_size beam_size L ) valid_length: NDArray or Symbol The current valid lengths of the samples outputs: NDArray or Symbol Decoder output ( unnormalized ) scores of the current step. Shape ( batch_size * beam_size...
def hybrid_forward(self, F, samples, valid_length, outputs, scores, beam_alive_mask, states): """ Parameters ---------- F samples : NDArray or Symbol The current samples generated by beam search. Shape (batch_size, beam_size, L) valid_length : NDArray or Symbo...
Sample by beam search.
def hybrid_forward(self, F, inputs, states): # pylint: disable=arguments-differ """Sample by beam search. Parameters ---------- F inputs : NDArray or Symbol The initial input of the decoder. Shape is (batch_size,). states : Object that contains NDArrays or ...
Returns a copy of this parameter on one context. Must have been initialized on this context before.
def data(self, ctx=None): """Returns a copy of this parameter on one context. Must have been initialized on this context before. Parameters ---------- ctx : Context Desired context. Returns ------- NDArray on ctx """ d = self._...
r ELMo 2 - layer BiLSTM with 1024 hidden units 128 projection size 1 highway layer.
def elmo_2x1024_128_2048cnn_1xhighway(dataset_name=None, pretrained=False, ctx=mx.cpu(), root=os.path.join(get_home_dir(), 'models'), **kwargs): r"""ELMo 2-layer BiLSTM with 1024 hidden units, 128 projection size, 1 highway layer. Parameters ---------- dataset_name...
Compute context insensitive token embeddings for ELMo representations.
def hybrid_forward(self, F, inputs): # pylint: disable=arguments-differ """ Compute context insensitive token embeddings for ELMo representations. Parameters ---------- inputs : NDArray Shape (batch_size, sequence_length, max_character_per_token) ...
Parameters ---------- inputs: NDArray Shape ( batch_size sequence_length max_character_per_token ) of character ids representing the current batch. states: ( list of list of NDArray list of list of NDArray ) The states. First tuple element is the forward layer states while the second is the states from backward layer. ...
def hybrid_forward(self, F, inputs, states=None, mask=None): # pylint: disable=arguments-differ """ Parameters ---------- inputs : NDArray Shape (batch_size, sequence_length, max_character_per_token) of character ids representing the current batch. ...
r 3 - layer LSTM language model with weight - drop variational dropout and tied weights.
def awd_lstm_lm_1150(dataset_name=None, vocab=None, pretrained=False, ctx=cpu(), root=os.path.join(get_home_dir(), 'models'), **kwargs): r"""3-layer LSTM language model with weight-drop, variational dropout, and tied weights. Embedding size is 400, and hidden layer size is 1150. Param...
r Standard 2 - layer LSTM language model with tied embedding and output weights.
def standard_lstm_lm_200(dataset_name=None, vocab=None, pretrained=False, ctx=cpu(), root=os.path.join(get_home_dir(), 'models'), **kwargs): r"""Standard 2-layer LSTM language model with tied embedding and output weights. Both embedding and hidden dimensions are 200. Parameters ...
r Big 1 - layer LSTMP language model.
def big_rnn_lm_2048_512(dataset_name=None, vocab=None, pretrained=False, ctx=cpu(), root=os.path.join(get_home_dir(), 'models'), **kwargs): r"""Big 1-layer LSTMP language model. Both embedding and projection size are 512. Hidden size is 2048. Parameters ---------- dataset_n...
Implement forward computation.
def forward(self, inputs, begin_state=None): # pylint: disable=arguments-differ """Implement forward computation. Parameters ----------- inputs : NDArray input tensor with shape `(sequence_length, batch_size)` when `layout` is "TNC". begin_state : list ...
Implement forward computation.
def forward(self, inputs, begin_state): # pylint: disable=arguments-differ """Implement forward computation. Parameters ----------- inputs : NDArray input tensor with shape `(sequence_length, batch_size)` when `layout` is "TNC". begin_state : list ...
Get the object type of the cell by parsing the input
def _get_cell_type(cell_type): """Get the object type of the cell by parsing the input Parameters ---------- cell_type : str or type Returns ------- cell_constructor: type The constructor of the RNNCell """ if isinstance(cell_type, str): if cell_type == 'lstm': ...
Compute the context with respect to a center word in a sentence.
def _get_context(center_idx, sentence_boundaries, window_size, random_window_size, seed): """Compute the context with respect to a center word in a sentence. Takes an numpy array of sentences boundaries. """ random.seed(seed + center_idx) sentence_index = np.searchsorted(sentence...
Construct the model.
def model(dropout, vocab, model_mode, output_size): """Construct the model.""" textCNN = SentimentNet(dropout=dropout, vocab_size=len(vocab), model_mode=model_mode,\ output_size=output_size) textCNN.hybridize() return textCNN
Initialize parameters.
def init(textCNN, vocab, model_mode, context, lr): """Initialize parameters.""" textCNN.initialize(mx.init.Xavier(), ctx=context, force_reinit=True) if model_mode != 'rand': textCNN.embedding.weight.set_data(vocab.embedding.idx_to_vec) if model_mode == 'multichannel': textCNN.embedding_...
Use multiprocessing to perform transform for dataset.
def preprocess_dataset(dataset, transform, num_workers=8): """Use multiprocessing to perform transform for dataset. Parameters ---------- dataset: dataset-like object Source dataset. transform: callable Transformer function. num_workers: int, default 8 The number of mult...
Returns a pre - defined model by name.
def get_model(name, dataset_name='wikitext-2', **kwargs): """Returns a pre-defined model by name. Parameters ---------- name : str Name of the model. dataset_name : str or None, default 'wikitext-2'. The dataset name on which the pre-trained model is trained. For language mo...
Ignore the masked elements when calculating the softmax
def _masked_softmax(F, att_score, mask, dtype): """Ignore the masked elements when calculating the softmax Parameters ---------- F : symbol or ndarray att_score : Symborl or NDArray Shape (batch_size, query_length, memory_length) mask : Symbol or NDArray or None Shape (batch_siz...
Read from the value matrix given the attention weights.
def _read_by_weight(self, F, att_weights, value): """Read from the value matrix given the attention weights. Parameters ---------- F : symbol or ndarray att_weights : Symbol or NDArray Attention weights. For single-head attention, Shape (b...
Get the translation result given the input sentence.
def translate(self, src_seq, src_valid_length): """Get the translation result given the input sentence. Parameters ---------- src_seq : mx.nd.NDArray Shape (batch_size, length) src_valid_length : mx.nd.NDArray Shape (batch_size,) Returns ...
Evaluate parser on a data set
def evaluate_official_script(parser, vocab, num_buckets_test, test_batch_size, test_file, output_file, debug=False): """Evaluate parser on a data set Parameters ---------- parser : BiaffineParser biaffine parser vocab : ParserVocabulary vocabulary built ...
Create parameter with its value initialized according to a numpy tensor
def parameter_from_numpy(self, name, array): """ Create parameter with its value initialized according to a numpy tensor Parameters ---------- name : str parameter name array : np.ndarray initiation value Returns ------- mxnet.glu...
Create parameter given name shape and initiator
def parameter_init(self, name, shape, init): """Create parameter given name, shape and initiator Parameters ---------- name : str parameter name shape : tuple parameter shape init : mxnet.initializer an initializer Returns ...
Run decoding
def forward(self, word_inputs, tag_inputs, arc_targets=None, rel_targets=None): """Run decoding Parameters ---------- word_inputs : mxnet.ndarray.NDArray word indices of seq_len x batch_size tag_inputs : mxnet.ndarray.NDArray tag indices of seq_len x batc...
Save model
def save_parameters(self, filename): """Save model Parameters ---------- filename : str path to model file """ params = self._collect_params_with_prefix() if self.pret_word_embs: # don't save word embeddings inside model params.pop('pret_...
Function for processing data in worker process.
def _worker_fn(samples, batchify_fn, dataset=None): """Function for processing data in worker process.""" # pylint: disable=unused-argument # it is required that each worker process has to fork a new MXIndexedRecordIO handle # preserving dataset as global variable can save tons of overhead and is safe i...
Threadpool worker function for processing data.
def _thread_worker_fn(samples, batchify_fn, dataset): """Threadpool worker function for processing data.""" if isinstance(samples[0], (list, tuple)): batch = [batchify_fn([dataset[i] for i in shard]) for shard in samples] else: batch = batchify_fn([dataset[i] for i in samples]) return ba...
Creates an instance of token embedding.
def create(embedding_name, **kwargs): """Creates an instance of token embedding. Creates a token embedding instance by loading embedding vectors from an externally hosted pre-trained token embedding file, such as those of GloVe and FastText. To get all the valid `embedding_name` and `source`, use :fun...
Get valid token embedding names and their pre - trained file names.
def list_sources(embedding_name=None): """Get valid token embedding names and their pre-trained file names. To load token embedding vectors from an externally hosted pre-trained token embedding file, such as those of GloVe and FastText, one should use `gluonnlp.embedding.create(embedding_name, source)...
Load embedding vectors from a pre - trained token embedding file.
def _load_embedding(self, pretrained_file_path, elem_delim, encoding='utf8'): """Load embedding vectors from a pre-trained token embedding file. Both text files and TokenEmbedding serialization files are supported. elem_delim and encoding are ignored for non-text files. ...
Load embedding vectors from a pre - trained token embedding file.
def _load_embedding_txt(self, pretrained_file_path, elem_delim, encoding='utf8'): """Load embedding vectors from a pre-trained token embedding file. For every unknown token, if its representation `self.unknown_token` is encountered in the pre-trained token embedding file, index 0 of `self.idx_t...