Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def print_config_values(self, prefix='- '): print('Configuration values from ' + self.config_dir) self.print_config_value(self.CONFIG_NAME_USER, prefix=prefix) self.print_config_value(self.CONFIG_NAME_PATH, prefix=prefix) self.print_c...
[ "a wrapper to print_config_value to print all configuration values\n Parameters\n ==========\n prefix: the character prefix to put before the printed config value\n defaults to \"- \"\n " ]
Please provide a description of the function:def competitions_list(self, group=None, category=None, sort_by=None, page=1, search=None): valid_groups = ['general', 'entered',...
[ " make call to list competitions, format the response, and return\n a list of Competition instances\n\n Parameters\n ==========\n\n page: the page to return (default is 1)\n search: a search term to use (default is empty string)\n sort_by: how to sor...
Please provide a description of the function:def competitions_list_cli(self, group=None, category=None, sort_by=None, page=1, search=None, c...
[ " a wrapper for competitions_list for the client.\n\n Parameters\n ==========\n group: group to filter result to\n category: category to filter result to\n sort_by: how to sort the result, see valid_sort_by for options\n page: the page to return (def...
Please provide a description of the function:def competition_submit(self, file_name, message, competition, quiet=False): if competition is None: competition = self.get_config_value(self.CONFIG_NAME_COMPETITION) if competition is not None and not quiet: print('Usi...
[ " submit a competition!\n\n Parameters\n ==========\n file_name: the competition metadata file\n message: the submission description\n competition: the competition name\n quiet: suppress verbose output (default is False)\n " ]
Please provide a description of the function:def competition_submit_cli(self, file_name, message, competition, competition_opt=None, quiet=False): c...
[ " submit a competition using the client. Arguments are same as for\n competition_submit, except for extra arguments provided here.\n Parameters\n ==========\n competition_opt: an alternative competition option provided by cli\n " ]
Please provide a description of the function:def competition_submissions(self, competition): submissions_result = self.process_response( self.competitions_submissions_list_with_http_info(id=competition)) return [Submission(s) for s in submissions_result]
[ " get the list of Submission for a particular competition\n\n Parameters\n ==========\n competition: the name of the competition\n " ]
Please provide a description of the function:def competition_submissions_cli(self, competition=None, competition_opt=None, csv_display=False, quiet=False): com...
[ " wrapper to competition_submission, will return either json or csv\n to the user. Additional parameters are listed below, see\n competition_submissions for rest.\n\n Parameters\n ==========\n competition: the name of the competition. If None, look to config\n ...
Please provide a description of the function:def competition_list_files(self, competition): competition_list_files_result = self.process_response( self.competitions_data_list_files_with_http_info(id=competition)) return [File(f) for f in competition_list_files_result]
[ " list files for competition\n Parameters\n ==========\n competition: the name of the competition\n " ]
Please provide a description of the function:def competition_list_files_cli(self, competition, competition_opt=None, csv_display=False, quiet=False): competition =...
[ " List files for a competition, if it exists\n\n Parameters\n ==========\n competition: the name of the competition. If None, look to config\n competition_opt: an alternative competition option provided by cli\n csv_display: if True, print comma separated value...
Please provide a description of the function:def competition_download_file(self, competition, file_name, path=None, force=False, quiet=False): ...
[ " download a competition file to a designated location, or use\n a default location\n\n Paramters\n =========\n competition: the name of the competition\n file_name: the configuration file name\n path: a path to download the file to\n forc...
Please provide a description of the function:def competition_download_files(self, competition, path=None, force=False, quiet=True): files = self.competition_list_f...
[ " a wrapper to competition_download_file to download all competition\n files.\n\n Parameters\n =========\n competition: the name of the competition\n path: a path to download the file to\n force: force the download if the file already exists (default...
Please provide a description of the function:def competition_download_cli(self, competition, competition_opt=None, file_name=None, path=None, force=False, ...
[ " a wrapper to competition_download_files, but first will parse input\n from API client. Additional parameters are listed here, see\n competition_download for remaining.\n\n Parameters\n =========\n competition: the name of the competition\n competit...
Please provide a description of the function:def competition_leaderboard_download(self, competition, path, quiet=True): response = self.process_response( self.competition_download_leaderboard_with_http_info( competition, _preload_content=False)) if path is None: ...
[ " Download competition leaderboards\n\n Parameters\n =========\n competition: the name of the competition\n path: a path to download the file to\n quiet: suppress verbose output (default is True)\n " ]
Please provide a description of the function:def competition_leaderboard_view(self, competition): result = self.process_response( self.competition_view_leaderboard_with_http_info(competition)) return [LeaderboardEntry(e) for e in result['submissions']]
[ " view a leaderboard based on a competition name\n\n Parameters\n ==========\n competition: the competition name to view leadboard for\n " ]
Please provide a description of the function:def competition_leaderboard_cli(self, competition, competition_opt=None, path=None, view=False, ...
[ " a wrapper for competition_leaderbord_view that will print the\n results as a table or comma separated values\n\n Parameters\n ==========\n competition: the competition name to view leadboard for\n competition_opt: an alternative competition option provided by...
Please provide a description of the function:def dataset_list(self, sort_by=None, size=None, file_type=None, license_name=None, tag_ids=None, search=None, user=None, ...
[ " return a list of datasets!\n\n Parameters\n ==========\n sort_by: how to sort the result, see valid_sort_bys for options\n size: the size of the dataset, see valid_sizes for string options\n file_type: the format, see valid_file_types for string options\n ...
Please provide a description of the function:def dataset_list_cli(self, sort_by=None, size=None, file_type=None, license_name=None, tag_ids=None, search=None, ...
[ " a wrapper to datasets_list for the client. Additional parameters\n are described here, see dataset_list for others.\n\n Parameters\n ==========\n sort_by: how to sort the result, see valid_sort_bys for options\n size: the size of the dataset, see valid_sizes ...
Please provide a description of the function:def dataset_view(self, dataset): if '/' in dataset: self.validate_dataset_string(dataset) dataset_urls = dataset.split('/') owner_slug = dataset_urls[0] dataset_slug = dataset_urls[1] else: ...
[ " view metadata for a dataset.\n\n Parameters\n ==========\n dataset: the string identified of the dataset\n should be in format [owner]/[dataset-name]\n " ]
Please provide a description of the function:def dataset_list_files(self, dataset): if dataset is None: raise ValueError('A dataset must be specified') if '/' in dataset: self.validate_dataset_string(dataset) dataset_urls = dataset.split('/') owne...
[ " list files for a dataset\n Parameters\n ==========\n dataset: the string identified of the dataset\n should be in format [owner]/[dataset-name]\n " ]
Please provide a description of the function:def dataset_list_files_cli(self, dataset, dataset_opt=None, csv_display=False): dataset = dataset or dataset_opt result = self.dataset_list_files(dataset) ...
[ " a wrapper to dataset_list_files for the client\n (list files for a dataset)\n Parameters\n ==========\n dataset: the string identified of the dataset\n should be in format [owner]/[dataset-name]\n dataset_opt: an alternative option to pro...
Please provide a description of the function:def dataset_status(self, dataset): if dataset is None: raise ValueError('A dataset must be specified') if '/' in dataset: self.validate_dataset_string(dataset) dataset_urls = dataset.split('/') owner_sl...
[ " call to get the status of a dataset from the API\n Parameters\n ==========\n dataset: the string identified of the dataset\n should be in format [owner]/[dataset-name]\n " ]
Please provide a description of the function:def dataset_status_cli(self, dataset, dataset_opt=None): dataset = dataset or dataset_opt return self.dataset_status(dataset)
[ " wrapper for client for dataset_status, with additional\n dataset_opt to get the status of a dataset from the API\n Parameters\n ==========\n dataset_opt: an alternative to dataset\n " ]
Please provide a description of the function:def dataset_download_file(self, dataset, file_name, path=None, force=False, quiet=True): if '/' in dataset: ...
[ " download a single file for a dataset\n\n Parameters\n ==========\n dataset: the string identified of the dataset\n should be in format [owner]/[dataset-name]\n file_name: the dataset configuration file\n path: if defined, download to this ...
Please provide a description of the function:def dataset_download_files(self, dataset, path=None, force=False, quiet=True, unzip=False): if dataset ...
[ " download all files for a dataset\n\n Parameters\n ==========\n dataset: the string identified of the dataset\n should be in format [owner]/[dataset-name]\n path: the path to download the dataset to\n force: force the download if the file a...
Please provide a description of the function:def dataset_download_cli(self, dataset, dataset_opt=None, file_name=None, path=None, unzip=False, for...
[ " client wrapper for dataset_download_files and download dataset file,\n either for a specific file (when file_name is provided),\n or all files for a dataset (plural)\n\n Parameters\n ==========\n dataset: the string identified of the dataset\n ...
Please provide a description of the function:def dataset_upload_file(self, path, quiet): file_name = os.path.basename(path) content_length = os.path.getsize(path) last_modified_date_utc = int(os.path.getmtime(path)) result = FileUploadInfo( self.process_response( ...
[ " upload a dataset file\n\n Parameters\n ==========\n path: the complete path to upload\n quiet: suppress verbose output (default is False)\n " ]
Please provide a description of the function:def dataset_create_version(self, folder, version_notes, quiet=False, convert_to_csv=True, delete_old_versions=False, ...
[ " create a version of a dataset\n\n Parameters\n ==========\n folder: the folder with the dataset configuration / data files\n version_notes: notes to add for the version\n quiet: suppress verbose output (default is False)\n convert_to_csv: on upload...
Please provide a description of the function:def dataset_create_version_cli(self, folder, version_notes, quiet=False, convert_to_csv=True, delete...
[ " client wrapper for creating a version of a dataset\n Parameters\n ==========\n folder: the folder with the dataset configuration / data files\n version_notes: notes to add for the version\n quiet: suppress verbose output (default is False)\n conve...
Please provide a description of the function:def dataset_initialize(self, folder): if not os.path.isdir(folder): raise ValueError('Invalid folder: ' + folder) ref = self.config_values[self.CONFIG_NAME_USER] + '/INSERT_SLUG_HERE' licenses = [] default_license = {'nam...
[ " initialize a folder with a a dataset configuration (metadata) file\n\n Parameters\n ==========\n folder: the folder to initialize the metadata file in\n " ]
Please provide a description of the function:def dataset_create_new(self, folder, public=False, quiet=False, convert_to_csv=True, dir_mode='skip'): if not os.path.isdir...
[ " create a new dataset, meaning the same as creating a version but\n with extra metadata like license and user/owner.\n Parameters\n ==========\n folder: the folder to initialize the metadata file in\n public: should the dataset be public?\n quiet: ...
Please provide a description of the function: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\n Parameters\n ==========\n folder: the folder to initialize the metadata file in\n public: should the dataset be public?\n quiet: suppress verbose output (default is False)\n convert_to_csv: if True, conv...
Please provide a description of the function:def download_file(self, response, outfile, quiet=True, chunk_size=1048576): outpath = os.path.dirname(outfile) if not os.path.exists(outpath): os.makedirs(outpath) size = int(response.headers['Content-Length']) size_read ...
[ " download a file to an output file based on a chunk size\n\n Parameters\n ==========\n response: the response to download\n outfile: the output file to download to\n quiet: suppress verbose output (default is True)\n chunk_size: the size of the chun...
Please provide a description of the function:def kernels_list(self, page=1, page_size=20, dataset=None, competition=None, parent_kernel=None, search=None, mine=False, ...
[ " list kernels based on a set of search criteria\n\n Parameters\n ==========\n page: the page of results to return (default is 1)\n page_size: results per page (default is 20)\n dataset: if defined, filter to this dataset (default None)\n competition...
Please provide a description of the function:def kernels_list_cli(self, mine=False, page=1, page_size=20, search=None, csv_display=False, parent=None, ...
[ " client wrapper for kernels_list, see this function for arguments.\n Additional arguments are provided here.\n Parameters\n ==========\n csv_display: if True, print comma separated values instead of table\n " ]
Please provide a description of the function:def kernels_initialize(self, folder): if not os.path.isdir(folder): raise ValueError('Invalid folder: ' + folder) resources = [] resource = {'path': 'INSERT_SCRIPT_PATH_HERE'} resources.append(resource) username ...
[ " create a new kernel in a specified folder from template, including\n json metadata that grabs values from the configuration.\n Parameters\n ==========\n folder: the path of the folder\n " ]
Please provide a description of the function:def kernels_initialize_cli(self, folder=None): folder = folder or os.getcwd() meta_file = self.kernels_initialize(folder) print('Kernel metadata template written to: ' + meta_file)
[ " client wrapper for kernels_initialize, takes same arguments but\n sets default folder to be None. If None, defaults to present\n working directory.\n Parameters\n ==========\n folder: the path of the folder (None defaults to ${PWD})\n " ]
Please provide a description of the function:def kernels_push(self, folder): if not os.path.isdir(folder): raise ValueError('Invalid folder: ' + folder) meta_file = os.path.join(folder, self.KERNEL_METADATA_FILE) if not os.path.isfile(meta_file): raise ValueErro...
[ " read the metadata file and kernel files from a notebook, validate\n both, and use Kernel API to push to Kaggle if all is valid.\n Parameters\n ==========\n folder: the path of the folder\n " ]
Please provide a description of the function:def kernels_push_cli(self, folder): 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: if result.invalid...
[ " client wrapper for kernels_push, with same arguments.\n " ]
Please provide a description of the function:def kernels_pull(self, kernel, path, metadata=False, quiet=True): existing_metadata = None if kernel is None: if path is None: existing_metadata_path = os.path.join( os.getcwd(), self.KERNEL_METADATA_FI...
[ " pull a kernel, including a metadata file (if metadata is True)\n and associated files to a specified path.\n Parameters\n ==========\n kernel: the kernel to pull\n path: the path to pull files to on the filesystem\n metadata: if True, also pull me...
Please provide a description of the function:def kernels_pull_cli(self, kernel, kernel_opt=None, path=None, metadata=False): kernel = kernel or kernel_opt effective_path = self.kernels_pull( ...
[ " client wrapper for kernels_pull\n " ]
Please provide a description of the function:def kernels_output(self, kernel, path, force=False, quiet=True): if kernel is None: raise ValueError('A kernel must be specified') if '/' in kernel: self.validate_kernel_string(kernel) kernel_url_list = kernel.spli...
[ " retrieve output for a specified kernel\n Parameters\n ==========\n kernel: the kernel to output\n path: the path to pull files to on the filesystem\n force: if output already exists, force overwrite (default False)\n quiet: suppress verbosity (def...
Please provide a description of the function:def kernels_output_cli(self, kernel, kernel_opt=None, path=None, force=False, quiet=False): kernel = kernel or kernel_opt ...
[ " client wrapper for kernels_output, with same arguments. Extra\n arguments are described below, and see kernels_output for others.\n Parameters\n ==========\n kernel_opt: option from client instead of kernel, if not defined\n " ]
Please provide a description of the function:def kernels_status(self, kernel): if kernel is None: raise ValueError('A kernel must be specified') if '/' in kernel: self.validate_kernel_string(kernel) kernel_url_list = kernel.split('/') owner_slug =...
[ " call to the api to get the status of a kernel.\n Parameters\n ==========\n kernel: the kernel to get the status for\n " ]
Please provide a description of the function:def kernels_status_cli(self, kernel, kernel_opt=None): kernel = kernel or kernel_opt response = self.kernels_status(kernel) status = response['status'] message = response['failureMessage'] if message: print('%s has...
[ " client wrapper for kernel_status\n Parameters\n ==========\n kernel_opt: additional option from the client, if kernel not defined\n " ]
Please provide a description of the function:def download_needed(self, response, outfile, quiet=True): try: remote_date = datetime.strptime(response.headers['Last-Modified'], '%a, %d %b %Y %X %Z') if isfile(outfile): lo...
[ " determine if a download is needed based on timestamp. Return True\n if needed (remote is newer) or False if local is newest.\n Parameters\n ==========\n response: the response from the API\n outfile: the output file to write to\n quiet: suppress v...
Please provide a description of the function:def print_table(self, items, fields): formats = [] borders = [] for f in fields: length = max( len(f), max([len(self.string(getattr(i, f))) for i in items])) justify = '>' if isinstance(getattr( ...
[ " print a table of items, for a set of fields defined\n\n Parameters\n ==========\n items: a list of items to print\n fields: a list of fields to select from items\n " ]
Please provide a description of the function:def print_csv(self, items, fields): writer = csv.writer(sys.stdout) writer.writerow(fields) for i in items: i_fields = [self.string(getattr(i, f)) for f in fields] writer.writerow(i_fields)
[ " print a set of fields in a set of items using a csv.writer\n\n Parameters\n ==========\n items: a list of items to print\n fields: a list of fields to select from items\n " ]
Please provide a description of the function:def process_response(self, result): if len(result) == 3: data = result[0] headers = result[2] if self.HEADER_API_VERSION in headers: api_version = headers[self.HEADER_API_VERSION] if (not se...
[ " process a response from the API. We check the API version against\n the client's to see if it's old, and give them a warning (once)\n\n Parameters\n ==========\n result: the result from the API\n " ]
Please provide a description of the function:def is_up_to_date(self, server_version): client_split = self.__version__.split('.') client_len = len(client_split) server_split = server_version.split('.') server_len = len(server_split) # Make both lists the same length ...
[ " determine if a client (on the local user's machine) is up to date\n with the version provided on the server. Return a boolean with True\n or False\n Parameters\n ==========\n server_version: the server version string to compare to the host\n " ]
Please provide a description of the function:def upload_files(self, request, resources, folder, quiet=False, dir_mode='skip'): for file_name in os.listdir(folder): if (file_name == self....
[ " upload files in a folder\n Parameters\n ==========\n request: the prepared request\n resources: the files to upload\n folder: the folder to upload from\n quiet: suppress verbose output (default is False)\n " ]
Please provide a description of the function:def _upload_file(self, file_name, full_path, quiet, request, resources): if not quiet: print('Starting upload for file ' + file_name) content_length = os.path.getsize(full_path) token = self.dataset_upload_file(full_path, quiet)...
[ " Helper function to upload a single file\n Parameters\n ==========\n file_name: name of the file to upload\n full_path: path to the file to upload\n request: the prepared request\n resources: optional file metadata\n quiet: suppress verbo...
Please provide a description of the function:def process_column(self, column): processed_column = DatasetColumn( name=self.get_or_fail(column, 'name'), description=self.get_or_default(column, 'description', '')) if 'type' in column: original_type = column['ty...
[ " process a column, check for the type, and return the processed\n column\n Parameters\n ==========\n column: a list of values in a column to be processed\n " ]
Please provide a description of the function:def upload_complete(self, path, url, quiet): file_size = os.path.getsize(path) try: with tqdm( total=file_size, unit='B', unit_scale=True, unit_divisor=1024, ...
[ " function to complete an upload to retrieve a path from a url\n Parameters\n ==========\n path: the path for the upload that is read in\n url: the url to send the POST to\n quiet: suppress verbose output (default is False)\n " ]
Please provide a description of the function:def validate_dataset_string(self, dataset): if dataset: if '/' not in dataset: raise ValueError('Dataset must be specified in the form of ' '\'{username}/{dataset-slug}\'') split = dat...
[ " determine if a dataset string is valid, meaning it is in the format\n of {username}/{dataset-slug}.\n Parameters\n ==========\n dataset: the dataset name to validate\n " ]
Please provide a description of the function:def validate_kernel_string(self, kernel): if kernel: if '/' not in kernel: raise ValueError('Kernel must be specified in the form of ' '\'{username}/{kernel-slug}\'') split = kernel.sp...
[ " determine if a kernel string is valid, meaning it is in the format\n of {username}/{kernel-slug}.\n Parameters\n ==========\n kernel: the kernel name to validate\n " ]
Please provide a description of the function:def validate_resources(self, folder, resources): self.validate_files_exist(folder, resources) self.validate_no_duplicate_paths(resources)
[ " validate resources is a wrapper to validate the existence of files\n and that there are no duplicates for a folder and set of resources.\n\n Parameters\n ==========\n folder: the folder to validate\n resources: one or more resources to validate within the fol...
Please provide a description of the function:def validate_files_exist(self, folder, resources): for item in resources: file_name = item.get('path') full_path = os.path.join(folder, file_name) if not os.path.isfile(full_path): raise ValueError('%s does...
[ " ensure that one or more resource files exist in a folder\n\n Parameters\n ==========\n folder: the folder to validate\n resources: one or more resources to validate within the folder\n " ]
Please provide a description of the function:def validate_no_duplicate_paths(self, resources): paths = set() for item in resources: file_name = item.get('path') if file_name in paths: raise ValueError( '%s path was specified more than ...
[ " ensure that the user has not provided duplicate paths in\n a list of resources.\n\n Parameters\n ==========\n resources: one or more resources to validate not duplicated\n " ]
Please provide a description of the function:def convert_to_dataset_file_metadata(self, file_data, path): as_metadata = { 'path': os.path.join(path, file_data['name']), 'description': file_data['description'] } schema = {} fields = [] for column ...
[ " convert a set of file_data to a metadata file at path\n\n Parameters\n ==========\n file_data: a dictionary of file data to write to file\n path: the path to write the metadata to\n " ]
Please provide a description of the function:def read(self, *args, **kwargs): buf = io.BufferedReader.read(self, *args, **kwargs) self.increment(len(buf)) return buf
[ " read the buffer, passing named and non named arguments to the\n io.BufferedReader function.\n " ]
Please provide a description of the function:def parameters_to_tuples(self, params, collection_formats): new_params = [] if collection_formats is None: collection_formats = {} for k, v in six.iteritems(params) if isinstance(params, dict) else params: # noqa: E501 ...
[ "Get parameters as list of tuples, formatting collections.\n\n :param params: Parameters as dict or list of two-tuples\n :param dict collection_formats: Parameter collection formats\n :return: Parameters as list of tuples, collections formatted\n " ]
Please provide a description of the function:def prepare_post_parameters(self, post_params=None, files=None): params = [] if post_params: params = post_params if files: for k, v in six.iteritems(files): if not v: continue ...
[ "Builds form parameters.\n\n :param post_params: Normal form parameters.\n :param files: File parameters.\n :return: Form parameters with files.\n " ]
Please provide a description of the function:def __deserialize_file(self, response): fd, path = tempfile.mkstemp(dir=self.configuration.temp_folder_path) os.close(fd) os.remove(path) content_disposition = response.getheader("Content-Disposition") if content_disposition:...
[ "Deserializes body to file\n\n Saves response body into a file in a temporary folder,\n using the filename from the `Content-Disposition` header if provided.\n\n :param response: RESTResponse.\n :return: file path.\n " ]
Please provide a description of the function:def __deserialize_primitive(self, data, klass): try: return klass(data) except UnicodeEncodeError: return six.text_type(data) except TypeError: return data
[ "Deserializes string to primitive type.\n\n :param data: str.\n :param klass: class literal.\n\n :return: int, long, float, str, bool.\n " ]
Please provide a description of the function: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 = logging.FileHandler(self.__logger...
[ "The logger file.\n\n If the logger_file is None, then add stream handler and remove file\n handler. Otherwise, add file handler and remove stream handler.\n\n :param value: The logger_file path.\n :type: str\n " ]
Please provide a description of the function: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", "copyright-authors", "other", "reddit-api", "world-bank"] # noqa: E501 if license_nam...
[ "Sets the license_name of this DatasetNewRequest.\n\n The license that should be associated with the dataset # noqa: E501\n\n :param license_name: The license_name of this DatasetNewRequest. # noqa: E501\n :type: str\n " ]
Please provide a description of the function:def train(net, train_data, test_data): 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=train_...
[ "Train textCNN model for sentiment analysis." ]
Please provide a description of the function:def embedding(self, sentences, oov_way='avg'): data_iter = self.data_loader(sentences=sentences) batches = [] for token_ids, valid_length, token_types in data_iter: token_ids = token_ids.as_in_context(self.ctx) valid_l...
[ "\n Get tokens, tokens embedding\n\n Parameters\n ----------\n sentences : List[str]\n sentences for encoding.\n oov_way : str, default avg.\n use **avg**, **sum** or **last** to get token embedding for those out of\n vocabulary words\n\n Re...
Please provide a description of the function:def data_loader(self, sentences, shuffle=False): dataset = BertEmbeddingDataset(sentences, self.transform) return DataLoader(dataset=dataset, batch_size=self.batch_size, shuffle=shuffle)
[ "Load, tokenize and prepare the input sentences." ]
Please provide a description of the function:def oov(self, batches, oov_way='avg'): sentences = [] for token_ids, sequence_outputs in batches: tokens = [] tensors = [] oov_len = 1 for token_id, sequence_output in zip(token_ids, sequence_outputs): ...
[ "\n How to handle oov. Also filter out [CLS], [SEP] tokens.\n\n Parameters\n ----------\n batches : List[(tokens_id,\n sequence_outputs,\n pooled_output].\n batch token_ids (max_seq_length, ),\n sequence_output...
Please provide a description of the function: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, ...
[ "Any BERT pretrained model.\n\n Parameters\n ----------\n model_name : str or None, default None\n Options include 'bert_24_1024_16' and 'bert_12_768_12'.\n dataset_name : str or None, default None\n Options include 'book_corpus_wiki_en_cased', 'book_corpus_wiki_en_uncased'\n for bo...
Please provide a description of the function: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: data = data.astype('floa...
[ "forward computation." ]
Please provide a description of the function:def _get_classifier(self, prefix): with self.name_scope(): classifier = nn.Dense(2, prefix=prefix) return classifier
[ " Construct a decoder for the next sentence prediction task " ]
Please provide a description of the function:def _get_decoder(self, units, vocab_size, embed, prefix): with self.name_scope(): decoder = nn.HybridSequential(prefix=prefix) decoder.add(nn.Dense(units, flatten=False)) decoder.add(GELU()) decoder.add(BERTLay...
[ " Construct a decoder for the masked language model task " ]
Please provide a description of the function: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 None if "word_embed" or ' \ 'token_type_embed i...
[ " Construct an embedding block. " ]
Please provide a description of the function:def _get_pooler(self, units, prefix): with self.name_scope(): pooler = nn.Dense(units=units, flatten=False, activation='tanh', prefix=prefix) return pooler
[ " Construct pooler.\n\n The pooler slices and projects the hidden output of first token\n in the sequence for segment level classification.\n\n " ]
Please provide a description of the function:def _encode_sequence(self, inputs, token_types, valid_length=None): # embedding word_embedding = self.word_embed(inputs) type_embedding = self.token_type_embed(token_types) embedding = word_embedding + type_embedding # encodin...
[ "Generate the representation given the input sequences.\n\n This is used for pre-training or fine-tuning a BERT model.\n " ]
Please provide a description of the function:def _decode(self, sequence, masked_positions): batch_size = sequence.shape[0] num_masked_positions = masked_positions.shape[1] ctx = masked_positions.context dtype = masked_positions.dtype # batch_idx = [0,0,0,1,1,1,2,2,2...] ...
[ "Generate unnormalized prediction for the masked language model task.\n\n This is only used for pre-training the BERT model.\n\n Inputs:\n - **sequence**: input tensor of sequence encodings.\n Shape (batch_size, seq_length, units).\n - **masked_positions**: input ten...
Please provide a description of the function:def _ngrams(segment, n): ngram_counts = Counter() for i in range(0, len(segment) - n + 1): ngram = tuple(segment[i:i + n]) ngram_counts[ngram] += 1 return ngram_counts
[ "Extracts n-grams from an input segment.\n\n Parameters\n ----------\n segment: list\n Text segment from which n-grams will be extracted.\n n: int\n Order of n-gram.\n\n Returns\n -------\n ngram_counts: Counter\n Contain all the nth n-grams in segment with a count of how m...
Please provide a description of the function:def _bpe_to_words(sentence, delimiter='@@'): words = [] word = '' delimiter_len = len(delimiter) for subwords in sentence: if len(subwords) >= delimiter_len and subwords[-delimiter_len:] == delimiter: word += subwords[:-delimiter_len]...
[ "Convert a sequence of bpe words into sentence." ]
Please provide a description of the function:def _tokenize_mteval_13a(segment): r norm = segment.rstrip() norm = norm.replace('<skipped>', '') norm = norm.replace('-\n', '') norm = norm.replace('\n', ' ') norm = norm.replace('&quot;', '"') norm = norm.replace('&amp;', '&') norm = norm....
[ "\n Tokenizes a string following the tokenizer in mteval-v13a.pl.\n See https://github.com/moses-smt/mosesdecoder/\"\n \"blob/master/scripts/generic/mteval-v14.pl#L917-L942\n Parameters\n ----------\n segment: str\n A string to be tokenized\n\n Returns\n -------\n The tokeni...
Please provide a description of the function:def _tokenize_mteval_v14_intl(segment): r segment = segment.rstrip() segment = unicodeRegex.nondigit_punct_re.sub(r'\1 \2 ', segment) segment = unicodeRegex.punct_nondigit_re.sub(r' \1 \2', segment) segment = unicodeRegex.symbol_re.sub(r' \1 ', segment) ...
[ "Tokenize a string following following the international tokenizer in mteval-v14a.pl.\n See https://github.com/moses-smt/mosesdecoder/\"\n \"blob/master/scripts/generic/mteval-v14.pl#L954-L983\n\n Parameters\n ----------\n segment: str\n A string to be tokenized\n\n Returns\n ----...
Please provide a description of the function: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 precision_numerators = [0 for _ in range(max_n)] preci...
[ "Compute bleu score of translation against references.\n\n Parameters\n ----------\n reference_corpus_list: list of list(list(str)) or list of list(str)\n list of list(list(str)): tokenized references\n list of list(str): plain text\n List of references for each translation.\n trans...
Please provide a description of the function:def _compute_precision(references, translation, n): matches = 0 candidates = 0 ref_ngram_counts = Counter() for reference in references: ref_ngram_counts |= _ngrams(reference, n) trans_ngram_counts = _ngrams(translation, n) overlap_ngram...
[ "Compute ngram precision.\n\n Parameters\n ----------\n references: list(list(str))\n A list of references.\n translation: list(str)\n A translation.\n n: int\n Order of n-gram.\n\n Returns\n -------\n matches: int\n Number of matched nth order n-grams\n candid...
Please provide a description of the function: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 else: return math.exp(1 - float(ref...
[ "Calculate brevity penalty.\n\n Parameters\n ----------\n ref_length: int\n Sum of all closest references'lengths for every translations in a corpus\n trans_length: int\n Sum of all translations's lengths in a corpus.\n\n Returns\n -------\n bleu's brevity penalty: float\n " ]
Please provide a description of the function:def _closest_ref_length(references, trans_length): ref_lengths = (len(reference) for reference in references) closest_ref_len = min(ref_lengths, key=lambda ref_length: (abs(ref_length - trans_length), ref_length)) return closest_re...
[ "Find the reference that has the closest length to the translation.\n\n Parameters\n ----------\n references: list(list(str))\n A list of references.\n trans_length: int\n Length of the translation.\n\n Returns\n -------\n closest_ref_len: int\n Length of the reference that...
Please provide a description of the function:def _smoothing(precision_fractions, c=1): ratios = [0] * len(precision_fractions) for i, precision_fraction in enumerate(precision_fractions): if precision_fraction[1] > 0: ratios[i] = float(precision_fraction[0] + c) / (precision_fraction[1]...
[ "Compute the smoothed precision for all the orders.\n\n Parameters\n ----------\n precision_fractions: list(tuple)\n Contain a list of (precision_numerator, precision_denominator) pairs\n c: int, default 1\n Smoothing constant to use\n\n Returns\n -------\n ratios: list of floats\...
Please provide a description of the function:def forward(self, true_classes): num_sampled = self._num_sampled ctx = true_classes.context num_tries = 0 log_range = math.log(self._range_max + 1) # sample candidates f = ndarray._internal._sample_unique_zipfian ...
[ "Draw samples from log uniform distribution and returns sampled candidates,\n expected count for true classes and sampled classes.\n\n Parameters\n ----------\n true_classes: NDArray\n The true classes.\n\n Returns\n -------\n samples: NDArray\n ...
Please provide a description of the function:def preprocess_dataset(data, min_freq=5, max_vocab_size=None): with print_time('count and construct vocabulary'): counter = nlp.data.count_tokens(itertools.chain.from_iterable(data)) vocab = nlp.Vocab(counter, unknown_token=None, padding_token=None, ...
[ "Dataset preprocessing helper.\n\n Parameters\n ----------\n data : mx.data.Dataset\n Input Dataset. For example gluonnlp.data.Text8 or gluonnlp.data.Fil9\n min_freq : int, default 5\n Minimum token frequency for a token to be included in the vocabulary\n and returned DataStream.\n ...
Please provide a description of the function:def wiki(wiki_root, wiki_date, wiki_language, max_vocab_size=None): data = WikiDumpStream( root=os.path.expanduser(wiki_root), language=wiki_language, date=wiki_date) vocab = data.vocab if max_vocab_size: for token in vocab.idx_to_tok...
[ "Wikipedia dump helper.\n\n Parameters\n ----------\n wiki_root : str\n Parameter for WikiDumpStream\n wiki_date : str\n Parameter for WikiDumpStream\n wiki_language : str\n Parameter for WikiDumpStream\n max_vocab_size : int, optional\n Specifies a maximum size for the...
Please provide a description of the function: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 DataStream of batches.\n\n Parameters\n ----------\n data : gluonnlp.data.DataStream\n DataStream where each sample is a valid input to\n gluonnlp.data.EmbeddingCenterContextBatchify.\n vocab : gluonnlp.Vocab\n Vocabulary containing all...
Please provide a description of the function:def transform_data_word2vec(data, vocab, idx_to_counts, cbow, batch_size, window_size, frequent_token_subsampling=1E-4, dtype='float32', index_dtype='int64'): sum_counts = float(sum(idx_to_counts)) idx_to_...
[ "Transform a DataStream of coded DataSets to a DataStream of batches.\n\n Parameters\n ----------\n data : gluonnlp.data.DataStream\n DataStream where each sample is a valid input to\n gluonnlp.data.EmbeddingCenterContextBatchify.\n vocab : gluonnlp.Vocab\n Vocabulary containing all...
Please provide a description of the function:def cbow_fasttext_batch(centers, contexts, num_tokens, subword_lookup, dtype, index_dtype): _, contexts_row, contexts_col = contexts data, row, col = subword_lookup(contexts_row, contexts_col) centers = mx.nd.array(centers, dtype=inde...
[ "Create a batch for CBOW training objective with subwords." ]
Please provide a description of the function:def skipgram_fasttext_batch(centers, contexts, num_tokens, subword_lookup, dtype, index_dtype): contexts = mx.nd.array(contexts[2], dtype=index_dtype) data, row, col = subword_lookup(centers) centers = mx.nd.array(centers, dtype=i...
[ "Create a batch for SG training objective with subwords." ]
Please provide a description of the function:def cbow_batch(centers, contexts, num_tokens, dtype, index_dtype): 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_col)...
[ "Create a batch for CBOW training objective." ]
Please provide a description of the function:def skipgram_batch(centers, contexts, num_tokens, dtype, index_dtype): 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_matrix(...
[ "Create a batch for SG training objective." ]
Please provide a description of the function:def skipgram_lookup(indices, subwordidxs, subwordidxsptr, offset=0): row = [] col = [] data = [] for i, idx in enumerate(indices): start = subwordidxsptr[idx] end = subwordidxsptr[idx + 1] row.append(i) col.append(idx) ...
[ "Get a sparse COO array of words and subwords for SkipGram.\n\n Parameters\n ----------\n indices : numpy.ndarray\n Array containing numbers in [0, vocabulary_size). The element at\n position idx is taken to be the word that occurs at row idx in the\n SkipGram batch.\n offset : int\...
Please provide a description of the function:def cbow_lookup(context_row, context_col, subwordidxs, subwordidxsptr, offset=0): row = [] col = [] data = [] num_rows = np.max(context_row) + 1 row_to_numwords = np.zeros(num_rows) for i, idx in enumerate(context_col): ...
[ "Get a sparse COO array of words and subwords for CBOW.\n\n Parameters\n ----------\n context_row : numpy.ndarray of dtype int64\n Array of same length as context_col containing numbers in [0,\n batch_size). For each idx, context_row[idx] specifies the row that\n context_col[idx] occur...
Please provide a description of the function: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._src_lang] [src_vocab_path] = self._fetch_data_path([(src_vocab_file_name, s...
[ "Source Vocabulary of the Dataset.\n\n Returns\n -------\n src_vocab : Vocab\n Source vocabulary.\n " ]
Please provide a description of the function: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._tgt_lang] [tgt_vocab_path] = self._fetch_data_path([(tgt_vocab_file_name, t...
[ "Target Vocabulary of the Dataset.\n\n Returns\n -------\n tgt_vocab : Vocab\n Target vocabulary.\n " ]