id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
32,500 | 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 |
32,501 | 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 |
32,502 | 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 |
32,503 | 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 |
32,504 | 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 |
32,505 | 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 |
32,506 | 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 |
32,507 | 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 |
32,508 | 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 |
32,509 | 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 |
32,510 | 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 |
32,511 | 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 |
32,512 | 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 |
32,513 | 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 |
32,514 | 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 |
32,515 | 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 |
32,516 | 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 |
32,517 | 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 |
32,518 | 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 |
32,519 | 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 |
32,520 | 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 |
32,521 | 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 |
32,522 | 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 |
32,523 | 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 |
32,524 | 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 |
32,525 | 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 |
32,526 | 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 |
32,527 | 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 |
32,528 | 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 |
32,529 | 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 |
32,530 | 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 |
32,531 | 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 |
32,532 | 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 |
32,533 | 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 |
32,534 | 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 |
32,535 | 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 |
32,536 | 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 |
32,537 | 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 |
32,538 | 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 |
32,539 | 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 |
32,540 | 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 |
32,541 | 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 |
32,542 | 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 |
32,543 | 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 |
32,544 | 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 |
32,545 | 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 |
32,546 | 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 |
32,547 | 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 |
32,548 | 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 |
32,549 | 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 |
32,550 | 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 |
32,551 | 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 |
32,552 | 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 |
32,553 | 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 |
32,554 | 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 |
32,555 | dmlc/gluon-nlp | src/gluonnlp/model/language_model.py | standard_lstm_lm_200 | def standard_lstm_lm_200(dataset_name=None, vocab=None, pretrained=False, ctx=cpu(),
root=os.path.join(get_home_dir(), 'models'), **kwargs):
r"""Standard 2-layer LSTM language model with tied embedding and output weights.
Both embedding and hidden dimensions are 200.
Parameters
... | python | def standard_lstm_lm_200(dataset_name=None, vocab=None, pretrained=False, ctx=cpu(),
root=os.path.join(get_home_dir(), 'models'), **kwargs):
r"""Standard 2-layer LSTM language model with tied embedding and output weights.
Both embedding and hidden dimensions are 200.
Parameters
... | [
"def",
"standard_lstm_lm_200",
"(",
"dataset_name",
"=",
"None",
",",
"vocab",
"=",
"None",
",",
"pretrained",
"=",
"False",
",",
"ctx",
"=",
"cpu",
"(",
")",
",",
"root",
"=",
"os",
".",
"path",
".",
"join",
"(",
"get_home_dir",
"(",
")",
",",
"'mod... | r"""Standard 2-layer LSTM language model with tied embedding and output weights.
Both embedding and hidden dimensions are 200.
Parameters
----------
dataset_name : str or None, default None
The dataset name on which the pre-trained model is trained.
Options are 'wikitext-2'. If specifi... | [
"r",
"Standard",
"2",
"-",
"layer",
"LSTM",
"language",
"model",
"with",
"tied",
"embedding",
"and",
"output",
"weights",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/language_model.py#L276-L317 |
32,556 | dmlc/gluon-nlp | src/gluonnlp/model/language_model.py | big_rnn_lm_2048_512 | def big_rnn_lm_2048_512(dataset_name=None, vocab=None, pretrained=False, ctx=cpu(),
root=os.path.join(get_home_dir(), 'models'), **kwargs):
r"""Big 1-layer LSTMP language model.
Both embedding and projection size are 512. Hidden size is 2048.
Parameters
----------
dataset_n... | python | def big_rnn_lm_2048_512(dataset_name=None, vocab=None, pretrained=False, ctx=cpu(),
root=os.path.join(get_home_dir(), 'models'), **kwargs):
r"""Big 1-layer LSTMP language model.
Both embedding and projection size are 512. Hidden size is 2048.
Parameters
----------
dataset_n... | [
"def",
"big_rnn_lm_2048_512",
"(",
"dataset_name",
"=",
"None",
",",
"vocab",
"=",
"None",
",",
"pretrained",
"=",
"False",
",",
"ctx",
"=",
"cpu",
"(",
")",
",",
"root",
"=",
"os",
".",
"path",
".",
"join",
"(",
"get_home_dir",
"(",
")",
",",
"'mode... | r"""Big 1-layer LSTMP language model.
Both embedding and projection size are 512. Hidden size is 2048.
Parameters
----------
dataset_name : str or None, default None
The dataset name on which the pre-trained model is trained.
Options are 'gbw'. If specified, then the returned vocabular... | [
"r",
"Big",
"1",
"-",
"layer",
"LSTMP",
"language",
"model",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/language_model.py#L512-L553 |
32,557 | dmlc/gluon-nlp | src/gluonnlp/model/seq2seq_encoder_decoder.py | _get_cell_type | def _get_cell_type(cell_type):
"""Get the object type of the cell by parsing the input
Parameters
----------
cell_type : str or type
Returns
-------
cell_constructor: type
The constructor of the RNNCell
"""
if isinstance(cell_type, str):
if cell_type == 'lstm':
... | python | def _get_cell_type(cell_type):
"""Get the object type of the cell by parsing the input
Parameters
----------
cell_type : str or type
Returns
-------
cell_constructor: type
The constructor of the RNNCell
"""
if isinstance(cell_type, str):
if cell_type == 'lstm':
... | [
"def",
"_get_cell_type",
"(",
"cell_type",
")",
":",
"if",
"isinstance",
"(",
"cell_type",
",",
"str",
")",
":",
"if",
"cell_type",
"==",
"'lstm'",
":",
"return",
"rnn",
".",
"LSTMCell",
"elif",
"cell_type",
"==",
"'gru'",
":",
"return",
"rnn",
".",
"GRU... | Get the object type of the cell by parsing the input
Parameters
----------
cell_type : str or type
Returns
-------
cell_constructor: type
The constructor of the RNNCell | [
"Get",
"the",
"object",
"type",
"of",
"the",
"cell",
"by",
"parsing",
"the",
"input"
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/seq2seq_encoder_decoder.py#L30-L54 |
32,558 | dmlc/gluon-nlp | src/gluonnlp/data/batchify/embedding.py | _get_context | def _get_context(center_idx, sentence_boundaries, window_size,
random_window_size, seed):
"""Compute the context with respect to a center word in a sentence.
Takes an numpy array of sentences boundaries.
"""
random.seed(seed + center_idx)
sentence_index = np.searchsorted(sentence... | python | def _get_context(center_idx, sentence_boundaries, window_size,
random_window_size, seed):
"""Compute the context with respect to a center word in a sentence.
Takes an numpy array of sentences boundaries.
"""
random.seed(seed + center_idx)
sentence_index = np.searchsorted(sentence... | [
"def",
"_get_context",
"(",
"center_idx",
",",
"sentence_boundaries",
",",
"window_size",
",",
"random_window_size",
",",
"seed",
")",
":",
"random",
".",
"seed",
"(",
"seed",
"+",
"center_idx",
")",
"sentence_index",
"=",
"np",
".",
"searchsorted",
"(",
"sent... | Compute the context with respect to a center word in a sentence.
Takes an numpy array of sentences boundaries. | [
"Compute",
"the",
"context",
"with",
"respect",
"to",
"a",
"center",
"word",
"in",
"a",
"sentence",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/batchify/embedding.py#L246-L274 |
32,559 | dmlc/gluon-nlp | scripts/sentiment_analysis/text_cnn.py | model | def model(dropout, vocab, model_mode, output_size):
"""Construct the model."""
textCNN = SentimentNet(dropout=dropout, vocab_size=len(vocab), model_mode=model_mode,\
output_size=output_size)
textCNN.hybridize()
return textCNN | python | def model(dropout, vocab, model_mode, output_size):
"""Construct the model."""
textCNN = SentimentNet(dropout=dropout, vocab_size=len(vocab), model_mode=model_mode,\
output_size=output_size)
textCNN.hybridize()
return textCNN | [
"def",
"model",
"(",
"dropout",
",",
"vocab",
",",
"model_mode",
",",
"output_size",
")",
":",
"textCNN",
"=",
"SentimentNet",
"(",
"dropout",
"=",
"dropout",
",",
"vocab_size",
"=",
"len",
"(",
"vocab",
")",
",",
"model_mode",
"=",
"model_mode",
",",
"o... | Construct the model. | [
"Construct",
"the",
"model",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/sentiment_analysis/text_cnn.py#L40-L46 |
32,560 | dmlc/gluon-nlp | scripts/sentiment_analysis/text_cnn.py | init | def init(textCNN, vocab, model_mode, context, lr):
"""Initialize parameters."""
textCNN.initialize(mx.init.Xavier(), ctx=context, force_reinit=True)
if model_mode != 'rand':
textCNN.embedding.weight.set_data(vocab.embedding.idx_to_vec)
if model_mode == 'multichannel':
textCNN.embedding_... | python | def init(textCNN, vocab, model_mode, context, lr):
"""Initialize parameters."""
textCNN.initialize(mx.init.Xavier(), ctx=context, force_reinit=True)
if model_mode != 'rand':
textCNN.embedding.weight.set_data(vocab.embedding.idx_to_vec)
if model_mode == 'multichannel':
textCNN.embedding_... | [
"def",
"init",
"(",
"textCNN",
",",
"vocab",
",",
"model_mode",
",",
"context",
",",
"lr",
")",
":",
"textCNN",
".",
"initialize",
"(",
"mx",
".",
"init",
".",
"Xavier",
"(",
")",
",",
"ctx",
"=",
"context",
",",
"force_reinit",
"=",
"True",
")",
"... | Initialize parameters. | [
"Initialize",
"parameters",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/sentiment_analysis/text_cnn.py#L48-L60 |
32,561 | dmlc/gluon-nlp | scripts/bert/bert_qa_dataset.py | preprocess_dataset | def preprocess_dataset(dataset, transform, num_workers=8):
"""Use multiprocessing to perform transform for dataset.
Parameters
----------
dataset: dataset-like object
Source dataset.
transform: callable
Transformer function.
num_workers: int, default 8
The number of mult... | python | def preprocess_dataset(dataset, transform, num_workers=8):
"""Use multiprocessing to perform transform for dataset.
Parameters
----------
dataset: dataset-like object
Source dataset.
transform: callable
Transformer function.
num_workers: int, default 8
The number of mult... | [
"def",
"preprocess_dataset",
"(",
"dataset",
",",
"transform",
",",
"num_workers",
"=",
"8",
")",
":",
"worker_fn",
"=",
"partial",
"(",
"_worker_fn",
",",
"transform",
"=",
"transform",
")",
"start",
"=",
"time",
".",
"time",
"(",
")",
"pool",
"=",
"mp"... | Use multiprocessing to perform transform for dataset.
Parameters
----------
dataset: dataset-like object
Source dataset.
transform: callable
Transformer function.
num_workers: int, default 8
The number of multiprocessing workers to use for data preprocessing. | [
"Use",
"multiprocessing",
"to",
"perform",
"transform",
"for",
"dataset",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/bert_qa_dataset.py#L56-L86 |
32,562 | dmlc/gluon-nlp | src/gluonnlp/model/attention_cell.py | _masked_softmax | def _masked_softmax(F, att_score, mask, dtype):
"""Ignore the masked elements when calculating the softmax
Parameters
----------
F : symbol or ndarray
att_score : Symborl or NDArray
Shape (batch_size, query_length, memory_length)
mask : Symbol or NDArray or None
Shape (batch_siz... | python | def _masked_softmax(F, att_score, mask, dtype):
"""Ignore the masked elements when calculating the softmax
Parameters
----------
F : symbol or ndarray
att_score : Symborl or NDArray
Shape (batch_size, query_length, memory_length)
mask : Symbol or NDArray or None
Shape (batch_siz... | [
"def",
"_masked_softmax",
"(",
"F",
",",
"att_score",
",",
"mask",
",",
"dtype",
")",
":",
"if",
"mask",
"is",
"not",
"None",
":",
"# Fill in the masked scores with a very small value",
"neg",
"=",
"-",
"1e4",
"if",
"np",
".",
"dtype",
"(",
"dtype",
")",
"... | Ignore the masked elements when calculating the softmax
Parameters
----------
F : symbol or ndarray
att_score : Symborl or NDArray
Shape (batch_size, query_length, memory_length)
mask : Symbol or NDArray or None
Shape (batch_size, query_length, memory_length)
Returns
-------... | [
"Ignore",
"the",
"masked",
"elements",
"when",
"calculating",
"the",
"softmax"
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/attention_cell.py#L33-L55 |
32,563 | dmlc/gluon-nlp | src/gluonnlp/model/attention_cell.py | AttentionCell._read_by_weight | def _read_by_weight(self, F, att_weights, value):
"""Read from the value matrix given the attention weights.
Parameters
----------
F : symbol or ndarray
att_weights : Symbol or NDArray
Attention weights.
For single-head attention,
Shape (b... | python | def _read_by_weight(self, F, att_weights, value):
"""Read from the value matrix given the attention weights.
Parameters
----------
F : symbol or ndarray
att_weights : Symbol or NDArray
Attention weights.
For single-head attention,
Shape (b... | [
"def",
"_read_by_weight",
"(",
"self",
",",
"F",
",",
"att_weights",
",",
"value",
")",
":",
"output",
"=",
"F",
".",
"batch_dot",
"(",
"att_weights",
",",
"value",
")",
"return",
"output"
] | Read from the value matrix given the attention weights.
Parameters
----------
F : symbol or ndarray
att_weights : Symbol or NDArray
Attention weights.
For single-head attention,
Shape (batch_size, query_length, memory_length).
For mult... | [
"Read",
"from",
"the",
"value",
"matrix",
"given",
"the",
"attention",
"weights",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/attention_cell.py#L99-L120 |
32,564 | dmlc/gluon-nlp | scripts/machine_translation/translation.py | BeamSearchTranslator.translate | def translate(self, src_seq, src_valid_length):
"""Get the translation result given the input sentence.
Parameters
----------
src_seq : mx.nd.NDArray
Shape (batch_size, length)
src_valid_length : mx.nd.NDArray
Shape (batch_size,)
Returns
... | python | def translate(self, src_seq, src_valid_length):
"""Get the translation result given the input sentence.
Parameters
----------
src_seq : mx.nd.NDArray
Shape (batch_size, length)
src_valid_length : mx.nd.NDArray
Shape (batch_size,)
Returns
... | [
"def",
"translate",
"(",
"self",
",",
"src_seq",
",",
"src_valid_length",
")",
":",
"batch_size",
"=",
"src_seq",
".",
"shape",
"[",
"0",
"]",
"encoder_outputs",
",",
"_",
"=",
"self",
".",
"_model",
".",
"encode",
"(",
"src_seq",
",",
"valid_length",
"=... | Get the translation result given the input sentence.
Parameters
----------
src_seq : mx.nd.NDArray
Shape (batch_size, length)
src_valid_length : mx.nd.NDArray
Shape (batch_size,)
Returns
-------
samples : NDArray
Samples draw ... | [
"Get",
"the",
"translation",
"result",
"given",
"the",
"input",
"sentence",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/machine_translation/translation.py#L55-L82 |
32,565 | dmlc/gluon-nlp | scripts/parsing/parser/evaluate/evaluate.py | evaluate_official_script | def evaluate_official_script(parser, vocab, num_buckets_test, test_batch_size, test_file, output_file,
debug=False):
"""Evaluate parser on a data set
Parameters
----------
parser : BiaffineParser
biaffine parser
vocab : ParserVocabulary
vocabulary built ... | python | def evaluate_official_script(parser, vocab, num_buckets_test, test_batch_size, test_file, output_file,
debug=False):
"""Evaluate parser on a data set
Parameters
----------
parser : BiaffineParser
biaffine parser
vocab : ParserVocabulary
vocabulary built ... | [
"def",
"evaluate_official_script",
"(",
"parser",
",",
"vocab",
",",
"num_buckets_test",
",",
"test_batch_size",
",",
"test_file",
",",
"output_file",
",",
"debug",
"=",
"False",
")",
":",
"if",
"output_file",
"is",
"None",
":",
"output_file",
"=",
"tempfile",
... | Evaluate parser on a data set
Parameters
----------
parser : BiaffineParser
biaffine parser
vocab : ParserVocabulary
vocabulary built from data set
num_buckets_test : int
size of buckets (cluster sentences into this number of clusters)
test_batch_size : int
batch... | [
"Evaluate",
"parser",
"on",
"a",
"data",
"set"
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/parser/evaluate/evaluate.py#L28-L102 |
32,566 | dmlc/gluon-nlp | scripts/parsing/parser/biaffine_parser.py | BiaffineParser.parameter_from_numpy | def parameter_from_numpy(self, name, array):
""" Create parameter with its value initialized according to a numpy tensor
Parameters
----------
name : str
parameter name
array : np.ndarray
initiation value
Returns
-------
mxnet.glu... | python | def parameter_from_numpy(self, name, array):
""" Create parameter with its value initialized according to a numpy tensor
Parameters
----------
name : str
parameter name
array : np.ndarray
initiation value
Returns
-------
mxnet.glu... | [
"def",
"parameter_from_numpy",
"(",
"self",
",",
"name",
",",
"array",
")",
":",
"p",
"=",
"self",
".",
"params",
".",
"get",
"(",
"name",
",",
"shape",
"=",
"array",
".",
"shape",
",",
"init",
"=",
"mx",
".",
"init",
".",
"Constant",
"(",
"array",... | Create parameter with its value initialized according to a numpy tensor
Parameters
----------
name : str
parameter name
array : np.ndarray
initiation value
Returns
-------
mxnet.gluon.parameter
a parameter object | [
"Create",
"parameter",
"with",
"its",
"value",
"initialized",
"according",
"to",
"a",
"numpy",
"tensor"
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/parser/biaffine_parser.py#L122-L138 |
32,567 | dmlc/gluon-nlp | scripts/parsing/parser/biaffine_parser.py | BiaffineParser.parameter_init | def parameter_init(self, name, shape, init):
"""Create parameter given name, shape and initiator
Parameters
----------
name : str
parameter name
shape : tuple
parameter shape
init : mxnet.initializer
an initializer
Returns
... | python | def parameter_init(self, name, shape, init):
"""Create parameter given name, shape and initiator
Parameters
----------
name : str
parameter name
shape : tuple
parameter shape
init : mxnet.initializer
an initializer
Returns
... | [
"def",
"parameter_init",
"(",
"self",
",",
"name",
",",
"shape",
",",
"init",
")",
":",
"p",
"=",
"self",
".",
"params",
".",
"get",
"(",
"name",
",",
"shape",
"=",
"shape",
",",
"init",
"=",
"init",
")",
"return",
"p"
] | Create parameter given name, shape and initiator
Parameters
----------
name : str
parameter name
shape : tuple
parameter shape
init : mxnet.initializer
an initializer
Returns
-------
mxnet.gluon.parameter
a... | [
"Create",
"parameter",
"given",
"name",
"shape",
"and",
"initiator"
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/parser/biaffine_parser.py#L140-L158 |
32,568 | dmlc/gluon-nlp | src/gluonnlp/data/dataloader.py | _thread_worker_fn | def _thread_worker_fn(samples, batchify_fn, dataset):
"""Threadpool worker function for processing data."""
if isinstance(samples[0], (list, tuple)):
batch = [batchify_fn([dataset[i] for i in shard]) for shard in samples]
else:
batch = batchify_fn([dataset[i] for i in samples])
return ba... | python | def _thread_worker_fn(samples, batchify_fn, dataset):
"""Threadpool worker function for processing data."""
if isinstance(samples[0], (list, tuple)):
batch = [batchify_fn([dataset[i] for i in shard]) for shard in samples]
else:
batch = batchify_fn([dataset[i] for i in samples])
return ba... | [
"def",
"_thread_worker_fn",
"(",
"samples",
",",
"batchify_fn",
",",
"dataset",
")",
":",
"if",
"isinstance",
"(",
"samples",
"[",
"0",
"]",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"batch",
"=",
"[",
"batchify_fn",
"(",
"[",
"dataset",
"[",
"i... | Threadpool worker function for processing data. | [
"Threadpool",
"worker",
"function",
"for",
"processing",
"data",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/dataloader.py#L54-L60 |
32,569 | dmlc/gluon-nlp | src/gluonnlp/embedding/token_embedding.py | TokenEmbedding._check_source | def _check_source(cls, source_file_hash, source):
"""Checks if a pre-trained token embedding source name is valid.
Parameters
----------
source : str
The pre-trained token embedding source.
"""
embedding_name = cls.__name__.lower()
if source not in s... | python | def _check_source(cls, source_file_hash, source):
"""Checks if a pre-trained token embedding source name is valid.
Parameters
----------
source : str
The pre-trained token embedding source.
"""
embedding_name = cls.__name__.lower()
if source not in s... | [
"def",
"_check_source",
"(",
"cls",
",",
"source_file_hash",
",",
"source",
")",
":",
"embedding_name",
"=",
"cls",
".",
"__name__",
".",
"lower",
"(",
")",
"if",
"source",
"not",
"in",
"source_file_hash",
":",
"raise",
"KeyError",
"(",
"'Cannot find pre-train... | Checks if a pre-trained token embedding source name is valid.
Parameters
----------
source : str
The pre-trained token embedding source. | [
"Checks",
"if",
"a",
"pre",
"-",
"trained",
"token",
"embedding",
"source",
"name",
"is",
"valid",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/embedding/token_embedding.py#L643-L657 |
32,570 | dmlc/gluon-nlp | src/gluonnlp/embedding/token_embedding.py | TokenEmbedding.from_file | def from_file(file_path, elem_delim=' ', encoding='utf8', **kwargs):
"""Creates a user-defined token embedding from a pre-trained embedding file.
This is to load embedding vectors from a user-defined pre-trained token embedding file.
For example, if `elem_delim` = ' ', the expected format of a... | python | def from_file(file_path, elem_delim=' ', encoding='utf8', **kwargs):
"""Creates a user-defined token embedding from a pre-trained embedding file.
This is to load embedding vectors from a user-defined pre-trained token embedding file.
For example, if `elem_delim` = ' ', the expected format of a... | [
"def",
"from_file",
"(",
"file_path",
",",
"elem_delim",
"=",
"' '",
",",
"encoding",
"=",
"'utf8'",
",",
"*",
"*",
"kwargs",
")",
":",
"embedding",
"=",
"TokenEmbedding",
"(",
"*",
"*",
"kwargs",
")",
"embedding",
".",
"_load_embedding",
"(",
"file_path",... | Creates a user-defined token embedding from a pre-trained embedding file.
This is to load embedding vectors from a user-defined pre-trained token embedding file.
For example, if `elem_delim` = ' ', the expected format of a custom pre-trained token
embedding file may look like:
'hello ... | [
"Creates",
"a",
"user",
"-",
"defined",
"token",
"embedding",
"from",
"a",
"pre",
"-",
"trained",
"embedding",
"file",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/embedding/token_embedding.py#L660-L694 |
32,571 | dmlc/gluon-nlp | src/gluonnlp/embedding/token_embedding.py | TokenEmbedding.serialize | def serialize(self, file_path, compress=True):
"""Serializes the TokenEmbedding to a file specified by file_path.
TokenEmbedding is serialized by converting the list of tokens, the
array of word embeddings and other metadata to numpy arrays, saving all
in a single (optionally compressed... | python | def serialize(self, file_path, compress=True):
"""Serializes the TokenEmbedding to a file specified by file_path.
TokenEmbedding is serialized by converting the list of tokens, the
array of word embeddings and other metadata to numpy arrays, saving all
in a single (optionally compressed... | [
"def",
"serialize",
"(",
"self",
",",
"file_path",
",",
"compress",
"=",
"True",
")",
":",
"if",
"self",
".",
"unknown_lookup",
"is",
"not",
"None",
":",
"warnings",
".",
"warn",
"(",
"'Serialization of `unknown_lookup` is not supported. '",
"'Save it manually and p... | Serializes the TokenEmbedding to a file specified by file_path.
TokenEmbedding is serialized by converting the list of tokens, the
array of word embeddings and other metadata to numpy arrays, saving all
in a single (optionally compressed) Zipfile. See
https://docs.scipy.org/doc/numpy-1.... | [
"Serializes",
"the",
"TokenEmbedding",
"to",
"a",
"file",
"specified",
"by",
"file_path",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/embedding/token_embedding.py#L696-L737 |
32,572 | dmlc/gluon-nlp | src/gluonnlp/embedding/token_embedding.py | TokenEmbedding.deserialize | def deserialize(cls, file_path, **kwargs):
"""Create a new TokenEmbedding from a serialized one.
TokenEmbedding is serialized by converting the list of tokens, the
array of word embeddings and other metadata to numpy arrays, saving all
in a single (optionally compressed) Zipfile. See
... | python | def deserialize(cls, file_path, **kwargs):
"""Create a new TokenEmbedding from a serialized one.
TokenEmbedding is serialized by converting the list of tokens, the
array of word embeddings and other metadata to numpy arrays, saving all
in a single (optionally compressed) Zipfile. See
... | [
"def",
"deserialize",
"(",
"cls",
",",
"file_path",
",",
"*",
"*",
"kwargs",
")",
":",
"# idx_to_token is of dtype 'O' so we need to allow pickle",
"npz_dict",
"=",
"np",
".",
"load",
"(",
"file_path",
",",
"allow_pickle",
"=",
"True",
")",
"unknown_token",
"=",
... | Create a new TokenEmbedding from a serialized one.
TokenEmbedding is serialized by converting the list of tokens, the
array of word embeddings and other metadata to numpy arrays, saving all
in a single (optionally compressed) Zipfile. See
https://docs.scipy.org/doc/numpy-1.14.2/neps/npy... | [
"Create",
"a",
"new",
"TokenEmbedding",
"from",
"a",
"serialized",
"one",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/embedding/token_embedding.py#L740-L784 |
32,573 | dmlc/gluon-nlp | scripts/bert/staticbert/static_export_squad.py | evaluate | def evaluate(data_source):
"""Evaluate the model on a mini-batch.
"""
log.info('Start predict')
tic = time.time()
for batch in data_source:
inputs, token_types, valid_length = batch
out = net(inputs.astype('float32').as_in_context(ctx),
token_types.astype('float32')... | python | def evaluate(data_source):
"""Evaluate the model on a mini-batch.
"""
log.info('Start predict')
tic = time.time()
for batch in data_source:
inputs, token_types, valid_length = batch
out = net(inputs.astype('float32').as_in_context(ctx),
token_types.astype('float32')... | [
"def",
"evaluate",
"(",
"data_source",
")",
":",
"log",
".",
"info",
"(",
"'Start predict'",
")",
"tic",
"=",
"time",
".",
"time",
"(",
")",
"for",
"batch",
"in",
"data_source",
":",
"inputs",
",",
"token_types",
",",
"valid_length",
"=",
"batch",
"out",... | Evaluate the model on a mini-batch. | [
"Evaluate",
"the",
"model",
"on",
"a",
"mini",
"-",
"batch",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/staticbert/static_export_squad.py#L210-L223 |
32,574 | dmlc/gluon-nlp | src/gluonnlp/data/registry.py | register | def register(class_=None, **kwargs):
"""Registers a dataset with segment specific hyperparameters.
When passing keyword arguments to `register`, they are checked to be valid
keyword arguments for the registered Dataset class constructor and are
saved in the registry. Registered keyword arguments can be... | python | def register(class_=None, **kwargs):
"""Registers a dataset with segment specific hyperparameters.
When passing keyword arguments to `register`, they are checked to be valid
keyword arguments for the registered Dataset class constructor and are
saved in the registry. Registered keyword arguments can be... | [
"def",
"register",
"(",
"class_",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"_real_register",
"(",
"class_",
")",
":",
"# Assert that the passed kwargs are meaningful",
"for",
"kwarg_name",
",",
"values",
"in",
"kwargs",
".",
"items",
"(",
")",
... | Registers a dataset with segment specific hyperparameters.
When passing keyword arguments to `register`, they are checked to be valid
keyword arguments for the registered Dataset class constructor and are
saved in the registry. Registered keyword arguments can be retrieved with
the `list_datasets` func... | [
"Registers",
"a",
"dataset",
"with",
"segment",
"specific",
"hyperparameters",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/registry.py#L34-L97 |
32,575 | dmlc/gluon-nlp | src/gluonnlp/data/registry.py | create | def create(name, **kwargs):
"""Creates an instance of a registered dataset.
Parameters
----------
name : str
The dataset name (case-insensitive).
Returns
-------
An instance of :class:`mxnet.gluon.data.Dataset` constructed with the
keyword arguments passed to the create functio... | python | def create(name, **kwargs):
"""Creates an instance of a registered dataset.
Parameters
----------
name : str
The dataset name (case-insensitive).
Returns
-------
An instance of :class:`mxnet.gluon.data.Dataset` constructed with the
keyword arguments passed to the create functio... | [
"def",
"create",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"create_",
"=",
"registry",
".",
"get_create_func",
"(",
"Dataset",
",",
"'dataset'",
")",
"return",
"create_",
"(",
"name",
",",
"*",
"*",
"kwargs",
")"
] | Creates an instance of a registered dataset.
Parameters
----------
name : str
The dataset name (case-insensitive).
Returns
-------
An instance of :class:`mxnet.gluon.data.Dataset` constructed with the
keyword arguments passed to the create function. | [
"Creates",
"an",
"instance",
"of",
"a",
"registered",
"dataset",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/registry.py#L100-L115 |
32,576 | dmlc/gluon-nlp | src/gluonnlp/data/registry.py | list_datasets | def list_datasets(name=None):
"""Get valid datasets and registered parameters.
Parameters
----------
name : str or None, default None
Return names and registered parameters of registered datasets. If name
is specified, only registered parameters of the respective dataset are
ret... | python | def list_datasets(name=None):
"""Get valid datasets and registered parameters.
Parameters
----------
name : str or None, default None
Return names and registered parameters of registered datasets. If name
is specified, only registered parameters of the respective dataset are
ret... | [
"def",
"list_datasets",
"(",
"name",
"=",
"None",
")",
":",
"reg",
"=",
"registry",
".",
"get_registry",
"(",
"Dataset",
")",
"if",
"name",
"is",
"not",
"None",
":",
"class_",
"=",
"reg",
"[",
"name",
".",
"lower",
"(",
")",
"]",
"return",
"_REGSITRY... | Get valid datasets and registered parameters.
Parameters
----------
name : str or None, default None
Return names and registered parameters of registered datasets. If name
is specified, only registered parameters of the respective dataset are
returned.
Returns
-------
d... | [
"Get",
"valid",
"datasets",
"and",
"registered",
"parameters",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/registry.py#L118-L146 |
32,577 | dmlc/gluon-nlp | scripts/word_embeddings/extract_vocab.py | get_vocab | def get_vocab(args):
"""Compute the vocabulary."""
counter = nlp.data.Counter()
start = time.time()
for filename in args.files:
print('Starting processing of {} after {:.1f} seconds.'.format(
filename,
time.time() - start))
with open(filename, 'r') as f:
... | python | def get_vocab(args):
"""Compute the vocabulary."""
counter = nlp.data.Counter()
start = time.time()
for filename in args.files:
print('Starting processing of {} after {:.1f} seconds.'.format(
filename,
time.time() - start))
with open(filename, 'r') as f:
... | [
"def",
"get_vocab",
"(",
"args",
")",
":",
"counter",
"=",
"nlp",
".",
"data",
".",
"Counter",
"(",
")",
"start",
"=",
"time",
".",
"time",
"(",
")",
"for",
"filename",
"in",
"args",
".",
"files",
":",
"print",
"(",
"'Starting processing of {} after {:.1... | Compute the vocabulary. | [
"Compute",
"the",
"vocabulary",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/extract_vocab.py#L47-L87 |
32,578 | dmlc/gluon-nlp | scripts/word_embeddings/evaluation.py | add_parameters | def add_parameters(parser):
"""Add evaluation specific parameters to parser."""
group = parser.add_argument_group('Evaluation arguments')
group.add_argument('--eval-batch-size', type=int, default=1024)
# Datasets
group.add_argument(
'--similarity-datasets', type=str,
default=nlp.da... | python | def add_parameters(parser):
"""Add evaluation specific parameters to parser."""
group = parser.add_argument_group('Evaluation arguments')
group.add_argument('--eval-batch-size', type=int, default=1024)
# Datasets
group.add_argument(
'--similarity-datasets', type=str,
default=nlp.da... | [
"def",
"add_parameters",
"(",
"parser",
")",
":",
"group",
"=",
"parser",
".",
"add_argument_group",
"(",
"'Evaluation arguments'",
")",
"group",
".",
"add_argument",
"(",
"'--eval-batch-size'",
",",
"type",
"=",
"int",
",",
"default",
"=",
"1024",
")",
"# Dat... | Add evaluation specific parameters to parser. | [
"Add",
"evaluation",
"specific",
"parameters",
"to",
"parser",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/evaluation.py#L38-L70 |
32,579 | dmlc/gluon-nlp | scripts/word_embeddings/evaluation.py | iterate_similarity_datasets | def iterate_similarity_datasets(args):
"""Generator over all similarity evaluation datasets.
Iterates over dataset names, keyword arguments for their creation and the
created dataset.
"""
for dataset_name in args.similarity_datasets:
parameters = nlp.data.list_datasets(dataset_name)
... | python | def iterate_similarity_datasets(args):
"""Generator over all similarity evaluation datasets.
Iterates over dataset names, keyword arguments for their creation and the
created dataset.
"""
for dataset_name in args.similarity_datasets:
parameters = nlp.data.list_datasets(dataset_name)
... | [
"def",
"iterate_similarity_datasets",
"(",
"args",
")",
":",
"for",
"dataset_name",
"in",
"args",
".",
"similarity_datasets",
":",
"parameters",
"=",
"nlp",
".",
"data",
".",
"list_datasets",
"(",
"dataset_name",
")",
"for",
"key_values",
"in",
"itertools",
".",... | Generator over all similarity evaluation datasets.
Iterates over dataset names, keyword arguments for their creation and the
created dataset. | [
"Generator",
"over",
"all",
"similarity",
"evaluation",
"datasets",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/evaluation.py#L92-L103 |
32,580 | dmlc/gluon-nlp | scripts/word_embeddings/evaluation.py | iterate_analogy_datasets | def iterate_analogy_datasets(args):
"""Generator over all analogy evaluation datasets.
Iterates over dataset names, keyword arguments for their creation and the
created dataset.
"""
for dataset_name in args.analogy_datasets:
parameters = nlp.data.list_datasets(dataset_name)
for key... | python | def iterate_analogy_datasets(args):
"""Generator over all analogy evaluation datasets.
Iterates over dataset names, keyword arguments for their creation and the
created dataset.
"""
for dataset_name in args.analogy_datasets:
parameters = nlp.data.list_datasets(dataset_name)
for key... | [
"def",
"iterate_analogy_datasets",
"(",
"args",
")",
":",
"for",
"dataset_name",
"in",
"args",
".",
"analogy_datasets",
":",
"parameters",
"=",
"nlp",
".",
"data",
".",
"list_datasets",
"(",
"dataset_name",
")",
"for",
"key_values",
"in",
"itertools",
".",
"pr... | Generator over all analogy evaluation datasets.
Iterates over dataset names, keyword arguments for their creation and the
created dataset. | [
"Generator",
"over",
"all",
"analogy",
"evaluation",
"datasets",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/evaluation.py#L106-L117 |
32,581 | dmlc/gluon-nlp | scripts/word_embeddings/evaluation.py | get_similarity_task_tokens | def get_similarity_task_tokens(args):
"""Returns a set of all tokens occurring the evaluation datasets."""
tokens = set()
for _, _, dataset in iterate_similarity_datasets(args):
tokens.update(
itertools.chain.from_iterable((d[0], d[1]) for d in dataset))
return tokens | python | def get_similarity_task_tokens(args):
"""Returns a set of all tokens occurring the evaluation datasets."""
tokens = set()
for _, _, dataset in iterate_similarity_datasets(args):
tokens.update(
itertools.chain.from_iterable((d[0], d[1]) for d in dataset))
return tokens | [
"def",
"get_similarity_task_tokens",
"(",
"args",
")",
":",
"tokens",
"=",
"set",
"(",
")",
"for",
"_",
",",
"_",
",",
"dataset",
"in",
"iterate_similarity_datasets",
"(",
"args",
")",
":",
"tokens",
".",
"update",
"(",
"itertools",
".",
"chain",
".",
"f... | Returns a set of all tokens occurring the evaluation datasets. | [
"Returns",
"a",
"set",
"of",
"all",
"tokens",
"occurring",
"the",
"evaluation",
"datasets",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/evaluation.py#L120-L126 |
32,582 | dmlc/gluon-nlp | scripts/word_embeddings/evaluation.py | get_analogy_task_tokens | def get_analogy_task_tokens(args):
"""Returns a set of all tokens occuring the evaluation datasets."""
tokens = set()
for _, _, dataset in iterate_analogy_datasets(args):
tokens.update(
itertools.chain.from_iterable(
(d[0], d[1], d[2], d[3]) for d in dataset))
return ... | python | def get_analogy_task_tokens(args):
"""Returns a set of all tokens occuring the evaluation datasets."""
tokens = set()
for _, _, dataset in iterate_analogy_datasets(args):
tokens.update(
itertools.chain.from_iterable(
(d[0], d[1], d[2], d[3]) for d in dataset))
return ... | [
"def",
"get_analogy_task_tokens",
"(",
"args",
")",
":",
"tokens",
"=",
"set",
"(",
")",
"for",
"_",
",",
"_",
",",
"dataset",
"in",
"iterate_analogy_datasets",
"(",
"args",
")",
":",
"tokens",
".",
"update",
"(",
"itertools",
".",
"chain",
".",
"from_it... | Returns a set of all tokens occuring the evaluation datasets. | [
"Returns",
"a",
"set",
"of",
"all",
"tokens",
"occuring",
"the",
"evaluation",
"datasets",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/evaluation.py#L129-L136 |
32,583 | dmlc/gluon-nlp | scripts/word_embeddings/evaluation.py | evaluate_similarity | def evaluate_similarity(args, token_embedding, ctx, logfile=None,
global_step=0):
"""Evaluate on specified similarity datasets."""
results = []
for similarity_function in args.similarity_functions:
evaluator = nlp.embedding.evaluation.WordEmbeddingSimilarity(
idx... | python | def evaluate_similarity(args, token_embedding, ctx, logfile=None,
global_step=0):
"""Evaluate on specified similarity datasets."""
results = []
for similarity_function in args.similarity_functions:
evaluator = nlp.embedding.evaluation.WordEmbeddingSimilarity(
idx... | [
"def",
"evaluate_similarity",
"(",
"args",
",",
"token_embedding",
",",
"ctx",
",",
"logfile",
"=",
"None",
",",
"global_step",
"=",
"0",
")",
":",
"results",
"=",
"[",
"]",
"for",
"similarity_function",
"in",
"args",
".",
"similarity_functions",
":",
"evalu... | Evaluate on specified similarity datasets. | [
"Evaluate",
"on",
"specified",
"similarity",
"datasets",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/evaluation.py#L145-L197 |
32,584 | dmlc/gluon-nlp | scripts/word_embeddings/evaluation.py | evaluate_analogy | def evaluate_analogy(args, token_embedding, ctx, logfile=None, global_step=0):
"""Evaluate on specified analogy datasets.
The analogy task is an open vocabulary task, make sure to pass a
token_embedding with a sufficiently large number of supported tokens.
"""
results = []
exclude_question_wor... | python | def evaluate_analogy(args, token_embedding, ctx, logfile=None, global_step=0):
"""Evaluate on specified analogy datasets.
The analogy task is an open vocabulary task, make sure to pass a
token_embedding with a sufficiently large number of supported tokens.
"""
results = []
exclude_question_wor... | [
"def",
"evaluate_analogy",
"(",
"args",
",",
"token_embedding",
",",
"ctx",
",",
"logfile",
"=",
"None",
",",
"global_step",
"=",
"0",
")",
":",
"results",
"=",
"[",
"]",
"exclude_question_words",
"=",
"not",
"args",
".",
"analogy_dont_exclude_question_words",
... | Evaluate on specified analogy datasets.
The analogy task is an open vocabulary task, make sure to pass a
token_embedding with a sufficiently large number of supported tokens. | [
"Evaluate",
"on",
"specified",
"analogy",
"datasets",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/evaluation.py#L200-L259 |
32,585 | dmlc/gluon-nlp | scripts/word_embeddings/evaluation.py | log_similarity_result | def log_similarity_result(logfile, result):
"""Log a similarity evaluation result dictionary as TSV to logfile."""
assert result['task'] == 'similarity'
if not logfile:
return
with open(logfile, 'a') as f:
f.write('\t'.join([
str(result['global_step']),
result['... | python | def log_similarity_result(logfile, result):
"""Log a similarity evaluation result dictionary as TSV to logfile."""
assert result['task'] == 'similarity'
if not logfile:
return
with open(logfile, 'a') as f:
f.write('\t'.join([
str(result['global_step']),
result['... | [
"def",
"log_similarity_result",
"(",
"logfile",
",",
"result",
")",
":",
"assert",
"result",
"[",
"'task'",
"]",
"==",
"'similarity'",
"if",
"not",
"logfile",
":",
"return",
"with",
"open",
"(",
"logfile",
",",
"'a'",
")",
"as",
"f",
":",
"f",
".",
"wr... | Log a similarity evaluation result dictionary as TSV to logfile. | [
"Log",
"a",
"similarity",
"evaluation",
"result",
"dictionary",
"as",
"TSV",
"to",
"logfile",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/evaluation.py#L262-L280 |
32,586 | dmlc/gluon-nlp | scripts/bert/pretraining_utils.py | get_model_loss | def get_model_loss(ctx, model, pretrained, dataset_name, dtype, ckpt_dir=None, start_step=None):
"""Get model for pre-training."""
# model
model, vocabulary = nlp.model.get_model(model,
dataset_name=dataset_name,
pretrai... | python | def get_model_loss(ctx, model, pretrained, dataset_name, dtype, ckpt_dir=None, start_step=None):
"""Get model for pre-training."""
# model
model, vocabulary = nlp.model.get_model(model,
dataset_name=dataset_name,
pretrai... | [
"def",
"get_model_loss",
"(",
"ctx",
",",
"model",
",",
"pretrained",
",",
"dataset_name",
",",
"dtype",
",",
"ckpt_dir",
"=",
"None",
",",
"start_step",
"=",
"None",
")",
":",
"# model",
"model",
",",
"vocabulary",
"=",
"nlp",
".",
"model",
".",
"get_mo... | Get model for pre-training. | [
"Get",
"model",
"for",
"pre",
"-",
"training",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/pretraining_utils.py#L36-L60 |
32,587 | dmlc/gluon-nlp | scripts/bert/pretraining_utils.py | get_pretrain_dataset | def get_pretrain_dataset(data, batch_size, num_ctxes, shuffle, use_avg_len,
num_buckets, num_parts=1, part_idx=0, prefetch=True):
"""create dataset for pretraining."""
num_files = len(glob.glob(os.path.expanduser(data)))
logging.debug('%d files found.', num_files)
assert num_fil... | python | def get_pretrain_dataset(data, batch_size, num_ctxes, shuffle, use_avg_len,
num_buckets, num_parts=1, part_idx=0, prefetch=True):
"""create dataset for pretraining."""
num_files = len(glob.glob(os.path.expanduser(data)))
logging.debug('%d files found.', num_files)
assert num_fil... | [
"def",
"get_pretrain_dataset",
"(",
"data",
",",
"batch_size",
",",
"num_ctxes",
",",
"shuffle",
",",
"use_avg_len",
",",
"num_buckets",
",",
"num_parts",
"=",
"1",
",",
"part_idx",
"=",
"0",
",",
"prefetch",
"=",
"True",
")",
":",
"num_files",
"=",
"len",... | create dataset for pretraining. | [
"create",
"dataset",
"for",
"pretraining",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/pretraining_utils.py#L62-L107 |
32,588 | dmlc/gluon-nlp | scripts/bert/pretraining_utils.py | get_dummy_dataloader | def get_dummy_dataloader(dataloader, target_shape):
"""Return a dummy data loader which returns a fixed data batch of target shape"""
data_iter = enumerate(dataloader)
_, data_batch = next(data_iter)
logging.debug('Searching target batch shape: %s', target_shape)
while data_batch[0].shape != target_... | python | def get_dummy_dataloader(dataloader, target_shape):
"""Return a dummy data loader which returns a fixed data batch of target shape"""
data_iter = enumerate(dataloader)
_, data_batch = next(data_iter)
logging.debug('Searching target batch shape: %s', target_shape)
while data_batch[0].shape != target_... | [
"def",
"get_dummy_dataloader",
"(",
"dataloader",
",",
"target_shape",
")",
":",
"data_iter",
"=",
"enumerate",
"(",
"dataloader",
")",
"_",
",",
"data_batch",
"=",
"next",
"(",
"data_iter",
")",
"logging",
".",
"debug",
"(",
"'Searching target batch shape: %s'",
... | Return a dummy data loader which returns a fixed data batch of target shape | [
"Return",
"a",
"dummy",
"data",
"loader",
"which",
"returns",
"a",
"fixed",
"data",
"batch",
"of",
"target",
"shape"
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/pretraining_utils.py#L109-L127 |
32,589 | dmlc/gluon-nlp | scripts/bert/pretraining_utils.py | save_params | def save_params(step_num, model, trainer, ckpt_dir):
"""Save the model parameter, marked by step_num."""
param_path = os.path.join(ckpt_dir, '%07d.params'%step_num)
trainer_path = os.path.join(ckpt_dir, '%07d.states'%step_num)
logging.info('[step %d] Saving checkpoints to %s, %s.',
step... | python | def save_params(step_num, model, trainer, ckpt_dir):
"""Save the model parameter, marked by step_num."""
param_path = os.path.join(ckpt_dir, '%07d.params'%step_num)
trainer_path = os.path.join(ckpt_dir, '%07d.states'%step_num)
logging.info('[step %d] Saving checkpoints to %s, %s.',
step... | [
"def",
"save_params",
"(",
"step_num",
",",
"model",
",",
"trainer",
",",
"ckpt_dir",
")",
":",
"param_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"ckpt_dir",
",",
"'%07d.params'",
"%",
"step_num",
")",
"trainer_path",
"=",
"os",
".",
"path",
".",
... | Save the model parameter, marked by step_num. | [
"Save",
"the",
"model",
"parameter",
"marked",
"by",
"step_num",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/pretraining_utils.py#L129-L136 |
32,590 | dmlc/gluon-nlp | scripts/bert/pretraining_utils.py | log | def log(begin_time, running_num_tks, running_mlm_loss, running_nsp_loss, step_num,
mlm_metric, nsp_metric, trainer, log_interval):
"""Log training progress."""
end_time = time.time()
duration = end_time - begin_time
throughput = running_num_tks / duration / 1000.0
running_mlm_loss = running_... | python | def log(begin_time, running_num_tks, running_mlm_loss, running_nsp_loss, step_num,
mlm_metric, nsp_metric, trainer, log_interval):
"""Log training progress."""
end_time = time.time()
duration = end_time - begin_time
throughput = running_num_tks / duration / 1000.0
running_mlm_loss = running_... | [
"def",
"log",
"(",
"begin_time",
",",
"running_num_tks",
",",
"running_mlm_loss",
",",
"running_nsp_loss",
",",
"step_num",
",",
"mlm_metric",
",",
"nsp_metric",
",",
"trainer",
",",
"log_interval",
")",
":",
"end_time",
"=",
"time",
".",
"time",
"(",
")",
"... | Log training progress. | [
"Log",
"training",
"progress",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/pretraining_utils.py#L138-L150 |
32,591 | dmlc/gluon-nlp | scripts/bert/pretraining_utils.py | split_and_load | def split_and_load(arrs, ctx):
"""split and load arrays to a list of contexts"""
assert isinstance(arrs, (list, tuple))
# split and load
loaded_arrs = [mx.gluon.utils.split_and_load(arr, ctx, even_split=False) for arr in arrs]
return zip(*loaded_arrs) | python | def split_and_load(arrs, ctx):
"""split and load arrays to a list of contexts"""
assert isinstance(arrs, (list, tuple))
# split and load
loaded_arrs = [mx.gluon.utils.split_and_load(arr, ctx, even_split=False) for arr in arrs]
return zip(*loaded_arrs) | [
"def",
"split_and_load",
"(",
"arrs",
",",
"ctx",
")",
":",
"assert",
"isinstance",
"(",
"arrs",
",",
"(",
"list",
",",
"tuple",
")",
")",
"# split and load",
"loaded_arrs",
"=",
"[",
"mx",
".",
"gluon",
".",
"utils",
".",
"split_and_load",
"(",
"arr",
... | split and load arrays to a list of contexts | [
"split",
"and",
"load",
"arrays",
"to",
"a",
"list",
"of",
"contexts"
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/pretraining_utils.py#L153-L158 |
32,592 | dmlc/gluon-nlp | scripts/bert/pretraining_utils.py | forward | def forward(data, model, mlm_loss, nsp_loss, vocab_size, dtype):
"""forward computation for evaluation"""
(input_id, masked_id, masked_position, masked_weight, \
next_sentence_label, segment_id, valid_length) = data
num_masks = masked_weight.sum() + 1e-8
valid_length = valid_length.reshape(-1)
... | python | def forward(data, model, mlm_loss, nsp_loss, vocab_size, dtype):
"""forward computation for evaluation"""
(input_id, masked_id, masked_position, masked_weight, \
next_sentence_label, segment_id, valid_length) = data
num_masks = masked_weight.sum() + 1e-8
valid_length = valid_length.reshape(-1)
... | [
"def",
"forward",
"(",
"data",
",",
"model",
",",
"mlm_loss",
",",
"nsp_loss",
",",
"vocab_size",
",",
"dtype",
")",
":",
"(",
"input_id",
",",
"masked_id",
",",
"masked_position",
",",
"masked_weight",
",",
"next_sentence_label",
",",
"segment_id",
",",
"va... | forward computation for evaluation | [
"forward",
"computation",
"for",
"evaluation"
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/pretraining_utils.py#L161-L179 |
32,593 | dmlc/gluon-nlp | scripts/bert/pretraining_utils.py | evaluate | def evaluate(data_eval, model, nsp_loss, mlm_loss, vocab_size, ctx, log_interval, dtype):
"""Evaluation function."""
mlm_metric = MaskedAccuracy()
nsp_metric = MaskedAccuracy()
mlm_metric.reset()
nsp_metric.reset()
eval_begin_time = time.time()
begin_time = time.time()
step_num = 0
... | python | def evaluate(data_eval, model, nsp_loss, mlm_loss, vocab_size, ctx, log_interval, dtype):
"""Evaluation function."""
mlm_metric = MaskedAccuracy()
nsp_metric = MaskedAccuracy()
mlm_metric.reset()
nsp_metric.reset()
eval_begin_time = time.time()
begin_time = time.time()
step_num = 0
... | [
"def",
"evaluate",
"(",
"data_eval",
",",
"model",
",",
"nsp_loss",
",",
"mlm_loss",
",",
"vocab_size",
",",
"ctx",
",",
"log_interval",
",",
"dtype",
")",
":",
"mlm_metric",
"=",
"MaskedAccuracy",
"(",
")",
"nsp_metric",
"=",
"MaskedAccuracy",
"(",
")",
"... | Evaluation function. | [
"Evaluation",
"function",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/pretraining_utils.py#L182-L238 |
32,594 | dmlc/gluon-nlp | scripts/machine_translation/dataprocessor.py | _cache_dataset | def _cache_dataset(dataset, prefix):
"""Cache the processed npy dataset the dataset into a npz
Parameters
----------
dataset : SimpleDataset
file_path : str
"""
if not os.path.exists(_constants.CACHE_PATH):
os.makedirs(_constants.CACHE_PATH)
src_data = np.concatenate([e[0] for e... | python | def _cache_dataset(dataset, prefix):
"""Cache the processed npy dataset the dataset into a npz
Parameters
----------
dataset : SimpleDataset
file_path : str
"""
if not os.path.exists(_constants.CACHE_PATH):
os.makedirs(_constants.CACHE_PATH)
src_data = np.concatenate([e[0] for e... | [
"def",
"_cache_dataset",
"(",
"dataset",
",",
"prefix",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"_constants",
".",
"CACHE_PATH",
")",
":",
"os",
".",
"makedirs",
"(",
"_constants",
".",
"CACHE_PATH",
")",
"src_data",
"=",
"np",
".... | Cache the processed npy dataset the dataset into a npz
Parameters
----------
dataset : SimpleDataset
file_path : str | [
"Cache",
"the",
"processed",
"npy",
"dataset",
"the",
"dataset",
"into",
"a",
"npz"
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/machine_translation/dataprocessor.py#L33-L49 |
32,595 | dmlc/gluon-nlp | src/gluonnlp/model/train/embedding.py | FasttextEmbeddingModel.load_fasttext_format | def load_fasttext_format(cls, path, ctx=cpu(), **kwargs):
"""Create an instance of the class and load weights.
Load the weights from the fastText binary format created by
https://github.com/facebookresearch/fastText
Parameters
----------
path : str
Path to t... | python | def load_fasttext_format(cls, path, ctx=cpu(), **kwargs):
"""Create an instance of the class and load weights.
Load the weights from the fastText binary format created by
https://github.com/facebookresearch/fastText
Parameters
----------
path : str
Path to t... | [
"def",
"load_fasttext_format",
"(",
"cls",
",",
"path",
",",
"ctx",
"=",
"cpu",
"(",
")",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"open",
"(",
"path",
",",
"'rb'",
")",
"as",
"f",
":",
"new_format",
",",
"dim",
",",
"bucket",
",",
"minn",
",",... | Create an instance of the class and load weights.
Load the weights from the fastText binary format created by
https://github.com/facebookresearch/fastText
Parameters
----------
path : str
Path to the .bin model file.
ctx : mx.Context, default mx.cpu()
... | [
"Create",
"an",
"instance",
"of",
"the",
"class",
"and",
"load",
"weights",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/train/embedding.py#L232-L280 |
32,596 | dmlc/gluon-nlp | scripts/natural_language_inference/utils.py | logging_config | def logging_config(logpath=None,
level=logging.DEBUG,
console_level=logging.INFO,
no_console=False):
"""
Config the logging.
"""
logger = logging.getLogger('nli')
# Remove all the current handlers
for handler in logger.handlers:
lo... | python | def logging_config(logpath=None,
level=logging.DEBUG,
console_level=logging.INFO,
no_console=False):
"""
Config the logging.
"""
logger = logging.getLogger('nli')
# Remove all the current handlers
for handler in logger.handlers:
lo... | [
"def",
"logging_config",
"(",
"logpath",
"=",
"None",
",",
"level",
"=",
"logging",
".",
"DEBUG",
",",
"console_level",
"=",
"logging",
".",
"INFO",
",",
"no_console",
"=",
"False",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"'nli'",
")",... | Config the logging. | [
"Config",
"the",
"logging",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/natural_language_inference/utils.py#L27-L56 |
32,597 | dmlc/gluon-nlp | scripts/word_embeddings/train_glove.py | get_train_data | def get_train_data(args):
"""Helper function to get training data."""
counter = dict()
with io.open(args.vocab, 'r', encoding='utf-8') as f:
for line in f:
token, count = line.split('\t')
counter[token] = int(count)
vocab = nlp.Vocab(counter, unknown_token=None, padding_t... | python | def get_train_data(args):
"""Helper function to get training data."""
counter = dict()
with io.open(args.vocab, 'r', encoding='utf-8') as f:
for line in f:
token, count = line.split('\t')
counter[token] = int(count)
vocab = nlp.Vocab(counter, unknown_token=None, padding_t... | [
"def",
"get_train_data",
"(",
"args",
")",
":",
"counter",
"=",
"dict",
"(",
")",
"with",
"io",
".",
"open",
"(",
"args",
".",
"vocab",
",",
"'r'",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
":",
"token",
",",... | Helper function to get training data. | [
"Helper",
"function",
"to",
"get",
"training",
"data",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/train_glove.py#L130-L161 |
32,598 | dmlc/gluon-nlp | scripts/word_embeddings/train_glove.py | log | def log(args, kwargs):
"""Log to a file."""
logfile = os.path.join(args.logdir, 'log.tsv')
if 'log_created' not in globals():
if os.path.exists(logfile):
logging.error('Logfile %s already exists.', logfile)
sys.exit(1)
global log_created
log_created = sorte... | python | def log(args, kwargs):
"""Log to a file."""
logfile = os.path.join(args.logdir, 'log.tsv')
if 'log_created' not in globals():
if os.path.exists(logfile):
logging.error('Logfile %s already exists.', logfile)
sys.exit(1)
global log_created
log_created = sorte... | [
"def",
"log",
"(",
"args",
",",
"kwargs",
")",
":",
"logfile",
"=",
"os",
".",
"path",
".",
"join",
"(",
"args",
".",
"logdir",
",",
"'log.tsv'",
")",
"if",
"'log_created'",
"not",
"in",
"globals",
"(",
")",
":",
"if",
"os",
".",
"path",
".",
"ex... | Log to a file. | [
"Log",
"to",
"a",
"file",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/train_glove.py#L396-L416 |
32,599 | dmlc/gluon-nlp | src/gluonnlp/metric/masked_accuracy.py | MaskedAccuracy.update | def update(self, labels, preds, masks=None):
# pylint: disable=arguments-differ
"""Updates the internal evaluation result.
Parameters
----------
labels : list of `NDArray`
The labels of the data with class indices as values, one per sample.
preds : list of `N... | python | def update(self, labels, preds, masks=None):
# pylint: disable=arguments-differ
"""Updates the internal evaluation result.
Parameters
----------
labels : list of `NDArray`
The labels of the data with class indices as values, one per sample.
preds : list of `N... | [
"def",
"update",
"(",
"self",
",",
"labels",
",",
"preds",
",",
"masks",
"=",
"None",
")",
":",
"# pylint: disable=arguments-differ",
"labels",
",",
"preds",
"=",
"check_label_shapes",
"(",
"labels",
",",
"preds",
",",
"True",
")",
"masks",
"=",
"[",
"None... | Updates the internal evaluation result.
Parameters
----------
labels : list of `NDArray`
The labels of the data with class indices as values, one per sample.
preds : list of `NDArray`
Prediction values for samples. Each prediction value can either be the class in... | [
"Updates",
"the",
"internal",
"evaluation",
"result",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/metric/masked_accuracy.py#L232-L275 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.