INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
wrapper for client for dataset_status, with additional dataset_opt to get the status of a dataset from the API Parameters ========== dataset_opt: an alternative to dataset
def dataset_status_cli(self, dataset, dataset_opt=None): """ wrapper for client for dataset_status, with additional dataset_opt to get the status of a dataset from the API Parameters ========== dataset_opt: an alternative to dataset """ dataset = ...
download a single file for a dataset Parameters ========== dataset: the string identified of the dataset should be in format [owner]/[dataset-name] file_name: the dataset configuration file path: if defined, download to this location ...
def dataset_download_file(self, dataset, file_name, path=None, force=False, quiet=True): """ download a single file for a dataset Parameters ...
download all files for a dataset Parameters ========== dataset: the string identified of the dataset should be in format [owner]/[dataset-name] path: the path to download the dataset to force: force the download if the file already exists...
def dataset_download_files(self, dataset, path=None, force=False, quiet=True, unzip=False): """ download all files for a dataset Parameters ...
client wrapper for dataset_download_files and download dataset file, either for a specific file (when file_name is provided), or all files for a dataset (plural) Parameters ========== dataset: the string identified of the dataset should b...
def dataset_download_cli(self, dataset, dataset_opt=None, file_name=None, path=None, unzip=False, force=False, quiet=...
create a version of a dataset Parameters ========== folder: the folder with the dataset configuration / data files version_notes: notes to add for the version quiet: suppress verbose output (default is False) convert_to_csv: on upload, if data sho...
def dataset_create_version(self, folder, version_notes, quiet=False, convert_to_csv=True, delete_old_versions=False, dir_mode='skip'):...
upload a dataset file Parameters ========== path: the complete path to upload quiet: suppress verbose output (default is False)
def dataset_upload_file(self, path, quiet): """ upload a dataset file Parameters ========== path: the complete path to upload quiet: suppress verbose output (default is False) """ file_name = os.path.basename(path) content_length = os.path...
client wrapper for creating a version of a dataset Parameters ========== folder: the folder with the dataset configuration / data files version_notes: notes to add for the version quiet: suppress verbose output (default is False) convert_to_csv: o...
def dataset_create_version_cli(self, folder, version_notes, quiet=False, convert_to_csv=True, delete_old_versions=False, ...
initialize a folder with a a dataset configuration (metadata) file Parameters ========== folder: the folder to initialize the metadata file in
def dataset_initialize(self, folder): """ initialize a folder with a a dataset configuration (metadata) file Parameters ========== folder: the folder to initialize the metadata file in """ if not os.path.isdir(folder): raise ValueError('Invalid fo...
create a new dataset, meaning the same as creating a version but with extra metadata like license and user/owner. Parameters ========== folder: the folder to initialize the metadata file in public: should the dataset be public? quiet: suppress ver...
def dataset_create_new(self, folder, public=False, quiet=False, convert_to_csv=True, dir_mode='skip'): """ create a new dataset, meaning the same as creating a version but ...
client wrapper for creating a new dataset Parameters ========== folder: the folder to initialize the metadata file in public: should the dataset be public? quiet: suppress verbose output (default is False) convert_to_csv: if True, convert data to ...
def dataset_create_new_cli(self, folder=None, public=False, quiet=False, convert_to_csv=True, dir_mode='skip'): """ client wrapper for creating a new dataset...
download a file to an output file based on a chunk size Parameters ========== response: the response to download outfile: the output file to download to quiet: suppress verbose output (default is True) chunk_size: the size of the chunk to stream
def download_file(self, response, outfile, quiet=True, chunk_size=1048576): """ download a file to an output file based on a chunk size Parameters ========== response: the response to download outfile: the output file to download to quiet: suppress ve...
list kernels based on a set of search criteria Parameters ========== page: the page of results to return (default is 1) page_size: results per page (default is 20) dataset: if defined, filter to this dataset (default None) competition: if defined,...
def kernels_list(self, page=1, page_size=20, dataset=None, competition=None, parent_kernel=None, search=None, mine=False, user=None, ...
client wrapper for kernels_list, see this function for arguments. Additional arguments are provided here. Parameters ========== csv_display: if True, print comma separated values instead of table
def kernels_list_cli(self, mine=False, page=1, page_size=20, search=None, csv_display=False, parent=None, competition=None, ...
create a new kernel in a specified folder from template, including json metadata that grabs values from the configuration. Parameters ========== folder: the path of the folder
def kernels_initialize(self, folder): """ create a new kernel in a specified folder from template, including json metadata that grabs values from the configuration. Parameters ========== folder: the path of the folder """ if not os.path.isdir(fold...
client wrapper for kernels_initialize, takes same arguments but sets default folder to be None. If None, defaults to present working directory. Parameters ========== folder: the path of the folder (None defaults to ${PWD})
def kernels_initialize_cli(self, folder=None): """ client wrapper for kernels_initialize, takes same arguments but sets default folder to be None. If None, defaults to present working directory. Parameters ========== folder: the path of the folder (No...
read the metadata file and kernel files from a notebook, validate both, and use Kernel API to push to Kaggle if all is valid. Parameters ========== folder: the path of the folder
def kernels_push(self, folder): """ read the metadata file and kernel files from a notebook, validate both, and use Kernel API to push to Kaggle if all is valid. Parameters ========== folder: the path of the folder """ if not os.path.isdir(folder)...
client wrapper for kernels_push, with same arguments.
def kernels_push_cli(self, folder): """ client wrapper for kernels_push, with same arguments. """ folder = folder or os.getcwd() result = self.kernels_push(folder) if result is None: print('Kernel push error: see previous output') elif not result.error: ...
pull a kernel, including a metadata file (if metadata is True) and associated files to a specified path. Parameters ========== kernel: the kernel to pull path: the path to pull files to on the filesystem metadata: if True, also pull metadata ...
def kernels_pull(self, kernel, path, metadata=False, quiet=True): """ pull a kernel, including a metadata file (if metadata is True) and associated files to a specified path. Parameters ========== kernel: the kernel to pull path: the path to pull file...
client wrapper for kernels_pull
def kernels_pull_cli(self, kernel, kernel_opt=None, path=None, metadata=False): """ client wrapper for kernels_pull """ kernel = kernel or kernel_opt effective_path = self.kernels_pull( ...
client wrapper for kernels_output, with same arguments. Extra arguments are described below, and see kernels_output for others. Parameters ========== kernel_opt: option from client instead of kernel, if not defined
def kernels_output_cli(self, kernel, kernel_opt=None, path=None, force=False, quiet=False): """ client wrapper for kernels_output, with same arguments. Extra argumen...
call to the api to get the status of a kernel. Parameters ========== kernel: the kernel to get the status for
def kernels_status(self, kernel): """ call to the api to get the status of a kernel. Parameters ========== kernel: the kernel to get the status for """ if kernel is None: raise ValueError('A kernel must be specified') if '/' in kernel: ...
determine if a download is needed based on timestamp. Return True if needed (remote is newer) or False if local is newest. Parameters ========== response: the response from the API outfile: the output file to write to quiet: suppress verbose outpu...
def download_needed(self, response, outfile, quiet=True): """ determine if a download is needed based on timestamp. Return True if needed (remote is newer) or False if local is newest. Parameters ========== response: the response from the API outfile:...
client wrapper for kernel_status Parameters ========== kernel_opt: additional option from the client, if kernel not defined
def kernels_status_cli(self, kernel, kernel_opt=None): """ client wrapper for kernel_status Parameters ========== kernel_opt: additional option from the client, if kernel not defined """ kernel = kernel or kernel_opt response = self.kernels_status(ker...
print a table of items, for a set of fields defined Parameters ========== items: a list of items to print fields: a list of fields to select from items
def print_table(self, items, fields): """ print a table of items, for a set of fields defined Parameters ========== items: a list of items to print fields: a list of fields to select from items """ formats = [] borders = [] for f i...
print a set of fields in a set of items using a csv.writer Parameters ========== items: a list of items to print fields: a list of fields to select from items
def print_csv(self, items, fields): """ print a set of fields in a set of items using a csv.writer Parameters ========== items: a list of items to print fields: a list of fields to select from items """ writer = csv.writer(sys.stdout) writ...
process a response from the API. We check the API version against the client's to see if it's old, and give them a warning (once) Parameters ========== result: the result from the API
def process_response(self, result): """ process a response from the API. We check the API version against the client's to see if it's old, and give them a warning (once) Parameters ========== result: the result from the API """ if len(result) == 3...
determine if a client (on the local user's machine) is up to date with the version provided on the server. Return a boolean with True or False Parameters ========== server_version: the server version string to compare to the host
def is_up_to_date(self, server_version): """ determine if a client (on the local user's machine) is up to date with the version provided on the server. Return a boolean with True or False Parameters ========== server_version: the server version string...
upload files in a folder Parameters ========== request: the prepared request resources: the files to upload folder: the folder to upload from quiet: suppress verbose output (default is False)
def upload_files(self, request, resources, folder, quiet=False, dir_mode='skip'): """ upload files in a folder Parameters ========== request: the prepared request ...
Helper function to upload a single file Parameters ========== file_name: name of the file to upload full_path: path to the file to upload request: the prepared request resources: optional file metadata quiet: suppress verbose output ...
def _upload_file(self, file_name, full_path, quiet, request, resources): """ Helper function to upload a single file Parameters ========== file_name: name of the file to upload full_path: path to the file to upload request: the prepared request ...
process a column, check for the type, and return the processed column Parameters ========== column: a list of values in a column to be processed
def process_column(self, column): """ process a column, check for the type, and return the processed column Parameters ========== column: a list of values in a column to be processed """ processed_column = DatasetColumn( name=self.get_...
function to complete an upload to retrieve a path from a url Parameters ========== path: the path for the upload that is read in url: the url to send the POST to quiet: suppress verbose output (default is False)
def upload_complete(self, path, url, quiet): """ function to complete an upload to retrieve a path from a url Parameters ========== path: the path for the upload that is read in url: the url to send the POST to quiet: suppress verbose output (default ...
determine if a dataset string is valid, meaning it is in the format of {username}/{dataset-slug}. Parameters ========== dataset: the dataset name to validate
def validate_dataset_string(self, dataset): """ determine if a dataset string is valid, meaning it is in the format of {username}/{dataset-slug}. Parameters ========== dataset: the dataset name to validate """ if dataset: if '/' not in...
determine if a kernel string is valid, meaning it is in the format of {username}/{kernel-slug}. Parameters ========== kernel: the kernel name to validate
def validate_kernel_string(self, kernel): """ determine if a kernel string is valid, meaning it is in the format of {username}/{kernel-slug}. Parameters ========== kernel: the kernel name to validate """ if kernel: if '/' not in kernel...
validate resources is a wrapper to validate the existence of files and that there are no duplicates for a folder and set of resources. Parameters ========== folder: the folder to validate resources: one or more resources to validate within the folder
def validate_resources(self, folder, resources): """ validate resources is a wrapper to validate the existence of files and that there are no duplicates for a folder and set of resources. Parameters ========== folder: the folder to validate resources:...
ensure that one or more resource files exist in a folder Parameters ========== folder: the folder to validate resources: one or more resources to validate within the folder
def validate_files_exist(self, folder, resources): """ ensure that one or more resource files exist in a folder Parameters ========== folder: the folder to validate resources: one or more resources to validate within the folder """ for item in res...
ensure that the user has not provided duplicate paths in a list of resources. Parameters ========== resources: one or more resources to validate not duplicated
def validate_no_duplicate_paths(self, resources): """ ensure that the user has not provided duplicate paths in a list of resources. Parameters ========== resources: one or more resources to validate not duplicated """ paths = set() for ite...
convert a set of file_data to a metadata file at path Parameters ========== file_data: a dictionary of file data to write to file path: the path to write the metadata to
def convert_to_dataset_file_metadata(self, file_data, path): """ convert a set of file_data to a metadata file at path Parameters ========== file_data: a dictionary of file data to write to file path: the path to write the metadata to """ as_metad...
read the buffer, passing named and non named arguments to the io.BufferedReader function.
def read(self, *args, **kwargs): """ read the buffer, passing named and non named arguments to the io.BufferedReader function. """ buf = io.BufferedReader.read(self, *args, **kwargs) self.increment(len(buf)) return buf
Get parameters as list of tuples, formatting collections. :param params: Parameters as dict or list of two-tuples :param dict collection_formats: Parameter collection formats :return: Parameters as list of tuples, collections formatted
def parameters_to_tuples(self, params, collection_formats): """Get parameters as list of tuples, formatting collections. :param params: Parameters as dict or list of two-tuples :param dict collection_formats: Parameter collection formats :return: Parameters as list of tuples, collection...
Builds form parameters. :param post_params: Normal form parameters. :param files: File parameters. :return: Form parameters with files.
def prepare_post_parameters(self, post_params=None, files=None): """Builds form parameters. :param post_params: Normal form parameters. :param files: File parameters. :return: Form parameters with files. """ params = [] if post_params: params = post_...
Deserializes body to file Saves response body into a file in a temporary folder, using the filename from the `Content-Disposition` header if provided. :param response: RESTResponse. :return: file path.
def __deserialize_file(self, response): """Deserializes body to file Saves response body into a file in a temporary folder, using the filename from the `Content-Disposition` header if provided. :param response: RESTResponse. :return: file path. """ fd, path = t...
Deserializes string to primitive type. :param data: str. :param klass: class literal. :return: int, long, float, str, bool.
def __deserialize_primitive(self, data, klass): """Deserializes string to primitive type. :param data: str. :param klass: class literal. :return: int, long, float, str, bool. """ try: return klass(data) except UnicodeEncodeError: return s...
The logger file. 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
def logger_file(self, value): """The logger file. If the logger_file is None, then add stream handler and remove file handler. Otherwise, add file handler and remove stream handler. :param value: The logger_file path. :type: str """ self.__logger_file = value ...
Sets the license_name of this DatasetNewRequest. The license that should be associated with the dataset # noqa: E501 :param license_name: The license_name of this DatasetNewRequest. # noqa: E501 :type: str
def license_name(self, license_name): """Sets the license_name of this DatasetNewRequest. The license that should be associated with the dataset # noqa: E501 :param license_name: The license_name of this DatasetNewRequest. # noqa: E501 :type: str """ allowed_values = ...
Train textCNN model for sentiment analysis.
def train(net, train_data, test_data): """Train textCNN model for sentiment analysis.""" start_pipeline_time = time.time() net, trainer = text_cnn.init(net, vocab, args.model_mode, context, args.lr) random.shuffle(train_data) sp = int(len(train_data)*0.9) train_dataloader = DataLoader(dataset=tr...
Get tokens, tokens embedding 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 ------- ...
def embedding(self, sentences, oov_way='avg'): """ Get tokens, tokens embedding Parameters ---------- sentences : List[str] sentences for encoding. oov_way : str, default avg. use **avg**, **sum** or **last** to get token embedding for those out o...
Load, tokenize and prepare the input sentences.
def data_loader(self, sentences, shuffle=False): """Load, tokenize and prepare the input sentences.""" dataset = BertEmbeddingDataset(sentences, self.transform) return DataLoader(dataset=dataset, batch_size=self.batch_size, shuffle=shuffle)
How to handle oov. Also filter out [CLS], [SEP] tokens. Parameters ---------- batches : List[(tokens_id, sequence_outputs, pooled_output]. batch token_ids (max_seq_length, ), sequence_outputs (max_seq_length, dim,...
def oov(self, batches, oov_way='avg'): """ How to handle oov. Also filter out [CLS], [SEP] tokens. Parameters ---------- batches : List[(tokens_id, sequence_outputs, pooled_output]. batch token_ids (max_seq_length, ),...
Any BERT pretrained model. 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...
def get_bert_model(model_name=None, dataset_name=None, vocab=None, pretrained=True, ctx=mx.cpu(), use_pooler=True, use_decoder=True, use_classifier=True, output_attention=False, output_all_encodings=False, root=os.path.join(get_home_dir(), 'mod...
forward computation.
def hybrid_forward(self, F, data, gamma, beta): """forward computation.""" # TODO(haibin): LayerNorm does not support fp16 safe reduction. Issue is tracked at: # https://github.com/apache/incubator-mxnet/issues/14073 if self._dtype: data = data.astype('float32') g...
Construct a decoder for the next sentence prediction task
def _get_classifier(self, prefix): """ Construct a decoder for the next sentence prediction task """ with self.name_scope(): classifier = nn.Dense(2, prefix=prefix) return classifier
Construct a decoder for the masked language model task
def _get_decoder(self, units, vocab_size, embed, prefix): """ Construct a decoder for the masked language model task """ with self.name_scope(): decoder = nn.HybridSequential(prefix=prefix) decoder.add(nn.Dense(units, flatten=False)) decoder.add(GELU()) de...
Construct an embedding block.
def _get_embed(self, embed, vocab_size, embed_size, initializer, dropout, prefix): """ Construct an embedding block. """ if embed is None: assert embed_size is not None, '"embed_size" cannot be None if "word_embed" or ' \ 'token_type_embed is not gi...
Construct pooler. The pooler slices and projects the hidden output of first token in the sequence for segment level classification.
def _get_pooler(self, units, prefix): """ Construct pooler. The pooler slices and projects the hidden output of first token in the sequence for segment level classification. """ with self.name_scope(): pooler = nn.Dense(units=units, flatten=False, activation='tanh',...
Generate the representation given the input sequences. This is used for pre-training or fine-tuning a BERT model.
def _encode_sequence(self, inputs, token_types, valid_length=None): """Generate the representation given the input sequences. This is used for pre-training or fine-tuning a BERT model. """ # embedding word_embedding = self.word_embed(inputs) type_embedding = self.token_t...
Generate unnormalized prediction for the masked language model task. 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...
def _decode(self, sequence, masked_positions): """Generate unnormalized prediction for the masked language model task. This is only used for pre-training the BERT model. Inputs: - **sequence**: input tensor of sequence encodings. Shape (batch_size, seq_length, units)....
Extracts n-grams from an input segment. 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-...
def _ngrams(segment, n): """Extracts n-grams from an input segment. Parameters ---------- segment: list Text segment from which n-grams will be extracted. n: int Order of n-gram. Returns ------- ngram_counts: Counter Contain all the nth n-grams in segment with a...
Convert a sequence of bpe words into sentence.
def _bpe_to_words(sentence, delimiter='@@'): """Convert a sequence of bpe words into sentence.""" words = [] word = '' delimiter_len = len(delimiter) for subwords in sentence: if len(subwords) >= delimiter_len and subwords[-delimiter_len:] == delimiter: word += subwords[:-delimit...
r""" Tokenizes a string following the tokenizer in mteval-v13a.pl. See https://github.com/moses-smt/mosesdecoder/" "blob/master/scripts/generic/mteval-v14.pl#L917-L942 Parameters ---------- segment: str A string to be tokenized Returns ------- The tokenized string
def _tokenize_mteval_13a(segment): r""" Tokenizes a string following the tokenizer in mteval-v13a.pl. See https://github.com/moses-smt/mosesdecoder/" "blob/master/scripts/generic/mteval-v14.pl#L917-L942 Parameters ---------- segment: str A string to be tokenized Returns ...
r"""Tokenize a string following following the international tokenizer in mteval-v14a.pl. See https://github.com/moses-smt/mosesdecoder/" "blob/master/scripts/generic/mteval-v14.pl#L954-L983 Parameters ---------- segment: str A string to be tokenized Returns ------- The t...
def _tokenize_mteval_v14_intl(segment): r"""Tokenize a string following following the international tokenizer in mteval-v14a.pl. See https://github.com/moses-smt/mosesdecoder/" "blob/master/scripts/generic/mteval-v14.pl#L954-L983 Parameters ---------- segment: str A string to be ...
r"""Compute bleu score of translation against references. 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...
def compute_bleu(reference_corpus_list, translation_corpus, tokenized=True, tokenizer='13a', max_n=4, smooth=False, lower_case=False, bpe=False, split_compound_word=False): r"""Compute bleu score of translation against references. Parameters ---------- reference_corpus...
Compute ngram precision. 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 ...
def _compute_precision(references, translation, n): """Compute ngram precision. Parameters ---------- references: list(list(str)) A list of references. translation: list(str) A translation. n: int Order of n-gram. Returns ------- matches: int Number ...
Calculate brevity penalty. 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
def _brevity_penalty(ref_length, trans_length): """Calculate brevity penalty. Parameters ---------- ref_length: int Sum of all closest references'lengths for every translations in a corpus trans_length: int Sum of all translations's lengths in a corpus. Returns ------- ...
Find the reference that has the closest length to the translation. 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...
def _closest_ref_length(references, trans_length): """Find the reference that has the closest length to the translation. Parameters ---------- references: list(list(str)) A list of references. trans_length: int Length of the translation. Returns ------- closest_ref_len:...
Compute the smoothed precision for all the orders. 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 ...
def _smoothing(precision_fractions, c=1): """Compute the smoothed precision for all the orders. Parameters ---------- precision_fractions: list(tuple) Contain a list of (precision_numerator, precision_denominator) pairs c: int, default 1 Smoothing constant to use Returns --...
Draw samples from log uniform distribution and returns sampled candidates, expected count for true classes and sampled classes. Parameters ---------- true_classes: NDArray The true classes. Returns ------- samples: NDArray The sampled can...
def forward(self, true_classes): """Draw samples from log uniform distribution and returns sampled candidates, expected count for true classes and sampled classes. Parameters ---------- true_classes: NDArray The true classes. Returns ------- ...
Dataset preprocessing helper. 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...
def preprocess_dataset(data, min_freq=5, max_vocab_size=None): """Dataset preprocessing helper. Parameters ---------- data : mx.data.Dataset Input Dataset. For example gluonnlp.data.Text8 or gluonnlp.data.Fil9 min_freq : int, default 5 Minimum token frequency for a token to be inclu...
Wikipedia dump helper. 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. ...
def wiki(wiki_root, wiki_date, wiki_language, max_vocab_size=None): """Wikipedia dump helper. Parameters ---------- wiki_root : str Parameter for WikiDumpStream wiki_date : str Parameter for WikiDumpStream wiki_language : str Parameter for WikiDumpStream max_vocab_si...
Transform a DataStream of coded DataSets to a DataStream of batches. 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...
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. 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...
def transform_data_word2vec(data, vocab, idx_to_counts, cbow, batch_size, window_size, frequent_token_subsampling=1E-4, dtype='float32', index_dtype='int64'): """Transform a DataStream of coded DataSets to a DataStream of batches. Parameters ---------...
Create a batch for CBOW training objective with subwords.
def cbow_fasttext_batch(centers, contexts, num_tokens, subword_lookup, dtype, index_dtype): """Create a batch for CBOW training objective with subwords.""" _, contexts_row, contexts_col = contexts data, row, col = subword_lookup(contexts_row, contexts_col) centers = mx.nd.array(c...
Create a batch for SG training objective with subwords.
def skipgram_fasttext_batch(centers, contexts, num_tokens, subword_lookup, dtype, index_dtype): """Create a batch for SG training objective with subwords.""" contexts = mx.nd.array(contexts[2], dtype=index_dtype) data, row, col = subword_lookup(centers) centers = mx.nd.array(...
Create a batch for CBOW training objective.
def cbow_batch(centers, contexts, num_tokens, dtype, index_dtype): """Create a batch for CBOW training objective.""" contexts_data, contexts_row, contexts_col = contexts centers = mx.nd.array(centers, dtype=index_dtype) contexts = mx.nd.sparse.csr_matrix( (contexts_data, (contexts_row, contexts_...
Create a batch for SG training objective.
def skipgram_batch(centers, contexts, num_tokens, dtype, index_dtype): """Create a batch for SG training objective.""" contexts = mx.nd.array(contexts[2], dtype=index_dtype) indptr = mx.nd.arange(len(centers) + 1) centers = mx.nd.array(centers, dtype=index_dtype) centers_csr = mx.nd.sparse.csr_matri...
Get a sparse COO array of words and subwords for SkipGram. 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...
def skipgram_lookup(indices, subwordidxs, subwordidxsptr, offset=0): """Get a sparse COO array of words and subwords for SkipGram. Parameters ---------- indices : numpy.ndarray Array containing numbers in [0, vocabulary_size). The element at position idx is taken to be the word that occ...
Get a sparse COO array of words and subwords for CBOW. 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...
def cbow_lookup(context_row, context_col, subwordidxs, subwordidxsptr, offset=0): """Get a sparse COO array of words and subwords for CBOW. Parameters ---------- context_row : numpy.ndarray of dtype int64 Array of same length as context_col containing numbers in [0, batc...
Source Vocabulary of the Dataset. Returns ------- src_vocab : Vocab Source vocabulary.
def src_vocab(self): """Source Vocabulary of the Dataset. Returns ------- src_vocab : Vocab Source vocabulary. """ if self._src_vocab is None: src_vocab_file_name, src_vocab_hash = \ self._data_file[self._pair_key]['vocab' + '_' + ...
Target Vocabulary of the Dataset. Returns ------- tgt_vocab : Vocab Target vocabulary.
def tgt_vocab(self): """Target Vocabulary of the Dataset. Returns ------- tgt_vocab : Vocab Target vocabulary. """ if self._tgt_vocab is None: tgt_vocab_file_name, tgt_vocab_hash = \ self._data_file[self._pair_key]['vocab' + '_' + ...
Evaluate given the data loader Parameters ---------- data_loader : DataLoader Returns ------- avg_loss : float Average loss real_translation_out : list of list of str The translation output
def evaluate(data_loader): """Evaluate given the data loader Parameters ---------- data_loader : DataLoader Returns ------- avg_loss : float Average loss real_translation_out : list of list of str The translation output """ translation_out = [] all_inst_ids ...
Training function.
def train(): """Training function.""" trainer = gluon.Trainer(model.collect_params(), args.optimizer, {'learning_rate': args.lr}) train_data_loader, val_data_loader, test_data_loader \ = dataprocessor.make_dataloader(data_train, data_val, data_test, args) best_valid_bleu = 0.0 for epoch_id...
r"""Returns a cache model using a pre-trained language model. 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, ...
def get_cache_model(name, dataset_name='wikitext-2', window=2000, theta=0.6, lambdas=0.2, ctx=mx.cpu(), **kwargs): r"""Returns a cache model using a pre-trained language model. We implement the neural cache language model proposed in the following work:: @article{grave2016improving...
Training helper.
def train(args): """Training helper.""" if not args.model.lower() in ['cbow', 'skipgram']: logging.error('Unsupported model %s.', args.model) sys.exit(1) if args.data.lower() == 'toy': data = mx.gluon.data.SimpleDataset(nlp.data.Text8(segment='train')[:2]) data, vocab, idx_t...
Evaluation helper
def evaluate(args, embedding, vocab, global_step, eval_analogy=False): """Evaluation helper""" if 'eval_tokens' not in globals(): global eval_tokens eval_tokens_set = evaluation.get_tokens_in_evaluation_datasets(args) if not args.no_eval_analogy: eval_tokens_set.update(vocab...
Return the dataset corresponds to the provided key. 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') ...
def get_field(self, field): """Return the dataset corresponds to the provided key. Example:: a = np.ones((2,2)) b = np.zeros((2,2)) np.savez('data.npz', a=a, b=b) dataset = NumpyDataset('data.npz') data_a = dataset.get_field('a') d...
Project the tokenized prediction back to the original text.
def get_final_text(pred_text, orig_text, tokenizer): """Project the tokenized prediction back to the original text.""" # When we created the data, we kept track of the alignment between original # (whitespace tokenized) tokens and our WordPiece tokenized tokens. So # now `orig_text` contains the span o...
Get prediction results 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...
def predictions(dev_dataset, all_results, tokenizer, max_answer_length=64, null_score_diff_threshold=0.0, n_best_size=10, version_2=False): """Get prediction results Parameters ---------- dev_dataset: datase...
Calculate the F1 and EM scores of the predicted results. Use only with the SQuAD1.1 dataset. Parameters ---------- dataset_file: string Path to the data file. predict_data: dict All final predictions. Returns ------- scores: dict F1 and EM 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: ...
Data preparation function.
def preprocess_data(tokenizer, task, batch_size, dev_batch_size, max_len, pad=False): """Data preparation function.""" # transformation trans = BERTDatasetTransform( tokenizer, max_len, labels=task.get_labels(), pad=pad, pair=task.is_pair, label_dtype='float32...
Evaluate the model on validation dataset.
def evaluate(dataloader_eval, metric): """Evaluate the model on validation dataset. """ metric.reset() for _, seqs in enumerate(dataloader_eval): input_ids, valid_len, type_ids, label = seqs out = model( input_ids.as_in_context(ctx), type_ids.as_in_context(ctx), v...
Generate and print out the log message for training.
def log_train(batch_id, batch_num, metric, step_loss, log_interval, epoch_id, learning_rate): """Generate and print out the log message for training. """ metric_nm, metric_val = metric.get() if not isinstance(metric_nm, list): metric_nm = [metric_nm] metric_val = [metric_val] train_...
Generate and print out the log message for inference.
def log_inference(batch_id, batch_num, metric, step_loss, log_interval): """Generate and print out the log message for inference. """ metric_nm, metric_val = metric.get() if not isinstance(metric_nm, list): metric_nm = [metric_nm] metric_val = [metric_val] eval_str = '[Batch %d/%d] ...
Training function.
def train(metric): """Training function.""" logging.info('Now we are doing BERT classification training on %s!', ctx) optimizer_params = {'learning_rate': lr, 'epsilon': epsilon, 'wd': 0.01} try: trainer = gluon.Trainer( model.collect_params(), args.optimizer, ...
Inference function.
def inference(metric): """Inference function.""" logging.info('Now we are doing BERT classification inference on %s!', ctx) model = BERTClassifier(bert, dropout=0.1, num_classes=len(task.get_labels())) model.hybridize(static_alloc=True) model.load_parameters(model_parameters, ctx=ctx) metric.r...
Process SQuAD dataset by creating NDArray version of data :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 ------- ...
def preprocess_dataset(dataset, question_max_length, context_max_length): """Process SQuAD dataset by creating NDArray version of data :param Dataset dataset: SQuAD dataset :param int question_max_length: Maximum length of question (padded or trimmed to that size) :param int context_max_length: Maximum...
Find all answer spans from the context, returning start_index and end_index :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...
def _get_answer_spans(answer_list, answer_start_list): """Find all answer spans from the context, returning start_index and end_index :param list[str] answer_list: List of all answers :param list[int] answer_start_list: List of all answers' start indices Returns ------- ...
Provides word level vocabulary Returns ------- Vocab Word level vocabulary
def get_word_level_vocab(self): """Provides word level vocabulary Returns ------- Vocab Word level vocabulary """ def simple_tokenize(source_str, token_delim=' ', seq_delim='\n'): return list(filter(None, re.split(token_delim + '|' + seq_delim, s...
Parameters ---------- states : list the stack outputs from RNN, which consists of output from each time step (TNC). Returns -------- loss : NDArray loss tensor with shape (batch_size,). Dimensions other than batch_axis are averaged out.
def hybrid_forward(self, F, *states): # pylint: disable=arguments-differ """ Parameters ---------- states : list the stack outputs from RNN, which consists of output from each time step (TNC). Returns -------- loss : NDArray loss tensor wi...
Tokenizes a piece of text.
def _tokenize(self, text): """Tokenizes a piece of text.""" text = self._clean_text(text) # This was added on November 1st, 2018 for the multilingual and Chinese # models. This is also applied to the English models now, but it doesn't # matter since the English models were not t...
Performs invalid character removal and whitespace cleanup on text.
def _clean_text(self, text): """Performs invalid character removal and whitespace cleanup on text.""" output = [] for char in text: cp = ord(char) if cp in (0, 0xfffd) or self._is_control(char): continue if self._is_whitespace(char): ...
Checks whether `chars` is a control character.
def _is_control(self, char): """Checks whether `chars` is a control character.""" # These are technically control characters but we count them as whitespace # characters. if char in ['\t', '\n', '\r']: return False cat = unicodedata.category(char) if cat.start...