repo
stringclasses
85 values
path
stringlengths
8
121
func_name
stringlengths
1
82
original_string
stringlengths
112
65.5k
language
stringclasses
1 value
code
stringlengths
112
65.5k
code_tokens
listlengths
20
4.09k
docstring
stringlengths
3
46.3k
docstring_tokens
listlengths
1
564
sha
stringclasses
85 values
url
stringlengths
93
218
partition
stringclasses
1 value
dmlc/gluon-nlp
scripts/sentiment_analysis/process_data.py
load_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...
python
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", "load_dataset", "(", "data_name", ")", ":", "if", "data_name", "==", "'MR'", "or", "data_name", "==", "'Subj'", ":", "train_dataset", ",", "output_size", "=", "_load_file", "(", "data_name", ")", "vocab", ",", "max_len", "=", "_build_vocab", "(", "dat...
Load sentiment dataset.
[ "Load", "sentiment", "dataset", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/sentiment_analysis/process_data.py#L120-L133
train
dmlc/gluon-nlp
src/gluonnlp/base.py
get_home_dir
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
python
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", "get_home_dir", "(", ")", ":", "_home_dir", "=", "os", ".", "environ", ".", "get", "(", "'MXNET_HOME'", ",", "os", ".", "path", ".", "join", "(", "'~'", ",", "'.mxnet'", ")", ")", "# expand ~ to actual path", "_home_dir", "=", "os", ".", "path", ...
Get home directory for storing datasets/models/pre-trained word embeddings
[ "Get", "home", "directory", "for", "storing", "datasets", "/", "models", "/", "pre", "-", "trained", "word", "embeddings" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/base.py#L68-L73
train
dmlc/gluon-nlp
scripts/natural_language_inference/dataset.py
read_dataset
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...
python
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", "read_dataset", "(", "args", ",", "dataset", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "vars", "(", "args", ")", "[", "dataset", "]", ")", "logger", ".", "info", "(", "'reading data from {}'", ".", "format", "(", "path", ")",...
Read dataset from tokenized files.
[ "Read", "dataset", "from", "tokenized", "files", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/natural_language_inference/dataset.py#L35-L51
train
dmlc/gluon-nlp
scripts/natural_language_inference/dataset.py
build_vocab
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
python
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", "build_vocab", "(", "dataset", ")", ":", "counter", "=", "nlp", ".", "data", ".", "count_tokens", "(", "[", "w", "for", "e", "in", "dataset", "for", "s", "in", "e", "[", ":", "2", "]", "for", "w", "in", "s", "]", ",", "to_lower", "=", "T...
Build vocab given a dataset.
[ "Build", "vocab", "given", "a", "dataset", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/natural_language_inference/dataset.py#L53-L60
train
dmlc/gluon-nlp
scripts/natural_language_inference/dataset.py
prepare_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...
python
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", "prepare_data_loader", "(", "args", ",", "dataset", ",", "vocab", ",", "test", "=", "False", ")", ":", "# Preprocess", "dataset", "=", "dataset", ".", "transform", "(", "lambda", "s1", ",", "s2", ",", "label", ":", "(", "vocab", "(", "s1", ")", ...
Read data and build data loader.
[ "Read", "data", "and", "build", "data", "loader", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/natural_language_inference/dataset.py#L62-L79
train
dmlc/gluon-nlp
scripts/parsing/common/utils.py
mxnet_prefer_gpu
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()
python
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", "mxnet_prefer_gpu", "(", ")", ":", "gpu", "=", "int", "(", "os", ".", "environ", ".", "get", "(", "'MXNET_GPU'", ",", "default", "=", "0", ")", ")", "if", "gpu", "in", "mx", ".", "test_utils", ".", "list_gpus", "(", ")", ":", "return", "mx",...
If gpu available return gpu, else cpu Returns ------- context : Context The preferable GPU context.
[ "If", "gpu", "available", "return", "gpu", "else", "cpu" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/utils.py#L150-L161
train
dmlc/gluon-nlp
scripts/parsing/common/utils.py
init_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_...
python
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", "init_logger", "(", "root_dir", ",", "name", "=", "\"train.log\"", ")", ":", "os", ".", "makedirs", "(", "root_dir", ",", "exist_ok", "=", "True", ")", "log_formatter", "=", "logging", ".", "Formatter", "(", "\"%(message)s\"", ")", "logger", "=", "l...
Initialize a logger Parameters ---------- root_dir : str directory for saving log name : str name of logger Returns ------- logger : logging.Logger a logger
[ "Initialize", "a", "logger" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/utils.py#L164-L189
train
dmlc/gluon-nlp
scripts/parsing/common/utils.py
orthonormal_VanillaLSTMBuilder
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...
python
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", "orthonormal_VanillaLSTMBuilder", "(", "lstm_layers", ",", "input_dims", ",", "lstm_hiddens", ",", "dropout_x", "=", "0.", ",", "dropout_h", "=", "0.", ",", "debug", "=", "False", ")", ":", "assert", "lstm_layers", "==", "1", ",", "'only accept one layer ...
Build a standard LSTM cell, with variational dropout, with weights initialized to be orthonormal (https://arxiv.org/abs/1312.6120) Parameters ---------- lstm_layers : int Currently only support one layer input_dims : int word vector dimensions lstm_hiddens : int hidden s...
[ "Build", "a", "standard", "LSTM", "cell", "with", "variational", "dropout", "with", "weights", "initialized", "to", "be", "orthonormal", "(", "https", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1312", ".", "6120", ")" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/utils.py#L192-L226
train
dmlc/gluon-nlp
scripts/parsing/common/utils.py
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 ...
python
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", "biLSTM", "(", "f_lstm", ",", "b_lstm", ",", "inputs", ",", "batch_size", "=", "None", ",", "dropout_x", "=", "0.", ",", "dropout_h", "=", "0.", ")", ":", "for", "f", ",", "b", "in", "zip", "(", "f_lstm", ",", "b_lstm", ")", ":", "inputs", ...
Feature extraction through BiLSTM Parameters ---------- f_lstm : VariationalDropoutCell Forward cell b_lstm : VariationalDropoutCell Backward cell inputs : NDArray seq_len x batch_size dropout_x : float Variational dropout on inputs dropout_h : Not us...
[ "Feature", "extraction", "through", "BiLSTM" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/utils.py#L229-L256
train
dmlc/gluon-nlp
scripts/parsing/common/utils.py
bilinear
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...
python
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", "bilinear", "(", "x", ",", "W", ",", "y", ",", "input_size", ",", "seq_len", ",", "batch_size", ",", "num_outputs", "=", "1", ",", "bias_x", "=", "False", ",", "bias_y", "=", "False", ")", ":", "if", "bias_x", ":", "x", "=", "nd", ".", "co...
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 input_size : int input dimension seq_len : int sequence length batch_size : int ...
[ "Do", "xWy" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/utils.py#L275-L320
train
dmlc/gluon-nlp
scripts/parsing/common/utils.py
orthonormal_initializer
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 ------- ...
python
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", "orthonormal_initializer", "(", "output_size", ",", "input_size", ",", "debug", "=", "False", ")", ":", "print", "(", "(", "output_size", ",", "input_size", ")", ")", "if", "debug", ":", "Q", "=", "np", ".", "random", ".", "randn", "(", "input_siz...
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 ------- Q : np.ndarray The orthonormal weight matrix of input_size x outpu...
[ "adopted", "from", "Timothy", "Dozat", "https", ":", "//", "github", ".", "com", "/", "tdozat", "/", "Parser", "/", "blob", "/", "master", "/", "lib", "/", "linalg", ".", "py" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/utils.py#L323-L364
train
dmlc/gluon-nlp
scripts/parsing/common/utils.py
arc_argmax
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...
python
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", "arc_argmax", "(", "parse_probs", ",", "length", ",", "tokens_to_keep", ",", "ensure_tree", "=", "True", ")", ":", "if", "ensure_tree", ":", "I", "=", "np", ".", "eye", "(", "len", "(", "tokens_to_keep", ")", ")", "# block loops and pad heads", "parse...
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 sentence length tokens_to_keep : NDArray mask matrix ensure_tree ...
[ "MST", "Adopted", "from", "Timothy", "Dozat", "https", ":", "//", "github", ".", "com", "/", "tdozat", "/", "Parser", "/", "blob", "/", "master", "/", "lib", "/", "models", "/", "nn", ".", "py" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/utils.py#L367-L455
train
dmlc/gluon-nlp
scripts/parsing/common/utils.py
rel_argmax
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 : ...
python
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", "rel_argmax", "(", "rel_probs", ",", "length", ",", "ensure_tree", "=", "True", ")", ":", "if", "ensure_tree", ":", "rel_probs", "[", ":", ",", "ParserVocabulary", ".", "PAD", "]", "=", "0", "root", "=", "ParserVocabulary", ".", "ROOT", "tokens", ...
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 : np.ndarray prediction of relations of size (seq_len,...
[ "Fix", "the", "relation", "prediction", "by", "heuristic", "rules" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/utils.py#L458-L494
train
dmlc/gluon-nlp
scripts/parsing/common/utils.py
reshape_fortran
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...
python
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", "reshape_fortran", "(", "tensor", ",", "shape", ")", ":", "return", "tensor", ".", "T", ".", "reshape", "(", "tuple", "(", "reversed", "(", "shape", ")", ")", ")", ".", "T" ]
The missing Fortran reshape for mx.NDArray Parameters ---------- tensor : NDArray source tensor shape : NDArray desired shape Returns ------- output : NDArray reordered result
[ "The", "missing", "Fortran", "reshape", "for", "mx", ".", "NDArray" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/utils.py#L497-L512
train
dmlc/gluon-nlp
scripts/parsing/common/utils.py
Progbar.update
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...
python
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", "update", "(", "self", ",", "current", ",", "values", "=", "[", "]", ",", "exact", "=", "[", "]", ",", "strict", "=", "[", "]", ")", ":", "for", "k", ",", "v", "in", "values", ":", "if", "k", "not", "in", "self", ".", "sum_values", ":"...
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 b...
[ "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", ...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/utils.py#L56-L144
train
dmlc/gluon-nlp
scripts/language_model/word_language_model.py
get_batch
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 ...
python
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", "get_batch", "(", "data_source", ",", "i", ",", "seq_len", "=", "None", ")", ":", "seq_len", "=", "min", "(", "seq_len", "if", "seq_len", "else", "args", ".", "bptt", ",", "len", "(", "data_source", ")", "-", "1", "-", "i", ")", "data", "=",...
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 ------- data: NDArray The context ...
[ "Get", "mini", "-", "batches", "of", "the", "dataset", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/language_model/word_language_model.py#L275-L297
train
dmlc/gluon-nlp
scripts/language_model/word_language_model.py
evaluate
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...
python
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", "evaluate", "(", "data_source", ",", "batch_size", ",", "params_file_name", ",", "ctx", "=", "None", ")", ":", "total_L", "=", "0.0", "ntotal", "=", "0", "model_eval", ".", "load_parameters", "(", "params_file_name", ",", "context", ")", "hidden", "="...
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 to evaluate, e.g., val.params or args.save ctx : mx.cpu() or ...
[ "Evaluate", "the", "model", "on", "the", "dataset", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/language_model/word_language_model.py#L300-L339
train
dmlc/gluon-nlp
scripts/language_model/word_language_model.py
train
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): ...
python
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", "train", "(", ")", ":", "ntasgd", "=", "False", "best_val", "=", "float", "(", "'Inf'", ")", "start_train_time", "=", "time", ".", "time", "(", ")", "parameters", "=", "model", ".", "collect_params", "(", ")", "param_dict_avg", "=", "None", "t", ...
Training loop for awd language model.
[ "Training", "loop", "for", "awd", "language", "model", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/language_model/word_language_model.py#L342-L463
train
dmlc/gluon-nlp
src/gluonnlp/embedding/evaluation.py
register
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...
python
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", "register", "(", "class_", ")", ":", "if", "issubclass", "(", "class_", ",", "WordEmbeddingSimilarityFunction", ")", ":", "register_", "=", "registry", ".", "get_register_func", "(", "WordEmbeddingSimilarityFunction", ",", "'word embedding similarity evaluation fun...
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.evaluation.WordEmbeddingSimilarityF...
[ "Registers", "a", "new", "word", "embedding", "evaluation", "function", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/embedding/evaluation.py#L67-L107
train
dmlc/gluon-nlp
src/gluonnlp/embedding/evaluation.py
create
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 ...
python
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", "create", "(", "kind", ",", "name", ",", "*", "*", "kwargs", ")", ":", "if", "kind", "not", "in", "_REGSITRY_KIND_CLASS_MAP", ".", "keys", "(", ")", ":", "raise", "KeyError", "(", "'Cannot find `kind` {}. Use '", "'`list_evaluation_functions(kind=None).keys...
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 name (case-insensitive). Returns ...
[ "Creates", "an", "instance", "of", "a", "registered", "word", "embedding", "evaluation", "function", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/embedding/evaluation.py#L110-L141
train
dmlc/gluon-nlp
src/gluonnlp/embedding/evaluation.py
list_evaluation_functions
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...
python
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", "list_evaluation_functions", "(", "kind", "=", "None", ")", ":", "if", "kind", "is", "None", ":", "kind", "=", "tuple", "(", "_REGSITRY_KIND_CLASS_MAP", ".", "keys", "(", ")", ")", "if", "not", "isinstance", "(", "kind", ",", "tuple", ")", ":", ...
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 valid evaluation function names for the specified ...
[ "Get", "valid", "word", "embedding", "functions", "names", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/embedding/evaluation.py#L144-L175
train
dmlc/gluon-nlp
src/gluonnlp/embedding/evaluation.py
WordEmbeddingSimilarity.hybrid_forward
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 : ...
python
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", ",", "weight", ")", ":", "# pylint: disable=arguments-differ", "embeddings_words1", "=", "F", ".", "Embedding", "(", "words1", ",", "weight", ",", "input_dim", "=", "self", ".", "_...
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 : Symbol or NDArray The indices of the words the we wish to compare to the words in words1...
[ "Predict", "the", "similarity", "of", "words1", "and", "words2", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/embedding/evaluation.py#L439-L461
train
dmlc/gluon-nlp
src/gluonnlp/embedding/evaluation.py
WordEmbeddingAnalogy.hybrid_forward
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...
python
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", "hybrid_forward", "(", "self", ",", "F", ",", "words1", ",", "words2", ",", "words3", ")", ":", "# pylint: disable=arguments-differ, unused-argument", "return", "self", ".", "analogy", "(", "words1", ",", "words2", ",", "words3", ")" ]
Compute analogies for given question words. Parameters ---------- words1 : Symbol or NDArray Word indices of first question words. Shape (batch_size, ). words2 : Symbol or NDArray Word indices of second question words. Shape (batch_size, ). words3 : Symbo...
[ "Compute", "analogies", "for", "given", "question", "words", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/embedding/evaluation.py#L501-L518
train
dmlc/gluon-nlp
scripts/language_model/cache_language_model.py
evaluate
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...
python
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", "evaluate", "(", "data_source", ",", "batch_size", ",", "ctx", "=", "None", ")", ":", "total_L", "=", "0", "hidden", "=", "cache_cell", ".", "begin_state", "(", "func", "=", "mx", ".", "nd", ".", "zeros", ",", "batch_size", "=", "batch_size", ",...
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 computation. Returns ------- loss: float ...
[ "Evaluate", "the", "model", "on", "the", "dataset", "with", "cache", "model", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/language_model/cache_language_model.py#L167-L203
train
dmlc/gluon-nlp
scripts/bert/staticbert/static_bert.py
get_model
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...
python
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", "get_model", "(", "name", ",", "dataset_name", "=", "'wikitext-2'", ",", "*", "*", "kwargs", ")", ":", "models", "=", "{", "'bert_12_768_12'", ":", "bert_12_768_12", ",", "'bert_24_1024_16'", ":", "bert_24_1024_16", "}", "name", "=", "name", ".", "low...
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 directly returned. vocab : gluonnlp.Vocab or None, default...
[ "Returns", "a", "pre", "-", "defined", "model", "by", "name", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/staticbert/static_bert.py#L572-L605
train
dmlc/gluon-nlp
scripts/bert/staticbert/static_bert.py
bert_12_768_12
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. ...
python
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", "bert_12_768_12", "(", "dataset_name", "=", "None", ",", "vocab", "=", "None", ",", "pretrained", "=", "True", ",", "ctx", "=", "mx", ".", "cpu", "(", ")", ",", "root", "=", "os", ".", "path", ".", "join", "(", "get_home_dir", "(", ")", ",",...
Static BERT BASE model. The number of layers (L) is 12, number of units (H) is 768, and the number of self-attention heads (A) is 12. Parameters ---------- dataset_name : str or None, default None Options include 'book_corpus_wiki_en_cased', 'book_corpus_wiki_en_uncased', 'wiki_cn_...
[ "Static", "BERT", "BASE", "model", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/staticbert/static_bert.py#L608-L652
train
dmlc/gluon-nlp
scripts/bert/staticbert/static_bert.py
StaticBERTModel.hybrid_forward
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. ...
python
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", "hybrid_forward", "(", "self", ",", "F", ",", "inputs", ",", "token_types", ",", "valid_length", "=", "None", ",", "masked_positions", "=", "None", ")", ":", "# pylint: disable=arguments-differ", "# pylint: disable=unused-argument", "outputs", "=", "[", "]", ...
Generate the representation given the inputs. This is used in training or fine-tuning a static (hybridized) BERT model.
[ "Generate", "the", "representation", "given", "the", "inputs", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/staticbert/static_bert.py#L481-L512
train
dmlc/gluon-nlp
src/gluonnlp/model/train/cache.py
CacheCell.load_parameters
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...
python
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", "load_parameters", "(", "self", ",", "filename", ",", "ctx", "=", "mx", ".", "cpu", "(", ")", ")", ":", "# pylint: disable=arguments-differ", "self", ".", "lm_model", ".", "load_parameters", "(", "filename", ",", "ctx", "=", "ctx", ")" ]
Load parameters from file. filename : str Path to parameter file. ctx : Context or list of Context, default cpu() Context(s) initialize loaded parameters on.
[ "Load", "parameters", "from", "file", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/train/cache.py#L84-L92
train
dmlc/gluon-nlp
src/gluonnlp/model/train/cache.py
CacheCell.forward
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 ...
python
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", "forward", "(", "self", ",", "inputs", ",", "target", ",", "next_word_history", ",", "cache_history", ",", "begin_state", "=", "None", ")", ":", "# pylint: disable=arguments-differ", "output", ",", "hidden", ",", "encoder_hs", ",", "_", "=", "super", "(...
Defines the forward computation for cache cell. Arguments can be either :py:class:`NDArray` or :py:class:`Symbol`. Parameters ---------- inputs: NDArray The input data target: NDArray The label next_word_history: NDArray The next word ...
[ "Defines", "the", "forward", "computation", "for", "cache", "cell", ".", "Arguments", "can", "be", "either", ":", "py", ":", "class", ":", "NDArray", "or", ":", "py", ":", "class", ":", "Symbol", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/train/cache.py#L100-L161
train
dmlc/gluon-nlp
src/gluonnlp/utils/parallel.py
Parallel.put
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) ...
python
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", "put", "(", "self", ",", "x", ")", ":", "if", "self", ".", "_num_serial", ">", "0", "or", "len", "(", "self", ".", "_threads", ")", "==", "0", ":", "self", ".", "_num_serial", "-=", "1", "out", "=", "self", ".", "_parallizable", ".", "forw...
Assign input `x` to an available worker and invoke `parallizable.forward_backward` with x.
[ "Assign", "input", "x", "to", "an", "available", "worker", "and", "invoke", "parallizable", ".", "forward_backward", "with", "x", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/utils/parallel.py#L130-L138
train
dmlc/gluon-nlp
src/gluonnlp/vocab/bert.py
BERTVocab.from_json
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) ...
python
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", "from_json", "(", "cls", ",", "json_str", ")", ":", "vocab_dict", "=", "json", ".", "loads", "(", "json_str", ")", "unknown_token", "=", "vocab_dict", ".", "get", "(", "'unknown_token'", ")", "bert_vocab", "=", "cls", "(", "unknown_token", "=", "unk...
Deserialize BERTVocab object from json string. Parameters ---------- json_str : str Serialized json string of a BERTVocab object. Returns ------- BERTVocab
[ "Deserialize", "BERTVocab", "object", "from", "json", "string", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/vocab/bert.py#L174-L203
train
dmlc/gluon-nlp
src/gluonnlp/model/train/language_model.py
StandardRNN.forward
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...
python
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", ",", "begin_state", "=", "None", ")", ":", "# pylint: disable=arguments-differ", "encoded", "=", "self", ".", "embedding", "(", "inputs", ")", "if", "not", "begin_state", ":", "begin_state", "=", "self", ".", "be...
Defines the forward computation. Arguments can be either :py:class:`NDArray` or :py:class:`Symbol`. Parameters ----------- inputs : NDArray input tensor with shape `(sequence_length, batch_size)` when `layout` is "TNC". begin_state : list init...
[ "Defines", "the", "forward", "computation", ".", "Arguments", "can", "be", "either", ":", "py", ":", "class", ":", "NDArray", "or", ":", "py", ":", "class", ":", "Symbol", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/train/language_model.py#L238-L276
train
dmlc/gluon-nlp
src/gluonnlp/model/train/language_model.py
BigRNN.forward
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...
python
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", "forward", "(", "self", ",", "inputs", ",", "label", ",", "begin_state", ",", "sampled_values", ")", ":", "# pylint: disable=arguments-differ", "encoded", "=", "self", ".", "embedding", "(", "inputs", ")", "length", "=", "inputs", ".", "shape", "[", "...
Defines the forward computation. Parameters ----------- inputs : NDArray input tensor with shape `(sequence_length, batch_size)` when `layout` is "TNC". begin_state : list initial recurrent state tensor with length equals to num_layers*2. ...
[ "Defines", "the", "forward", "computation", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/train/language_model.py#L389-L427
train
dmlc/gluon-nlp
scripts/word_embeddings/model.py
SG.hybrid_forward
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...
python
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", "hybrid_forward", "(", "self", ",", "F", ",", "center", ",", "context", ",", "center_words", ")", ":", "# negatives sampling", "negatives", "=", "[", "]", "mask", "=", "[", "]", "for", "_", "in", "range", "(", "self", ".", "_kwargs", "[", "'num_...
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 for center words are computed via F.sparse.dot between the...
[ "SkipGram", "forward", "pass", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/model.py#L101-L149
train
dmlc/gluon-nlp
scripts/sentiment_analysis/finetune_lm.py
evaluate
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...
python
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", "evaluate", "(", "dataloader", ")", ":", "total_L", "=", "0.0", "total_sample_num", "=", "0", "total_correct_num", "=", "0", "start_log_interval_time", "=", "time", ".", "time", "(", ")", "print", "(", "'Begin Testing...'", ")", "for", "i", ",", "(", ...
Evaluate network on the specified dataset
[ "Evaluate", "network", "on", "the", "specified", "dataset" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/sentiment_analysis/finetune_lm.py#L237-L260
train
dmlc/gluon-nlp
scripts/sentiment_analysis/finetune_lm.py
train
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...
python
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", "train", "(", ")", ":", "start_pipeline_time", "=", "time", ".", "time", "(", ")", "# Training/Testing", "best_valid_acc", "=", "0", "stop_early", "=", "0", "for", "epoch", "in", "range", "(", "args", ".", "epochs", ")", ":", "# Epoch training stats",...
Training process
[ "Training", "process" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/sentiment_analysis/finetune_lm.py#L263-L340
train
dmlc/gluon-nlp
scripts/sentiment_analysis/finetune_lm.py
AggregationLayer.hybrid_forward
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, ...
python
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", ",", "data", ",", "valid_length", ")", ":", "# pylint: disable=arguments-differ", "# Data will have shape (T, N, C)", "if", "self", ".", "_use_mean_pool", ":", "masked_encoded", "=", "F", ".", "SequenceMask", "(", "dat...
Forward logic
[ "Forward", "logic" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/sentiment_analysis/finetune_lm.py#L105-L118
train
dmlc/gluon-nlp
src/gluonnlp/model/lstmpcellwithclip.py
LSTMPCellWithClip.hybrid_forward
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...
python
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", "hybrid_forward", "(", "self", ",", "F", ",", "inputs", ",", "states", ",", "i2h_weight", ",", "h2h_weight", ",", "h2r_weight", ",", "i2h_bias", ",", "h2h_bias", ")", ":", "prefix", "=", "'t%d_'", "%", "self", ".", "_counter", "i2h", "=", "F", "...
r"""Hybrid forward computation for Long-Short Term Memory Projected network cell with cell clip and projection clip. Parameters ---------- inputs : input tensor with shape `(batch_size, input_size)`. states : a list of two initial recurrent state tensors, with shape ...
[ "r", "Hybrid", "forward", "computation", "for", "Long", "-", "Short", "Term", "Memory", "Projected", "network", "cell", "with", "cell", "clip", "and", "projection", "clip", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/lstmpcellwithclip.py#L100-L139
train
dmlc/gluon-nlp
src/gluonnlp/utils/parameter.py
clip_grad_global_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 ...
python
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", "clip_grad_global_norm", "(", "parameters", ",", "max_norm", ",", "check_isfinite", "=", "True", ")", ":", "def", "_norm", "(", "array", ")", ":", "if", "array", ".", "stype", "==", "'default'", ":", "x", "=", "array", ".", "reshape", "(", "(", ...
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. .. note:: 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...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/utils/parameter.py#L28-L97
train
dmlc/gluon-nlp
scripts/bert/run_pretraining.py
train
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':...
python
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", "train", "(", "data_train", ",", "model", ",", "nsp_loss", ",", "mlm_loss", ",", "vocab_size", ",", "ctx", ",", "store", ")", ":", "mlm_metric", "=", "nlp", ".", "metric", ".", "MaskedAccuracy", "(", ")", "nsp_metric", "=", "nlp", ".", "metric", ...
Training function.
[ "Training", "function", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/run_pretraining.py#L92-L215
train
dmlc/gluon-nlp
scripts/bert/run_pretraining.py
ParallelBERT.forward_backward
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, ...
python
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", "forward_backward", "(", "self", ",", "x", ")", ":", "with", "mx", ".", "autograd", ".", "record", "(", ")", ":", "(", "ls", ",", "next_sentence_label", ",", "classified", ",", "masked_id", ",", "decoded", ",", "masked_weight", ",", "ls1", ",", ...
forward backward implementation
[ "forward", "backward", "implementation" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/run_pretraining.py#L77-L90
train
dmlc/gluon-nlp
scripts/parsing/common/data.py
ParserVocabulary.log_info
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...
python
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", "log_info", "(", "self", ",", "logger", ")", ":", "logger", ".", "info", "(", "'#words in training set: %d'", "%", "self", ".", "_words_in_train_data", ")", "logger", ".", "info", "(", "\"Vocab info: #words %d, #tags %d #rels %d\"", "%", "(", "self", ".", ...
Print statistical information via the provided logger Parameters ---------- logger : logging.Logger logger created using logging.getLogger()
[ "Print", "statistical", "information", "via", "the", "provided", "logger" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/data.py#L162-L171
train
dmlc/gluon-nlp
scripts/parsing/common/data.py
ParserVocabulary._add_pret_words
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 ...
python
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", "_add_pret_words", "(", "self", ",", "pret_embeddings", ")", ":", "words_in_train_data", "=", "set", "(", "self", ".", "_id2word", ")", "pret_embeddings", "=", "gluonnlp", ".", "embedding", ".", "create", "(", "pret_embeddings", "[", "0", "]", ",", "s...
Read pre-trained embedding file for extending vocabulary Parameters ---------- pret_embeddings : tuple (embedding_name, source), used for gluonnlp.embedding.create(embedding_name, source)
[ "Read", "pre", "-", "trained", "embedding", "file", "for", "extending", "vocabulary" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/data.py#L173-L186
train
dmlc/gluon-nlp
scripts/parsing/common/data.py
ParserVocabulary.get_pret_embs
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 (...
python
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_pret_embs", "(", "self", ",", "word_dims", "=", "None", ")", ":", "assert", "(", "self", ".", "_pret_embeddings", "is", "not", "None", ")", ",", "\"No pretrained file provided.\"", "pret_embeddings", "=", "gluonnlp", ".", "embedding", ".", "create", ...
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
[ "Read", "pre", "-", "trained", "embedding", "file" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/data.py#L198-L221
train
dmlc/gluon-nlp
scripts/parsing/common/data.py
ParserVocabulary.get_word_embs
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...
python
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_word_embs", "(", "self", ",", "word_dims", ")", ":", "if", "self", ".", "_pret_embeddings", "is", "not", "None", ":", "return", "np", ".", "random", ".", "randn", "(", "self", ".", "words_in_train", ",", "word_dims", ")", ".", "astype", "(", ...
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 NDArray
[ "Get", "randomly", "initialized", "embeddings", "when", "pre", "-", "trained", "embeddings", "are", "used", "otherwise", "zero", "vectors" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/data.py#L223-L237
train
dmlc/gluon-nlp
scripts/parsing/common/data.py
ParserVocabulary.get_tag_embs
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...
python
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", "get_tag_embs", "(", "self", ",", "tag_dims", ")", ":", "return", "np", ".", "random", ".", "randn", "(", "self", ".", "tag_size", ",", "tag_dims", ")", ".", "astype", "(", "np", ".", "float32", ")" ]
Randomly initialize embeddings for tag Parameters ---------- tag_dims : int tag vector size Returns ------- numpy.ndarray random embeddings
[ "Randomly", "initialize", "embeddings", "for", "tag" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/data.py#L239-L252
train
dmlc/gluon-nlp
scripts/parsing/common/data.py
ParserVocabulary.word2id
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...
python
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", "word2id", "(", "self", ",", "xs", ")", ":", "if", "isinstance", "(", "xs", ",", "list", ")", ":", "return", "[", "self", ".", "_word2id", ".", "get", "(", "x", ",", "self", ".", "UNK", ")", "for", "x", "in", "xs", "]", "return", "self",...
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
[ "Map", "word", "(", "s", ")", "to", "its", "id", "(", "s", ")" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/data.py#L254-L269
train
dmlc/gluon-nlp
scripts/parsing/common/data.py
ParserVocabulary.id2word
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 ...
python
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", "id2word", "(", "self", ",", "xs", ")", ":", "if", "isinstance", "(", "xs", ",", "list", ")", ":", "return", "[", "self", ".", "_id2word", "[", "x", "]", "for", "x", "in", "xs", "]", "return", "self", ".", "_id2word", "[", "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
[ "Map", "id", "(", "s", ")", "to", "word", "(", "s", ")" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/data.py#L271-L286
train
dmlc/gluon-nlp
scripts/parsing/common/data.py
ParserVocabulary.rel2id
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] ...
python
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", "rel2id", "(", "self", ",", "xs", ")", ":", "if", "isinstance", "(", "xs", ",", "list", ")", ":", "return", "[", "self", ".", "_rel2id", "[", "x", "]", "for", "x", "in", "xs", "]", "return", "self", ".", "_rel2id", "[", "xs", "]" ]
Map relation(s) to id(s) Parameters ---------- xs : str or list relation Returns ------- int or list id(s) of relation
[ "Map", "relation", "(", "s", ")", "to", "id", "(", "s", ")" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/data.py#L288-L303
train
dmlc/gluon-nlp
scripts/parsing/common/data.py
ParserVocabulary.id2rel
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...
python
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", "id2rel", "(", "self", ",", "xs", ")", ":", "if", "isinstance", "(", "xs", ",", "list", ")", ":", "return", "[", "self", ".", "_id2rel", "[", "x", "]", "for", "x", "in", "xs", "]", "return", "self", ".", "_id2rel", "[", "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
[ "Map", "id", "(", "s", ")", "to", "relation", "(", "s", ")" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/data.py#L305-L320
train
dmlc/gluon-nlp
scripts/parsing/common/data.py
ParserVocabulary.tag2id
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...
python
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", "tag2id", "(", "self", ",", "xs", ")", ":", "if", "isinstance", "(", "xs", ",", "list", ")", ":", "return", "[", "self", ".", "_tag2id", ".", "get", "(", "x", ",", "self", ".", "UNK", ")", "for", "x", "in", "xs", "]", "return", "self", ...
Map tag(s) to id(s) Parameters ---------- xs : str or list tag or tags Returns ------- int or list id(s) of tag(s)
[ "Map", "tag", "(", "s", ")", "to", "id", "(", "s", ")" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/data.py#L322-L337
train
dmlc/gluon-nlp
scripts/parsing/common/data.py
DataLoader.idx_sequence
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...
python
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", "idx_sequence", "(", "self", ")", ":", "return", "[", "x", "[", "1", "]", "for", "x", "in", "sorted", "(", "zip", "(", "self", ".", "_record", ",", "list", "(", "range", "(", "len", "(", "self", ".", "_record", ")", ")", ")", ")", ")", ...
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
[ "Indices", "of", "sentences", "when", "enumerating", "data", "set", "from", "batches", ".", "Useful", "when", "retrieving", "the", "correct", "order", "of", "sentences" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/data.py#L431-L440
train
dmlc/gluon-nlp
scripts/parsing/common/data.py
DataLoader.get_batches
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 ------...
python
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", "get_batches", "(", "self", ",", "batch_size", ",", "shuffle", "=", "True", ")", ":", "batches", "=", "[", "]", "for", "bkt_idx", ",", "bucket", "in", "enumerate", "(", "self", ".", "_buckets", ")", ":", "bucket_size", "=", "bucket", ".", "shape...
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 ------- tuple word_inputs, tag_inputs, arc_tar...
[ "Get", "batch", "iterator" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/data.py#L442-L473
train
dmlc/gluon-nlp
scripts/text_classification/fasttext_word_ngram.py
create_ngram_set
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)] ...
python
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", "create_ngram_set", "(", "input_list", ",", "ngram_value", "=", "2", ")", ":", "return", "set", "(", "zip", "(", "*", "[", "input_list", "[", "i", ":", "]", "for", "i", "in", "range", "(", "ngram_value", ")", "]", ")", ")" ]
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)]
[ "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", ")", "("...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/text_classification/fasttext_word_ngram.py#L96-L104
train
dmlc/gluon-nlp
scripts/text_classification/fasttext_word_ngram.py
add_ngram
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...
python
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", "add_ngram", "(", "sequences", ",", "token_indice", ",", "ngram_range", "=", "2", ")", ":", "new_sequences", "=", "[", "]", "for", "input_list", "in", "sequences", ":", "new_list", "=", "input_list", "[", ":", "]", "for", "i", "in", "range", "(", ...
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,...
[ "Augment", "the", "input", "list", "of", "list", "(", "sequences", ")", "by", "appending", "n", "-", "grams", "values", ".", "Example", ":", "adding", "bi", "-", "gram", ">>>", "sequences", "=", "[[", "1", "3", "4", "5", "]", "[", "1", "3", "7", ...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/text_classification/fasttext_word_ngram.py#L107-L131
train
dmlc/gluon-nlp
scripts/text_classification/fasttext_word_ngram.py
evaluate_accuracy
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) ...
python
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", "evaluate_accuracy", "(", "data_iterator", ",", "net", ",", "ctx", ",", "loss_fun", ",", "num_classes", ")", ":", "acc", "=", "mx", ".", "metric", ".", "Accuracy", "(", ")", "loss_avg", "=", "0.", "for", "i", ",", "(", "(", "data", ",", "lengt...
This function is used for evaluating accuracy of a given data iterator. (Either Train/Test data) It takes in the loss function used too!
[ "This", "function", "is", "used", "for", "evaluating", "accuracy", "of", "a", "given", "data", "iterator", ".", "(", "Either", "Train", "/", "Test", "data", ")", "It", "takes", "in", "the", "loss", "function", "used", "too!" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/text_classification/fasttext_word_ngram.py#L134-L156
train
dmlc/gluon-nlp
scripts/text_classification/fasttext_word_ngram.py
read_input_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()) ...
python
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", "read_input_data", "(", "filename", ")", ":", "logging", ".", "info", "(", "'Opening file %s for reading input'", ",", "filename", ")", "input_file", "=", "open", "(", "filename", ",", "'r'", ")", "data", "=", "[", "]", "labels", "=", "[", "]", "for...
Helper function to get training data
[ "Helper", "function", "to", "get", "training", "data" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/text_classification/fasttext_word_ngram.py#L159-L169
train
dmlc/gluon-nlp
scripts/text_classification/fasttext_word_ngram.py
parse_args
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...
python
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", "parse_args", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Text Classification with FastText'", ",", "formatter_class", "=", "argparse", ".", "ArgumentDefaultsHelpFormatter", ")", "# Computation options", "group", "=...
Parse command line arguments.
[ "Parse", "command", "line", "arguments", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/text_classification/fasttext_word_ngram.py#L175-L214
train
dmlc/gluon-nlp
scripts/text_classification/fasttext_word_ngram.py
get_label_mapping
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)) ...
python
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", "get_label_mapping", "(", "train_labels", ")", ":", "sorted_labels", "=", "np", ".", "sort", "(", "np", ".", "unique", "(", "train_labels", ")", ")", "label_mapping", "=", "{", "}", "for", "i", ",", "label", "in", "enumerate", "(", "sorted_labels", ...
Create the mapping from label to numeric label
[ "Create", "the", "mapping", "from", "label", "to", "numeric", "label" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/text_classification/fasttext_word_ngram.py#L217-L226
train
dmlc/gluon-nlp
scripts/text_classification/fasttext_word_ngram.py
convert_to_sequences
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...
python
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", "convert_to_sequences", "(", "dataset", ",", "vocab", ")", ":", "start", "=", "time", ".", "time", "(", ")", "dataset_vocab", "=", "map", "(", "lambda", "x", ":", "(", "x", ",", "vocab", ")", ",", "dataset", ")", "with", "mp", ".", "Pool", "...
This function takes a dataset and converts it into sequences via multiprocessing
[ "This", "function", "takes", "a", "dataset", "and", "converts", "it", "into", "sequences", "via", "multiprocessing" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/text_classification/fasttext_word_ngram.py#L256-L268
train
dmlc/gluon-nlp
scripts/text_classification/fasttext_word_ngram.py
preprocess_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...
python
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", "preprocess_dataset", "(", "dataset", ",", "labels", ")", ":", "start", "=", "time", ".", "time", "(", ")", "with", "mp", ".", "Pool", "(", ")", "as", "pool", ":", "# Each sample is processed in an asynchronous manner.", "dataset", "=", "gluon", ".", ...
Preprocess and prepare a dataset
[ "Preprocess", "and", "prepare", "a", "dataset" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/text_classification/fasttext_word_ngram.py#L271-L281
train
dmlc/gluon-nlp
scripts/text_classification/fasttext_word_ngram.py
get_dataloader
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), ...
python
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", "get_dataloader", "(", "train_dataset", ",", "train_data_lengths", ",", "test_dataset", ",", "batch_size", ")", ":", "bucket_num", ",", "bucket_ratio", "=", "20", ",", "0.2", "batchify_fn", "=", "gluonnlp", ".", "data", ".", "batchify", ".", "Tuple", "(...
Construct the DataLoader. Pad data, stack label and lengths
[ "Construct", "the", "DataLoader", ".", "Pad", "data", "stack", "label", "and", "lengths" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/text_classification/fasttext_word_ngram.py#L284-L306
train
dmlc/gluon-nlp
scripts/text_classification/fasttext_word_ngram.py
train
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...
python
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", "train", "(", "args", ")", ":", "train_file", "=", "args", ".", "input", "test_file", "=", "args", ".", "validation", "ngram_range", "=", "args", ".", "ngrams", "logging", ".", "info", "(", "'Ngrams range for the training run : %s'", ",", "ngram_range", ...
Training function that orchestrates the Classification!
[ "Training", "function", "that", "orchestrates", "the", "Classification!" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/text_classification/fasttext_word_ngram.py#L311-L416
train
dmlc/gluon-nlp
scripts/bert/staticbert/static_bert_qa_model.py
StaticBertForQA.hybrid_forward
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_...
python
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", ",", "inputs", ",", "token_types", ",", "valid_length", "=", "None", ")", ":", "# pylint: disable=arguments-differ", "# pylint: disable=unused-argument", "bert_output", "=", "self", ".", "bert", "(", "inputs", ",", "...
Generate the unnormalized score for the given the input sequences. Parameters ---------- inputs : NDArray, shape (batch_size, seq_length) Input words for the sequences. token_types : NDArray, shape (batch_size, seq_length) Token types for the sequences, used to i...
[ "Generate", "the", "unnormalized", "score", "for", "the", "given", "the", "input", "sequences", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/staticbert/static_bert_qa_model.py#L50-L72
train
dmlc/gluon-nlp
scripts/bert/staticbert/static_bert_qa_model.py
BertForQALoss.hybrid_forward
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...
python
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", "hybrid_forward", "(", "self", ",", "F", ",", "pred", ",", "label", ")", ":", "# pylint: disable=arguments-differ", "pred", "=", "F", ".", "split", "(", "pred", ",", "axis", "=", "2", ",", "num_outputs", "=", "2", ")", "start_pred", "=", "pred", ...
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. R...
[ "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",...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/staticbert/static_bert_qa_model.py#L85-L106
train
dmlc/gluon-nlp
src/gluonnlp/model/translation.py
NMTModel.encode
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 : ...
python
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", "encode", "(", "self", ",", "inputs", ",", "states", "=", "None", ",", "valid_length", "=", "None", ")", ":", "return", "self", ".", "encoder", "(", "self", ".", "src_embed", "(", "inputs", ")", ",", "states", ",", "valid_length", ")" ]
Encode the input sequence. Parameters ---------- inputs : NDArray states : list of NDArrays or None, default None valid_length : NDArray or None, default None Returns ------- outputs : list Outputs of the encoder.
[ "Encode", "the", "input", "sequence", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/translation.py#L129-L143
train
dmlc/gluon-nlp
src/gluonnlp/model/translation.py
NMTModel.decode_seq
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 ...
python
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_seq", "(", "self", ",", "inputs", ",", "states", ",", "valid_length", "=", "None", ")", ":", "outputs", ",", "states", ",", "additional_outputs", "=", "self", ".", "decoder", ".", "decode_seq", "(", "inputs", "=", "self", ".", "tgt_embed", ...
Decode given the input sequence. Parameters ---------- inputs : NDArray states : list of NDArrays valid_length : NDArray or None, default None Returns ------- output : NDArray The output of the decoder. Shape is (batch_size, length, tgt_word_...
[ "Decode", "given", "the", "input", "sequence", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/translation.py#L145-L168
train
dmlc/gluon-nlp
src/gluonnlp/model/translation.py
NMTModel.decode_step
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_...
python
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", "decode_step", "(", "self", ",", "step_input", ",", "states", ")", ":", "step_output", ",", "states", ",", "step_additional_outputs", "=", "self", ".", "decoder", "(", "self", ".", "tgt_embed", "(", "step_input", ")", ",", "states", ")", "step_output"...
One step decoding of the translation model. Parameters ---------- step_input : NDArray Shape (batch_size,) states : list of NDArrays Returns ------- step_output : NDArray Shape (batch_size, C_out) states : list step_additi...
[ "One", "step", "decoding", "of", "the", "translation", "model", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/translation.py#L170-L190
train
dmlc/gluon-nlp
src/gluonnlp/model/translation.py
NMTModel.forward
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...
python
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", "forward", "(", "self", ",", "src_seq", ",", "tgt_seq", ",", "src_valid_length", "=", "None", ",", "tgt_valid_length", "=", "None", ")", ":", "#pylint: disable=arguments-differ", "additional_outputs", "=", "[", "]", "encoder_outputs", ",", "encoder_additional...
Generate the prediction given the src_seq and tgt_seq. This is used in training an NMT model. Parameters ---------- src_seq : NDArray tgt_seq : NDArray src_valid_length : NDArray or None tgt_valid_length : NDArray or None Returns ------- ...
[ "Generate", "the", "prediction", "given", "the", "src_seq", "and", "tgt_seq", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/translation.py#L213-L241
train
dmlc/gluon-nlp
src/gluonnlp/vocab/subwords.py
create_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)
python
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", "create_subword_function", "(", "subword_function_name", ",", "*", "*", "kwargs", ")", ":", "create_", "=", "registry", ".", "get_create_func", "(", "SubwordFunction", ",", "'token embedding'", ")", "return", "create_", "(", "subword_function_name", ",", "*",...
Creates an instance of a subword function.
[ "Creates", "an", "instance", "of", "a", "subword", "function", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/vocab/subwords.py#L43-L47
train
dmlc/gluon-nlp
src/gluonnlp/vocab/vocab.py
Vocab._index_special_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...
python
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_special_tokens", "(", "self", ",", "unknown_token", ",", "special_tokens", ")", ":", "self", ".", "_idx_to_token", "=", "[", "unknown_token", "]", "if", "unknown_token", "else", "[", "]", "if", "not", "special_tokens", ":", "self", ".", "_reserv...
Indexes unknown and reserved tokens.
[ "Indexes", "unknown", "and", "reserved", "tokens", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/vocab/vocab.py#L163-L177
train
dmlc/gluon-nlp
src/gluonnlp/vocab/vocab.py
Vocab._index_counter_keys
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 = ...
python
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", "_index_counter_keys", "(", "self", ",", "counter", ",", "unknown_token", ",", "special_tokens", ",", "max_size", ",", "min_freq", ")", ":", "unknown_and_special_tokens", "=", "set", "(", "special_tokens", ")", "if", "special_tokens", "else", "set", "(", ...
Indexes keys of `counter`. Indexes keys of `counter` according to frequency thresholds such as `max_size` and `min_freq`.
[ "Indexes", "keys", "of", "counter", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/vocab/vocab.py#L179-L204
train
dmlc/gluon-nlp
src/gluonnlp/vocab/vocab.py
Vocab.set_embedding
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...
python
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", "set_embedding", "(", "self", ",", "*", "embeddings", ")", ":", "if", "len", "(", "embeddings", ")", "==", "1", "and", "embeddings", "[", "0", "]", "is", "None", ":", "self", ".", "_embedding", "=", "None", "return", "for", "embs", "in", "embe...
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 multiple embeddings are provided, their...
[ "Attaches", "one", "or", "more", "embeddings", "to", "the", "indexed", "text", "tokens", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/vocab/vocab.py#L281-L328
train
dmlc/gluon-nlp
src/gluonnlp/vocab/vocab.py
Vocab.to_tokens
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 ...
python
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_tokens", "(", "self", ",", "indices", ")", ":", "to_reduce", "=", "False", "if", "not", "isinstance", "(", "indices", ",", "(", "list", ",", "tuple", ")", ")", ":", "indices", "=", "[", "indices", "]", "to_reduce", "=", "True", "max_idx", ...
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 A token or a list of tokens according t...
[ "Converts", "token", "indices", "to", "tokens", "according", "to", "the", "vocabulary", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/vocab/vocab.py#L330-L360
train
dmlc/gluon-nlp
src/gluonnlp/vocab/vocab.py
Vocab.to_json
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. ' ...
python
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", "to_json", "(", "self", ")", ":", "if", "self", ".", "_embedding", ":", "warnings", ".", "warn", "(", "'Serialization of attached embedding '", "'to json is not supported. '", "'You may serialize the embedding to a binary format '", "'separately using vocab.embedding.seria...
Serialize Vocab object to json string. This method does not serialize the underlying embedding.
[ "Serialize", "Vocab", "object", "to", "json", "string", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/vocab/vocab.py#L402-L420
train
dmlc/gluon-nlp
src/gluonnlp/vocab/vocab.py
Vocab.from_json
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...
python
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", "from_json", "(", "cls", ",", "json_str", ")", ":", "vocab_dict", "=", "json", ".", "loads", "(", "json_str", ")", "unknown_token", "=", "vocab_dict", ".", "get", "(", "'unknown_token'", ")", "vocab", "=", "cls", "(", "unknown_token", "=", "unknown_...
Deserialize Vocab object from json string. Parameters ---------- json_str : str Serialized json string of a Vocab object. Returns ------- Vocab
[ "Deserialize", "Vocab", "object", "from", "json", "string", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/vocab/vocab.py#L423-L449
train
dmlc/gluon-nlp
scripts/bert/run_pretraining_hvd.py
train
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...
python
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", "(", "data_train", ",", "model", ",", "nsp_loss", ",", "mlm_loss", ",", "vocab_size", ",", "ctx", ")", ":", "hvd", ".", "broadcast_parameters", "(", "model", ".", "collect_params", "(", ")", ",", "root_rank", "=", "0", ")", "mlm_metric", ...
Training function.
[ "Training", "function", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/run_pretraining_hvd.py#L71-L204
train
dmlc/gluon-nlp
scripts/bert/staticbert/static_finetune_squad.py
train
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...
python
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", "train", "(", ")", ":", "log", ".", "info", "(", "'Loader Train data...'", ")", "if", "version_2", ":", "train_data", "=", "SQuAD", "(", "'train'", ",", "version", "=", "'2.0'", ")", "else", ":", "train_data", "=", "SQuAD", "(", "'train'", ",", ...
Training function.
[ "Training", "function", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/staticbert/static_finetune_squad.py#L301-L426
train
dmlc/gluon-nlp
scripts/bert/staticbert/static_finetune_squad.py
evaluate
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 ...
python
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", "evaluate", "(", ")", ":", "log", ".", "info", "(", "'Loader dev data...'", ")", "if", "version_2", ":", "dev_data", "=", "SQuAD", "(", "'dev'", ",", "version", "=", "'2.0'", ")", "else", ":", "dev_data", "=", "SQuAD", "(", "'dev'", ",", "versio...
Evaluate the model on validation dataset.
[ "Evaluate", "the", "model", "on", "validation", "dataset", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/staticbert/static_finetune_squad.py#L429-L517
train
dmlc/gluon-nlp
src/gluonnlp/data/batchify/batchify.py
_pad_arrs_to_max_length
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...
python
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", "_pad_arrs_to_max_length", "(", "arrs", ",", "pad_axis", ",", "pad_val", ",", "use_shared_mem", ",", "dtype", ")", ":", "if", "isinstance", "(", "arrs", "[", "0", "]", ",", "mx", ".", "nd", ".", "NDArray", ")", ":", "dtype", "=", "arrs", "[", ...
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 : NDArray
[ "Inner", "Implementation", "of", "the", "Pad", "batchify" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/batchify/batchify.py#L29-L75
train
dmlc/gluon-nlp
scripts/parsing/parser/dep_parser.py
DepParser.train
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...
python
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", "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", "=...
Train a deep biaffine dependency parser Parameters ---------- train_file : str path to training set dev_file : str path to dev set test_file : str path to test set save_dir : str a directory for saving model and related met...
[ "Train", "a", "deep", "biaffine", "dependency", "parser" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/parser/dep_parser.py#L44-L199
train
dmlc/gluon-nlp
scripts/parsing/parser/dep_parser.py
DepParser.load
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...
python
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", "load", "(", "self", ",", "path", ")", ":", "config", "=", "_Config", ".", "load", "(", "os", ".", "path", ".", "join", "(", "path", ",", "'config.pkl'", ")", ")", "config", ".", "save_dir", "=", "path", "# redirect root path to what user specified"...
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
[ "Load", "from", "disk" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/parser/dep_parser.py#L201-L224
train
dmlc/gluon-nlp
scripts/parsing/parser/dep_parser.py
DepParser.evaluate
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...
python
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", "evaluate", "(", "self", ",", "test_file", ",", "save_dir", "=", "None", ",", "logger", "=", "None", ",", "num_buckets_test", "=", "10", ",", "test_batch_size", "=", "5000", ")", ":", "parser", "=", "self", ".", "_parser", "vocab", "=", "self", ...
Run evaluation on test set Parameters ---------- test_file : str path to test set save_dir : str where to store intermediate results and log logger : logging.logger logger for printing results num_buckets_test : int number ...
[ "Run", "evaluation", "on", "test", "set" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/parser/dep_parser.py#L226-L256
train
dmlc/gluon-nlp
scripts/parsing/parser/dep_parser.py
DepParser.parse
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) ...
python
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", "parse", "(", "self", ",", "sentence", ")", ":", "words", "=", "np", ".", "zeros", "(", "(", "len", "(", "sentence", ")", "+", "1", ",", "1", ")", ",", "np", ".", "int32", ")", "tags", "=", "np", ".", "zeros", "(", "(", "len", "(", "...
Parse raw sentence into ConllSentence Parameters ---------- sentence : list a list of (word, tag) tuples Returns ------- ConllSentence ConllSentence object
[ "Parse", "raw", "sentence", "into", "ConllSentence" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/parser/dep_parser.py#L258-L285
train
dmlc/gluon-nlp
src/gluonnlp/model/utils.py
apply_weight_drop
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...
python
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", "apply_weight_drop", "(", "block", ",", "local_param_regex", ",", "rate", ",", "axes", "=", "(", ")", ",", "weight_dropout_mode", "=", "'training'", ")", ":", "if", "not", "rate", ":", "return", "existing_params", "=", "_find_params", "(", "block", ",...
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_regex : str The regex for parameter names used in the self.params.get(), such as 'weight'. rate : float Fract...
[ "Apply", "weight", "drop", "to", "the", "parameter", "of", "a", "block", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/utils.py#L36-L114
train
dmlc/gluon-nlp
src/gluonnlp/model/utils.py
_get_rnn_cell
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...
python
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_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", ",", "cel...
create rnn cell given specs Parameters ---------- mode : str The type of RNN cell to use. Options are 'lstmpc', 'rnn_tanh', 'rnn_relu', 'lstm', 'gru'. num_layers : int The number of RNN cells in the encoder. input_size : int The initial input size of in the RNN cell. hid...
[ "create", "rnn", "cell", "given", "specs" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/utils.py#L162-L242
train
dmlc/gluon-nlp
src/gluonnlp/model/utils.py
_get_rnn_layer
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...
python
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", "_get_rnn_layer", "(", "mode", ",", "num_layers", ",", "input_size", ",", "hidden_size", ",", "dropout", ",", "weight_dropout", ")", ":", "if", "mode", "==", "'rnn_relu'", ":", "rnn_block", "=", "functools", ".", "partial", "(", "rnn", ".", "RNN", "...
create rnn layer given specs
[ "create", "rnn", "layer", "given", "specs" ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/utils.py#L245-L262
train
dmlc/gluon-nlp
src/gluonnlp/model/sampled_block.py
_SampledDenseHelper.hybrid_forward
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 = ...
python
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", ",", "w_all", ",", "b_all", ")", ":", "sampled_candidates", ",", "expected_count_sampled", ",", "expected_count_true", "=", "sampled_values", "# (num_sampled, in_unit)", ...
Forward computation.
[ "Forward", "computation", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/sampled_block.py#L52-L95
train
dmlc/gluon-nlp
src/gluonnlp/model/sampled_block.py
_SampledDense.hybrid_forward
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) ...
python
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", "hybrid_forward", "(", "self", ",", "F", ",", "x", ",", "sampled_values", ",", "label", ",", "weight", ",", "bias", ")", ":", "sampled_candidates", ",", "_", ",", "_", "=", "sampled_values", "# (batch_size,)", "label", "=", "F", ".", "reshape", "(...
Forward computation.
[ "Forward", "computation", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/sampled_block.py#L169-L183
train
dmlc/gluon-nlp
src/gluonnlp/model/sampled_block.py
_SparseSampledDense.forward
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 ...
python
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", "forward", "(", "self", ",", "x", ",", "sampled_values", ",", "label", ")", ":", "sampled_candidates", ",", "_", ",", "_", "=", "sampled_values", "# (batch_size,)", "label", "=", "label", ".", "reshape", "(", "shape", "=", "(", "-", "1", ",", ")...
Forward computation.
[ "Forward", "computation", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/sampled_block.py#L472-L487
train
dmlc/gluon-nlp
src/gluonnlp/model/sequence_sampler.py
_extract_and_flatten_nested_structure
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...
python
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", "_extract_and_flatten_nested_structure", "(", "data", ",", "flattened", "=", "None", ")", ":", "if", "flattened", "is", "None", ":", "flattened", "=", "[", "]", "structure", "=", "_extract_and_flatten_nested_structure", "(", "data", ",", "flattened", ")", ...
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 The container thats holds flattened result. Returns ------- st...
[ "Flatten", "the", "structure", "of", "a", "nested", "container", "to", "a", "list", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/sequence_sampler.py#L88-L119
train
dmlc/gluon-nlp
src/gluonnlp/model/sequence_sampler.py
_reconstruct_flattened_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 ...
python
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", "_reconstruct_flattened_structure", "(", "structure", ",", "flattened", ")", ":", "if", "isinstance", "(", "structure", ",", "list", ")", ":", "return", "list", "(", "_reconstruct_flattened_structure", "(", "x", ",", "flattened", ")", "for", "x", "in", ...
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 The container thats holds flattened result. Returns ...
[ "Reconstruct", "the", "flattened", "list", "back", "to", "(", "possibly", ")", "nested", "structure", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/sequence_sampler.py#L122-L145
train
dmlc/gluon-nlp
src/gluonnlp/model/sequence_sampler.py
_expand_to_beam_size
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...
python
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", "_expand_to_beam_size", "(", "data", ",", "beam_size", ",", "batch_size", ",", "state_info", "=", "None", ")", ":", "assert", "not", "state_info", "or", "isinstance", "(", "state_info", ",", "(", "type", "(", "data", ")", ",", "dict", ")", ")", ",...
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 state_info is None, or same as the layout in state_info when it's not None....
[ "Tile", "all", "the", "states", "to", "have", "batch_size", "*", "beam_size", "on", "the", "batch", "axis", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/sequence_sampler.py#L148-L211
train
dmlc/gluon-nlp
src/gluonnlp/model/sequence_sampler.py
_SamplingStepUpdate.hybrid_forward
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...
python
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", ",", "samples", ",", "valid_length", ",", "outputs", ",", "scores", ",", "beam_alive_mask", ",", "states", ")", ":", "beam_size", "=", "self", ".", "_beam_size", "# outputs: (batch_size, beam_size, vocab_size)", "out...
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 outp...
[ "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", "curren...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/sequence_sampler.py#L377-L442
train
dmlc/gluon-nlp
src/gluonnlp/model/sequence_sampler.py
HybridBeamSearchSampler.hybrid_forward
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 ...
python
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", "hybrid_forward", "(", "self", ",", "F", ",", "inputs", ",", "states", ")", ":", "# pylint: disable=arguments-differ", "batch_size", "=", "self", ".", "_batch_size", "beam_size", "=", "self", ".", "_beam_size", "vocab_size", "=", "self", ".", "_vocab_size...
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 Symbols The initial states of the decoder. Returns ------- ...
[ "Sample", "by", "beam", "search", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/sequence_sampler.py#L605-L710
train
dmlc/gluon-nlp
src/gluonnlp/model/parameter.py
WeightDropParameter.data
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._...
python
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", "data", "(", "self", ",", "ctx", "=", "None", ")", ":", "d", "=", "self", ".", "_check_and_get", "(", "self", ".", "_data", ",", "ctx", ")", "if", "self", ".", "_rate", ":", "d", "=", "nd", ".", "Dropout", "(", "d", ",", "self", ".", "...
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
[ "Returns", "a", "copy", "of", "this", "parameter", "on", "one", "context", ".", "Must", "have", "been", "initialized", "on", "this", "context", "before", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/parameter.py#L59-L74
train
dmlc/gluon-nlp
src/gluonnlp/model/elmo.py
elmo_2x1024_128_2048cnn_1xhighway
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...
python
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", "elmo_2x1024_128_2048cnn_1xhighway", "(", "dataset_name", "=", "None", ",", "pretrained", "=", "False", ",", "ctx", "=", "mx", ".", "cpu", "(", ")", ",", "root", "=", "os", ".", "path", ".", "join", "(", "get_home_dir", "(", ")", ",", "'models'", ...
r"""ELMo 2-layer BiLSTM with 1024 hidden units, 128 projection size, 1 highway layer. Parameters ---------- dataset_name : str or None, default None The dataset name on which the pre-trained model is trained. Options are 'gbw'. pretrained : bool, default False Whether to load th...
[ "r", "ELMo", "2", "-", "layer", "BiLSTM", "with", "1024", "hidden", "units", "128", "projection", "size", "1", "highway", "layer", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/elmo.py#L308-L349
train
dmlc/gluon-nlp
src/gluonnlp/model/elmo.py
ELMoCharacterEncoder.hybrid_forward
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) ...
python
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", ")", ":", "# pylint: disable=arguments-differ", "# the character id embedding", "# (batch_size * sequence_length, max_chars_per_token, embed_dim)", "character_embedding", "=", "self", ".", "_char_embedding", "(", "i...
Compute context insensitive token embeddings for ELMo representations. Parameters ---------- inputs : NDArray Shape (batch_size, sequence_length, max_character_per_token) of character ids representing the current batch. Returns ------- token_embe...
[ "Compute", "context", "insensitive", "token", "embeddings", "for", "ELMo", "representations", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/elmo.py#L103-L131
train
dmlc/gluon-nlp
src/gluonnlp/model/elmo.py
ELMoBiLM.hybrid_forward
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. ...
python
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", "hybrid_forward", "(", "self", ",", "F", ",", "inputs", ",", "states", "=", "None", ",", "mask", "=", "None", ")", ":", "# pylint: disable=arguments-differ", "type_representation", "=", "self", ".", "_elmo_char_encoder", "(", "inputs", ")", "type_represen...
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 laye...
[ "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"...
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/elmo.py#L243-L284
train
dmlc/gluon-nlp
src/gluonnlp/model/language_model.py
awd_lstm_lm_1150
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...
python
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...
[ "def", "awd_lstm_lm_1150", "(", "dataset_name", "=", "None", ",", "vocab", "=", "None", ",", "pretrained", "=", "False", ",", "ctx", "=", "cpu", "(", ")", ",", "root", "=", "os", ".", "path", ".", "join", "(", "get_home_dir", "(", ")", ",", "'models'...
r"""3-layer LSTM language model with weight-drop, variational dropout, and tied weights. Embedding size is 400, and hidden layer size is 1150. Parameters ---------- dataset_name : str or None, default None The dataset name on which the pre-trained model is trained. Options are 'wikitex...
[ "r", "3", "-", "layer", "LSTM", "language", "model", "with", "weight", "-", "drop", "variational", "dropout", "and", "tied", "weights", "." ]
4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/language_model.py#L181-L226
train