INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Deserializes string to primitive type.
def __deserialize_primitive(self, data, klass): """Deserializes string to primitive type. :param data: str. :param klass: class literal. :return: int, long, float, str, bool. """ try: return klass(data) except UnicodeEncodeError: return s...
The logger file.
def logger_file(self, value): """The logger file. If the logger_file is None, then add stream handler and remove file handler. Otherwise, add file handler and remove stream handler. :param value: The logger_file path. :type: str """ self.__logger_file = value ...
Sets the license_name of this DatasetNewRequest.
def license_name(self, license_name): """Sets the license_name of this DatasetNewRequest. The license that should be associated with the dataset # noqa: E501 :param license_name: The license_name of this DatasetNewRequest. # noqa: E501 :type: str """ allowed_values = ...
Train textCNN model for sentiment analysis.
def train(net, train_data, test_data): """Train textCNN model for sentiment analysis.""" start_pipeline_time = time.time() net, trainer = text_cnn.init(net, vocab, args.model_mode, context, args.lr) random.shuffle(train_data) sp = int(len(train_data)*0.9) train_dataloader = DataLoader(dataset=tr...
Get tokens tokens embedding
def embedding(self, sentences, oov_way='avg'): """ Get tokens, tokens embedding Parameters ---------- sentences : List[str] sentences for encoding. oov_way : str, default avg. use **avg**, **sum** or **last** to get token embedding for those out o...
Load tokenize and prepare the input sentences.
def data_loader(self, sentences, shuffle=False): """Load, tokenize and prepare the input sentences.""" dataset = BertEmbeddingDataset(sentences, self.transform) return DataLoader(dataset=dataset, batch_size=self.batch_size, shuffle=shuffle)
How to handle oov. Also filter out [ CLS ] [ SEP ] tokens.
def oov(self, batches, oov_way='avg'): """ How to handle oov. Also filter out [CLS], [SEP] tokens. Parameters ---------- batches : List[(tokens_id, sequence_outputs, pooled_output]. batch token_ids (max_seq_length, ),...
Any BERT pretrained model.
def get_bert_model(model_name=None, dataset_name=None, vocab=None, pretrained=True, ctx=mx.cpu(), use_pooler=True, use_decoder=True, use_classifier=True, output_attention=False, output_all_encodings=False, root=os.path.join(get_home_dir(), 'mod...
forward computation.
def hybrid_forward(self, F, data, gamma, beta): """forward computation.""" # TODO(haibin): LayerNorm does not support fp16 safe reduction. Issue is tracked at: # https://github.com/apache/incubator-mxnet/issues/14073 if self._dtype: data = data.astype('float32') g...
Construct a decoder for the next sentence prediction task
def _get_classifier(self, prefix): """ Construct a decoder for the next sentence prediction task """ with self.name_scope(): classifier = nn.Dense(2, prefix=prefix) return classifier
Construct a decoder for the masked language model task
def _get_decoder(self, units, vocab_size, embed, prefix): """ Construct a decoder for the masked language model task """ with self.name_scope(): decoder = nn.HybridSequential(prefix=prefix) decoder.add(nn.Dense(units, flatten=False)) decoder.add(GELU()) de...
Construct an embedding block.
def _get_embed(self, embed, vocab_size, embed_size, initializer, dropout, prefix): """ Construct an embedding block. """ if embed is None: assert embed_size is not None, '"embed_size" cannot be None if "word_embed" or ' \ 'token_type_embed is not gi...
Construct pooler.
def _get_pooler(self, units, prefix): """ Construct pooler. The pooler slices and projects the hidden output of first token in the sequence for segment level classification. """ with self.name_scope(): pooler = nn.Dense(units=units, flatten=False, activation='tanh',...
Generate the representation given the input sequences.
def _encode_sequence(self, inputs, token_types, valid_length=None): """Generate the representation given the input sequences. This is used for pre-training or fine-tuning a BERT model. """ # embedding word_embedding = self.word_embed(inputs) type_embedding = self.token_t...
Generate unnormalized prediction for the masked language model task.
def _decode(self, sequence, masked_positions): """Generate unnormalized prediction for the masked language model task. This is only used for pre-training the BERT model. Inputs: - **sequence**: input tensor of sequence encodings. Shape (batch_size, seq_length, units)....
Extracts n - grams from an input segment.
def _ngrams(segment, n): """Extracts n-grams from an input segment. Parameters ---------- segment: list Text segment from which n-grams will be extracted. n: int Order of n-gram. Returns ------- ngram_counts: Counter Contain all the nth n-grams in segment with a...
Convert a sequence of bpe words into sentence.
def _bpe_to_words(sentence, delimiter='@@'): """Convert a sequence of bpe words into sentence.""" words = [] word = '' delimiter_len = len(delimiter) for subwords in sentence: if len(subwords) >= delimiter_len and subwords[-delimiter_len:] == delimiter: word += subwords[:-delimit...
r Tokenizes a string following the tokenizer in mteval - v13a. pl. See https:// github. com/ moses - smt/ mosesdecoder/ blob/ master/ scripts/ generic/ mteval - v14. pl#L917 - L942 Parameters ---------- segment: str A string to be tokenized
def _tokenize_mteval_13a(segment): r""" Tokenizes a string following the tokenizer in mteval-v13a.pl. See https://github.com/moses-smt/mosesdecoder/" "blob/master/scripts/generic/mteval-v14.pl#L917-L942 Parameters ---------- segment: str A string to be tokenized Returns ...
r Tokenize a string following following the international tokenizer in mteval - v14a. pl. See https:// github. com/ moses - smt/ mosesdecoder/ blob/ master/ scripts/ generic/ mteval - v14. pl#L954 - L983
def _tokenize_mteval_v14_intl(segment): r"""Tokenize a string following following the international tokenizer in mteval-v14a.pl. See https://github.com/moses-smt/mosesdecoder/" "blob/master/scripts/generic/mteval-v14.pl#L954-L983 Parameters ---------- segment: str A string to be ...
r Compute bleu score of translation against references.
def compute_bleu(reference_corpus_list, translation_corpus, tokenized=True, tokenizer='13a', max_n=4, smooth=False, lower_case=False, bpe=False, split_compound_word=False): r"""Compute bleu score of translation against references. Parameters ---------- reference_corpus...
Compute ngram precision.
def _compute_precision(references, translation, n): """Compute ngram precision. Parameters ---------- references: list(list(str)) A list of references. translation: list(str) A translation. n: int Order of n-gram. Returns ------- matches: int Number ...
Calculate brevity penalty.
def _brevity_penalty(ref_length, trans_length): """Calculate brevity penalty. Parameters ---------- ref_length: int Sum of all closest references'lengths for every translations in a corpus trans_length: int Sum of all translations's lengths in a corpus. Returns ------- ...
Find the reference that has the closest length to the translation.
def _closest_ref_length(references, trans_length): """Find the reference that has the closest length to the translation. Parameters ---------- references: list(list(str)) A list of references. trans_length: int Length of the translation. Returns ------- closest_ref_len:...
Compute the smoothed precision for all the orders.
def _smoothing(precision_fractions, c=1): """Compute the smoothed precision for all the orders. Parameters ---------- precision_fractions: list(tuple) Contain a list of (precision_numerator, precision_denominator) pairs c: int, default 1 Smoothing constant to use Returns --...
Draw samples from log uniform distribution and returns sampled candidates expected count for true classes and sampled classes.
def forward(self, true_classes): """Draw samples from log uniform distribution and returns sampled candidates, expected count for true classes and sampled classes. Parameters ---------- true_classes: NDArray The true classes. Returns ------- ...
Dataset preprocessing helper.
def preprocess_dataset(data, min_freq=5, max_vocab_size=None): """Dataset preprocessing helper. Parameters ---------- data : mx.data.Dataset Input Dataset. For example gluonnlp.data.Text8 or gluonnlp.data.Fil9 min_freq : int, default 5 Minimum token frequency for a token to be inclu...
Wikipedia dump helper.
def wiki(wiki_root, wiki_date, wiki_language, max_vocab_size=None): """Wikipedia dump helper. Parameters ---------- wiki_root : str Parameter for WikiDumpStream wiki_date : str Parameter for WikiDumpStream wiki_language : str Parameter for WikiDumpStream max_vocab_si...
Transform a DataStream of coded DataSets to a DataStream of batches.
def transform_data_fasttext(data, vocab, idx_to_counts, cbow, ngram_buckets, ngrams, batch_size, window_size, frequent_token_subsampling=1E-4, dtype='float32', index_dtype='int64'): """Transform a DataStream of coded DataSets to a D...
Transform a DataStream of coded DataSets to a DataStream of batches.
def transform_data_word2vec(data, vocab, idx_to_counts, cbow, batch_size, window_size, frequent_token_subsampling=1E-4, dtype='float32', index_dtype='int64'): """Transform a DataStream of coded DataSets to a DataStream of batches. Parameters ---------...
Create a batch for CBOW training objective with subwords.
def cbow_fasttext_batch(centers, contexts, num_tokens, subword_lookup, dtype, index_dtype): """Create a batch for CBOW training objective with subwords.""" _, contexts_row, contexts_col = contexts data, row, col = subword_lookup(contexts_row, contexts_col) centers = mx.nd.array(c...
Create a batch for SG training objective with subwords.
def skipgram_fasttext_batch(centers, contexts, num_tokens, subword_lookup, dtype, index_dtype): """Create a batch for SG training objective with subwords.""" contexts = mx.nd.array(contexts[2], dtype=index_dtype) data, row, col = subword_lookup(centers) centers = mx.nd.array(...
Create a batch for CBOW training objective.
def cbow_batch(centers, contexts, num_tokens, dtype, index_dtype): """Create a batch for CBOW training objective.""" contexts_data, contexts_row, contexts_col = contexts centers = mx.nd.array(centers, dtype=index_dtype) contexts = mx.nd.sparse.csr_matrix( (contexts_data, (contexts_row, contexts_...
Create a batch for SG training objective.
def skipgram_batch(centers, contexts, num_tokens, dtype, index_dtype): """Create a batch for SG training objective.""" contexts = mx.nd.array(contexts[2], dtype=index_dtype) indptr = mx.nd.arange(len(centers) + 1) centers = mx.nd.array(centers, dtype=index_dtype) centers_csr = mx.nd.sparse.csr_matri...
Get a sparse COO array of words and subwords for SkipGram.
def skipgram_lookup(indices, subwordidxs, subwordidxsptr, offset=0): """Get a sparse COO array of words and subwords for SkipGram. Parameters ---------- indices : numpy.ndarray Array containing numbers in [0, vocabulary_size). The element at position idx is taken to be the word that occ...
Get a sparse COO array of words and subwords for CBOW.
def cbow_lookup(context_row, context_col, subwordidxs, subwordidxsptr, offset=0): """Get a sparse COO array of words and subwords for CBOW. Parameters ---------- context_row : numpy.ndarray of dtype int64 Array of same length as context_col containing numbers in [0, batc...
Source Vocabulary of the Dataset.
def src_vocab(self): """Source Vocabulary of the Dataset. Returns ------- src_vocab : Vocab Source vocabulary. """ if self._src_vocab is None: src_vocab_file_name, src_vocab_hash = \ self._data_file[self._pair_key]['vocab' + '_' + ...
Target Vocabulary of the Dataset.
def tgt_vocab(self): """Target Vocabulary of the Dataset. Returns ------- tgt_vocab : Vocab Target vocabulary. """ if self._tgt_vocab is None: tgt_vocab_file_name, tgt_vocab_hash = \ self._data_file[self._pair_key]['vocab' + '_' + ...
Evaluate given the data loader
def evaluate(data_loader): """Evaluate given the data loader Parameters ---------- data_loader : DataLoader Returns ------- avg_loss : float Average loss real_translation_out : list of list of str The translation output """ translation_out = [] all_inst_ids ...
Training function.
def train(): """Training function.""" trainer = gluon.Trainer(model.collect_params(), args.optimizer, {'learning_rate': args.lr}) train_data_loader, val_data_loader, test_data_loader \ = dataprocessor.make_dataloader(data_train, data_val, data_test, args) best_valid_bleu = 0.0 for epoch_id...
r Returns a cache model using a pre - trained language model.
def get_cache_model(name, dataset_name='wikitext-2', window=2000, theta=0.6, lambdas=0.2, ctx=mx.cpu(), **kwargs): r"""Returns a cache model using a pre-trained language model. We implement the neural cache language model proposed in the following work:: @article{grave2016improving...
Training helper.
def train(args): """Training helper.""" if not args.model.lower() in ['cbow', 'skipgram']: logging.error('Unsupported model %s.', args.model) sys.exit(1) if args.data.lower() == 'toy': data = mx.gluon.data.SimpleDataset(nlp.data.Text8(segment='train')[:2]) data, vocab, idx_t...
Evaluation helper
def evaluate(args, embedding, vocab, global_step, eval_analogy=False): """Evaluation helper""" if 'eval_tokens' not in globals(): global eval_tokens eval_tokens_set = evaluation.get_tokens_in_evaluation_datasets(args) if not args.no_eval_analogy: eval_tokens_set.update(vocab...
Return the dataset corresponds to the provided key.
def get_field(self, field): """Return the dataset corresponds to the provided key. Example:: a = np.ones((2,2)) b = np.zeros((2,2)) np.savez('data.npz', a=a, b=b) dataset = NumpyDataset('data.npz') data_a = dataset.get_field('a') d...
Project the tokenized prediction back to the original text.
def get_final_text(pred_text, orig_text, tokenizer): """Project the tokenized prediction back to the original text.""" # When we created the data, we kept track of the alignment between original # (whitespace tokenized) tokens and our WordPiece tokenized tokens. So # now `orig_text` contains the span o...
Get prediction results
def predictions(dev_dataset, all_results, tokenizer, max_answer_length=64, null_score_diff_threshold=0.0, n_best_size=10, version_2=False): """Get prediction results Parameters ---------- dev_dataset: datase...
Calculate the F1 and EM scores of the predicted results. Use only with the SQuAD1. 1 dataset.
def get_F1_EM(dataset, predict_data): """Calculate the F1 and EM scores of the predicted results. Use only with the SQuAD1.1 dataset. Parameters ---------- dataset_file: string Path to the data file. predict_data: dict All final predictions. Returns ------- scores: ...
Data preparation function.
def preprocess_data(tokenizer, task, batch_size, dev_batch_size, max_len, pad=False): """Data preparation function.""" # transformation trans = BERTDatasetTransform( tokenizer, max_len, labels=task.get_labels(), pad=pad, pair=task.is_pair, label_dtype='float32...
Evaluate the model on validation dataset.
def evaluate(dataloader_eval, metric): """Evaluate the model on validation dataset. """ metric.reset() for _, seqs in enumerate(dataloader_eval): input_ids, valid_len, type_ids, label = seqs out = model( input_ids.as_in_context(ctx), type_ids.as_in_context(ctx), v...
Generate and print out the log message for training.
def log_train(batch_id, batch_num, metric, step_loss, log_interval, epoch_id, learning_rate): """Generate and print out the log message for training. """ metric_nm, metric_val = metric.get() if not isinstance(metric_nm, list): metric_nm = [metric_nm] metric_val = [metric_val] train_...
Generate and print out the log message for inference.
def log_inference(batch_id, batch_num, metric, step_loss, log_interval): """Generate and print out the log message for inference. """ metric_nm, metric_val = metric.get() if not isinstance(metric_nm, list): metric_nm = [metric_nm] metric_val = [metric_val] eval_str = '[Batch %d/%d] ...
Training function.
def train(metric): """Training function.""" logging.info('Now we are doing BERT classification training on %s!', ctx) optimizer_params = {'learning_rate': lr, 'epsilon': epsilon, 'wd': 0.01} try: trainer = gluon.Trainer( model.collect_params(), args.optimizer, ...
Inference function.
def inference(metric): """Inference function.""" logging.info('Now we are doing BERT classification inference on %s!', ctx) model = BERTClassifier(bert, dropout=0.1, num_classes=len(task.get_labels())) model.hybridize(static_alloc=True) model.load_parameters(model_parameters, ctx=ctx) metric.r...
Process SQuAD dataset by creating NDArray version of data
def preprocess_dataset(dataset, question_max_length, context_max_length): """Process SQuAD dataset by creating NDArray version of data :param Dataset dataset: SQuAD dataset :param int question_max_length: Maximum length of question (padded or trimmed to that size) :param int context_max_length: Maximum...
Find all answer spans from the context returning start_index and end_index
def _get_answer_spans(answer_list, answer_start_list): """Find all answer spans from the context, returning start_index and end_index :param list[str] answer_list: List of all answers :param list[int] answer_start_list: List of all answers' start indices Returns ------- ...
Provides word level vocabulary
def get_word_level_vocab(self): """Provides word level vocabulary Returns ------- Vocab Word level vocabulary """ def simple_tokenize(source_str, token_delim=' ', seq_delim='\n'): return list(filter(None, re.split(token_delim + '|' + seq_delim, s...
Parameters ---------- states: list the stack outputs from RNN which consists of output from each time step ( TNC ).
def hybrid_forward(self, F, *states): # pylint: disable=arguments-differ """ Parameters ---------- states : list the stack outputs from RNN, which consists of output from each time step (TNC). Returns -------- loss : NDArray loss tensor wi...
Tokenizes a piece of text.
def _tokenize(self, text): """Tokenizes a piece of text.""" text = self._clean_text(text) # This was added on November 1st, 2018 for the multilingual and Chinese # models. This is also applied to the English models now, but it doesn't # matter since the English models were not t...
Performs invalid character removal and whitespace cleanup on text.
def _clean_text(self, text): """Performs invalid character removal and whitespace cleanup on text.""" output = [] for char in text: cp = ord(char) if cp in (0, 0xfffd) or self._is_control(char): continue if self._is_whitespace(char): ...
Checks whether chars is a control character.
def _is_control(self, char): """Checks whether `chars` is a control character.""" # These are technically control characters but we count them as whitespace # characters. if char in ['\t', '\n', '\r']: return False cat = unicodedata.category(char) if cat.start...
Splits punctuation on a piece of text.
def _run_split_on_punc(self, text): """Splits punctuation on a piece of text.""" chars = list(text) i = 0 start_new_word = True output = [] while i < len(chars): char = chars[i] if self._is_punctuation(char): output.append([char]) ...
Checks whether chars is a punctuation character.
def _is_punctuation(self, char): """Checks whether `chars` is a punctuation character.""" cp = ord(char) # We treat all non-letter/number ASCII as punctuation. # Characters such as "^", "$", and "`" are not in the Unicode # Punctuation class but we treat them as punctuation anywa...
Checks whether chars is a whitespace character.
def _is_whitespace(self, char): """Checks whether `chars` is a whitespace character.""" # \t, \n, and \r are technically contorl characters but we treat them # as whitespace since they are generally considered as such. if char in [' ', '\t', '\n', '\r']: return True c...
Runs basic whitespace cleaning and splitting on a piece of text.
def _whitespace_tokenize(self, text): """Runs basic whitespace cleaning and splitting on a piece of text.""" text = text.strip() tokens = text.split() return tokens
Tokenizes a piece of text into its word pieces.
def _tokenize_wordpiece(self, text): """Tokenizes a piece of text into its word pieces. This uses a greedy longest-match-first algorithm to perform tokenization using the given vocabulary. For example: input = "unaffable" output = ["un", "##aff", "##able"] ...
Truncates a sequence pair in place to the maximum length.
def _truncate_seq_pair(self, tokens_a, tokens_b, max_length): """Truncates a sequence pair in place to the maximum length.""" # This is a simple heuristic which will always truncate the longer sequence # one token at a time. This makes more sense than truncating an equal percent # of tok...
Construct the argument parser.
def get_args(): """Construct the argument parser.""" parser = argparse.ArgumentParser( description='Word embedding evaluation with Gluon.', formatter_class=argparse.ArgumentDefaultsHelpFormatter) # Embeddings arguments group = parser.add_argument_group('Embedding arguments') group.a...
Validate provided arguments and act on -- help.
def validate_args(args): """Validate provided arguments and act on --help.""" if args.list_embedding_sources: print('Listing all sources for {} embeddings.'.format( args.embedding_name)) print('Specify --embedding-name if you wish to ' 'list sources of other embeddings'...
Load a TokenEmbedding.
def load_embedding_from_path(args): """Load a TokenEmbedding.""" if args.embedding_path.endswith('.bin'): with utils.print_time('load fastText model.'): model = \ nlp.model.train.FasttextEmbeddingModel.load_fasttext_format( args.embedding_path) idx...
Calculate the 2 - norm of gradients of parameters and how much they should be scaled down such that their 2 - norm does not exceed max_norm.
def grad_global_norm(parameters, max_norm): """Calculate the 2-norm of gradients of parameters, and how much they should be scaled down such that their 2-norm does not exceed `max_norm`. If gradients exist for more than one context for a parameter, user needs to explicitly call ``trainer.allreduce_grad...
backward propagation with loss
def backward(self, loss): """backward propagation with loss""" with mx.autograd.record(): if isinstance(loss, (tuple, list)): ls = [l * self._scaler.loss_scale for l in loss] else: ls = loss * self._scaler.loss_scale mx.autograd.backward(ls...
Makes one step of parameter update. Should be called after fp16_optimizer. backward () and outside of record () scope.
def step(self, batch_size, max_norm=None): """Makes one step of parameter update. Should be called after `fp16_optimizer.backward()`, and outside of `record()` scope. Parameters ---------- batch_size : int Batch size of data processed. Gradient will be normalized by ...
detect inf and nan
def has_overflow(self, params): """ detect inf and nan """ is_not_finite = 0 for param in params: if param.grad_req != 'null': grad = param.list_grad()[0] is_not_finite += mx.nd.contrib.isnan(grad).sum() is_not_finite += mx.nd.contrib.i...
dynamically update loss scale
def update_scale(self, overflow): """dynamically update loss scale""" iter_since_rescale = self._num_steps - self._last_rescale_iter if overflow: self._last_overflow_iter = self._num_steps self._overflows_since_rescale += 1 percentage = self._overflows_since_r...
Return a string representing the statistics of the bucketing sampler.
def stats(self): """Return a string representing the statistics of the bucketing sampler. Returns ------- ret : str String representing the statistics of the buckets. """ ret = '{name}:\n' \ ' sample_num={sample_num}, batch_num={batch_num}\n' \ ...
Training loop for language model.
def train(): """Training loop for language model. """ print(model) from_epoch = 0 model.initialize(mx.init.Xavier(factor_type='out'), ctx=context) trainer_params = {'learning_rate': args.lr, 'wd': 0, 'eps': args.eps} trainer = gluon.Trainer(model.collect_params(), 'adagrad', trainer_params) ...
Evaluate loop for the trained model
def evaluate(): """ Evaluate loop for the trained model """ print(eval_model) eval_model.initialize(mx.init.Xavier(), ctx=context[0]) eval_model.hybridize(static_alloc=True, static_shape=True) epoch = args.from_epoch if args.from_epoch else 0 while epoch < args.epochs: checkpoint_name = ...
Load sentiment dataset.
def load_dataset(data_name): """Load sentiment dataset.""" if data_name == 'MR' or data_name == 'Subj': train_dataset, output_size = _load_file(data_name) vocab, max_len = _build_vocab(data_name, train_dataset, []) train_dataset, train_data_lengths = _preprocess_dataset(train_dataset, vo...
Get home directory for storing datasets/ models/ pre - trained word embeddings
def get_home_dir(): """Get home directory for storing datasets/models/pre-trained word embeddings""" _home_dir = os.environ.get('MXNET_HOME', os.path.join('~', '.mxnet')) # expand ~ to actual path _home_dir = os.path.expanduser(_home_dir) return _home_dir
Read dataset from tokenized files.
def read_dataset(args, dataset): """ Read dataset from tokenized files. """ path = os.path.join(vars(args)[dataset]) logger.info('reading data from {}'.format(path)) examples = [line.strip().split('\t') for line in open(path)] if args.max_num_examples > 0: examples = examples[:args.m...
Build vocab given a dataset.
def build_vocab(dataset): """ Build vocab given a dataset. """ counter = nlp.data.count_tokens([w for e in dataset for s in e[:2] for w in s], to_lower=True) vocab = nlp.Vocab(counter) return vocab
Read data and build data loader.
def prepare_data_loader(args, dataset, vocab, test=False): """ Read data and build data loader. """ # Preprocess dataset = dataset.transform(lambda s1, s2, label: (vocab(s1), vocab(s2), label), lazy=False) # Batching batchify_fn = btf.Tuple(btf.Pad(), btf.Pad...
If gpu available return gpu else cpu
def mxnet_prefer_gpu(): """If gpu available return gpu, else cpu Returns ------- context : Context The preferable GPU context. """ gpu = int(os.environ.get('MXNET_GPU', default=0)) if gpu in mx.test_utils.list_gpus(): return mx.gpu(gpu) return mx.cpu()
Initialize a logger
def init_logger(root_dir, name="train.log"): """Initialize a logger Parameters ---------- root_dir : str directory for saving log name : str name of logger Returns ------- logger : logging.Logger a logger """ os.makedirs(root_dir, exist_ok=True) log_...
Build a standard LSTM cell with variational dropout with weights initialized to be orthonormal ( https:// arxiv. org/ abs/ 1312. 6120 )
def orthonormal_VanillaLSTMBuilder(lstm_layers, input_dims, lstm_hiddens, dropout_x=0., dropout_h=0., debug=False): """Build a standard LSTM cell, with variational dropout, with weights initialized to be orthonormal (https://arxiv.org/abs/1312.6120) Parameters ---------- lstm_layers : int C...
Feature extraction through BiLSTM
def biLSTM(f_lstm, b_lstm, inputs, batch_size=None, dropout_x=0., dropout_h=0.): """Feature extraction through BiLSTM Parameters ---------- f_lstm : VariationalDropoutCell Forward cell b_lstm : VariationalDropoutCell Backward cell inputs : NDArray seq_len x batch_size ...
Do xWy
def bilinear(x, W, y, input_size, seq_len, batch_size, num_outputs=1, bias_x=False, bias_y=False): """Do xWy Parameters ---------- x : NDArray (input_size x seq_len) x batch_size W : NDArray (num_outputs x ny) x nx y : NDArray (input_size x seq_len) x batch_size inpu...
adopted from Timothy Dozat https:// github. com/ tdozat/ Parser/ blob/ master/ lib/ linalg. py
def orthonormal_initializer(output_size, input_size, debug=False): """adopted from Timothy Dozat https://github.com/tdozat/Parser/blob/master/lib/linalg.py Parameters ---------- output_size : int input_size : int debug : bool Whether to skip this initializer Returns ------- ...
MST Adopted from Timothy Dozat https:// github. com/ tdozat/ Parser/ blob/ master/ lib/ models/ nn. py
def arc_argmax(parse_probs, length, tokens_to_keep, ensure_tree=True): """MST Adopted from Timothy Dozat https://github.com/tdozat/Parser/blob/master/lib/models/nn.py Parameters ---------- parse_probs : NDArray seq_len x seq_len, the probability of arcs length : NDArray real sen...
Fix the relation prediction by heuristic rules
def rel_argmax(rel_probs, length, ensure_tree=True): """Fix the relation prediction by heuristic rules Parameters ---------- rel_probs : NDArray seq_len x rel_size length : real sentence length ensure_tree : whether to apply rules Returns ------- rel_preds : ...
The missing Fortran reshape for mx. NDArray
def reshape_fortran(tensor, shape): """The missing Fortran reshape for mx.NDArray Parameters ---------- tensor : NDArray source tensor shape : NDArray desired shape Returns ------- output : NDArray reordered result """ return tensor.T.reshape(tuple(rever...
Updates the progress bar. # Arguments current: Index of current step. values: List of tuples ( name value_for_last_step ). The progress bar will display averages for these values. exact: List of tuples ( name value_for_last_step ). The progress bar will display these values directly.
def update(self, current, values=[], exact=[], strict=[]): """ Updates the progress bar. # Arguments current: Index of current step. values: List of tuples (name, value_for_last_step). The progress bar will display averages for these values. ex...
Get mini - batches of the dataset.
def get_batch(data_source, i, seq_len=None): """Get mini-batches of the dataset. Parameters ---------- data_source : NDArray The dataset is evaluated on. i : int The index of the batch, starting from 0. seq_len : int The length of each sample in the batch. Returns ...
Evaluate the model on the dataset.
def evaluate(data_source, batch_size, params_file_name, ctx=None): """Evaluate the model on the dataset. Parameters ---------- data_source : NDArray The dataset is evaluated on. batch_size : int The size of the mini-batch. params_file_name : str The parameter file to use...
Training loop for awd language model.
def train(): """Training loop for awd language model. """ ntasgd = False best_val = float('Inf') start_train_time = time.time() parameters = model.collect_params() param_dict_avg = None t = 0 avg_trigger = 0 n = 5 valid_losses = [] for epoch in range(args.epochs): ...
Registers a new word embedding evaluation function.
def register(class_): """Registers a new word embedding evaluation function. Once registered, we can create an instance with :func:`~gluonnlp.embedding.evaluation.create`. Examples -------- >>> @gluonnlp.embedding.evaluation.register ... class MySimilarityFunction(gluonnlp.embedding.evalua...
Creates an instance of a registered word embedding evaluation function.
def create(kind, name, **kwargs): """Creates an instance of a registered word embedding evaluation function. Parameters ---------- kind : ['similarity', 'analogy'] Return only valid names for similarity, analogy or both kinds of functions. name : str The evaluation function ...
Get valid word embedding functions names.
def list_evaluation_functions(kind=None): """Get valid word embedding functions names. Parameters ---------- kind : ['similarity', 'analogy', None] Return only valid names for similarity, analogy or both kinds of functions. Returns ------- dict or list: A list of all the va...
Predict the similarity of words1 and words2.
def hybrid_forward(self, F, words1, words2, weight): # pylint: disable=arguments-differ """Predict the similarity of words1 and words2. Parameters ---------- words1 : Symbol or NDArray The indices of the words the we wish to compare to the words in words2. words2 : ...
Compute analogies for given question words.
def hybrid_forward(self, F, words1, words2, words3): # pylint: disable=arguments-differ, unused-argument """Compute analogies for given question words. Parameters ---------- words1 : Symbol or NDArray Word indices of first question words. Shape (batch_size, ). words...
Evaluate the model on the dataset with cache model.
def evaluate(data_source, batch_size, ctx=None): """Evaluate the model on the dataset with cache model. Parameters ---------- data_source : NDArray The dataset is evaluated on. batch_size : int The size of the mini-batch. ctx : mx.cpu() or mx.gpu() The context of the com...