Search is not available for this dataset
text stringlengths 75 104k |
|---|
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... |
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 |
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... |
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 |
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... |
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() |
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_... |
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... |
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
... |
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... |
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
-------
... |
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... |
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 : ... |
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... |
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... |
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
... |
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... |
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):
... |
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... |
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 ... |
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... |
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 : ... |
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... |
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... |
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... |
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.
... |
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.
... |
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... |
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
... |
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)
... |
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)
... |
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... |
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... |
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... |
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... |
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... |
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,
... |
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... |
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 ... |
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':... |
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,
... |
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... |
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 ... |
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 (... |
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... |
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... |
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... |
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 ... |
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]
... |
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... |
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... |
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... |
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
------... |
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)]
... |
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... |
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) ... |
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())
... |
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... |
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))
... |
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... |
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... |
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),
... |
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... |
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_... |
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... |
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 : ... |
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
... |
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_... |
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... |
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) |
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... |
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 = ... |
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... |
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
... |
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. '
... |
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... |
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... |
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... |
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 ... |
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... |
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... |
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... |
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... |
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) ... |
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... |
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... |
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... |
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 = ... |
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)
... |
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 ... |
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... |
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
... |
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... |
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... |
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 ... |
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._... |
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... |
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)
... |
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.
... |
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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.