partition stringclasses 3
values | func_name stringlengths 1 134 | docstring stringlengths 1 46.9k | path stringlengths 4 223 | original_string stringlengths 75 104k | code stringlengths 75 104k | docstring_tokens listlengths 1 1.97k | repo stringlengths 7 55 | language stringclasses 1
value | url stringlengths 87 315 | code_tokens listlengths 19 28.4k | sha stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|
train | ApiClient.__deserialize_primitive | Deserializes string to primitive type.
:param data: str.
:param klass: class literal.
:return: int, long, float, str, bool. | kaggle/api_client.py | def __deserialize_primitive(self, data, klass):
"""Deserializes string to primitive type.
:param data: str.
:param klass: class literal.
:return: int, long, float, str, bool.
"""
try:
return klass(data)
except UnicodeEncodeError:
return s... | def __deserialize_primitive(self, data, klass):
"""Deserializes string to primitive type.
:param data: str.
:param klass: class literal.
:return: int, long, float, str, bool.
"""
try:
return klass(data)
except UnicodeEncodeError:
return s... | [
"Deserializes",
"string",
"to",
"primitive",
"type",
"."
] | Kaggle/kaggle-api | python | https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api_client.py#L545-L558 | [
"def",
"__deserialize_primitive",
"(",
"self",
",",
"data",
",",
"klass",
")",
":",
"try",
":",
"return",
"klass",
"(",
"data",
")",
"except",
"UnicodeEncodeError",
":",
"return",
"six",
".",
"text_type",
"(",
"data",
")",
"except",
"TypeError",
":",
"retu... | 65f14b1386470c5784d4753e491478e7537660d9 |
train | Configuration.logger_file | The logger file.
If the logger_file is None, then add stream handler and remove file
handler. Otherwise, add file handler and remove stream handler.
:param value: The logger_file path.
:type: str | kaggle/configuration.py | def logger_file(self, value):
"""The logger file.
If the logger_file is None, then add stream handler and remove file
handler. Otherwise, add file handler and remove stream handler.
:param value: The logger_file path.
:type: str
"""
self.__logger_file = value
... | def logger_file(self, value):
"""The logger file.
If the logger_file is None, then add stream handler and remove file
handler. Otherwise, add file handler and remove stream handler.
:param value: The logger_file path.
:type: str
"""
self.__logger_file = value
... | [
"The",
"logger",
"file",
"."
] | Kaggle/kaggle-api | python | https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/configuration.py#L133-L160 | [
"def",
"logger_file",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"__logger_file",
"=",
"value",
"if",
"self",
".",
"__logger_file",
":",
"# If set logging file,",
"# then add file handler and remove stream handler.",
"self",
".",
"logger_file_handler",
"=",
"lo... | 65f14b1386470c5784d4753e491478e7537660d9 |
train | DatasetNewRequest.license_name | Sets the license_name of this DatasetNewRequest.
The license that should be associated with the dataset # noqa: E501
:param license_name: The license_name of this DatasetNewRequest. # noqa: E501
:type: str | kaggle/models/dataset_new_request.py | def license_name(self, license_name):
"""Sets the license_name of this DatasetNewRequest.
The license that should be associated with the dataset # noqa: E501
:param license_name: The license_name of this DatasetNewRequest. # noqa: E501
:type: str
"""
allowed_values = ... | def license_name(self, license_name):
"""Sets the license_name of this DatasetNewRequest.
The license that should be associated with the dataset # noqa: E501
:param license_name: The license_name of this DatasetNewRequest. # noqa: E501
:type: str
"""
allowed_values = ... | [
"Sets",
"the",
"license_name",
"of",
"this",
"DatasetNewRequest",
"."
] | Kaggle/kaggle-api | python | https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/models/dataset_new_request.py#L194-L209 | [
"def",
"license_name",
"(",
"self",
",",
"license_name",
")",
":",
"allowed_values",
"=",
"[",
"\"CC0-1.0\"",
",",
"\"CC-BY-SA-4.0\"",
",",
"\"GPL-2.0\"",
",",
"\"ODbL-1.0\"",
",",
"\"CC-BY-NC-SA-4.0\"",
",",
"\"unknown\"",
",",
"\"DbCL-1.0\"",
",",
"\"CC-BY-SA-3.0\... | 65f14b1386470c5784d4753e491478e7537660d9 |
train | train | Train textCNN model for sentiment analysis. | scripts/sentiment_analysis/sentiment_analysis_cnn.py | def train(net, train_data, test_data):
"""Train textCNN model for sentiment analysis."""
start_pipeline_time = time.time()
net, trainer = text_cnn.init(net, vocab, args.model_mode, context, args.lr)
random.shuffle(train_data)
sp = int(len(train_data)*0.9)
train_dataloader = DataLoader(dataset=tr... | def train(net, train_data, test_data):
"""Train textCNN model for sentiment analysis."""
start_pipeline_time = time.time()
net, trainer = text_cnn.init(net, vocab, args.model_mode, context, args.lr)
random.shuffle(train_data)
sp = int(len(train_data)*0.9)
train_dataloader = DataLoader(dataset=tr... | [
"Train",
"textCNN",
"model",
"for",
"sentiment",
"analysis",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/sentiment_analysis/sentiment_analysis_cnn.py#L114-L184 | [
"def",
"train",
"(",
"net",
",",
"train_data",
",",
"test_data",
")",
":",
"start_pipeline_time",
"=",
"time",
".",
"time",
"(",
")",
"net",
",",
"trainer",
"=",
"text_cnn",
".",
"init",
"(",
"net",
",",
"vocab",
",",
"args",
".",
"model_mode",
",",
... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | BertEmbedding.embedding | Get tokens, tokens embedding
Parameters
----------
sentences : List[str]
sentences for encoding.
oov_way : str, default avg.
use **avg**, **sum** or **last** to get token embedding for those out of
vocabulary words
Returns
-------
... | scripts/bert/embedding.py | def embedding(self, sentences, oov_way='avg'):
"""
Get tokens, tokens embedding
Parameters
----------
sentences : List[str]
sentences for encoding.
oov_way : str, default avg.
use **avg**, **sum** or **last** to get token embedding for those out o... | def embedding(self, sentences, oov_way='avg'):
"""
Get tokens, tokens embedding
Parameters
----------
sentences : List[str]
sentences for encoding.
oov_way : str, default avg.
use **avg**, **sum** or **last** to get token embedding for those out o... | [
"Get",
"tokens",
"tokens",
"embedding"
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/embedding.py#L111-L139 | [
"def",
"embedding",
"(",
"self",
",",
"sentences",
",",
"oov_way",
"=",
"'avg'",
")",
":",
"data_iter",
"=",
"self",
".",
"data_loader",
"(",
"sentences",
"=",
"sentences",
")",
"batches",
"=",
"[",
"]",
"for",
"token_ids",
",",
"valid_length",
",",
"tok... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | BertEmbedding.data_loader | Load, tokenize and prepare the input sentences. | scripts/bert/embedding.py | def data_loader(self, sentences, shuffle=False):
"""Load, tokenize and prepare the input sentences."""
dataset = BertEmbeddingDataset(sentences, self.transform)
return DataLoader(dataset=dataset, batch_size=self.batch_size, shuffle=shuffle) | def data_loader(self, sentences, shuffle=False):
"""Load, tokenize and prepare the input sentences."""
dataset = BertEmbeddingDataset(sentences, self.transform)
return DataLoader(dataset=dataset, batch_size=self.batch_size, shuffle=shuffle) | [
"Load",
"tokenize",
"and",
"prepare",
"the",
"input",
"sentences",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/embedding.py#L141-L144 | [
"def",
"data_loader",
"(",
"self",
",",
"sentences",
",",
"shuffle",
"=",
"False",
")",
":",
"dataset",
"=",
"BertEmbeddingDataset",
"(",
"sentences",
",",
"self",
".",
"transform",
")",
"return",
"DataLoader",
"(",
"dataset",
"=",
"dataset",
",",
"batch_siz... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | BertEmbedding.oov | How to handle oov. Also filter out [CLS], [SEP] tokens.
Parameters
----------
batches : List[(tokens_id,
sequence_outputs,
pooled_output].
batch token_ids (max_seq_length, ),
sequence_outputs (max_seq_length, dim,... | scripts/bert/embedding.py | def oov(self, batches, oov_way='avg'):
"""
How to handle oov. Also filter out [CLS], [SEP] tokens.
Parameters
----------
batches : List[(tokens_id,
sequence_outputs,
pooled_output].
batch token_ids (max_seq_length, ),... | def oov(self, batches, oov_way='avg'):
"""
How to handle oov. Also filter out [CLS], [SEP] tokens.
Parameters
----------
batches : List[(tokens_id,
sequence_outputs,
pooled_output].
batch token_ids (max_seq_length, ),... | [
"How",
"to",
"handle",
"oov",
".",
"Also",
"filter",
"out",
"[",
"CLS",
"]",
"[",
"SEP",
"]",
"tokens",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/embedding.py#L146-L198 | [
"def",
"oov",
"(",
"self",
",",
"batches",
",",
"oov_way",
"=",
"'avg'",
")",
":",
"sentences",
"=",
"[",
"]",
"for",
"token_ids",
",",
"sequence_outputs",
"in",
"batches",
":",
"tokens",
"=",
"[",
"]",
"tensors",
"=",
"[",
"]",
"oov_len",
"=",
"1",
... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | get_bert_model | Any BERT pretrained model.
Parameters
----------
model_name : str or None, default None
Options include 'bert_24_1024_16' and 'bert_12_768_12'.
dataset_name : str or None, default None
Options include 'book_corpus_wiki_en_cased', 'book_corpus_wiki_en_uncased'
for both bert_24_10... | src/gluonnlp/model/bert.py | def get_bert_model(model_name=None, dataset_name=None, vocab=None,
pretrained=True, ctx=mx.cpu(),
use_pooler=True, use_decoder=True, use_classifier=True,
output_attention=False, output_all_encodings=False,
root=os.path.join(get_home_dir(), 'mod... | def get_bert_model(model_name=None, dataset_name=None, vocab=None,
pretrained=True, ctx=mx.cpu(),
use_pooler=True, use_decoder=True, use_classifier=True,
output_attention=False, output_all_encodings=False,
root=os.path.join(get_home_dir(), 'mod... | [
"Any",
"BERT",
"pretrained",
"model",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/bert.py#L630-L709 | [
"def",
"get_bert_model",
"(",
"model_name",
"=",
"None",
",",
"dataset_name",
"=",
"None",
",",
"vocab",
"=",
"None",
",",
"pretrained",
"=",
"True",
",",
"ctx",
"=",
"mx",
".",
"cpu",
"(",
")",
",",
"use_pooler",
"=",
"True",
",",
"use_decoder",
"=",
... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | BERTLayerNorm.hybrid_forward | forward computation. | src/gluonnlp/model/bert.py | def hybrid_forward(self, F, data, gamma, beta):
"""forward computation."""
# TODO(haibin): LayerNorm does not support fp16 safe reduction. Issue is tracked at:
# https://github.com/apache/incubator-mxnet/issues/14073
if self._dtype:
data = data.astype('float32')
g... | def hybrid_forward(self, F, data, gamma, beta):
"""forward computation."""
# TODO(haibin): LayerNorm does not support fp16 safe reduction. Issue is tracked at:
# https://github.com/apache/incubator-mxnet/issues/14073
if self._dtype:
data = data.astype('float32')
g... | [
"forward",
"computation",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/bert.py#L59-L70 | [
"def",
"hybrid_forward",
"(",
"self",
",",
"F",
",",
"data",
",",
"gamma",
",",
"beta",
")",
":",
"# TODO(haibin): LayerNorm does not support fp16 safe reduction. Issue is tracked at:",
"# https://github.com/apache/incubator-mxnet/issues/14073",
"if",
"self",
".",
"_dtype",
"... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | BERTModel._get_classifier | Construct a decoder for the next sentence prediction task | src/gluonnlp/model/bert.py | def _get_classifier(self, prefix):
""" Construct a decoder for the next sentence prediction task """
with self.name_scope():
classifier = nn.Dense(2, prefix=prefix)
return classifier | def _get_classifier(self, prefix):
""" Construct a decoder for the next sentence prediction task """
with self.name_scope():
classifier = nn.Dense(2, prefix=prefix)
return classifier | [
"Construct",
"a",
"decoder",
"for",
"the",
"next",
"sentence",
"prediction",
"task"
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/bert.py#L364-L368 | [
"def",
"_get_classifier",
"(",
"self",
",",
"prefix",
")",
":",
"with",
"self",
".",
"name_scope",
"(",
")",
":",
"classifier",
"=",
"nn",
".",
"Dense",
"(",
"2",
",",
"prefix",
"=",
"prefix",
")",
"return",
"classifier"
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | BERTModel._get_decoder | Construct a decoder for the masked language model task | src/gluonnlp/model/bert.py | def _get_decoder(self, units, vocab_size, embed, prefix):
""" Construct a decoder for the masked language model task """
with self.name_scope():
decoder = nn.HybridSequential(prefix=prefix)
decoder.add(nn.Dense(units, flatten=False))
decoder.add(GELU())
de... | def _get_decoder(self, units, vocab_size, embed, prefix):
""" Construct a decoder for the masked language model task """
with self.name_scope():
decoder = nn.HybridSequential(prefix=prefix)
decoder.add(nn.Dense(units, flatten=False))
decoder.add(GELU())
de... | [
"Construct",
"a",
"decoder",
"for",
"the",
"masked",
"language",
"model",
"task"
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/bert.py#L370-L380 | [
"def",
"_get_decoder",
"(",
"self",
",",
"units",
",",
"vocab_size",
",",
"embed",
",",
"prefix",
")",
":",
"with",
"self",
".",
"name_scope",
"(",
")",
":",
"decoder",
"=",
"nn",
".",
"HybridSequential",
"(",
"prefix",
"=",
"prefix",
")",
"decoder",
"... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | BERTModel._get_embed | Construct an embedding block. | src/gluonnlp/model/bert.py | def _get_embed(self, embed, vocab_size, embed_size, initializer, dropout, prefix):
""" Construct an embedding block. """
if embed is None:
assert embed_size is not None, '"embed_size" cannot be None if "word_embed" or ' \
'token_type_embed is not gi... | def _get_embed(self, embed, vocab_size, embed_size, initializer, dropout, prefix):
""" Construct an embedding block. """
if embed is None:
assert embed_size is not None, '"embed_size" cannot be None if "word_embed" or ' \
'token_type_embed is not gi... | [
"Construct",
"an",
"embedding",
"block",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/bert.py#L382-L395 | [
"def",
"_get_embed",
"(",
"self",
",",
"embed",
",",
"vocab_size",
",",
"embed_size",
",",
"initializer",
",",
"dropout",
",",
"prefix",
")",
":",
"if",
"embed",
"is",
"None",
":",
"assert",
"embed_size",
"is",
"not",
"None",
",",
"'\"embed_size\" cannot be ... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | BERTModel._get_pooler | Construct pooler.
The pooler slices and projects the hidden output of first token
in the sequence for segment level classification. | src/gluonnlp/model/bert.py | def _get_pooler(self, units, prefix):
""" Construct pooler.
The pooler slices and projects the hidden output of first token
in the sequence for segment level classification.
"""
with self.name_scope():
pooler = nn.Dense(units=units, flatten=False, activation='tanh',... | def _get_pooler(self, units, prefix):
""" Construct pooler.
The pooler slices and projects the hidden output of first token
in the sequence for segment level classification.
"""
with self.name_scope():
pooler = nn.Dense(units=units, flatten=False, activation='tanh',... | [
"Construct",
"pooler",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/bert.py#L397-L407 | [
"def",
"_get_pooler",
"(",
"self",
",",
"units",
",",
"prefix",
")",
":",
"with",
"self",
".",
"name_scope",
"(",
")",
":",
"pooler",
"=",
"nn",
".",
"Dense",
"(",
"units",
"=",
"units",
",",
"flatten",
"=",
"False",
",",
"activation",
"=",
"'tanh'",... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | BERTModel._encode_sequence | Generate the representation given the input sequences.
This is used for pre-training or fine-tuning a BERT model. | src/gluonnlp/model/bert.py | def _encode_sequence(self, inputs, token_types, valid_length=None):
"""Generate the representation given the input sequences.
This is used for pre-training or fine-tuning a BERT model.
"""
# embedding
word_embedding = self.word_embed(inputs)
type_embedding = self.token_t... | def _encode_sequence(self, inputs, token_types, valid_length=None):
"""Generate the representation given the input sequences.
This is used for pre-training or fine-tuning a BERT model.
"""
# embedding
word_embedding = self.word_embed(inputs)
type_embedding = self.token_t... | [
"Generate",
"the",
"representation",
"given",
"the",
"input",
"sequences",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/bert.py#L440-L451 | [
"def",
"_encode_sequence",
"(",
"self",
",",
"inputs",
",",
"token_types",
",",
"valid_length",
"=",
"None",
")",
":",
"# embedding",
"word_embedding",
"=",
"self",
".",
"word_embed",
"(",
"inputs",
")",
"type_embedding",
"=",
"self",
".",
"token_type_embed",
... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | BERTModel._decode | Generate unnormalized prediction for the masked language model task.
This is only used for pre-training the BERT model.
Inputs:
- **sequence**: input tensor of sequence encodings.
Shape (batch_size, seq_length, units).
- **masked_positions**: input tensor of posit... | src/gluonnlp/model/bert.py | def _decode(self, sequence, masked_positions):
"""Generate unnormalized prediction for the masked language model task.
This is only used for pre-training the BERT model.
Inputs:
- **sequence**: input tensor of sequence encodings.
Shape (batch_size, seq_length, units).... | def _decode(self, sequence, masked_positions):
"""Generate unnormalized prediction for the masked language model task.
This is only used for pre-training the BERT model.
Inputs:
- **sequence**: input tensor of sequence encodings.
Shape (batch_size, seq_length, units).... | [
"Generate",
"unnormalized",
"prediction",
"for",
"the",
"masked",
"language",
"model",
"task",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/bert.py#L461-L490 | [
"def",
"_decode",
"(",
"self",
",",
"sequence",
",",
"masked_positions",
")",
":",
"batch_size",
"=",
"sequence",
".",
"shape",
"[",
"0",
"]",
"num_masked_positions",
"=",
"masked_positions",
".",
"shape",
"[",
"1",
"]",
"ctx",
"=",
"masked_positions",
".",
... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | _ngrams | Extracts n-grams from an input segment.
Parameters
----------
segment: list
Text segment from which n-grams will be extracted.
n: int
Order of n-gram.
Returns
-------
ngram_counts: Counter
Contain all the nth n-grams in segment with a count of how many times each n-... | scripts/machine_translation/bleu.py | def _ngrams(segment, n):
"""Extracts n-grams from an input segment.
Parameters
----------
segment: list
Text segment from which n-grams will be extracted.
n: int
Order of n-gram.
Returns
-------
ngram_counts: Counter
Contain all the nth n-grams in segment with a... | def _ngrams(segment, n):
"""Extracts n-grams from an input segment.
Parameters
----------
segment: list
Text segment from which n-grams will be extracted.
n: int
Order of n-gram.
Returns
-------
ngram_counts: Counter
Contain all the nth n-grams in segment with a... | [
"Extracts",
"n",
"-",
"grams",
"from",
"an",
"input",
"segment",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/machine_translation/bleu.py#L32-L51 | [
"def",
"_ngrams",
"(",
"segment",
",",
"n",
")",
":",
"ngram_counts",
"=",
"Counter",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"segment",
")",
"-",
"n",
"+",
"1",
")",
":",
"ngram",
"=",
"tuple",
"(",
"segment",
"[",
"i",... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | _bpe_to_words | Convert a sequence of bpe words into sentence. | scripts/machine_translation/bleu.py | def _bpe_to_words(sentence, delimiter='@@'):
"""Convert a sequence of bpe words into sentence."""
words = []
word = ''
delimiter_len = len(delimiter)
for subwords in sentence:
if len(subwords) >= delimiter_len and subwords[-delimiter_len:] == delimiter:
word += subwords[:-delimit... | def _bpe_to_words(sentence, delimiter='@@'):
"""Convert a sequence of bpe words into sentence."""
words = []
word = ''
delimiter_len = len(delimiter)
for subwords in sentence:
if len(subwords) >= delimiter_len and subwords[-delimiter_len:] == delimiter:
word += subwords[:-delimit... | [
"Convert",
"a",
"sequence",
"of",
"bpe",
"words",
"into",
"sentence",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/machine_translation/bleu.py#L61-L73 | [
"def",
"_bpe_to_words",
"(",
"sentence",
",",
"delimiter",
"=",
"'@@'",
")",
":",
"words",
"=",
"[",
"]",
"word",
"=",
"''",
"delimiter_len",
"=",
"len",
"(",
"delimiter",
")",
"for",
"subwords",
"in",
"sentence",
":",
"if",
"len",
"(",
"subwords",
")"... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | _tokenize_mteval_13a | r"""
Tokenizes a string following the tokenizer in mteval-v13a.pl.
See https://github.com/moses-smt/mosesdecoder/"
"blob/master/scripts/generic/mteval-v14.pl#L917-L942
Parameters
----------
segment: str
A string to be tokenized
Returns
-------
The tokenized string | scripts/machine_translation/bleu.py | def _tokenize_mteval_13a(segment):
r"""
Tokenizes a string following the tokenizer in mteval-v13a.pl.
See https://github.com/moses-smt/mosesdecoder/"
"blob/master/scripts/generic/mteval-v14.pl#L917-L942
Parameters
----------
segment: str
A string to be tokenized
Returns
... | def _tokenize_mteval_13a(segment):
r"""
Tokenizes a string following the tokenizer in mteval-v13a.pl.
See https://github.com/moses-smt/mosesdecoder/"
"blob/master/scripts/generic/mteval-v14.pl#L917-L942
Parameters
----------
segment: str
A string to be tokenized
Returns
... | [
"r",
"Tokenizes",
"a",
"string",
"following",
"the",
"tokenizer",
"in",
"mteval",
"-",
"v13a",
".",
"pl",
".",
"See",
"https",
":",
"//",
"github",
".",
"com",
"/",
"moses",
"-",
"smt",
"/",
"mosesdecoder",
"/",
"blob",
"/",
"master",
"/",
"scripts",
... | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/machine_translation/bleu.py#L76-L110 | [
"def",
"_tokenize_mteval_13a",
"(",
"segment",
")",
":",
"norm",
"=",
"segment",
".",
"rstrip",
"(",
")",
"norm",
"=",
"norm",
".",
"replace",
"(",
"'<skipped>'",
",",
"''",
")",
"norm",
"=",
"norm",
".",
"replace",
"(",
"'-\\n'",
",",
"''",
")",
"no... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | _tokenize_mteval_v14_intl | r"""Tokenize a string following following the international tokenizer in mteval-v14a.pl.
See https://github.com/moses-smt/mosesdecoder/"
"blob/master/scripts/generic/mteval-v14.pl#L954-L983
Parameters
----------
segment: str
A string to be tokenized
Returns
-------
The t... | scripts/machine_translation/bleu.py | def _tokenize_mteval_v14_intl(segment):
r"""Tokenize a string following following the international tokenizer in mteval-v14a.pl.
See https://github.com/moses-smt/mosesdecoder/"
"blob/master/scripts/generic/mteval-v14.pl#L954-L983
Parameters
----------
segment: str
A string to be ... | def _tokenize_mteval_v14_intl(segment):
r"""Tokenize a string following following the international tokenizer in mteval-v14a.pl.
See https://github.com/moses-smt/mosesdecoder/"
"blob/master/scripts/generic/mteval-v14.pl#L954-L983
Parameters
----------
segment: str
A string to be ... | [
"r",
"Tokenize",
"a",
"string",
"following",
"following",
"the",
"international",
"tokenizer",
"in",
"mteval",
"-",
"v14a",
".",
"pl",
".",
"See",
"https",
":",
"//",
"github",
".",
"com",
"/",
"moses",
"-",
"smt",
"/",
"mosesdecoder",
"/",
"blob",
"/",
... | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/machine_translation/bleu.py#L130-L148 | [
"def",
"_tokenize_mteval_v14_intl",
"(",
"segment",
")",
":",
"segment",
"=",
"segment",
".",
"rstrip",
"(",
")",
"segment",
"=",
"unicodeRegex",
".",
"nondigit_punct_re",
".",
"sub",
"(",
"r'\\1 \\2 '",
",",
"segment",
")",
"segment",
"=",
"unicodeRegex",
"."... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | compute_bleu | r"""Compute bleu score of translation against references.
Parameters
----------
reference_corpus_list: list of list(list(str)) or list of list(str)
list of list(list(str)): tokenized references
list of list(str): plain text
List of references for each translation.
translation_co... | scripts/machine_translation/bleu.py | def compute_bleu(reference_corpus_list, translation_corpus, tokenized=True,
tokenizer='13a', max_n=4, smooth=False, lower_case=False,
bpe=False, split_compound_word=False):
r"""Compute bleu score of translation against references.
Parameters
----------
reference_corpus... | def compute_bleu(reference_corpus_list, translation_corpus, tokenized=True,
tokenizer='13a', max_n=4, smooth=False, lower_case=False,
bpe=False, split_compound_word=False):
r"""Compute bleu score of translation against references.
Parameters
----------
reference_corpus... | [
"r",
"Compute",
"bleu",
"score",
"of",
"translation",
"against",
"references",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/machine_translation/bleu.py#L158-L249 | [
"def",
"compute_bleu",
"(",
"reference_corpus_list",
",",
"translation_corpus",
",",
"tokenized",
"=",
"True",
",",
"tokenizer",
"=",
"'13a'",
",",
"max_n",
"=",
"4",
",",
"smooth",
"=",
"False",
",",
"lower_case",
"=",
"False",
",",
"bpe",
"=",
"False",
"... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | _compute_precision | Compute ngram precision.
Parameters
----------
references: list(list(str))
A list of references.
translation: list(str)
A translation.
n: int
Order of n-gram.
Returns
-------
matches: int
Number of matched nth order n-grams
candidates
Number ... | scripts/machine_translation/bleu.py | def _compute_precision(references, translation, n):
"""Compute ngram precision.
Parameters
----------
references: list(list(str))
A list of references.
translation: list(str)
A translation.
n: int
Order of n-gram.
Returns
-------
matches: int
Number ... | def _compute_precision(references, translation, n):
"""Compute ngram precision.
Parameters
----------
references: list(list(str))
A list of references.
translation: list(str)
A translation.
n: int
Order of n-gram.
Returns
-------
matches: int
Number ... | [
"Compute",
"ngram",
"precision",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/machine_translation/bleu.py#L252-L284 | [
"def",
"_compute_precision",
"(",
"references",
",",
"translation",
",",
"n",
")",
":",
"matches",
"=",
"0",
"candidates",
"=",
"0",
"ref_ngram_counts",
"=",
"Counter",
"(",
")",
"for",
"reference",
"in",
"references",
":",
"ref_ngram_counts",
"|=",
"_ngrams",... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | _brevity_penalty | Calculate brevity penalty.
Parameters
----------
ref_length: int
Sum of all closest references'lengths for every translations in a corpus
trans_length: int
Sum of all translations's lengths in a corpus.
Returns
-------
bleu's brevity penalty: float | scripts/machine_translation/bleu.py | def _brevity_penalty(ref_length, trans_length):
"""Calculate brevity penalty.
Parameters
----------
ref_length: int
Sum of all closest references'lengths for every translations in a corpus
trans_length: int
Sum of all translations's lengths in a corpus.
Returns
-------
... | def _brevity_penalty(ref_length, trans_length):
"""Calculate brevity penalty.
Parameters
----------
ref_length: int
Sum of all closest references'lengths for every translations in a corpus
trans_length: int
Sum of all translations's lengths in a corpus.
Returns
-------
... | [
"Calculate",
"brevity",
"penalty",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/machine_translation/bleu.py#L287-L307 | [
"def",
"_brevity_penalty",
"(",
"ref_length",
",",
"trans_length",
")",
":",
"if",
"trans_length",
">",
"ref_length",
":",
"return",
"1",
"# If translation is empty, brevity penalty = 0 should result in BLEU = 0.0",
"elif",
"trans_length",
"==",
"0",
":",
"return",
"0",
... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | _closest_ref_length | Find the reference that has the closest length to the translation.
Parameters
----------
references: list(list(str))
A list of references.
trans_length: int
Length of the translation.
Returns
-------
closest_ref_len: int
Length of the reference that is closest to th... | scripts/machine_translation/bleu.py | def _closest_ref_length(references, trans_length):
"""Find the reference that has the closest length to the translation.
Parameters
----------
references: list(list(str))
A list of references.
trans_length: int
Length of the translation.
Returns
-------
closest_ref_len:... | def _closest_ref_length(references, trans_length):
"""Find the reference that has the closest length to the translation.
Parameters
----------
references: list(list(str))
A list of references.
trans_length: int
Length of the translation.
Returns
-------
closest_ref_len:... | [
"Find",
"the",
"reference",
"that",
"has",
"the",
"closest",
"length",
"to",
"the",
"translation",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/machine_translation/bleu.py#L310-L329 | [
"def",
"_closest_ref_length",
"(",
"references",
",",
"trans_length",
")",
":",
"ref_lengths",
"=",
"(",
"len",
"(",
"reference",
")",
"for",
"reference",
"in",
"references",
")",
"closest_ref_len",
"=",
"min",
"(",
"ref_lengths",
",",
"key",
"=",
"lambda",
... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | _smoothing | Compute the smoothed precision for all the orders.
Parameters
----------
precision_fractions: list(tuple)
Contain a list of (precision_numerator, precision_denominator) pairs
c: int, default 1
Smoothing constant to use
Returns
-------
ratios: list of floats
Contain ... | scripts/machine_translation/bleu.py | def _smoothing(precision_fractions, c=1):
"""Compute the smoothed precision for all the orders.
Parameters
----------
precision_fractions: list(tuple)
Contain a list of (precision_numerator, precision_denominator) pairs
c: int, default 1
Smoothing constant to use
Returns
--... | def _smoothing(precision_fractions, c=1):
"""Compute the smoothed precision for all the orders.
Parameters
----------
precision_fractions: list(tuple)
Contain a list of (precision_numerator, precision_denominator) pairs
c: int, default 1
Smoothing constant to use
Returns
--... | [
"Compute",
"the",
"smoothed",
"precision",
"for",
"all",
"the",
"orders",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/machine_translation/bleu.py#L332-L354 | [
"def",
"_smoothing",
"(",
"precision_fractions",
",",
"c",
"=",
"1",
")",
":",
"ratios",
"=",
"[",
"0",
"]",
"*",
"len",
"(",
"precision_fractions",
")",
"for",
"i",
",",
"precision_fraction",
"in",
"enumerate",
"(",
"precision_fractions",
")",
":",
"if",
... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | LogUniformSampler.forward | Draw samples from log uniform distribution and returns sampled candidates,
expected count for true classes and sampled classes.
Parameters
----------
true_classes: NDArray
The true classes.
Returns
-------
samples: NDArray
The sampled can... | scripts/language_model/sampler.py | def forward(self, true_classes):
"""Draw samples from log uniform distribution and returns sampled candidates,
expected count for true classes and sampled classes.
Parameters
----------
true_classes: NDArray
The true classes.
Returns
-------
... | def forward(self, true_classes):
"""Draw samples from log uniform distribution and returns sampled candidates,
expected count for true classes and sampled classes.
Parameters
----------
true_classes: NDArray
The true classes.
Returns
-------
... | [
"Draw",
"samples",
"from",
"log",
"uniform",
"distribution",
"and",
"returns",
"sampled",
"candidates",
"expected",
"count",
"for",
"true",
"classes",
"and",
"sampled",
"classes",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/language_model/sampler.py#L66-L109 | [
"def",
"forward",
"(",
"self",
",",
"true_classes",
")",
":",
"num_sampled",
"=",
"self",
".",
"_num_sampled",
"ctx",
"=",
"true_classes",
".",
"context",
"num_tries",
"=",
"0",
"log_range",
"=",
"math",
".",
"log",
"(",
"self",
".",
"_range_max",
"+",
"... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | preprocess_dataset | Dataset preprocessing helper.
Parameters
----------
data : mx.data.Dataset
Input Dataset. For example gluonnlp.data.Text8 or gluonnlp.data.Fil9
min_freq : int, default 5
Minimum token frequency for a token to be included in the vocabulary
and returned DataStream.
max_vocab_s... | scripts/word_embeddings/data.py | def preprocess_dataset(data, min_freq=5, max_vocab_size=None):
"""Dataset preprocessing helper.
Parameters
----------
data : mx.data.Dataset
Input Dataset. For example gluonnlp.data.Text8 or gluonnlp.data.Fil9
min_freq : int, default 5
Minimum token frequency for a token to be inclu... | def preprocess_dataset(data, min_freq=5, max_vocab_size=None):
"""Dataset preprocessing helper.
Parameters
----------
data : mx.data.Dataset
Input Dataset. For example gluonnlp.data.Text8 or gluonnlp.data.Fil9
min_freq : int, default 5
Minimum token frequency for a token to be inclu... | [
"Dataset",
"preprocessing",
"helper",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/data.py#L47-L86 | [
"def",
"preprocess_dataset",
"(",
"data",
",",
"min_freq",
"=",
"5",
",",
"max_vocab_size",
"=",
"None",
")",
":",
"with",
"print_time",
"(",
"'count and construct vocabulary'",
")",
":",
"counter",
"=",
"nlp",
".",
"data",
".",
"count_tokens",
"(",
"itertools... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | wiki | Wikipedia dump helper.
Parameters
----------
wiki_root : str
Parameter for WikiDumpStream
wiki_date : str
Parameter for WikiDumpStream
wiki_language : str
Parameter for WikiDumpStream
max_vocab_size : int, optional
Specifies a maximum size for the vocabulary.
... | scripts/word_embeddings/data.py | def wiki(wiki_root, wiki_date, wiki_language, max_vocab_size=None):
"""Wikipedia dump helper.
Parameters
----------
wiki_root : str
Parameter for WikiDumpStream
wiki_date : str
Parameter for WikiDumpStream
wiki_language : str
Parameter for WikiDumpStream
max_vocab_si... | def wiki(wiki_root, wiki_date, wiki_language, max_vocab_size=None):
"""Wikipedia dump helper.
Parameters
----------
wiki_root : str
Parameter for WikiDumpStream
wiki_date : str
Parameter for WikiDumpStream
wiki_language : str
Parameter for WikiDumpStream
max_vocab_si... | [
"Wikipedia",
"dump",
"helper",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/data.py#L89-L131 | [
"def",
"wiki",
"(",
"wiki_root",
",",
"wiki_date",
",",
"wiki_language",
",",
"max_vocab_size",
"=",
"None",
")",
":",
"data",
"=",
"WikiDumpStream",
"(",
"root",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"wiki_root",
")",
",",
"language",
"=",
"wi... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | transform_data_fasttext | Transform a DataStream of coded DataSets to a DataStream of batches.
Parameters
----------
data : gluonnlp.data.DataStream
DataStream where each sample is a valid input to
gluonnlp.data.EmbeddingCenterContextBatchify.
vocab : gluonnlp.Vocab
Vocabulary containing all tokens whose... | scripts/word_embeddings/data.py | def transform_data_fasttext(data, vocab, idx_to_counts, cbow, ngram_buckets,
ngrams, batch_size, window_size,
frequent_token_subsampling=1E-4, dtype='float32',
index_dtype='int64'):
"""Transform a DataStream of coded DataSets to a D... | def transform_data_fasttext(data, vocab, idx_to_counts, cbow, ngram_buckets,
ngrams, batch_size, window_size,
frequent_token_subsampling=1E-4, dtype='float32',
index_dtype='int64'):
"""Transform a DataStream of coded DataSets to a D... | [
"Transform",
"a",
"DataStream",
"of",
"coded",
"DataSets",
"to",
"a",
"DataStream",
"of",
"batches",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/data.py#L134-L252 | [
"def",
"transform_data_fasttext",
"(",
"data",
",",
"vocab",
",",
"idx_to_counts",
",",
"cbow",
",",
"ngram_buckets",
",",
"ngrams",
",",
"batch_size",
",",
"window_size",
",",
"frequent_token_subsampling",
"=",
"1E-4",
",",
"dtype",
"=",
"'float32'",
",",
"inde... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | transform_data_word2vec | Transform a DataStream of coded DataSets to a DataStream of batches.
Parameters
----------
data : gluonnlp.data.DataStream
DataStream where each sample is a valid input to
gluonnlp.data.EmbeddingCenterContextBatchify.
vocab : gluonnlp.Vocab
Vocabulary containing all tokens whose... | scripts/word_embeddings/data.py | def transform_data_word2vec(data, vocab, idx_to_counts, cbow, batch_size,
window_size, frequent_token_subsampling=1E-4,
dtype='float32', index_dtype='int64'):
"""Transform a DataStream of coded DataSets to a DataStream of batches.
Parameters
---------... | def transform_data_word2vec(data, vocab, idx_to_counts, cbow, batch_size,
window_size, frequent_token_subsampling=1E-4,
dtype='float32', index_dtype='int64'):
"""Transform a DataStream of coded DataSets to a DataStream of batches.
Parameters
---------... | [
"Transform",
"a",
"DataStream",
"of",
"coded",
"DataSets",
"to",
"a",
"DataStream",
"of",
"batches",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/data.py#L255-L319 | [
"def",
"transform_data_word2vec",
"(",
"data",
",",
"vocab",
",",
"idx_to_counts",
",",
"cbow",
",",
"batch_size",
",",
"window_size",
",",
"frequent_token_subsampling",
"=",
"1E-4",
",",
"dtype",
"=",
"'float32'",
",",
"index_dtype",
"=",
"'int64'",
")",
":",
... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | cbow_fasttext_batch | Create a batch for CBOW training objective with subwords. | scripts/word_embeddings/data.py | def cbow_fasttext_batch(centers, contexts, num_tokens, subword_lookup, dtype,
index_dtype):
"""Create a batch for CBOW training objective with subwords."""
_, contexts_row, contexts_col = contexts
data, row, col = subword_lookup(contexts_row, contexts_col)
centers = mx.nd.array(c... | def cbow_fasttext_batch(centers, contexts, num_tokens, subword_lookup, dtype,
index_dtype):
"""Create a batch for CBOW training objective with subwords."""
_, contexts_row, contexts_col = contexts
data, row, col = subword_lookup(contexts_row, contexts_col)
centers = mx.nd.array(c... | [
"Create",
"a",
"batch",
"for",
"CBOW",
"training",
"objective",
"with",
"subwords",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/data.py#L322-L331 | [
"def",
"cbow_fasttext_batch",
"(",
"centers",
",",
"contexts",
",",
"num_tokens",
",",
"subword_lookup",
",",
"dtype",
",",
"index_dtype",
")",
":",
"_",
",",
"contexts_row",
",",
"contexts_col",
"=",
"contexts",
"data",
",",
"row",
",",
"col",
"=",
"subword... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | skipgram_fasttext_batch | Create a batch for SG training objective with subwords. | scripts/word_embeddings/data.py | def skipgram_fasttext_batch(centers, contexts, num_tokens, subword_lookup,
dtype, index_dtype):
"""Create a batch for SG training objective with subwords."""
contexts = mx.nd.array(contexts[2], dtype=index_dtype)
data, row, col = subword_lookup(centers)
centers = mx.nd.array(... | def skipgram_fasttext_batch(centers, contexts, num_tokens, subword_lookup,
dtype, index_dtype):
"""Create a batch for SG training objective with subwords."""
contexts = mx.nd.array(contexts[2], dtype=index_dtype)
data, row, col = subword_lookup(centers)
centers = mx.nd.array(... | [
"Create",
"a",
"batch",
"for",
"SG",
"training",
"objective",
"with",
"subwords",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/data.py#L334-L343 | [
"def",
"skipgram_fasttext_batch",
"(",
"centers",
",",
"contexts",
",",
"num_tokens",
",",
"subword_lookup",
",",
"dtype",
",",
"index_dtype",
")",
":",
"contexts",
"=",
"mx",
".",
"nd",
".",
"array",
"(",
"contexts",
"[",
"2",
"]",
",",
"dtype",
"=",
"i... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | cbow_batch | Create a batch for CBOW training objective. | scripts/word_embeddings/data.py | def cbow_batch(centers, contexts, num_tokens, dtype, index_dtype):
"""Create a batch for CBOW training objective."""
contexts_data, contexts_row, contexts_col = contexts
centers = mx.nd.array(centers, dtype=index_dtype)
contexts = mx.nd.sparse.csr_matrix(
(contexts_data, (contexts_row, contexts_... | def cbow_batch(centers, contexts, num_tokens, dtype, index_dtype):
"""Create a batch for CBOW training objective."""
contexts_data, contexts_row, contexts_col = contexts
centers = mx.nd.array(centers, dtype=index_dtype)
contexts = mx.nd.sparse.csr_matrix(
(contexts_data, (contexts_row, contexts_... | [
"Create",
"a",
"batch",
"for",
"CBOW",
"training",
"objective",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/data.py#L346-L353 | [
"def",
"cbow_batch",
"(",
"centers",
",",
"contexts",
",",
"num_tokens",
",",
"dtype",
",",
"index_dtype",
")",
":",
"contexts_data",
",",
"contexts_row",
",",
"contexts_col",
"=",
"contexts",
"centers",
"=",
"mx",
".",
"nd",
".",
"array",
"(",
"centers",
... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | skipgram_batch | Create a batch for SG training objective. | scripts/word_embeddings/data.py | def skipgram_batch(centers, contexts, num_tokens, dtype, index_dtype):
"""Create a batch for SG training objective."""
contexts = mx.nd.array(contexts[2], dtype=index_dtype)
indptr = mx.nd.arange(len(centers) + 1)
centers = mx.nd.array(centers, dtype=index_dtype)
centers_csr = mx.nd.sparse.csr_matri... | def skipgram_batch(centers, contexts, num_tokens, dtype, index_dtype):
"""Create a batch for SG training objective."""
contexts = mx.nd.array(contexts[2], dtype=index_dtype)
indptr = mx.nd.arange(len(centers) + 1)
centers = mx.nd.array(centers, dtype=index_dtype)
centers_csr = mx.nd.sparse.csr_matri... | [
"Create",
"a",
"batch",
"for",
"SG",
"training",
"objective",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/data.py#L356-L364 | [
"def",
"skipgram_batch",
"(",
"centers",
",",
"contexts",
",",
"num_tokens",
",",
"dtype",
",",
"index_dtype",
")",
":",
"contexts",
"=",
"mx",
".",
"nd",
".",
"array",
"(",
"contexts",
"[",
"2",
"]",
",",
"dtype",
"=",
"index_dtype",
")",
"indptr",
"=... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | skipgram_lookup | Get a sparse COO array of words and subwords for SkipGram.
Parameters
----------
indices : numpy.ndarray
Array containing numbers in [0, vocabulary_size). The element at
position idx is taken to be the word that occurs at row idx in the
SkipGram batch.
offset : int
Offse... | scripts/word_embeddings/data.py | def skipgram_lookup(indices, subwordidxs, subwordidxsptr, offset=0):
"""Get a sparse COO array of words and subwords for SkipGram.
Parameters
----------
indices : numpy.ndarray
Array containing numbers in [0, vocabulary_size). The element at
position idx is taken to be the word that occ... | def skipgram_lookup(indices, subwordidxs, subwordidxsptr, offset=0):
"""Get a sparse COO array of words and subwords for SkipGram.
Parameters
----------
indices : numpy.ndarray
Array containing numbers in [0, vocabulary_size). The element at
position idx is taken to be the word that occ... | [
"Get",
"a",
"sparse",
"COO",
"array",
"of",
"words",
"and",
"subwords",
"for",
"SkipGram",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/data.py#L376-L427 | [
"def",
"skipgram_lookup",
"(",
"indices",
",",
"subwordidxs",
",",
"subwordidxsptr",
",",
"offset",
"=",
"0",
")",
":",
"row",
"=",
"[",
"]",
"col",
"=",
"[",
"]",
"data",
"=",
"[",
"]",
"for",
"i",
",",
"idx",
"in",
"enumerate",
"(",
"indices",
")... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | cbow_lookup | Get a sparse COO array of words and subwords for CBOW.
Parameters
----------
context_row : numpy.ndarray of dtype int64
Array of same length as context_col containing numbers in [0,
batch_size). For each idx, context_row[idx] specifies the row that
context_col[idx] occurs in a spars... | scripts/word_embeddings/data.py | def cbow_lookup(context_row, context_col, subwordidxs, subwordidxsptr,
offset=0):
"""Get a sparse COO array of words and subwords for CBOW.
Parameters
----------
context_row : numpy.ndarray of dtype int64
Array of same length as context_col containing numbers in [0,
batc... | def cbow_lookup(context_row, context_col, subwordidxs, subwordidxsptr,
offset=0):
"""Get a sparse COO array of words and subwords for CBOW.
Parameters
----------
context_row : numpy.ndarray of dtype int64
Array of same length as context_col containing numbers in [0,
batc... | [
"Get",
"a",
"sparse",
"COO",
"array",
"of",
"words",
"and",
"subwords",
"for",
"CBOW",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/data.py#L431-L501 | [
"def",
"cbow_lookup",
"(",
"context_row",
",",
"context_col",
",",
"subwordidxs",
",",
"subwordidxsptr",
",",
"offset",
"=",
"0",
")",
":",
"row",
"=",
"[",
"]",
"col",
"=",
"[",
"]",
"data",
"=",
"[",
"]",
"num_rows",
"=",
"np",
".",
"max",
"(",
"... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | _TranslationDataset.src_vocab | Source Vocabulary of the Dataset.
Returns
-------
src_vocab : Vocab
Source vocabulary. | src/gluonnlp/data/translation.py | def src_vocab(self):
"""Source Vocabulary of the Dataset.
Returns
-------
src_vocab : Vocab
Source vocabulary.
"""
if self._src_vocab is None:
src_vocab_file_name, src_vocab_hash = \
self._data_file[self._pair_key]['vocab' + '_' + ... | def src_vocab(self):
"""Source Vocabulary of the Dataset.
Returns
-------
src_vocab : Vocab
Source vocabulary.
"""
if self._src_vocab is None:
src_vocab_file_name, src_vocab_hash = \
self._data_file[self._pair_key]['vocab' + '_' + ... | [
"Source",
"Vocabulary",
"of",
"the",
"Dataset",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/translation.py#L119-L133 | [
"def",
"src_vocab",
"(",
"self",
")",
":",
"if",
"self",
".",
"_src_vocab",
"is",
"None",
":",
"src_vocab_file_name",
",",
"src_vocab_hash",
"=",
"self",
".",
"_data_file",
"[",
"self",
".",
"_pair_key",
"]",
"[",
"'vocab'",
"+",
"'_'",
"+",
"self",
".",... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | _TranslationDataset.tgt_vocab | Target Vocabulary of the Dataset.
Returns
-------
tgt_vocab : Vocab
Target vocabulary. | src/gluonnlp/data/translation.py | def tgt_vocab(self):
"""Target Vocabulary of the Dataset.
Returns
-------
tgt_vocab : Vocab
Target vocabulary.
"""
if self._tgt_vocab is None:
tgt_vocab_file_name, tgt_vocab_hash = \
self._data_file[self._pair_key]['vocab' + '_' + ... | def tgt_vocab(self):
"""Target Vocabulary of the Dataset.
Returns
-------
tgt_vocab : Vocab
Target vocabulary.
"""
if self._tgt_vocab is None:
tgt_vocab_file_name, tgt_vocab_hash = \
self._data_file[self._pair_key]['vocab' + '_' + ... | [
"Target",
"Vocabulary",
"of",
"the",
"Dataset",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/translation.py#L136-L150 | [
"def",
"tgt_vocab",
"(",
"self",
")",
":",
"if",
"self",
".",
"_tgt_vocab",
"is",
"None",
":",
"tgt_vocab_file_name",
",",
"tgt_vocab_hash",
"=",
"self",
".",
"_data_file",
"[",
"self",
".",
"_pair_key",
"]",
"[",
"'vocab'",
"+",
"'_'",
"+",
"self",
".",... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | evaluate | Evaluate given the data loader
Parameters
----------
data_loader : DataLoader
Returns
-------
avg_loss : float
Average loss
real_translation_out : list of list of str
The translation output | scripts/machine_translation/train_gnmt.py | def evaluate(data_loader):
"""Evaluate given the data loader
Parameters
----------
data_loader : DataLoader
Returns
-------
avg_loss : float
Average loss
real_translation_out : list of list of str
The translation output
"""
translation_out = []
all_inst_ids ... | def evaluate(data_loader):
"""Evaluate given the data loader
Parameters
----------
data_loader : DataLoader
Returns
-------
avg_loss : float
Average loss
real_translation_out : list of list of str
The translation output
"""
translation_out = []
all_inst_ids ... | [
"Evaluate",
"given",
"the",
"data",
"loader"
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/machine_translation/train_gnmt.py#L147-L190 | [
"def",
"evaluate",
"(",
"data_loader",
")",
":",
"translation_out",
"=",
"[",
"]",
"all_inst_ids",
"=",
"[",
"]",
"avg_loss_denom",
"=",
"0",
"avg_loss",
"=",
"0.0",
"for",
"_",
",",
"(",
"src_seq",
",",
"tgt_seq",
",",
"src_valid_length",
",",
"tgt_valid_... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | train | Training function. | scripts/machine_translation/train_gnmt.py | def train():
"""Training function."""
trainer = gluon.Trainer(model.collect_params(), args.optimizer, {'learning_rate': args.lr})
train_data_loader, val_data_loader, test_data_loader \
= dataprocessor.make_dataloader(data_train, data_val, data_test, args)
best_valid_bleu = 0.0
for epoch_id... | def train():
"""Training function."""
trainer = gluon.Trainer(model.collect_params(), args.optimizer, {'learning_rate': args.lr})
train_data_loader, val_data_loader, test_data_loader \
= dataprocessor.make_dataloader(data_train, data_val, data_test, args)
best_valid_bleu = 0.0
for epoch_id... | [
"Training",
"function",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/machine_translation/train_gnmt.py#L193-L276 | [
"def",
"train",
"(",
")",
":",
"trainer",
"=",
"gluon",
".",
"Trainer",
"(",
"model",
".",
"collect_params",
"(",
")",
",",
"args",
".",
"optimizer",
",",
"{",
"'learning_rate'",
":",
"args",
".",
"lr",
"}",
")",
"train_data_loader",
",",
"val_data_loade... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | get_cache_model | r"""Returns a cache model using a pre-trained language model.
We implement the neural cache language model proposed in the following work::
@article{grave2016improving,
title={Improving neural language models with a continuous cache},
author={Grave, Edouard and Joulin, Armand and Usunier, ... | src/gluonnlp/model/train/__init__.py | def get_cache_model(name, dataset_name='wikitext-2', window=2000,
theta=0.6, lambdas=0.2, ctx=mx.cpu(), **kwargs):
r"""Returns a cache model using a pre-trained language model.
We implement the neural cache language model proposed in the following work::
@article{grave2016improving... | def get_cache_model(name, dataset_name='wikitext-2', window=2000,
theta=0.6, lambdas=0.2, ctx=mx.cpu(), **kwargs):
r"""Returns a cache model using a pre-trained language model.
We implement the neural cache language model proposed in the following work::
@article{grave2016improving... | [
"r",
"Returns",
"a",
"cache",
"model",
"using",
"a",
"pre",
"-",
"trained",
"language",
"model",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/train/__init__.py#L36-L98 | [
"def",
"get_cache_model",
"(",
"name",
",",
"dataset_name",
"=",
"'wikitext-2'",
",",
"window",
"=",
"2000",
",",
"theta",
"=",
"0.6",
",",
"lambdas",
"=",
"0.2",
",",
"ctx",
"=",
"mx",
".",
"cpu",
"(",
")",
",",
"*",
"*",
"kwargs",
")",
":",
"lm_m... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | train | Training helper. | scripts/word_embeddings/train_sg_cbow.py | def train(args):
"""Training helper."""
if not args.model.lower() in ['cbow', 'skipgram']:
logging.error('Unsupported model %s.', args.model)
sys.exit(1)
if args.data.lower() == 'toy':
data = mx.gluon.data.SimpleDataset(nlp.data.Text8(segment='train')[:2])
data, vocab, idx_t... | def train(args):
"""Training helper."""
if not args.model.lower() in ['cbow', 'skipgram']:
logging.error('Unsupported model %s.', args.model)
sys.exit(1)
if args.data.lower() == 'toy':
data = mx.gluon.data.SimpleDataset(nlp.data.Text8(segment='train')[:2])
data, vocab, idx_t... | [
"Training",
"helper",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/train_sg_cbow.py#L138-L279 | [
"def",
"train",
"(",
"args",
")",
":",
"if",
"not",
"args",
".",
"model",
".",
"lower",
"(",
")",
"in",
"[",
"'cbow'",
",",
"'skipgram'",
"]",
":",
"logging",
".",
"error",
"(",
"'Unsupported model %s.'",
",",
"args",
".",
"model",
")",
"sys",
".",
... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | evaluate | Evaluation helper | scripts/word_embeddings/train_sg_cbow.py | def evaluate(args, embedding, vocab, global_step, eval_analogy=False):
"""Evaluation helper"""
if 'eval_tokens' not in globals():
global eval_tokens
eval_tokens_set = evaluation.get_tokens_in_evaluation_datasets(args)
if not args.no_eval_analogy:
eval_tokens_set.update(vocab... | def evaluate(args, embedding, vocab, global_step, eval_analogy=False):
"""Evaluation helper"""
if 'eval_tokens' not in globals():
global eval_tokens
eval_tokens_set = evaluation.get_tokens_in_evaluation_datasets(args)
if not args.no_eval_analogy:
eval_tokens_set.update(vocab... | [
"Evaluation",
"helper"
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/train_sg_cbow.py#L282-L317 | [
"def",
"evaluate",
"(",
"args",
",",
"embedding",
",",
"vocab",
",",
"global_step",
",",
"eval_analogy",
"=",
"False",
")",
":",
"if",
"'eval_tokens'",
"not",
"in",
"globals",
"(",
")",
":",
"global",
"eval_tokens",
"eval_tokens_set",
"=",
"evaluation",
".",... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | NumpyDataset.get_field | Return the dataset corresponds to the provided key.
Example::
a = np.ones((2,2))
b = np.zeros((2,2))
np.savez('data.npz', a=a, b=b)
dataset = NumpyDataset('data.npz')
data_a = dataset.get_field('a')
data_b = dataset.get_field('b')
... | src/gluonnlp/data/dataset.py | def get_field(self, field):
"""Return the dataset corresponds to the provided key.
Example::
a = np.ones((2,2))
b = np.zeros((2,2))
np.savez('data.npz', a=a, b=b)
dataset = NumpyDataset('data.npz')
data_a = dataset.get_field('a')
d... | def get_field(self, field):
"""Return the dataset corresponds to the provided key.
Example::
a = np.ones((2,2))
b = np.zeros((2,2))
np.savez('data.npz', a=a, b=b)
dataset = NumpyDataset('data.npz')
data_a = dataset.get_field('a')
d... | [
"Return",
"the",
"dataset",
"corresponds",
"to",
"the",
"provided",
"key",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/dataset.py#L259-L276 | [
"def",
"get_field",
"(",
"self",
",",
"field",
")",
":",
"idx",
"=",
"self",
".",
"_keys",
".",
"index",
"(",
"field",
")",
"return",
"self",
".",
"_data",
"[",
"idx",
"]"
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | get_final_text | Project the tokenized prediction back to the original text. | scripts/bert/bert_qa_evaluate.py | def get_final_text(pred_text, orig_text, tokenizer):
"""Project the tokenized prediction back to the original text."""
# When we created the data, we kept track of the alignment between original
# (whitespace tokenized) tokens and our WordPiece tokenized tokens. So
# now `orig_text` contains the span o... | def get_final_text(pred_text, orig_text, tokenizer):
"""Project the tokenized prediction back to the original text."""
# When we created the data, we kept track of the alignment between original
# (whitespace tokenized) tokens and our WordPiece tokenized tokens. So
# now `orig_text` contains the span o... | [
"Project",
"the",
"tokenized",
"prediction",
"back",
"to",
"the",
"original",
"text",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/bert_qa_evaluate.py#L38-L120 | [
"def",
"get_final_text",
"(",
"pred_text",
",",
"orig_text",
",",
"tokenizer",
")",
":",
"# When we created the data, we kept track of the alignment between original",
"# (whitespace tokenized) tokens and our WordPiece tokenized tokens. So",
"# now `orig_text` contains the span of our origin... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | predictions | Get prediction results
Parameters
----------
dev_dataset: dataset
Examples of transform.
all_results: dict
A dictionary containing model prediction results.
tokenizer: callable
Tokenizer function.
max_answer_length: int, default 64
Maximum length of the answer to... | scripts/bert/bert_qa_evaluate.py | def predictions(dev_dataset,
all_results,
tokenizer,
max_answer_length=64,
null_score_diff_threshold=0.0,
n_best_size=10,
version_2=False):
"""Get prediction results
Parameters
----------
dev_dataset: datase... | def predictions(dev_dataset,
all_results,
tokenizer,
max_answer_length=64,
null_score_diff_threshold=0.0,
n_best_size=10,
version_2=False):
"""Get prediction results
Parameters
----------
dev_dataset: datase... | [
"Get",
"prediction",
"results"
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/bert_qa_evaluate.py#L123-L323 | [
"def",
"predictions",
"(",
"dev_dataset",
",",
"all_results",
",",
"tokenizer",
",",
"max_answer_length",
"=",
"64",
",",
"null_score_diff_threshold",
"=",
"0.0",
",",
"n_best_size",
"=",
"10",
",",
"version_2",
"=",
"False",
")",
":",
"_PrelimPrediction",
"=",
... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | get_F1_EM | Calculate the F1 and EM scores of the predicted results.
Use only with the SQuAD1.1 dataset.
Parameters
----------
dataset_file: string
Path to the data file.
predict_data: dict
All final predictions.
Returns
-------
scores: dict
F1 and EM scores. | scripts/bert/bert_qa_evaluate.py | def get_F1_EM(dataset, predict_data):
"""Calculate the F1 and EM scores of the predicted results.
Use only with the SQuAD1.1 dataset.
Parameters
----------
dataset_file: string
Path to the data file.
predict_data: dict
All final predictions.
Returns
-------
scores: ... | def get_F1_EM(dataset, predict_data):
"""Calculate the F1 and EM scores of the predicted results.
Use only with the SQuAD1.1 dataset.
Parameters
----------
dataset_file: string
Path to the data file.
predict_data: dict
All final predictions.
Returns
-------
scores: ... | [
"Calculate",
"the",
"F1",
"and",
"EM",
"scores",
"of",
"the",
"predicted",
"results",
".",
"Use",
"only",
"with",
"the",
"SQuAD1",
".",
"1",
"dataset",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/bert_qa_evaluate.py#L374-L409 | [
"def",
"get_F1_EM",
"(",
"dataset",
",",
"predict_data",
")",
":",
"f1",
"=",
"exact_match",
"=",
"total",
"=",
"0",
"for",
"record",
"in",
"dataset",
":",
"total",
"+=",
"1",
"if",
"record",
"[",
"1",
"]",
"not",
"in",
"predict_data",
":",
"message",
... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | preprocess_data | Data preparation function. | scripts/bert/finetune_classifier.py | def preprocess_data(tokenizer, task, batch_size, dev_batch_size, max_len, pad=False):
"""Data preparation function."""
# transformation
trans = BERTDatasetTransform(
tokenizer,
max_len,
labels=task.get_labels(),
pad=pad,
pair=task.is_pair,
label_dtype='float32... | def preprocess_data(tokenizer, task, batch_size, dev_batch_size, max_len, pad=False):
"""Data preparation function."""
# transformation
trans = BERTDatasetTransform(
tokenizer,
max_len,
labels=task.get_labels(),
pad=pad,
pair=task.is_pair,
label_dtype='float32... | [
"Data",
"preparation",
"function",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/finetune_classifier.py#L247-L301 | [
"def",
"preprocess_data",
"(",
"tokenizer",
",",
"task",
",",
"batch_size",
",",
"dev_batch_size",
",",
"max_len",
",",
"pad",
"=",
"False",
")",
":",
"# transformation",
"trans",
"=",
"BERTDatasetTransform",
"(",
"tokenizer",
",",
"max_len",
",",
"labels",
"=... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | evaluate | Evaluate the model on validation dataset. | scripts/bert/finetune_classifier.py | def evaluate(dataloader_eval, metric):
"""Evaluate the model on validation dataset.
"""
metric.reset()
for _, seqs in enumerate(dataloader_eval):
input_ids, valid_len, type_ids, label = seqs
out = model(
input_ids.as_in_context(ctx), type_ids.as_in_context(ctx),
v... | def evaluate(dataloader_eval, metric):
"""Evaluate the model on validation dataset.
"""
metric.reset()
for _, seqs in enumerate(dataloader_eval):
input_ids, valid_len, type_ids, label = seqs
out = model(
input_ids.as_in_context(ctx), type_ids.as_in_context(ctx),
v... | [
"Evaluate",
"the",
"model",
"on",
"validation",
"dataset",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/finetune_classifier.py#L314-L330 | [
"def",
"evaluate",
"(",
"dataloader_eval",
",",
"metric",
")",
":",
"metric",
".",
"reset",
"(",
")",
"for",
"_",
",",
"seqs",
"in",
"enumerate",
"(",
"dataloader_eval",
")",
":",
"input_ids",
",",
"valid_len",
",",
"type_ids",
",",
"label",
"=",
"seqs",... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | log_train | Generate and print out the log message for training. | scripts/bert/finetune_classifier.py | def log_train(batch_id, batch_num, metric, step_loss, log_interval, epoch_id, learning_rate):
"""Generate and print out the log message for training.
"""
metric_nm, metric_val = metric.get()
if not isinstance(metric_nm, list):
metric_nm = [metric_nm]
metric_val = [metric_val]
train_... | def log_train(batch_id, batch_num, metric, step_loss, log_interval, epoch_id, learning_rate):
"""Generate and print out the log message for training.
"""
metric_nm, metric_val = metric.get()
if not isinstance(metric_nm, list):
metric_nm = [metric_nm]
metric_val = [metric_val]
train_... | [
"Generate",
"and",
"print",
"out",
"the",
"log",
"message",
"for",
"training",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/finetune_classifier.py#L333-L346 | [
"def",
"log_train",
"(",
"batch_id",
",",
"batch_num",
",",
"metric",
",",
"step_loss",
",",
"log_interval",
",",
"epoch_id",
",",
"learning_rate",
")",
":",
"metric_nm",
",",
"metric_val",
"=",
"metric",
".",
"get",
"(",
")",
"if",
"not",
"isinstance",
"(... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | log_inference | Generate and print out the log message for inference. | scripts/bert/finetune_classifier.py | def log_inference(batch_id, batch_num, metric, step_loss, log_interval):
"""Generate and print out the log message for inference.
"""
metric_nm, metric_val = metric.get()
if not isinstance(metric_nm, list):
metric_nm = [metric_nm]
metric_val = [metric_val]
eval_str = '[Batch %d/%d] ... | def log_inference(batch_id, batch_num, metric, step_loss, log_interval):
"""Generate and print out the log message for inference.
"""
metric_nm, metric_val = metric.get()
if not isinstance(metric_nm, list):
metric_nm = [metric_nm]
metric_val = [metric_val]
eval_str = '[Batch %d/%d] ... | [
"Generate",
"and",
"print",
"out",
"the",
"log",
"message",
"for",
"inference",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/finetune_classifier.py#L349-L361 | [
"def",
"log_inference",
"(",
"batch_id",
",",
"batch_num",
",",
"metric",
",",
"step_loss",
",",
"log_interval",
")",
":",
"metric_nm",
",",
"metric_val",
"=",
"metric",
".",
"get",
"(",
")",
"if",
"not",
"isinstance",
"(",
"metric_nm",
",",
"list",
")",
... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | train | Training function. | scripts/bert/finetune_classifier.py | def train(metric):
"""Training function."""
logging.info('Now we are doing BERT classification training on %s!', ctx)
optimizer_params = {'learning_rate': lr, 'epsilon': epsilon, 'wd': 0.01}
try:
trainer = gluon.Trainer(
model.collect_params(),
args.optimizer,
... | def train(metric):
"""Training function."""
logging.info('Now we are doing BERT classification training on %s!', ctx)
optimizer_params = {'learning_rate': lr, 'epsilon': epsilon, 'wd': 0.01}
try:
trainer = gluon.Trainer(
model.collect_params(),
args.optimizer,
... | [
"Training",
"function",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/finetune_classifier.py#L364-L459 | [
"def",
"train",
"(",
"metric",
")",
":",
"logging",
".",
"info",
"(",
"'Now we are doing BERT classification training on %s!'",
",",
"ctx",
")",
"optimizer_params",
"=",
"{",
"'learning_rate'",
":",
"lr",
",",
"'epsilon'",
":",
"epsilon",
",",
"'wd'",
":",
"0.01... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | inference | Inference function. | scripts/bert/finetune_classifier.py | def inference(metric):
"""Inference function."""
logging.info('Now we are doing BERT classification inference on %s!', ctx)
model = BERTClassifier(bert, dropout=0.1, num_classes=len(task.get_labels()))
model.hybridize(static_alloc=True)
model.load_parameters(model_parameters, ctx=ctx)
metric.r... | def inference(metric):
"""Inference function."""
logging.info('Now we are doing BERT classification inference on %s!', ctx)
model = BERTClassifier(bert, dropout=0.1, num_classes=len(task.get_labels()))
model.hybridize(static_alloc=True)
model.load_parameters(model_parameters, ctx=ctx)
metric.r... | [
"Inference",
"function",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/finetune_classifier.py#L462-L492 | [
"def",
"inference",
"(",
"metric",
")",
":",
"logging",
".",
"info",
"(",
"'Now we are doing BERT classification inference on %s!'",
",",
"ctx",
")",
"model",
"=",
"BERTClassifier",
"(",
"bert",
",",
"dropout",
"=",
"0.1",
",",
"num_classes",
"=",
"len",
"(",
... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | preprocess_dataset | Process SQuAD dataset by creating NDArray version of data
:param Dataset dataset: SQuAD dataset
:param int question_max_length: Maximum length of question (padded or trimmed to that size)
:param int context_max_length: Maximum length of context (padded or trimmed to that size)
Returns
-------
... | scripts/question_answering/data_processing.py | def preprocess_dataset(dataset, question_max_length, context_max_length):
"""Process SQuAD dataset by creating NDArray version of data
:param Dataset dataset: SQuAD dataset
:param int question_max_length: Maximum length of question (padded or trimmed to that size)
:param int context_max_length: Maximum... | def preprocess_dataset(dataset, question_max_length, context_max_length):
"""Process SQuAD dataset by creating NDArray version of data
:param Dataset dataset: SQuAD dataset
:param int question_max_length: Maximum length of question (padded or trimmed to that size)
:param int context_max_length: Maximum... | [
"Process",
"SQuAD",
"dataset",
"by",
"creating",
"NDArray",
"version",
"of",
"data"
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/question_answering/data_processing.py#L34-L51 | [
"def",
"preprocess_dataset",
"(",
"dataset",
",",
"question_max_length",
",",
"context_max_length",
")",
":",
"vocab_provider",
"=",
"VocabProvider",
"(",
"dataset",
")",
"transformer",
"=",
"SQuADTransform",
"(",
"vocab_provider",
",",
"question_max_length",
",",
"co... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | SQuADTransform._get_answer_spans | Find all answer spans from the context, returning start_index and end_index
:param list[str] answer_list: List of all answers
:param list[int] answer_start_list: List of all answers' start indices
Returns
-------
List[Tuple]
list of Tuple(answer_start_index answer_e... | scripts/question_answering/data_processing.py | def _get_answer_spans(answer_list, answer_start_list):
"""Find all answer spans from the context, returning start_index and end_index
:param list[str] answer_list: List of all answers
:param list[int] answer_start_list: List of all answers' start indices
Returns
-------
... | def _get_answer_spans(answer_list, answer_start_list):
"""Find all answer spans from the context, returning start_index and end_index
:param list[str] answer_list: List of all answers
:param list[int] answer_start_list: List of all answers' start indices
Returns
-------
... | [
"Find",
"all",
"answer",
"spans",
"from",
"the",
"context",
"returning",
"start_index",
"and",
"end_index"
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/question_answering/data_processing.py#L98-L110 | [
"def",
"_get_answer_spans",
"(",
"answer_list",
",",
"answer_start_list",
")",
":",
"return",
"[",
"(",
"answer_start_list",
"[",
"i",
"]",
",",
"answer_start_list",
"[",
"i",
"]",
"+",
"len",
"(",
"answer",
")",
")",
"for",
"i",
",",
"answer",
"in",
"en... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | VocabProvider.get_word_level_vocab | Provides word level vocabulary
Returns
-------
Vocab
Word level vocabulary | scripts/question_answering/data_processing.py | def get_word_level_vocab(self):
"""Provides word level vocabulary
Returns
-------
Vocab
Word level vocabulary
"""
def simple_tokenize(source_str, token_delim=' ', seq_delim='\n'):
return list(filter(None, re.split(token_delim + '|' + seq_delim, s... | def get_word_level_vocab(self):
"""Provides word level vocabulary
Returns
-------
Vocab
Word level vocabulary
"""
def simple_tokenize(source_str, token_delim=' ', seq_delim='\n'):
return list(filter(None, re.split(token_delim + '|' + seq_delim, s... | [
"Provides",
"word",
"level",
"vocabulary"
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/question_answering/data_processing.py#L130-L142 | [
"def",
"get_word_level_vocab",
"(",
"self",
")",
":",
"def",
"simple_tokenize",
"(",
"source_str",
",",
"token_delim",
"=",
"' '",
",",
"seq_delim",
"=",
"'\\n'",
")",
":",
"return",
"list",
"(",
"filter",
"(",
"None",
",",
"re",
".",
"split",
"(",
"toke... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | TemporalActivationRegularizationLoss.hybrid_forward | Parameters
----------
states : list
the stack outputs from RNN, which consists of output from each time step (TNC).
Returns
--------
loss : NDArray
loss tensor with shape (batch_size,). Dimensions other than batch_axis are averaged out. | src/gluonnlp/loss/activation_regularizer.py | def hybrid_forward(self, F, *states): # pylint: disable=arguments-differ
"""
Parameters
----------
states : list
the stack outputs from RNN, which consists of output from each time step (TNC).
Returns
--------
loss : NDArray
loss tensor wi... | def hybrid_forward(self, F, *states): # pylint: disable=arguments-differ
"""
Parameters
----------
states : list
the stack outputs from RNN, which consists of output from each time step (TNC).
Returns
--------
loss : NDArray
loss tensor wi... | [
"Parameters",
"----------",
"states",
":",
"list",
"the",
"stack",
"outputs",
"from",
"RNN",
"which",
"consists",
"of",
"output",
"from",
"each",
"time",
"step",
"(",
"TNC",
")",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/loss/activation_regularizer.py#L128-L148 | [
"def",
"hybrid_forward",
"(",
"self",
",",
"F",
",",
"*",
"states",
")",
":",
"# pylint: disable=arguments-differ",
"# pylint: disable=unused-argument",
"if",
"self",
".",
"_beta",
"!=",
"0",
":",
"if",
"states",
":",
"means",
"=",
"[",
"self",
".",
"_beta",
... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | BERTBasicTokenizer._tokenize | Tokenizes a piece of text. | src/gluonnlp/data/transforms.py | def _tokenize(self, text):
"""Tokenizes a piece of text."""
text = self._clean_text(text)
# This was added on November 1st, 2018 for the multilingual and Chinese
# models. This is also applied to the English models now, but it doesn't
# matter since the English models were not t... | def _tokenize(self, text):
"""Tokenizes a piece of text."""
text = self._clean_text(text)
# This was added on November 1st, 2018 for the multilingual and Chinese
# models. This is also applied to the English models now, but it doesn't
# matter since the English models were not t... | [
"Tokenizes",
"a",
"piece",
"of",
"text",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/transforms.py#L758-L778 | [
"def",
"_tokenize",
"(",
"self",
",",
"text",
")",
":",
"text",
"=",
"self",
".",
"_clean_text",
"(",
"text",
")",
"# This was added on November 1st, 2018 for the multilingual and Chinese",
"# models. This is also applied to the English models now, but it doesn't",
"# matter sinc... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | BERTBasicTokenizer._clean_text | Performs invalid character removal and whitespace cleanup on text. | src/gluonnlp/data/transforms.py | def _clean_text(self, text):
"""Performs invalid character removal and whitespace cleanup on text."""
output = []
for char in text:
cp = ord(char)
if cp in (0, 0xfffd) or self._is_control(char):
continue
if self._is_whitespace(char):
... | def _clean_text(self, text):
"""Performs invalid character removal and whitespace cleanup on text."""
output = []
for char in text:
cp = ord(char)
if cp in (0, 0xfffd) or self._is_control(char):
continue
if self._is_whitespace(char):
... | [
"Performs",
"invalid",
"character",
"removal",
"and",
"whitespace",
"cleanup",
"on",
"text",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/transforms.py#L780-L791 | [
"def",
"_clean_text",
"(",
"self",
",",
"text",
")",
":",
"output",
"=",
"[",
"]",
"for",
"char",
"in",
"text",
":",
"cp",
"=",
"ord",
"(",
"char",
")",
"if",
"cp",
"in",
"(",
"0",
",",
"0xfffd",
")",
"or",
"self",
".",
"_is_control",
"(",
"cha... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | BERTBasicTokenizer._is_control | Checks whether `chars` is a control character. | src/gluonnlp/data/transforms.py | def _is_control(self, char):
"""Checks whether `chars` is a control character."""
# These are technically control characters but we count them as whitespace
# characters.
if char in ['\t', '\n', '\r']:
return False
cat = unicodedata.category(char)
if cat.start... | def _is_control(self, char):
"""Checks whether `chars` is a control character."""
# These are technically control characters but we count them as whitespace
# characters.
if char in ['\t', '\n', '\r']:
return False
cat = unicodedata.category(char)
if cat.start... | [
"Checks",
"whether",
"chars",
"is",
"a",
"control",
"character",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/transforms.py#L793-L802 | [
"def",
"_is_control",
"(",
"self",
",",
"char",
")",
":",
"# These are technically control characters but we count them as whitespace",
"# characters.",
"if",
"char",
"in",
"[",
"'\\t'",
",",
"'\\n'",
",",
"'\\r'",
"]",
":",
"return",
"False",
"cat",
"=",
"unicodeda... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | BERTBasicTokenizer._run_split_on_punc | Splits punctuation on a piece of text. | src/gluonnlp/data/transforms.py | def _run_split_on_punc(self, text):
"""Splits punctuation on a piece of text."""
chars = list(text)
i = 0
start_new_word = True
output = []
while i < len(chars):
char = chars[i]
if self._is_punctuation(char):
output.append([char])
... | def _run_split_on_punc(self, text):
"""Splits punctuation on a piece of text."""
chars = list(text)
i = 0
start_new_word = True
output = []
while i < len(chars):
char = chars[i]
if self._is_punctuation(char):
output.append([char])
... | [
"Splits",
"punctuation",
"on",
"a",
"piece",
"of",
"text",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/transforms.py#L850-L868 | [
"def",
"_run_split_on_punc",
"(",
"self",
",",
"text",
")",
":",
"chars",
"=",
"list",
"(",
"text",
")",
"i",
"=",
"0",
"start_new_word",
"=",
"True",
"output",
"=",
"[",
"]",
"while",
"i",
"<",
"len",
"(",
"chars",
")",
":",
"char",
"=",
"chars",
... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | BERTBasicTokenizer._is_punctuation | Checks whether `chars` is a punctuation character. | src/gluonnlp/data/transforms.py | def _is_punctuation(self, char):
"""Checks whether `chars` is a punctuation character."""
cp = ord(char)
# We treat all non-letter/number ASCII as punctuation.
# Characters such as "^", "$", and "`" are not in the Unicode
# Punctuation class but we treat them as punctuation anywa... | def _is_punctuation(self, char):
"""Checks whether `chars` is a punctuation character."""
cp = ord(char)
# We treat all non-letter/number ASCII as punctuation.
# Characters such as "^", "$", and "`" are not in the Unicode
# Punctuation class but we treat them as punctuation anywa... | [
"Checks",
"whether",
"chars",
"is",
"a",
"punctuation",
"character",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/transforms.py#L870-L886 | [
"def",
"_is_punctuation",
"(",
"self",
",",
"char",
")",
":",
"cp",
"=",
"ord",
"(",
"char",
")",
"# We treat all non-letter/number ASCII as punctuation.",
"# Characters such as \"^\", \"$\", and \"`\" are not in the Unicode",
"# Punctuation class but we treat them as punctuation any... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | BERTBasicTokenizer._is_whitespace | Checks whether `chars` is a whitespace character. | src/gluonnlp/data/transforms.py | def _is_whitespace(self, char):
"""Checks whether `chars` is a whitespace character."""
# \t, \n, and \r are technically contorl characters but we treat them
# as whitespace since they are generally considered as such.
if char in [' ', '\t', '\n', '\r']:
return True
c... | def _is_whitespace(self, char):
"""Checks whether `chars` is a whitespace character."""
# \t, \n, and \r are technically contorl characters but we treat them
# as whitespace since they are generally considered as such.
if char in [' ', '\t', '\n', '\r']:
return True
c... | [
"Checks",
"whether",
"chars",
"is",
"a",
"whitespace",
"character",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/transforms.py#L888-L897 | [
"def",
"_is_whitespace",
"(",
"self",
",",
"char",
")",
":",
"# \\t, \\n, and \\r are technically contorl characters but we treat them",
"# as whitespace since they are generally considered as such.",
"if",
"char",
"in",
"[",
"' '",
",",
"'\\t'",
",",
"'\\n'",
",",
"'\\r'",
... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | BERTBasicTokenizer._whitespace_tokenize | Runs basic whitespace cleaning and splitting on a piece of text. | src/gluonnlp/data/transforms.py | def _whitespace_tokenize(self, text):
"""Runs basic whitespace cleaning and splitting on a piece of text."""
text = text.strip()
tokens = text.split()
return tokens | def _whitespace_tokenize(self, text):
"""Runs basic whitespace cleaning and splitting on a piece of text."""
text = text.strip()
tokens = text.split()
return tokens | [
"Runs",
"basic",
"whitespace",
"cleaning",
"and",
"splitting",
"on",
"a",
"piece",
"of",
"text",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/transforms.py#L899-L903 | [
"def",
"_whitespace_tokenize",
"(",
"self",
",",
"text",
")",
":",
"text",
"=",
"text",
".",
"strip",
"(",
")",
"tokens",
"=",
"text",
".",
"split",
"(",
")",
"return",
"tokens"
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | BERTTokenizer._tokenize_wordpiece | Tokenizes a piece of text into its word pieces.
This uses a greedy longest-match-first algorithm to perform tokenization
using the given vocabulary.
For example:
input = "unaffable"
output = ["un", "##aff", "##able"]
Args:
text: A single token or whitespa... | src/gluonnlp/data/transforms.py | def _tokenize_wordpiece(self, text):
"""Tokenizes a piece of text into its word pieces.
This uses a greedy longest-match-first algorithm to perform tokenization
using the given vocabulary.
For example:
input = "unaffable"
output = ["un", "##aff", "##able"]
... | def _tokenize_wordpiece(self, text):
"""Tokenizes a piece of text into its word pieces.
This uses a greedy longest-match-first algorithm to perform tokenization
using the given vocabulary.
For example:
input = "unaffable"
output = ["un", "##aff", "##able"]
... | [
"Tokenizes",
"a",
"piece",
"of",
"text",
"into",
"its",
"word",
"pieces",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/transforms.py#L960-L1007 | [
"def",
"_tokenize_wordpiece",
"(",
"self",
",",
"text",
")",
":",
"output_tokens",
"=",
"[",
"]",
"for",
"token",
"in",
"self",
".",
"basic_tokenizer",
".",
"_whitespace_tokenize",
"(",
"text",
")",
":",
"chars",
"=",
"list",
"(",
"token",
")",
"if",
"le... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | BERTSentenceTransform._truncate_seq_pair | Truncates a sequence pair in place to the maximum length. | src/gluonnlp/data/transforms.py | def _truncate_seq_pair(self, tokens_a, tokens_b, max_length):
"""Truncates a sequence pair in place to the maximum length."""
# This is a simple heuristic which will always truncate the longer sequence
# one token at a time. This makes more sense than truncating an equal percent
# of tok... | def _truncate_seq_pair(self, tokens_a, tokens_b, max_length):
"""Truncates a sequence pair in place to the maximum length."""
# This is a simple heuristic which will always truncate the longer sequence
# one token at a time. This makes more sense than truncating an equal percent
# of tok... | [
"Truncates",
"a",
"sequence",
"pair",
"in",
"place",
"to",
"the",
"maximum",
"length",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/transforms.py#L1144-L1157 | [
"def",
"_truncate_seq_pair",
"(",
"self",
",",
"tokens_a",
",",
"tokens_b",
",",
"max_length",
")",
":",
"# This is a simple heuristic which will always truncate the longer sequence",
"# one token at a time. This makes more sense than truncating an equal percent",
"# of tokens from each,... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | get_args | Construct the argument parser. | scripts/word_embeddings/evaluate_pretrained.py | def get_args():
"""Construct the argument parser."""
parser = argparse.ArgumentParser(
description='Word embedding evaluation with Gluon.',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
# Embeddings arguments
group = parser.add_argument_group('Embedding arguments')
group.a... | def get_args():
"""Construct the argument parser."""
parser = argparse.ArgumentParser(
description='Word embedding evaluation with Gluon.',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
# Embeddings arguments
group = parser.add_argument_group('Embedding arguments')
group.a... | [
"Construct",
"the",
"argument",
"parser",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/evaluate_pretrained.py#L40-L97 | [
"def",
"get_args",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Word embedding evaluation with Gluon.'",
",",
"formatter_class",
"=",
"argparse",
".",
"ArgumentDefaultsHelpFormatter",
")",
"# Embeddings arguments",
"group",
... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | validate_args | Validate provided arguments and act on --help. | scripts/word_embeddings/evaluate_pretrained.py | def validate_args(args):
"""Validate provided arguments and act on --help."""
if args.list_embedding_sources:
print('Listing all sources for {} embeddings.'.format(
args.embedding_name))
print('Specify --embedding-name if you wish to '
'list sources of other embeddings'... | def validate_args(args):
"""Validate provided arguments and act on --help."""
if args.list_embedding_sources:
print('Listing all sources for {} embeddings.'.format(
args.embedding_name))
print('Specify --embedding-name if you wish to '
'list sources of other embeddings'... | [
"Validate",
"provided",
"arguments",
"and",
"act",
"on",
"--",
"help",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/evaluate_pretrained.py#L100-L131 | [
"def",
"validate_args",
"(",
"args",
")",
":",
"if",
"args",
".",
"list_embedding_sources",
":",
"print",
"(",
"'Listing all sources for {} embeddings.'",
".",
"format",
"(",
"args",
".",
"embedding_name",
")",
")",
"print",
"(",
"'Specify --embedding-name if you wish... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | load_embedding_from_path | Load a TokenEmbedding. | scripts/word_embeddings/evaluate_pretrained.py | def load_embedding_from_path(args):
"""Load a TokenEmbedding."""
if args.embedding_path.endswith('.bin'):
with utils.print_time('load fastText model.'):
model = \
nlp.model.train.FasttextEmbeddingModel.load_fasttext_format(
args.embedding_path)
idx... | def load_embedding_from_path(args):
"""Load a TokenEmbedding."""
if args.embedding_path.endswith('.bin'):
with utils.print_time('load fastText model.'):
model = \
nlp.model.train.FasttextEmbeddingModel.load_fasttext_format(
args.embedding_path)
idx... | [
"Load",
"a",
"TokenEmbedding",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/evaluate_pretrained.py#L134-L163 | [
"def",
"load_embedding_from_path",
"(",
"args",
")",
":",
"if",
"args",
".",
"embedding_path",
".",
"endswith",
"(",
"'.bin'",
")",
":",
"with",
"utils",
".",
"print_time",
"(",
"'load fastText model.'",
")",
":",
"model",
"=",
"nlp",
".",
"model",
".",
"t... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | grad_global_norm | Calculate the 2-norm of gradients of parameters, and how much they should be scaled down
such that their 2-norm does not exceed `max_norm`.
If gradients exist for more than one context for a parameter, user needs to explicitly call
``trainer.allreduce_grads`` so that the gradients are summed first before c... | scripts/bert/fp16_utils.py | def grad_global_norm(parameters, max_norm):
"""Calculate the 2-norm of gradients of parameters, and how much they should be scaled down
such that their 2-norm does not exceed `max_norm`.
If gradients exist for more than one context for a parameter, user needs to explicitly call
``trainer.allreduce_grad... | def grad_global_norm(parameters, max_norm):
"""Calculate the 2-norm of gradients of parameters, and how much they should be scaled down
such that their 2-norm does not exceed `max_norm`.
If gradients exist for more than one context for a parameter, user needs to explicitly call
``trainer.allreduce_grad... | [
"Calculate",
"the",
"2",
"-",
"norm",
"of",
"gradients",
"of",
"parameters",
"and",
"how",
"much",
"they",
"should",
"be",
"scaled",
"down",
"such",
"that",
"their",
"2",
"-",
"norm",
"does",
"not",
"exceed",
"max_norm",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/fp16_utils.py#L26-L107 | [
"def",
"grad_global_norm",
"(",
"parameters",
",",
"max_norm",
")",
":",
"# collect gradient arrays",
"arrays",
"=",
"[",
"]",
"idx",
"=",
"0",
"for",
"p",
"in",
"parameters",
":",
"if",
"p",
".",
"grad_req",
"!=",
"'null'",
":",
"p_grads",
"=",
"p",
"."... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | FP16Trainer.backward | backward propagation with loss | scripts/bert/fp16_utils.py | def backward(self, loss):
"""backward propagation with loss"""
with mx.autograd.record():
if isinstance(loss, (tuple, list)):
ls = [l * self._scaler.loss_scale for l in loss]
else:
ls = loss * self._scaler.loss_scale
mx.autograd.backward(ls... | def backward(self, loss):
"""backward propagation with loss"""
with mx.autograd.record():
if isinstance(loss, (tuple, list)):
ls = [l * self._scaler.loss_scale for l in loss]
else:
ls = loss * self._scaler.loss_scale
mx.autograd.backward(ls... | [
"backward",
"propagation",
"with",
"loss"
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/fp16_utils.py#L138-L145 | [
"def",
"backward",
"(",
"self",
",",
"loss",
")",
":",
"with",
"mx",
".",
"autograd",
".",
"record",
"(",
")",
":",
"if",
"isinstance",
"(",
"loss",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"ls",
"=",
"[",
"l",
"*",
"self",
".",
"_scaler"... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | FP16Trainer.step | Makes one step of parameter update. Should be called after
`fp16_optimizer.backward()`, and outside of `record()` scope.
Parameters
----------
batch_size : int
Batch size of data processed. Gradient will be normalized by `1/batch_size`.
Set this to 1 if you norma... | scripts/bert/fp16_utils.py | def step(self, batch_size, max_norm=None):
"""Makes one step of parameter update. Should be called after
`fp16_optimizer.backward()`, and outside of `record()` scope.
Parameters
----------
batch_size : int
Batch size of data processed. Gradient will be normalized by ... | def step(self, batch_size, max_norm=None):
"""Makes one step of parameter update. Should be called after
`fp16_optimizer.backward()`, and outside of `record()` scope.
Parameters
----------
batch_size : int
Batch size of data processed. Gradient will be normalized by ... | [
"Makes",
"one",
"step",
"of",
"parameter",
"update",
".",
"Should",
"be",
"called",
"after",
"fp16_optimizer",
".",
"backward",
"()",
"and",
"outside",
"of",
"record",
"()",
"scope",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/fp16_utils.py#L147-L183 | [
"def",
"step",
"(",
"self",
",",
"batch_size",
",",
"max_norm",
"=",
"None",
")",
":",
"self",
".",
"fp32_trainer",
".",
"allreduce_grads",
"(",
")",
"step_size",
"=",
"batch_size",
"*",
"self",
".",
"_scaler",
".",
"loss_scale",
"if",
"max_norm",
":",
"... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | LossScaler.has_overflow | detect inf and nan | scripts/bert/fp16_utils.py | def has_overflow(self, params):
""" detect inf and nan """
is_not_finite = 0
for param in params:
if param.grad_req != 'null':
grad = param.list_grad()[0]
is_not_finite += mx.nd.contrib.isnan(grad).sum()
is_not_finite += mx.nd.contrib.i... | def has_overflow(self, params):
""" detect inf and nan """
is_not_finite = 0
for param in params:
if param.grad_req != 'null':
grad = param.list_grad()[0]
is_not_finite += mx.nd.contrib.isnan(grad).sum()
is_not_finite += mx.nd.contrib.i... | [
"detect",
"inf",
"and",
"nan"
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/fp16_utils.py#L187-L199 | [
"def",
"has_overflow",
"(",
"self",
",",
"params",
")",
":",
"is_not_finite",
"=",
"0",
"for",
"param",
"in",
"params",
":",
"if",
"param",
".",
"grad_req",
"!=",
"'null'",
":",
"grad",
"=",
"param",
".",
"list_grad",
"(",
")",
"[",
"0",
"]",
"is_not... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | DynamicLossScaler.update_scale | dynamically update loss scale | scripts/bert/fp16_utils.py | def update_scale(self, overflow):
"""dynamically update loss scale"""
iter_since_rescale = self._num_steps - self._last_rescale_iter
if overflow:
self._last_overflow_iter = self._num_steps
self._overflows_since_rescale += 1
percentage = self._overflows_since_r... | def update_scale(self, overflow):
"""dynamically update loss scale"""
iter_since_rescale = self._num_steps - self._last_rescale_iter
if overflow:
self._last_overflow_iter = self._num_steps
self._overflows_since_rescale += 1
percentage = self._overflows_since_r... | [
"dynamically",
"update",
"loss",
"scale"
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/fp16_utils.py#L236-L253 | [
"def",
"update_scale",
"(",
"self",
",",
"overflow",
")",
":",
"iter_since_rescale",
"=",
"self",
".",
"_num_steps",
"-",
"self",
".",
"_last_rescale_iter",
"if",
"overflow",
":",
"self",
".",
"_last_overflow_iter",
"=",
"self",
".",
"_num_steps",
"self",
".",... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | FixedBucketSampler.stats | Return a string representing the statistics of the bucketing sampler.
Returns
-------
ret : str
String representing the statistics of the buckets. | src/gluonnlp/data/sampler.py | def stats(self):
"""Return a string representing the statistics of the bucketing sampler.
Returns
-------
ret : str
String representing the statistics of the buckets.
"""
ret = '{name}:\n' \
' sample_num={sample_num}, batch_num={batch_num}\n' \
... | def stats(self):
"""Return a string representing the statistics of the bucketing sampler.
Returns
-------
ret : str
String representing the statistics of the buckets.
"""
ret = '{name}:\n' \
' sample_num={sample_num}, batch_num={batch_num}\n' \
... | [
"Return",
"a",
"string",
"representing",
"the",
"statistics",
"of",
"the",
"bucketing",
"sampler",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/sampler.py#L420-L439 | [
"def",
"stats",
"(",
"self",
")",
":",
"ret",
"=",
"'{name}:\\n'",
"' sample_num={sample_num}, batch_num={batch_num}\\n'",
"' key={bucket_keys}\\n'",
"' cnt={bucket_counts}\\n'",
"' batch_size={bucket_batch_sizes}'",
".",
"format",
"(",
"name",
"=",
"self",
".",
"__class_... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | train | Training loop for language model. | scripts/language_model/large_word_language_model.py | def train():
"""Training loop for language model.
"""
print(model)
from_epoch = 0
model.initialize(mx.init.Xavier(factor_type='out'), ctx=context)
trainer_params = {'learning_rate': args.lr, 'wd': 0, 'eps': args.eps}
trainer = gluon.Trainer(model.collect_params(), 'adagrad', trainer_params)
... | def train():
"""Training loop for language model.
"""
print(model)
from_epoch = 0
model.initialize(mx.init.Xavier(factor_type='out'), ctx=context)
trainer_params = {'learning_rate': args.lr, 'wd': 0, 'eps': args.eps}
trainer = gluon.Trainer(model.collect_params(), 'adagrad', trainer_params)
... | [
"Training",
"loop",
"for",
"language",
"model",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/language_model/large_word_language_model.py#L210-L290 | [
"def",
"train",
"(",
")",
":",
"print",
"(",
"model",
")",
"from_epoch",
"=",
"0",
"model",
".",
"initialize",
"(",
"mx",
".",
"init",
".",
"Xavier",
"(",
"factor_type",
"=",
"'out'",
")",
",",
"ctx",
"=",
"context",
")",
"trainer_params",
"=",
"{",
... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | evaluate | Evaluate loop for the trained model | scripts/language_model/large_word_language_model.py | def evaluate():
""" Evaluate loop for the trained model """
print(eval_model)
eval_model.initialize(mx.init.Xavier(), ctx=context[0])
eval_model.hybridize(static_alloc=True, static_shape=True)
epoch = args.from_epoch if args.from_epoch else 0
while epoch < args.epochs:
checkpoint_name = ... | def evaluate():
""" Evaluate loop for the trained model """
print(eval_model)
eval_model.initialize(mx.init.Xavier(), ctx=context[0])
eval_model.hybridize(static_alloc=True, static_shape=True)
epoch = args.from_epoch if args.from_epoch else 0
while epoch < args.epochs:
checkpoint_name = ... | [
"Evaluate",
"loop",
"for",
"the",
"trained",
"model"
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/language_model/large_word_language_model.py#L345-L367 | [
"def",
"evaluate",
"(",
")",
":",
"print",
"(",
"eval_model",
")",
"eval_model",
".",
"initialize",
"(",
"mx",
".",
"init",
".",
"Xavier",
"(",
")",
",",
"ctx",
"=",
"context",
"[",
"0",
"]",
")",
"eval_model",
".",
"hybridize",
"(",
"static_alloc",
... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | load_dataset | Load sentiment dataset. | scripts/sentiment_analysis/process_data.py | def load_dataset(data_name):
"""Load sentiment dataset."""
if data_name == 'MR' or data_name == 'Subj':
train_dataset, output_size = _load_file(data_name)
vocab, max_len = _build_vocab(data_name, train_dataset, [])
train_dataset, train_data_lengths = _preprocess_dataset(train_dataset, vo... | def load_dataset(data_name):
"""Load sentiment dataset."""
if data_name == 'MR' or data_name == 'Subj':
train_dataset, output_size = _load_file(data_name)
vocab, max_len = _build_vocab(data_name, train_dataset, [])
train_dataset, train_data_lengths = _preprocess_dataset(train_dataset, vo... | [
"Load",
"sentiment",
"dataset",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/sentiment_analysis/process_data.py#L120-L133 | [
"def",
"load_dataset",
"(",
"data_name",
")",
":",
"if",
"data_name",
"==",
"'MR'",
"or",
"data_name",
"==",
"'Subj'",
":",
"train_dataset",
",",
"output_size",
"=",
"_load_file",
"(",
"data_name",
")",
"vocab",
",",
"max_len",
"=",
"_build_vocab",
"(",
"dat... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | get_home_dir | Get home directory for storing datasets/models/pre-trained word embeddings | src/gluonnlp/base.py | def get_home_dir():
"""Get home directory for storing datasets/models/pre-trained word embeddings"""
_home_dir = os.environ.get('MXNET_HOME', os.path.join('~', '.mxnet'))
# expand ~ to actual path
_home_dir = os.path.expanduser(_home_dir)
return _home_dir | def get_home_dir():
"""Get home directory for storing datasets/models/pre-trained word embeddings"""
_home_dir = os.environ.get('MXNET_HOME', os.path.join('~', '.mxnet'))
# expand ~ to actual path
_home_dir = os.path.expanduser(_home_dir)
return _home_dir | [
"Get",
"home",
"directory",
"for",
"storing",
"datasets",
"/",
"models",
"/",
"pre",
"-",
"trained",
"word",
"embeddings"
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/base.py#L68-L73 | [
"def",
"get_home_dir",
"(",
")",
":",
"_home_dir",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'MXNET_HOME'",
",",
"os",
".",
"path",
".",
"join",
"(",
"'~'",
",",
"'.mxnet'",
")",
")",
"# expand ~ to actual path",
"_home_dir",
"=",
"os",
".",
"path",
... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | read_dataset | Read dataset from tokenized files. | scripts/natural_language_inference/dataset.py | def read_dataset(args, dataset):
"""
Read dataset from tokenized files.
"""
path = os.path.join(vars(args)[dataset])
logger.info('reading data from {}'.format(path))
examples = [line.strip().split('\t') for line in open(path)]
if args.max_num_examples > 0:
examples = examples[:args.m... | def read_dataset(args, dataset):
"""
Read dataset from tokenized files.
"""
path = os.path.join(vars(args)[dataset])
logger.info('reading data from {}'.format(path))
examples = [line.strip().split('\t') for line in open(path)]
if args.max_num_examples > 0:
examples = examples[:args.m... | [
"Read",
"dataset",
"from",
"tokenized",
"files",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/natural_language_inference/dataset.py#L35-L51 | [
"def",
"read_dataset",
"(",
"args",
",",
"dataset",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"vars",
"(",
"args",
")",
"[",
"dataset",
"]",
")",
"logger",
".",
"info",
"(",
"'reading data from {}'",
".",
"format",
"(",
"path",
")",... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | build_vocab | Build vocab given a dataset. | scripts/natural_language_inference/dataset.py | def build_vocab(dataset):
"""
Build vocab given a dataset.
"""
counter = nlp.data.count_tokens([w for e in dataset for s in e[:2] for w in s],
to_lower=True)
vocab = nlp.Vocab(counter)
return vocab | def build_vocab(dataset):
"""
Build vocab given a dataset.
"""
counter = nlp.data.count_tokens([w for e in dataset for s in e[:2] for w in s],
to_lower=True)
vocab = nlp.Vocab(counter)
return vocab | [
"Build",
"vocab",
"given",
"a",
"dataset",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/natural_language_inference/dataset.py#L53-L60 | [
"def",
"build_vocab",
"(",
"dataset",
")",
":",
"counter",
"=",
"nlp",
".",
"data",
".",
"count_tokens",
"(",
"[",
"w",
"for",
"e",
"in",
"dataset",
"for",
"s",
"in",
"e",
"[",
":",
"2",
"]",
"for",
"w",
"in",
"s",
"]",
",",
"to_lower",
"=",
"T... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | prepare_data_loader | Read data and build data loader. | scripts/natural_language_inference/dataset.py | 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):
"""
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... | [
"Read",
"data",
"and",
"build",
"data",
"loader",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/natural_language_inference/dataset.py#L62-L79 | [
"def",
"prepare_data_loader",
"(",
"args",
",",
"dataset",
",",
"vocab",
",",
"test",
"=",
"False",
")",
":",
"# Preprocess",
"dataset",
"=",
"dataset",
".",
"transform",
"(",
"lambda",
"s1",
",",
"s2",
",",
"label",
":",
"(",
"vocab",
"(",
"s1",
")",
... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | mxnet_prefer_gpu | If gpu available return gpu, else cpu
Returns
-------
context : Context
The preferable GPU context. | scripts/parsing/common/utils.py | 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():
"""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() | [
"If",
"gpu",
"available",
"return",
"gpu",
"else",
"cpu"
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/utils.py#L150-L161 | [
"def",
"mxnet_prefer_gpu",
"(",
")",
":",
"gpu",
"=",
"int",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"'MXNET_GPU'",
",",
"default",
"=",
"0",
")",
")",
"if",
"gpu",
"in",
"mx",
".",
"test_utils",
".",
"list_gpus",
"(",
")",
":",
"return",
"mx",... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | init_logger | Initialize a logger
Parameters
----------
root_dir : str
directory for saving log
name : str
name of logger
Returns
-------
logger : logging.Logger
a logger | scripts/parsing/common/utils.py | 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"):
"""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_... | [
"Initialize",
"a",
"logger"
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/utils.py#L164-L189 | [
"def",
"init_logger",
"(",
"root_dir",
",",
"name",
"=",
"\"train.log\"",
")",
":",
"os",
".",
"makedirs",
"(",
"root_dir",
",",
"exist_ok",
"=",
"True",
")",
"log_formatter",
"=",
"logging",
".",
"Formatter",
"(",
"\"%(message)s\"",
")",
"logger",
"=",
"l... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | orthonormal_VanillaLSTMBuilder | Build a standard LSTM cell, with variational dropout,
with weights initialized to be orthonormal (https://arxiv.org/abs/1312.6120)
Parameters
----------
lstm_layers : int
Currently only support one layer
input_dims : int
word vector dimensions
lstm_hiddens : int
hidden s... | scripts/parsing/common/utils.py | def orthonormal_VanillaLSTMBuilder(lstm_layers, input_dims, lstm_hiddens, dropout_x=0., dropout_h=0., debug=False):
"""Build a standard LSTM cell, with variational dropout,
with weights initialized to be orthonormal (https://arxiv.org/abs/1312.6120)
Parameters
----------
lstm_layers : int
C... | def orthonormal_VanillaLSTMBuilder(lstm_layers, input_dims, lstm_hiddens, dropout_x=0., dropout_h=0., debug=False):
"""Build a standard LSTM cell, with variational dropout,
with weights initialized to be orthonormal (https://arxiv.org/abs/1312.6120)
Parameters
----------
lstm_layers : int
C... | [
"Build",
"a",
"standard",
"LSTM",
"cell",
"with",
"variational",
"dropout",
"with",
"weights",
"initialized",
"to",
"be",
"orthonormal",
"(",
"https",
":",
"//",
"arxiv",
".",
"org",
"/",
"abs",
"/",
"1312",
".",
"6120",
")"
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/utils.py#L192-L226 | [
"def",
"orthonormal_VanillaLSTMBuilder",
"(",
"lstm_layers",
",",
"input_dims",
",",
"lstm_hiddens",
",",
"dropout_x",
"=",
"0.",
",",
"dropout_h",
"=",
"0.",
",",
"debug",
"=",
"False",
")",
":",
"assert",
"lstm_layers",
"==",
"1",
",",
"'only accept one layer ... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | biLSTM | 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... | scripts/parsing/common/utils.py | 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.):
"""Feature extraction through BiLSTM
Parameters
----------
f_lstm : VariationalDropoutCell
Forward cell
b_lstm : VariationalDropoutCell
Backward cell
inputs : NDArray
seq_len x batch_size
... | [
"Feature",
"extraction",
"through",
"BiLSTM"
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/utils.py#L229-L256 | [
"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",
... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | bilinear | Do xWy
Parameters
----------
x : NDArray
(input_size x seq_len) x batch_size
W : NDArray
(num_outputs x ny) x nx
y : NDArray
(input_size x seq_len) x batch_size
input_size : int
input dimension
seq_len : int
sequence length
batch_size : int
... | scripts/parsing/common/utils.py | def bilinear(x, W, y, input_size, seq_len, batch_size, num_outputs=1, bias_x=False, bias_y=False):
"""Do xWy
Parameters
----------
x : NDArray
(input_size x seq_len) x batch_size
W : NDArray
(num_outputs x ny) x nx
y : NDArray
(input_size x seq_len) x batch_size
inpu... | def bilinear(x, W, y, input_size, seq_len, batch_size, num_outputs=1, bias_x=False, bias_y=False):
"""Do xWy
Parameters
----------
x : NDArray
(input_size x seq_len) x batch_size
W : NDArray
(num_outputs x ny) x nx
y : NDArray
(input_size x seq_len) x batch_size
inpu... | [
"Do",
"xWy"
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/utils.py#L275-L320 | [
"def",
"bilinear",
"(",
"x",
",",
"W",
",",
"y",
",",
"input_size",
",",
"seq_len",
",",
"batch_size",
",",
"num_outputs",
"=",
"1",
",",
"bias_x",
"=",
"False",
",",
"bias_y",
"=",
"False",
")",
":",
"if",
"bias_x",
":",
"x",
"=",
"nd",
".",
"co... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | orthonormal_initializer | adopted from Timothy Dozat https://github.com/tdozat/Parser/blob/master/lib/linalg.py
Parameters
----------
output_size : int
input_size : int
debug : bool
Whether to skip this initializer
Returns
-------
Q : np.ndarray
The orthonormal weight matrix of input_size x outpu... | scripts/parsing/common/utils.py | def orthonormal_initializer(output_size, input_size, debug=False):
"""adopted from Timothy Dozat https://github.com/tdozat/Parser/blob/master/lib/linalg.py
Parameters
----------
output_size : int
input_size : int
debug : bool
Whether to skip this initializer
Returns
-------
... | def orthonormal_initializer(output_size, input_size, debug=False):
"""adopted from Timothy Dozat https://github.com/tdozat/Parser/blob/master/lib/linalg.py
Parameters
----------
output_size : int
input_size : int
debug : bool
Whether to skip this initializer
Returns
-------
... | [
"adopted",
"from",
"Timothy",
"Dozat",
"https",
":",
"//",
"github",
".",
"com",
"/",
"tdozat",
"/",
"Parser",
"/",
"blob",
"/",
"master",
"/",
"lib",
"/",
"linalg",
".",
"py"
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/utils.py#L323-L364 | [
"def",
"orthonormal_initializer",
"(",
"output_size",
",",
"input_size",
",",
"debug",
"=",
"False",
")",
":",
"print",
"(",
"(",
"output_size",
",",
"input_size",
")",
")",
"if",
"debug",
":",
"Q",
"=",
"np",
".",
"random",
".",
"randn",
"(",
"input_siz... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | arc_argmax | MST
Adopted from Timothy Dozat https://github.com/tdozat/Parser/blob/master/lib/models/nn.py
Parameters
----------
parse_probs : NDArray
seq_len x seq_len, the probability of arcs
length : NDArray
real sentence length
tokens_to_keep : NDArray
mask matrix
ensure_tree ... | scripts/parsing/common/utils.py | def arc_argmax(parse_probs, length, tokens_to_keep, ensure_tree=True):
"""MST
Adopted from Timothy Dozat https://github.com/tdozat/Parser/blob/master/lib/models/nn.py
Parameters
----------
parse_probs : NDArray
seq_len x seq_len, the probability of arcs
length : NDArray
real sen... | def arc_argmax(parse_probs, length, tokens_to_keep, ensure_tree=True):
"""MST
Adopted from Timothy Dozat https://github.com/tdozat/Parser/blob/master/lib/models/nn.py
Parameters
----------
parse_probs : NDArray
seq_len x seq_len, the probability of arcs
length : NDArray
real sen... | [
"MST",
"Adopted",
"from",
"Timothy",
"Dozat",
"https",
":",
"//",
"github",
".",
"com",
"/",
"tdozat",
"/",
"Parser",
"/",
"blob",
"/",
"master",
"/",
"lib",
"/",
"models",
"/",
"nn",
".",
"py"
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/utils.py#L367-L455 | [
"def",
"arc_argmax",
"(",
"parse_probs",
",",
"length",
",",
"tokens_to_keep",
",",
"ensure_tree",
"=",
"True",
")",
":",
"if",
"ensure_tree",
":",
"I",
"=",
"np",
".",
"eye",
"(",
"len",
"(",
"tokens_to_keep",
")",
")",
"# block loops and pad heads",
"parse... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | rel_argmax | 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,... | scripts/parsing/common/utils.py | 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):
"""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 : ... | [
"Fix",
"the",
"relation",
"prediction",
"by",
"heuristic",
"rules"
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/utils.py#L458-L494 | [
"def",
"rel_argmax",
"(",
"rel_probs",
",",
"length",
",",
"ensure_tree",
"=",
"True",
")",
":",
"if",
"ensure_tree",
":",
"rel_probs",
"[",
":",
",",
"ParserVocabulary",
".",
"PAD",
"]",
"=",
"0",
"root",
"=",
"ParserVocabulary",
".",
"ROOT",
"tokens",
... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | reshape_fortran | The missing Fortran reshape for mx.NDArray
Parameters
----------
tensor : NDArray
source tensor
shape : NDArray
desired shape
Returns
-------
output : NDArray
reordered result | scripts/parsing/common/utils.py | 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):
"""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... | [
"The",
"missing",
"Fortran",
"reshape",
"for",
"mx",
".",
"NDArray"
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/utils.py#L497-L512 | [
"def",
"reshape_fortran",
"(",
"tensor",
",",
"shape",
")",
":",
"return",
"tensor",
".",
"T",
".",
"reshape",
"(",
"tuple",
"(",
"reversed",
"(",
"shape",
")",
")",
")",
".",
"T"
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | Progbar.update | Updates the progress bar.
# Arguments
current: Index of current step.
values: List of tuples (name, value_for_last_step).
The progress bar will display averages for these values.
exact: List of tuples (name, value_for_last_step).
The progress b... | scripts/parsing/common/utils.py | def update(self, current, values=[], exact=[], strict=[]):
"""
Updates the progress bar.
# Arguments
current: Index of current step.
values: List of tuples (name, value_for_last_step).
The progress bar will display averages for these values.
ex... | def update(self, current, values=[], exact=[], strict=[]):
"""
Updates the progress bar.
# Arguments
current: Index of current step.
values: List of tuples (name, value_for_last_step).
The progress bar will display averages for these values.
ex... | [
"Updates",
"the",
"progress",
"bar",
".",
"#",
"Arguments",
"current",
":",
"Index",
"of",
"current",
"step",
".",
"values",
":",
"List",
"of",
"tuples",
"(",
"name",
"value_for_last_step",
")",
".",
"The",
"progress",
"bar",
"will",
"display",
"averages",
... | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/utils.py#L56-L144 | [
"def",
"update",
"(",
"self",
",",
"current",
",",
"values",
"=",
"[",
"]",
",",
"exact",
"=",
"[",
"]",
",",
"strict",
"=",
"[",
"]",
")",
":",
"for",
"k",
",",
"v",
"in",
"values",
":",
"if",
"k",
"not",
"in",
"self",
".",
"sum_values",
":"... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | get_batch | 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
... | scripts/language_model/word_language_model.py | 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):
"""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
... | [
"Get",
"mini",
"-",
"batches",
"of",
"the",
"dataset",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/language_model/word_language_model.py#L275-L297 | [
"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",
"=",... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | evaluate | 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 ... | scripts/language_model/word_language_model.py | 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):
"""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... | [
"Evaluate",
"the",
"model",
"on",
"the",
"dataset",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/language_model/word_language_model.py#L300-L339 | [
"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",
"="... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | train | Training loop for awd language model. | scripts/language_model/word_language_model.py | def train():
"""Training loop for awd language model.
"""
ntasgd = False
best_val = float('Inf')
start_train_time = time.time()
parameters = model.collect_params()
param_dict_avg = None
t = 0
avg_trigger = 0
n = 5
valid_losses = []
for epoch in range(args.epochs):
... | def train():
"""Training loop for awd language model.
"""
ntasgd = False
best_val = float('Inf')
start_train_time = time.time()
parameters = model.collect_params()
param_dict_avg = None
t = 0
avg_trigger = 0
n = 5
valid_losses = []
for epoch in range(args.epochs):
... | [
"Training",
"loop",
"for",
"awd",
"language",
"model",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/language_model/word_language_model.py#L342-L463 | [
"def",
"train",
"(",
")",
":",
"ntasgd",
"=",
"False",
"best_val",
"=",
"float",
"(",
"'Inf'",
")",
"start_train_time",
"=",
"time",
".",
"time",
"(",
")",
"parameters",
"=",
"model",
".",
"collect_params",
"(",
")",
"param_dict_avg",
"=",
"None",
"t",
... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | register | 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... | src/gluonnlp/embedding/evaluation.py | 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_):
"""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... | [
"Registers",
"a",
"new",
"word",
"embedding",
"evaluation",
"function",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/embedding/evaluation.py#L67-L107 | [
"def",
"register",
"(",
"class_",
")",
":",
"if",
"issubclass",
"(",
"class_",
",",
"WordEmbeddingSimilarityFunction",
")",
":",
"register_",
"=",
"registry",
".",
"get_register_func",
"(",
"WordEmbeddingSimilarityFunction",
",",
"'word embedding similarity evaluation fun... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | create | 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
... | src/gluonnlp/embedding/evaluation.py | 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):
"""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 ... | [
"Creates",
"an",
"instance",
"of",
"a",
"registered",
"word",
"embedding",
"evaluation",
"function",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/embedding/evaluation.py#L110-L141 | [
"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... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | list_evaluation_functions | 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
... | src/gluonnlp/embedding/evaluation.py | 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):
"""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... | [
"Get",
"valid",
"word",
"embedding",
"functions",
"names",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/embedding/evaluation.py#L144-L175 | [
"def",
"list_evaluation_functions",
"(",
"kind",
"=",
"None",
")",
":",
"if",
"kind",
"is",
"None",
":",
"kind",
"=",
"tuple",
"(",
"_REGSITRY_KIND_CLASS_MAP",
".",
"keys",
"(",
")",
")",
"if",
"not",
"isinstance",
"(",
"kind",
",",
"tuple",
")",
":",
... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | WordEmbeddingSimilarity.hybrid_forward | 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... | src/gluonnlp/embedding/evaluation.py | 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
"""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 : ... | [
"Predict",
"the",
"similarity",
"of",
"words1",
"and",
"words2",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/embedding/evaluation.py#L439-L461 | [
"def",
"hybrid_forward",
"(",
"self",
",",
"F",
",",
"words1",
",",
"words2",
",",
"weight",
")",
":",
"# pylint: disable=arguments-differ",
"embeddings_words1",
"=",
"F",
".",
"Embedding",
"(",
"words1",
",",
"weight",
",",
"input_dim",
"=",
"self",
".",
"_... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | WordEmbeddingAnalogy.hybrid_forward | 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... | src/gluonnlp/embedding/evaluation.py | 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
"""Compute analogies for given question words.
Parameters
----------
words1 : Symbol or NDArray
Word indices of first question words. Shape (batch_size, ).
words... | [
"Compute",
"analogies",
"for",
"given",
"question",
"words",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/embedding/evaluation.py#L501-L518 | [
"def",
"hybrid_forward",
"(",
"self",
",",
"F",
",",
"words1",
",",
"words2",
",",
"words3",
")",
":",
"# pylint: disable=arguments-differ, unused-argument",
"return",
"self",
".",
"analogy",
"(",
"words1",
",",
"words2",
",",
"words3",
")"
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
train | evaluate | 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
... | scripts/language_model/cache_language_model.py | 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):
"""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... | [
"Evaluate",
"the",
"model",
"on",
"the",
"dataset",
"with",
"cache",
"model",
"."
] | dmlc/gluon-nlp | python | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/language_model/cache_language_model.py#L167-L203 | [
"def",
"evaluate",
"(",
"data_source",
",",
"batch_size",
",",
"ctx",
"=",
"None",
")",
":",
"total_L",
"=",
"0",
"hidden",
"=",
"cache_cell",
".",
"begin_state",
"(",
"func",
"=",
"mx",
".",
"nd",
".",
"zeros",
",",
"batch_size",
"=",
"batch_size",
",... | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.