text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def competitions_list(self, group=None, category=None, sort_by=None, page=1, search=None): """ make call to list competitions, format the response, and return a ...
valid_groups = ['general', 'entered', 'inClass'] if group and group not in valid_groups: raise ValueError('Invalid group specified. Valid options are ' + str(valid_groups)) valid_categories = [ 'all', 'featured', 'research', 'recruitment', '...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def competitions_list_cli(self, group=None, category=None, sort_by=None, page=1, search=None, csv_display=False): """ a wrapper for competitions_list for the cli...
competitions = self.competitions_list( group=group, category=category, sort_by=sort_by, page=page, search=search) fields = [ 'ref', 'deadline', 'category', 'reward', 'teamCount', 'userHasEntered' ] if co...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def competition_submit(self, file_name, message, competition, quiet=False): """ submit a competition! Parameters ========== file_name: the competition metadata f...
if competition is None: competition = self.get_config_value(self.CONFIG_NAME_COMPETITION) if competition is not None and not quiet: print('Using competition: ' + competition) if competition is None: raise ValueError('No competition specified') ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def competition_submissions(self, competition): """ get the list of Submission for a particular competition Parameters ========== competition: the name of the co...
submissions_result = self.process_response( self.competitions_submissions_list_with_http_info(id=competition)) return [Submission(s) for s in submissions_result]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def competition_submissions_cli(self, competition=None, competition_opt=None, csv_display=False, quiet=False): """ wrapper to competition_submission, will return...
competition = competition or competition_opt if competition is None: competition = self.get_config_value(self.CONFIG_NAME_COMPETITION) if competition is not None and not quiet: print('Using competition: ' + competition) if competition is None: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def competition_list_files_cli(self, competition, competition_opt=None, csv_display=False, quiet=False): """ List files for a competition, if it exists Parameter...
competition = competition or competition_opt if competition is None: competition = self.get_config_value(self.CONFIG_NAME_COMPETITION) if competition is not None and not quiet: print('Using competition: ' + competition) if competition is None: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def competition_download_file(self, competition, file_name, path=None, force=False, quiet=False): """ download a competition file to a designated location, or us...
if path is None: effective_path = self.get_default_download_dir( 'competitions', competition) else: effective_path = path response = self.process_response( self.competitions_data_download_file_with_http_info( id=competition, f...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def competition_download_files(self, competition, path=None, force=False, quiet=True): """ a wrapper to competition_download_file to download all competition fil...
files = self.competition_list_files(competition) if not files: print('This competition does not have any available data files') for file_name in files: self.competition_download_file(competition, file_name.ref, path, force, quie...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def competition_download_cli(self, competition, competition_opt=None, file_name=None, path=None, force=False, quiet=False): """ a wrapper to competition_download...
competition = competition or competition_opt if competition is None: competition = self.get_config_value(self.CONFIG_NAME_COMPETITION) if competition is not None and not quiet: print('Using competition: ' + competition) if competition is None: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def competition_leaderboard_download(self, competition, path, quiet=True): """ Download competition leaderboards Parameters ========= competition: the name of th...
response = self.process_response( self.competition_download_leaderboard_with_http_info( competition, _preload_content=False)) if path is None: effective_path = self.get_default_download_dir( 'competitions', competition) else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def competition_leaderboard_view(self, competition): """ view a leaderboard based on a competition name Parameters ========== competition: the competition name t...
result = self.process_response( self.competition_view_leaderboard_with_http_info(competition)) return [LeaderboardEntry(e) for e in result['submissions']]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def competition_leaderboard_cli(self, competition, competition_opt=None, path=None, view=False, download=False, csv_display=False, quiet=False): """ a wrapper fo...
competition = competition or competition_opt if not view and not download: raise ValueError('Either --show or --download must be specified') if competition is None: competition = self.get_config_value(self.CONFIG_NAME_COMPETITION) if competition is not None ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dataset_list(self, sort_by=None, size=None, file_type=None, license_name=None, tag_ids=None, search=None, user=None, mine=False, page=1): """ return a list o...
valid_sort_bys = ['hottest', 'votes', 'updated', 'active', 'published'] if sort_by and sort_by not in valid_sort_bys: raise ValueError('Invalid sort by specified. Valid options are ' + str(valid_sort_bys)) valid_sizes = ['all', 'small', 'medium', 'large...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dataset_list_cli(self, sort_by=None, size=None, file_type=None, license_name=None, tag_ids=None, search=None, user=None, mine=False, page=1, csv_display=False...
datasets = self.dataset_list(sort_by, size, file_type, license_name, tag_ids, search, user, mine, page) fields = ['ref', 'title', 'size', 'lastUpdated', 'downloadCount'] if datasets: if csv_display: self.print_csv(datasets, fields...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dataset_view(self, dataset): """ view metadata for a dataset. Parameters ========== dataset: the string identified of the dataset should be in format [owner]...
if '/' in dataset: self.validate_dataset_string(dataset) dataset_urls = dataset.split('/') owner_slug = dataset_urls[0] dataset_slug = dataset_urls[1] else: owner_slug = self.get_config_value(self.CONFIG_NAME_USER) dataset_slug = d...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dataset_download_file(self, dataset, file_name, path=None, force=False, quiet=True): """ download a single file for a dataset Parameters ========== dataset: ...
if '/' in dataset: self.validate_dataset_string(dataset) dataset_urls = dataset.split('/') owner_slug = dataset_urls[0] dataset_slug = dataset_urls[1] else: owner_slug = self.get_config_value(self.CONFIG_NAME_USER) dataset_slug = d...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dataset_download_files(self, dataset, path=None, force=False, quiet=True, unzip=False): """ download all files for a dataset Parameters ========== dataset: t...
if dataset is None: raise ValueError('A dataset must be specified') if '/' in dataset: self.validate_dataset_string(dataset) dataset_urls = dataset.split('/') owner_slug = dataset_urls[0] dataset_slug = dataset_urls[1] else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dataset_upload_file(self, path, quiet): """ upload a dataset file Parameters ========== path: the complete path to upload quiet: suppress verbose output (def...
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( self.datasets_upload_file_with_http_info( file_name, content_len...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dataset_create_version(self, folder, version_notes, quiet=False, convert_to_csv=True, delete_old_versions=False, dir_mode='skip'): """ create a version of a ...
if not os.path.isdir(folder): raise ValueError('Invalid folder: ' + folder) meta_file = self.get_dataset_metadata_file(folder) # read json with open(meta_file) as f: meta_data = json.load(f) ref = self.get_or_default(meta_data, 'id', None) id_no...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download_file(self, response, outfile, quiet=True, chunk_size=1048576): """ download a file to an output file based on a chunk size Parameters ========== res...
outpath = os.path.dirname(outfile) if not os.path.exists(outpath): os.makedirs(outpath) size = int(response.headers['Content-Length']) size_read = 0 if not quiet: print('Downloading ' + os.path.basename(outfile) + ' to ' + outpath) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def kernels_list(self, page=1, page_size=20, dataset=None, competition=None, parent_kernel=None, search=None, mine=False, user=None, language=None, kernel_type=No...
if int(page) <= 0: raise ValueError('Page number must be >= 1') page_size = int(page_size) if page_size <= 0: raise ValueError('Page size must be >= 1') if page_size > 100: page_size = 100 valid_languages = ['all', 'python', 'r', 'sqlite', '...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: if result.invalidTags: print( 'The following are not valid tags and co...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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( kernel, path=path, metadata=metadata, quiet=False) if metadata: print('Source code and metadata downloaded to ' + effective_path) else: print('Source code downloaded to ' + effective_pa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 lis...
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( items[0], f), int) or f == 'size' or f == 'reward' else '<' formats.ap...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: ...
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 fo...
self.validate_files_exist(folder, resources) self.validate_no_duplicate_paths(resources)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_files_exist(self, folder, resources): """ ensure that one or more resource files exist in a folder Parameters ========== folder: the folder to valid...
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 not exist' % full_path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_no_duplicate_paths(self, resources): """ ensure that the user has not provided duplicate paths in a list of resources. Parameters ========== resourc...
paths = set() for item in resources: file_name = item.get('path') if file_name in paths: raise ValueError( '%s path was specified more than once in the metadata' % file_name) paths.add(file_name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 diction...
as_metadata = { 'path': os.path.join(path, file_data['name']), 'description': file_data['description'] } schema = {} fields = [] for column in file_data['columns']: field = { 'name': column['name'], 'title': co...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parameters_to_tuples(self, params, collection_formats): """Get parameters as list of tuples, formatting collections. :param params: Parameters as dict or lis...
new_params = [] if collection_formats is None: collection_formats = {} for k, v in six.iteritems(params) if isinstance(params, dict) else params: # noqa: E501 if k in collection_formats: collection_format = collection_formats[k] if collec...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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-...
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: filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def license_name(self, license_name): """Sets the license_name of this DatasetNewRequest. The license that should be associated with the dataset # noqa: E501 :pa...
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_name not in allowed_values: raise ValueError( "Invalid value for `...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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=train_data[:sp], batch_size=args.batch_size, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def embedding(self, sentences, oov_way='avg'): """ Get tokens, tokens embedding Parameters sentences : List[str] sentences for encoding. oov_way : str, default a...
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_length = valid_length.as_in_context(self.ctx) token_types = token_types.as_in_context(sel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_a...
predefined_args = bert_hparams[model_name] mutable_args = ['use_residual', 'dropout', 'embed_dropout', 'word_embed'] mutable_args = frozenset(mutable_args) assert all((k not in kwargs or k in mutable_args) for k in predefined_args), \ 'Cannot override predefined model settings.' predefined_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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') gamma = gamma.astype('float32') beta = beta.astype('float32') n...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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()) decoder.add(BERTLayerNorm(in_channels=units)) decoder.add(nn.Dense(vocab_size, flatten=False, params=embed.collect_par...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 given.' with self.name_scope(): embed = nn.HybridSequential(prefix=prefix) with embed....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 cla...
with self.name_scope(): pooler = nn.Dense(units=units, flatten=False, activation='tanh', prefix=prefix) return pooler
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _encode_sequence(self, inputs, token_types, valid_length=None): """Generate the representation given the input sequences. This is used for pre-training or fi...
# embedding word_embedding = self.word_embed(inputs) type_embedding = self.token_type_embed(token_types) embedding = word_embedding + type_embedding # encoding outputs, additional_outputs = self.encoder(embedding, None, valid_length) return outputs, additional_ou...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _decode(self, sequence, masked_positions): """Generate unnormalized prediction for the masked language model task. This is only used for pre-training the BER...
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...] # masked_positions = [1,2,4,0,3,4,2,3,5...] batch_idx = mx.nd.arange(0, batch_size, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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[:-delimiter_len] else: word += subwords words.append(word) word = ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compute_bleu(reference_corpus_list, translation_corpus, tokenized=True, tokenizer='13a', max_n=4, smooth=False, lower_case=False, bpe=False, split_compound_wo...
precision_numerators = [0 for _ in range(max_n)] precision_denominators = [0 for _ in range(max_n)] ref_length, trans_length = 0, 0 for references in reference_corpus_list: assert len(references) == len(translation_corpus), \ 'The number of translations and their references do not m...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _compute_precision(references, translation, n): """Compute ngram precision. Parameters references: list(list(str)) A list of references. translation: list(st...
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_counts = trans_ngram_counts & ref_ngram_counts matches += sum(overlap_ngram_counts.values()) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _brevity_penalty(ref_length, trans_length): """Calculate brevity penalty. Parameters ref_length: int Sum of all closest references'lengths for every translat...
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_length) / trans_length)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _closest_ref_length(references, trans_length): """Find the reference that has the closest length to the translation. Parameters references: list(list(str)) A...
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_ref_len
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _smoothing(precision_fractions, c=1): """Compute the smoothed precision for all the orders. Parameters precision_fractions: list(tuple) Contain a list of (pr...
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] + c) else: ratios[i] = 0.0 return ratios
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def preprocess_dataset(data, min_freq=5, max_vocab_size=None): """Dataset preprocessing helper. Parameters data : mx.data.Dataset Input Dataset. For example gluo...
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, bos_token=None, eos_token=None, min_freq=min_freq, max_size=...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wiki(wiki_root, wiki_date, wiki_language, max_vocab_size=None): """Wikipedia dump helper. Parameters wiki_root : str Parameter for WikiDumpStream wiki_date :...
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_token[max_vocab_size:]: vocab.token_to_idx.pop(token) vocab.idx_to_token = vocab.idx_to_token[:max_v...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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(centers, dtype=index_dtype) contexts = mx.nd.sparse.csr_matrix( (data, (row, col)), dtype=dtype, shape=(len(centers), num_tokens)) # yapf: disable return cente...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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(centers, dtype=index_dtype) centers_csr = mx.nd.sparse.csr_matrix( (data, (row, col)), dtype=dtype, shape=(len(centers), num_tokens)) # yapf: disable return centers...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_col)), dtype=dtype, shape=(len(centers), num_tokens)) # yapf: disable return centers, contexts
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_matrix( (mx.nd.ones(centers.shape), centers, indptr), dtype=dtype, shape=(len(centers), num_tokens)) return...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def skipgram_lookup(indices, subwordidxs, subwordidxsptr, offset=0): """Get a sparse COO array of words and subwords for SkipGram. Parameters indices : numpy.nda...
row = [] col = [] data = [] for i, idx in enumerate(indices): start = subwordidxsptr[idx] end = subwordidxsptr[idx + 1] row.append(i) col.append(idx) data.append(1 / (1 + end - start)) for subword in subwordidxs[start:end]: row.append(i) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cbow_lookup(context_row, context_col, subwordidxs, subwordidxsptr, offset=0): """Get a sparse COO array of words and subwords for CBOW. Parameters context_ro...
row = [] col = [] data = [] num_rows = np.max(context_row) + 1 row_to_numwords = np.zeros(num_rows) for i, idx in enumerate(context_col): start = subwordidxsptr[idx] end = subwordidxsptr[idx + 1] row_ = context_row[i] row_to_numwords[row_] += 1 row.ap...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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' + '_' + self._src_lang] [src_vocab_path] = self._fetch_data_path([(src_vocab_file_name, src_vocab_hash)]) with io.open(src_vocab_path, 'r', encoding='u...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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' + '_' + self._tgt_lang] [tgt_vocab_path] = self._fetch_data_path([(tgt_vocab_file_name, tgt_vocab_hash)]) with io.open(tgt_vocab_path, 'r', encoding='u...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def evaluate(data_loader): """Evaluate given the data loader Parameters data_loader : DataLoader Returns ------- avg_loss : float Average loss real_translation_o...
translation_out = [] all_inst_ids = [] avg_loss_denom = 0 avg_loss = 0.0 for _, (src_seq, tgt_seq, src_valid_length, tgt_valid_length, inst_ids) \ in enumerate(data_loader): src_seq = src_seq.as_in_context(ctx) tgt_seq = tgt_seq.as_in_context(ctx) src_valid_lengt...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
lm_model, vocab = nlp.model.\ get_model(name, dataset_name=dataset_name, pretrained=True, ctx=ctx, **kwargs) cache_cell = CacheCell(lm_model, len(vocab), window, theta, lambdas) return cache_cell
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
idx = self._keys.index(field) return self._data[idx]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: st...
f1 = exact_match = total = 0 for record in dataset: total += 1 if record[1] not in predict_data: message = 'Unanswered question ' + record[1] + \ ' will receive score 0.' print(message) continue ground_truths = record[4] predic...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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' if not task.get_labels() else 'int32') data_train = task('train').transform(trans, lazy=False) data_train_len =...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_str = '[Epoch %d Batch %d/%d] loss=%.4f, lr=%.7f, metrics:' + \ ','.join([i + ':%.4f' for i in metric_nm]) logging.info(train_str, epoch_id +...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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] loss=%.4f, metrics:' + \ ','.join([i + ':%.4f' for i in metric_nm]) logging.info(eval_str, batch_id + 1, batch_num, \ ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.reset() step_loss = 0 tic = time.time() f...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def preprocess_dataset(dataset, question_max_length, context_max_length): """Process SQuAD dataset by creating NDArray version of data :param Dataset dataset: SQ...
vocab_provider = VocabProvider(dataset) transformer = SQuADTransform( vocab_provider, question_max_length, context_max_length) processed_dataset = SimpleDataset( dataset.transform(transformer, lazy=False)) return processed_dataset
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_lis...
return [(answer_start_list[i], answer_start_list[i] + len(answer)) for i, answer in enumerate(answer_list)]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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, source_str))) return VocabProvider._create_squad_vocab(simple_tokenize, self._dataset)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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): output.append(' ') else: output.append(char) return ''.join(output)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.startswith('C'): return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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]) start_new_word = True else: if start_new_word...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 cat = unicodedata.category(char) if cat == 'Zs': return True return ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 tokens from each, since if one sequence is very short then each token # that's truncated likely contains more information than a...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.add_argument('--embedding-path', type=str, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_to_token = sorted(model._token_to_idx, key=model._token_to_idx.get)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 do...
# collect gradient arrays arrays = [] idx = 0 for p in parameters: if p.grad_req != 'null': p_grads = p.list_grad() arrays.append(p_grads[idx % len(p_grads)]) idx += 1 assert len(arrays) > 0, 'No parameter found available for gradient norm.' # comput...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.isinf(grad).sum() # NDArray is implicitly converted to bool...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_rescale / float(iter_since_rescale) # we tolerate a certrain amoun...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stats(self): """Return a string representing the statistics of the bucketing sampler. Returns ------- ret : str String representing the statistics of the buc...
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__.__name__, sample_num=len(self._length...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 = '%s.%s'%(args.save, format(epoch, '02d')) if not os.pat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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, vocab, max_len) return vocab, max_len, output_size, trai...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.max_num_examples] # NOTE: assume data has been tokenized dataset = gluon.data.Si...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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(), btf.Stack(dtype='int32')) data_lengths = [max(len(d[0]), len(d[1])) for d in dataset] batch_sampler...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ------- ...
os.makedirs(root_dir, exist_ok=True) log_formatter = logging.Formatter("%(message)s") logger = logging.getLogger(name) file_handler = logging.FileHandler("{0}/{1}".format(root_dir, name), mode='w') file_handler.setFormatter(log_formatter) logger.addHandler(file_handler) console_handler = lo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def biLSTM(f_lstm, b_lstm, inputs, batch_size=None, dropout_x=0., dropout_h=0.): """Feature extraction through BiLSTM Parameters f_lstm : VariationalDropoutCell ...
for f, b in zip(f_lstm, b_lstm): inputs = nd.Dropout(inputs, dropout_x, axes=[0]) # important for variational dropout fo, fs = f.unroll(length=inputs.shape[0], inputs=inputs, layout='TNC', merge_outputs=True) bo, bs = b.unroll(length=inputs.shape[0], inputs=inputs.flip(axis=0), layout='TNC...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 :...
if ensure_tree: rel_probs[:, ParserVocabulary.PAD] = 0 root = ParserVocabulary.ROOT tokens = np.arange(1, length) rel_preds = np.argmax(rel_probs, axis=1) roots = np.where(rel_preds[tokens] == root)[0] + 1 if len(roots) < 1: rel_preds[1 + np.argmax(rel_pr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reshape_fortran(tensor, shape): """The missing Fortran reshape for mx.NDArray Parameters tensor : NDArray source tensor shape : NDArray desired shape Returns...
return tensor.T.reshape(tuple(reversed(shape))).T
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
seq_len = min(seq_len if seq_len else args.bptt, len(data_source) - 1 - i) data = data_source[i:i+seq_len] target = data_source[i+1:i+1+seq_len] return data, target
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def evaluate(data_source, batch_size, params_file_name, ctx=None): """Evaluate the model on the dataset. Parameters data_source : NDArray The dataset is evaluate...
total_L = 0.0 ntotal = 0 model_eval.load_parameters(params_file_name, context) hidden = model_eval.begin_state(batch_size=batch_size, func=mx.nd.zeros, ctx=context[0]) i = 0 while i < len(data_source) - 1 - 1: data, target = get_batch(data_source, i, seq_len=args.bptt) data =...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register(class_): """Registers a new word embedding evaluation function. Once registered, we can create an instance with :func:`~gluonnlp.embedding.evaluatio...
if issubclass(class_, WordEmbeddingSimilarityFunction): register_ = registry.get_register_func( WordEmbeddingSimilarityFunction, 'word embedding similarity evaluation function') elif issubclass(class_, WordEmbeddingAnalogyFunction): register_ = registry.get_register_fun...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(kind, name, **kwargs): """Creates an instance of a registered word embedding evaluation function. Parameters kind : ['similarity', 'analogy'] Return o...
if kind not in _REGSITRY_KIND_CLASS_MAP.keys(): raise KeyError( 'Cannot find `kind` {}. Use ' '`list_evaluation_functions(kind=None).keys()` to get' 'all the valid kinds of evaluation functions.'.format(kind)) create_ = registry.get_create_func( _REGSITRY_KI...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_evaluation_functions(kind=None): """Get valid word embedding functions names. Parameters kind : ['similarity', 'analogy', None] Return only valid names ...
if kind is None: kind = tuple(_REGSITRY_KIND_CLASS_MAP.keys()) if not isinstance(kind, tuple): if kind not in _REGSITRY_KIND_CLASS_MAP.keys(): raise KeyError( 'Cannot find `kind` {}. Use ' '`list_evaluation_functions(kind=None).keys()` to get all th...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hybrid_forward(self, F, words1, words2, weight): # pylint: disable=arguments-differ """Predict the similarity of words1 and words2. Parameters words1 : Symbo...
embeddings_words1 = F.Embedding(words1, weight, input_dim=self._vocab_size, output_dim=self._embed_size) embeddings_words2 = F.Embedding(words2, weight, input_dim=self._vocab_size, ...